diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/gerrit-gwtui/src/main/java/com/google/gerrit/client/changes/CommitMessageBlock.java b/gerrit-gwtui/src/main/java/com/google/gerrit/client/changes/CommitMessageBlock.java
index 86a2f5ce7..561b43f6f 100644
--- a/gerrit-gwtui/src/main/java/com/google/gerrit/client/changes/CommitMessageBlock.java
+++ b/gerrit-gwtui/src/main/java/com/google/gerrit/client/changes/CommitMessageBlock.java
@@ -1,107 +1,109 @@
// Copyright (C) 2010 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.gerrit.client.changes;
import com.google.gerrit.client.Gerrit;
import com.google.gerrit.client.ui.ChangeLink;
import com.google.gerrit.client.ui.CommentLinkProcessor;
import com.google.gerrit.reviewdb.client.Change;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.PreElement;
import com.google.gwt.dom.client.Style.Display;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.gwtexpui.clippy.client.CopyableLabel;
import com.google.gwtexpui.globalkey.client.KeyCommandSet;
import com.google.gwtexpui.safehtml.client.SafeHtml;
import com.google.gwtexpui.safehtml.client.SafeHtmlBuilder;
public class CommitMessageBlock extends Composite {
interface Binder extends UiBinder<HTMLPanel, CommitMessageBlock> {
}
private static Binder uiBinder = GWT.create(Binder.class);
private KeyCommandSet keysAction;
@UiField
SimplePanel starPanel;
@UiField
FlowPanel permalinkPanel;
@UiField
PreElement commitSummaryPre;
@UiField
PreElement commitBodyPre;
public CommitMessageBlock() {
initWidget(uiBinder.createAndBindUi(this));
}
public CommitMessageBlock(KeyCommandSet keysAction) {
this.keysAction = keysAction;
initWidget(uiBinder.createAndBindUi(this));
}
public void display(final String commitMessage) {
display(null, null, commitMessage);
}
public void display(Change.Id changeId, Boolean starred, String commitMessage) {
starPanel.clear();
if (changeId != null && starred != null && Gerrit.isSignedIn()) {
StarredChanges.Icon star = StarredChanges.createIcon(changeId, starred);
star.setStyleName(Gerrit.RESOURCES.css().changeScreenStarIcon());
starPanel.add(star);
if (keysAction != null) {
keysAction.add(StarredChanges.newKeyCommand(star));
}
}
- permalinkPanel.add(new ChangeLink(Util.C.changePermalink(), changeId));
- permalinkPanel.add(new CopyableLabel(ChangeLink.permalink(changeId), false));
+ if (changeId != null) {
+ permalinkPanel.add(new ChangeLink(Util.C.changePermalink(), changeId));
+ permalinkPanel.add(new CopyableLabel(ChangeLink.permalink(changeId), false));
+ }
String[] splitCommitMessage = commitMessage.split("\n", 2);
String commitSummary = splitCommitMessage[0];
String commitBody = "";
if (splitCommitMessage.length > 1) {
commitBody = splitCommitMessage[1];
}
// Linkify commit summary
SafeHtml commitSummaryLinkified = new SafeHtmlBuilder().append(commitSummary);
commitSummaryLinkified = commitSummaryLinkified.linkify();
commitSummaryLinkified = CommentLinkProcessor.apply(commitSummaryLinkified);
commitSummaryPre.setInnerHTML(commitSummaryLinkified.asString());
// Hide commit body if there is no body
if (commitBody.trim().isEmpty()) {
commitBodyPre.getStyle().setDisplay(Display.NONE);
} else {
// Linkify commit body
SafeHtml commitBodyLinkified = new SafeHtmlBuilder().append(commitBody);
commitBodyLinkified = commitBodyLinkified.linkify();
commitBodyLinkified = CommentLinkProcessor.apply(commitBodyLinkified);
commitBodyPre.setInnerHTML(commitBodyLinkified.asString());
}
}
}
| true | true | public void display(Change.Id changeId, Boolean starred, String commitMessage) {
starPanel.clear();
if (changeId != null && starred != null && Gerrit.isSignedIn()) {
StarredChanges.Icon star = StarredChanges.createIcon(changeId, starred);
star.setStyleName(Gerrit.RESOURCES.css().changeScreenStarIcon());
starPanel.add(star);
if (keysAction != null) {
keysAction.add(StarredChanges.newKeyCommand(star));
}
}
permalinkPanel.add(new ChangeLink(Util.C.changePermalink(), changeId));
permalinkPanel.add(new CopyableLabel(ChangeLink.permalink(changeId), false));
String[] splitCommitMessage = commitMessage.split("\n", 2);
String commitSummary = splitCommitMessage[0];
String commitBody = "";
if (splitCommitMessage.length > 1) {
commitBody = splitCommitMessage[1];
}
// Linkify commit summary
SafeHtml commitSummaryLinkified = new SafeHtmlBuilder().append(commitSummary);
commitSummaryLinkified = commitSummaryLinkified.linkify();
commitSummaryLinkified = CommentLinkProcessor.apply(commitSummaryLinkified);
commitSummaryPre.setInnerHTML(commitSummaryLinkified.asString());
// Hide commit body if there is no body
if (commitBody.trim().isEmpty()) {
commitBodyPre.getStyle().setDisplay(Display.NONE);
} else {
// Linkify commit body
SafeHtml commitBodyLinkified = new SafeHtmlBuilder().append(commitBody);
commitBodyLinkified = commitBodyLinkified.linkify();
commitBodyLinkified = CommentLinkProcessor.apply(commitBodyLinkified);
commitBodyPre.setInnerHTML(commitBodyLinkified.asString());
}
}
| public void display(Change.Id changeId, Boolean starred, String commitMessage) {
starPanel.clear();
if (changeId != null && starred != null && Gerrit.isSignedIn()) {
StarredChanges.Icon star = StarredChanges.createIcon(changeId, starred);
star.setStyleName(Gerrit.RESOURCES.css().changeScreenStarIcon());
starPanel.add(star);
if (keysAction != null) {
keysAction.add(StarredChanges.newKeyCommand(star));
}
}
if (changeId != null) {
permalinkPanel.add(new ChangeLink(Util.C.changePermalink(), changeId));
permalinkPanel.add(new CopyableLabel(ChangeLink.permalink(changeId), false));
}
String[] splitCommitMessage = commitMessage.split("\n", 2);
String commitSummary = splitCommitMessage[0];
String commitBody = "";
if (splitCommitMessage.length > 1) {
commitBody = splitCommitMessage[1];
}
// Linkify commit summary
SafeHtml commitSummaryLinkified = new SafeHtmlBuilder().append(commitSummary);
commitSummaryLinkified = commitSummaryLinkified.linkify();
commitSummaryLinkified = CommentLinkProcessor.apply(commitSummaryLinkified);
commitSummaryPre.setInnerHTML(commitSummaryLinkified.asString());
// Hide commit body if there is no body
if (commitBody.trim().isEmpty()) {
commitBodyPre.getStyle().setDisplay(Display.NONE);
} else {
// Linkify commit body
SafeHtml commitBodyLinkified = new SafeHtmlBuilder().append(commitBody);
commitBodyLinkified = commitBodyLinkified.linkify();
commitBodyLinkified = CommentLinkProcessor.apply(commitBodyLinkified);
commitBodyPre.setInnerHTML(commitBodyLinkified.asString());
}
}
|
diff --git a/javasrc/src/org/ccnx/ccn/protocol/ContentObject.java b/javasrc/src/org/ccnx/ccn/protocol/ContentObject.java
index fb1e6d2b0..9a3089239 100644
--- a/javasrc/src/org/ccnx/ccn/protocol/ContentObject.java
+++ b/javasrc/src/org/ccnx/ccn/protocol/ContentObject.java
@@ -1,844 +1,838 @@
/**
* Part of the CCNx Java Library.
*
* Copyright (C) 2008, 2009, 2010 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.protocol;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.DigestOutputStream;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.SignatureException;
import java.security.cert.CertificateEncodingException;
import java.util.Arrays;
import java.util.logging.Level;
import org.ccnx.ccn.ContentVerifier;
import org.ccnx.ccn.KeyManager;
import org.ccnx.ccn.config.SystemConfiguration;
import org.ccnx.ccn.impl.encoding.BinaryXMLCodec;
import org.ccnx.ccn.impl.encoding.CCNProtocolDTags;
import org.ccnx.ccn.impl.encoding.GenericXMLEncodable;
import org.ccnx.ccn.impl.encoding.XMLCodecFactory;
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.security.crypto.CCNDigestHelper;
import org.ccnx.ccn.impl.security.crypto.CCNSignatureHelper;
import org.ccnx.ccn.impl.support.DataUtils;
import org.ccnx.ccn.impl.support.Log;
import org.ccnx.ccn.io.NullOutputStream;
import org.ccnx.ccn.io.content.ContentDecodingException;
import org.ccnx.ccn.io.content.ContentEncodingException;
import org.ccnx.ccn.protocol.SignedInfo.ContentType;
/**
* Represents a CCNx data packet.
* cf. Interest
*/
public class ContentObject extends GenericXMLEncodable implements XMLEncodable, Comparable<ContentObject> {
public static boolean DEBUG_SIGNING = false;
protected ContentName _name;
protected SignedInfo _signedInfo;
protected byte [] _content;
/**
* Cache of the complete ContentObject's digest. Set when first calculated.
* Used as the implicit last name component.
*/
protected byte [] _digest = null;
protected Signature _signature;
/**
* We don't specify a required publisher, and right now we don't enforce
* that publisherID is the digest of the key used to sign (which could actually
* be handy to preserve privacy); we just use the key locator and publisherID
* combined to look up keys in caches (though for right now we only put keys in
* caches by straight digest; would have to offer option to put keys in caches
* using some privacy-preserving function as well..
*
* TODO evaluate when the gap between checking verifier and checking
* publisherID matters. Probably does; could have bogus publisherID, and
* then real key locator and content that uses key locator would then verify
* content and user might rely on publisher ID. Make that an option, though,
* even if it costs more time to check.
*/
public static class SimpleVerifier implements ContentVerifier {
public static SimpleVerifier _defaultVerifier = null;
PublisherPublicKeyDigest _requiredPublisher;
KeyManager _keyManager;
public static ContentVerifier getDefaultVerifier() {
if (null == _defaultVerifier) {
synchronized(SimpleVerifier.class) {
if (null == _defaultVerifier) {
_defaultVerifier = new SimpleVerifier(null);
}
}
}
return _defaultVerifier;
}
public SimpleVerifier(PublisherPublicKeyDigest requiredPublisher) {
_requiredPublisher = requiredPublisher;
_keyManager = KeyManager.getDefaultKeyManager();
}
public SimpleVerifier(PublisherPublicKeyDigest publisher, KeyManager keyManager) {
_requiredPublisher = publisher;
_keyManager = (null != keyManager) ? keyManager : KeyManager.getDefaultKeyManager();
}
/* (non-Javadoc)
* @see com.parc.ccn.data.security.ContentVerifier#verifyBlock(com.parc.ccn.data.ContentObject)
*/
public boolean verify(ContentObject object) {
if (null == object)
return false;
if (null != _requiredPublisher) {
if (!_requiredPublisher.equals(object.signedInfo().getPublisherKeyID()))
return false;
}
try {
return object.verify(_keyManager);
} catch (Exception e) {
if (Log.isLoggable(Level.FINE)) {
Log.fine(e.getClass().getName() + " exception attempting to retrieve public key with key locator {0}: " + e.getMessage(), object.signedInfo().getKeyLocator());
Log.logStackTrace(Level.FINE, e);
}
return false;
}
}
}
/**
* We copy the content when we get it. The intent is for this object to
* be immutable.
* @param digestAlgorithm
* @param name
* @param signedInfo
* @param content
* @param signature already immutable
*/
public ContentObject(String digestAlgorithm, // prefer OID
ContentName name,
SignedInfo signedInfo,
byte [] content,
Signature signature
) {
this(name, signedInfo, content, 0, ((null == content) ? 0 : content.length), signature);
}
public ContentObject(String digestAlgorithm, // prefer OID
ContentName name,
SignedInfo signedInfo,
byte [] content, int offset, int length,
Signature signature) {
_name = name;
_signedInfo = signedInfo;
_content = new byte[length];
if (null != content)
System.arraycopy(content, offset, _content, 0, length);
_signature = signature;
if ((null != signature) && Log.isLoggable(Log.FAC_SIGNING, Level.FINEST)) {
try {
byte [] digest = CCNDigestHelper.digest(this.encode());
byte [] tbsdigest = CCNDigestHelper.digest(prepareContent(name, signedInfo, content, offset, length));
if (Log.isLoggable(Level.INFO)) {
Log.info("Created content object: " + name + " timestamp: " + signedInfo.getTimestamp() + " encoded digest: " + DataUtils.printBytes(digest) + " tbs content: " + DataUtils.printBytes(tbsdigest));
Log.info("Signature: " + this.signature());
}
} catch (Exception e) {
if (Log.isLoggable(Level.WARNING)) {
Log.warning("Exception attempting to verify signature: " + e.getClass().getName() + ": " + e.getMessage());
Log.warningStackTrace(e);
}
}
}
}
/**
* Minimum-copy constructor.
* @param digestAlgorithm
* @param name
* @param signedInfo
* @param contentStream a stream from which to read a block of content
* @param length number of bytes to try to read; will size content to this
* or to the number of bytes left in the stream, whichever is smaller.
* DKS TODO -- need timeout?
*
* Set signature with setSignature or sign once it's constructed.
* @throws IOException if no bytes left in stream
*/
public ContentObject(String digestAlgorithm, // prefer OID
ContentName name,
SignedInfo signedInfo,
InputStream contentStream, int length) throws IOException {
_name = name;
_signedInfo = signedInfo;
_content = new byte[length];
int count = contentStream.read(_content);
if (count < _content.length) {
if (count < 0) {
throw new IOException("End of stream reached when building content object!");
} else {
byte [] newContent = new byte[count];
System.arraycopy(_content, 0, newContent, 0, count);
_content = newContent;
}
}
}
public ContentObject(
ContentName name,
SignedInfo signedInfo,
InputStream contentStream, int length) throws IOException {
this(CCNDigestHelper.DEFAULT_DIGEST_ALGORITHM, name, signedInfo, contentStream, length);
}
public ContentObject(ContentName name, SignedInfo signedInfo, byte [] content,
Signature signature) {
this(CCNDigestHelper.DEFAULT_DIGEST_ALGORITHM, name, signedInfo, content, signature);
}
public ContentObject(ContentName name, SignedInfo signedInfo,
byte [] content, int offset, int length,
Signature signature) {
this(CCNDigestHelper.DEFAULT_DIGEST_ALGORITHM, name, signedInfo, content, offset, length, signature);
}
/**
* Generate a signedInfo and a signature.
* @throws SignatureException
* @throws InvalidKeyException
*/
public ContentObject(ContentName name,
SignedInfo signedInfo,
byte [] content, int offset, int length,
PrivateKey signingKey) throws InvalidKeyException, SignatureException {
this(name, signedInfo, content, offset, length, (Signature)null);
setSignature(sign(_name, _signedInfo, _content, 0, _content.length, signingKey));
}
public ContentObject(ContentName name,
SignedInfo signedInfo,
byte [] content, PrivateKey signingKey) throws InvalidKeyException, SignatureException {
this(name, signedInfo, content, 0, ((null == content) ? 0 : content.length), signingKey);
}
/*
* Used for testing and for building small content objects deep in the
* library code for specialized applications.
*/
public static ContentObject buildContentObject(ContentName name, ContentType type, byte[] contents,
PublisherPublicKeyDigest publisher, KeyLocator locator,
KeyManager keyManager, Integer freshnessSeconds, byte[] finalBlockID) {
try {
if (null == keyManager) {
keyManager = KeyManager.getDefaultKeyManager();
}
PrivateKey signingKey = keyManager.getSigningKey(publisher);
if ((null == publisher) || (null == signingKey)) {
signingKey = keyManager.getDefaultSigningKey();
publisher = keyManager.getPublisherKeyID(signingKey);
}
if (null == locator)
locator = keyManager.getKeyLocator(signingKey);
return new ContentObject(name,
new SignedInfo(publisher, null, type, locator, freshnessSeconds, finalBlockID),
contents, signingKey);
} catch (Exception e) {
Log.warning("Cannot build content object for publisher: {0}", publisher);
Log.infoStackTrace(e);
}
return null;
}
public static ContentObject buildContentObject(ContentName name, ContentType type, byte[] contents,
PublisherPublicKeyDigest publisher, KeyLocator locator,
KeyManager keyManager, byte[] finalBlockID) {
return buildContentObject(name, type, contents, publisher, locator, keyManager, null, finalBlockID);
}
public static ContentObject buildContentObject(ContentName name, ContentType type, byte[] contents,
PublisherPublicKeyDigest publisher,
KeyManager keyManager, byte[] finalBlockID) {
return buildContentObject(name, type, contents, publisher, null, keyManager, finalBlockID);
}
public static ContentObject buildContentObject(ContentName name, byte[] contents,
PublisherPublicKeyDigest publisher,
KeyManager keyManager, byte[] finalBlockID) {
return buildContentObject(name, ContentType.DATA, contents, publisher, keyManager, finalBlockID);
}
public static ContentObject buildContentObject(ContentName name, byte [] contents) {
return buildContentObject(name, contents, null, null, null);
}
public static ContentObject buildContentObject(ContentName name, ContentType type, byte [] contents) {
return buildContentObject(name, type, contents, null, null, null);
}
public static ContentObject buildContentObject(ContentName name, byte [] contents, PublisherPublicKeyDigest publisher) {
return buildContentObject(name, contents, publisher, null, null);
}
public ContentObject() {} // for use by decoders
public ContentObject clone() {
// Constructor will clone the _content, signedInfo and signature are immutable types.
return new ContentObject(_name.clone(), _signedInfo, _content, _signature);
}
/**
* DKS -- return these as final for now; stopgap till refactor that makes
* internal version final.
* @return Name of the content object - without the final implicit digest component.
*/
public final ContentName name() { return _name; }
/**
* @return Name of the content object, complete with the final implicit digest component.
*/
public ContentName fullName() {
return new ContentName(_name, digest());
}
public final SignedInfo signedInfo() { return _signedInfo;}
/**
* Final here doesn't really make it immutable. There have been
* proposals to clone() the content on return, but many places use this
* and it would be expensive.
* @return
*/
public final byte [] content() { return _content; }
/**
* Avoid problems where content().length might be expensive.
* @return content length in bytes
*/
public final int contentLength() { return ((null == _content) ? 0 : _content.length); }
public final Signature signature() { return _signature; }
/**
* Used by NetworkObject to decode the object from a network stream.
* @see org.ccnx.ccn.impl.encoding.XMLEncodable
*/
public void decode(XMLDecoder decoder) throws ContentDecodingException {
decoder.readStartElement(getElementLabel());
_signature = new Signature();
_signature.decode(decoder);
_name = new ContentName();
_name.decode(decoder);
_signedInfo = new SignedInfo();
_signedInfo.decode(decoder);
_content = decoder.readBinaryElement(CCNProtocolDTags.Content);
decoder.readEndElement();
}
/**
* Used by NetworkObject to encode the object to a network stream.
* @see org.ccnx.ccn.impl.encoding.XMLEncodable
*/
public void encode(XMLEncoder encoder) throws ContentEncodingException {
if (!validate()) {
throw new ContentEncodingException("Cannot encode " + this.getClass().getName() + ": field values missing.");
}
encoder.writeStartElement(getElementLabel());
signature().encode(encoder);
name().encode(encoder);
signedInfo().encode(encoder);
encoder.writeElement(CCNProtocolDTags.Content, _content);
encoder.writeEndElement();
}
@Override
public long getElementLabel() { return CCNProtocolDTags.ContentObject; }
@Override
public boolean validate() {
// recursive?
// null content ok
return ((null != name()) && (null != signedInfo()) && (null != signature()));
}
@Override
public int hashCode() {
final int PRIME = 31;
int result = 1;
result = PRIME * result + ((_name == null) ? 0 : _name.hashCode());
result = PRIME * result + ((_signedInfo == null) ? 0 : _signedInfo.hashCode());
result = PRIME * result + ((_signature == null) ? 0 : _signature.hashCode());
result = PRIME * result + Arrays.hashCode(_content);
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final ContentObject other = (ContentObject) obj;
if (_name == null) {
if (other.name() != null)
return false;
} else if (!_name.equals(other.name()))
return false;
if (_signedInfo == null) {
if (other.signedInfo() != null)
return false;
} else if (!_signedInfo.equals(other.signedInfo()))
return false;
if (_signature == null) {
if (other.signature() != null)
return false;
} else if (!_signature.equals(other.signature()))
return false;
if (!Arrays.equals(_content, other._content))
return false;
return true;
}
/**
* External function to set signature if generating it some special way
* (e.g. with a bulk signer).
* @param signature
*/
public void setSignature(Signature signature) {
if (null != _signature) {
// Only do this if FAC_SIGNING is on, as we use it in tests.
if (Log.isLoggable(Log.FAC_SIGNING, Level.FINE))
Log.fine(Log.FAC_SIGNING, "Setting signature on content object: " + name() + " after signature already set!");
}
if (null == signature) {
if (Log.isLoggable(Log.FAC_SIGNING, Level.FINE))
Log.fine(Log.FAC_SIGNING, "Setting signature to null on content object: " + name());
}
_signature = signature;
}
public void sign(PrivateKey signingKey) throws InvalidKeyException, SignatureException {
// Use _content to avoid case where content() might want to clone.
setSignature(sign(this.name(), this.signedInfo(), this._content, 0, this._content.length, signingKey));
}
public void sign(String digestAlgorithm, PrivateKey signingKey) throws InvalidKeyException, SignatureException, NoSuchAlgorithmException {
setSignature(sign(this.name(), this.signedInfo(), this._content, 0, this._content.length,
digestAlgorithm, signingKey));
}
public static Signature sign(ContentName name,
SignedInfo signedInfo,
byte [] content, int offset, int length,
PrivateKey signingKey)
throws SignatureException, InvalidKeyException {
try {
return sign(name, signedInfo, content, offset, length,
CCNDigestHelper.DEFAULT_DIGEST_ALGORITHM, signingKey);
} catch (NoSuchAlgorithmException e) {
if (Log.isLoggable(Level.WARNING))
Log.warning("Cannot find default digest algorithm: " + CCNDigestHelper.DEFAULT_DIGEST_ALGORITHM);
Log.warningStackTrace(e);
throw new SignatureException(e);
}
}
/**
* Generate a signature on a name-content mapping. This
* signature is specific to both this content signedInfo
* and this name. The SignedInfo no longer contains
* a proxy for the content, so we sign the content itself
* directly. This is used with simple algorithms that don't
* generate a witness.
* @throws SignatureException
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
*/
public static Signature sign(ContentName name,
SignedInfo signedInfo,
byte [] content, int offset, int length,
String digestAlgorithm,
PrivateKey signingKey)
throws SignatureException, InvalidKeyException, NoSuchAlgorithmException {
// Build XML document
byte [] signature = null;
try {
byte [] toBeSigned = prepareContent(name, signedInfo, content, offset, length);
signature =
CCNSignatureHelper.sign(digestAlgorithm,
toBeSigned,
signingKey);
} catch (ContentEncodingException e) {
Log.logException("Exception encoding internally-generated XML name!", e);
throw new SignatureException(e);
}
return new Signature(digestAlgorithm, null, signature);
}
/**
* @see ContentObject#verify(ContentObject, PublicKey)
*/
public boolean verify(PublicKey publicKey)
throws InvalidKeyException, SignatureException, NoSuchAlgorithmException,
ContentEncodingException {
return verify(this, publicKey);
}
public boolean verify(KeyManager keyManager) throws SignatureException,
NoSuchAlgorithmException, ContentEncodingException, InvalidKeyException {
return verify(this, keyManager);
}
/**
* Want to verify a content object. First compute the
* witness result (e.g. Merkle path root, or possibly content
* proxy), and make it available to the caller if caller just
* needs to check whether it matches a previous round. Then
* verify the actual signature.
*
* @param verifySignature If we have a collection of blocks
* all authenticated by the public key signature, we may
* only need to verify that signature once. If verifySignature
* is true, we do that work. If it is false, we simply verify
* that this piece of content matches that signature; assuming
* that the caller has already verified that signature. If you're
* not sure what all this means, you shouldn't be calling this
* one; use the simple verify above.
* @param publicKey If the caller already knows a public key
* that should be used to verify the signature, they can
* pass it in. Otherwise, the key locator in the object
* will be used to find the key.
* @throws SignatureException
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
*/
public static boolean verify(ContentObject object,
PublicKey publicKey) throws SignatureException, InvalidKeyException,
NoSuchAlgorithmException, ContentEncodingException {
if (null == publicKey) {
throw new SignatureException("Cannot verify object without public key -- public key cannot be null!");
}
// Start with the cheap part. Derive the content proxy that was signed. This is
// either the root of the MerkleHash tree, the content itself, or the digest of
// the content.
byte [] contentProxy = null;
try {
// Callers that think they don't need to recompute the signature can just compute
// the proxy and check.
// The proxy may be dependent on the whole object. If there is a proxy, signature
// is over that. Otherwise, signature is over hash of the content and name and signedInfo.
contentProxy = object.computeProxy();
} catch (CertificateEncodingException e) {
if (Log.isLoggable(Level.INFO))
Log.info("Encoding exception attempting to verify content digest for object: " + object.name() + ". Signature verification fails.");
return false;
}
boolean result;
if (null != contentProxy) {
result = CCNSignatureHelper.verify(contentProxy, object.signature().signature(), object.signature().digestAlgorithm(), publicKey);
} else {
result = verify(object.name(), object.signedInfo(), object.content(), object.signature(), publicKey);
}
if ((!result) && Log.isLoggable(Log.FAC_VERIFY, Level.WARNING)) {
- String proxyString = null;
- try {
- proxyString = DataUtils.printHexBytes(CCNDigestHelper.digest(object.computeProxy()));
- } catch (CertificateEncodingException e) {
- proxyString = "<encoding error>";
- }
Log.info("VERIFICATION FAILURE: " + object.name() + " timestamp: " + object.signedInfo().getTimestamp() + " content length: " + object.contentLength() +
" ephemeral digest: " + DataUtils.printBytes(object.digest()) +
- " proxy sha256 digest: " + proxyString);
+ " to be signed sha256 digest: " + DataUtils.printHexBytes(CCNDigestHelper.digest(object.prepareContent())));
SystemConfiguration.outputDebugObject(object);
}
return result;
}
public static boolean verify(ContentObject object,
KeyManager keyManager) throws SignatureException, InvalidKeyException,
NoSuchAlgorithmException, ContentEncodingException {
try {
if (null == keyManager)
keyManager = KeyManager.getDefaultKeyManager();
PublicKey publicKey = keyManager.getPublicKey(
object.signedInfo().getPublisherKeyID(),
object.signedInfo().getKeyLocator());
if (null == publicKey) {
throw new SignatureException("Cannot obtain public key to verify object. Publisher: " +
object.signedInfo().getPublisherKeyID() + " Key locator: " +
object.signedInfo().getKeyLocator());
}
return verify(object, publicKey);
} catch (IOException e) {
throw new SignatureException("Cannot obtain public key to verify object. Key locator: " +
object.signedInfo().getKeyLocator() + " exception: " + e.getMessage(), e);
}
}
/**
* Verify the public key signature on a content object.
* Does not verify that the content matches the signature,
* merely that the signature over the name and content
* signedInfo is correct and was performed with the
* indicated public key.
* @param contentProxy the proxy for the content that was signed. This could
* be the content itself, a digest of the content, or the root of a Merkle hash tree.
* @return
* @throws SignatureException
* @throws NoSuchAlgorithmException
* @throws ContentEncodingException
* @throws InvalidKeyException
*/
public static boolean verify(
ContentName name,
SignedInfo signedInfo,
byte [] content,
Signature signature,
PublicKey publicKey) throws SignatureException, InvalidKeyException, NoSuchAlgorithmException,
ContentEncodingException {
if (null == publicKey) {
throw new SignatureException("Cannot verify object without public key -- public key cannot be null!");
}
byte [] preparedContent = prepareContent(name, signedInfo, content);
// Now, check the signature.
boolean result =
CCNSignatureHelper.verify(preparedContent,
signature.signature(),
(signature.digestAlgorithm() == null) ? CCNDigestHelper.DEFAULT_DIGEST_ALGORITHM : signature.digestAlgorithm(),
publicKey);
return result;
}
public static boolean verify(byte[] proxy, byte [] signature, SignedInfo signedInfo,
String digestAlgorithm, PublicKey publicKey) throws InvalidKeyException, SignatureException,
NoSuchAlgorithmException {
if (null == publicKey) {
throw new SignatureException("Cannot verify object without public key -- public key cannot be null!");
}
// Now, check the signature.
boolean result =
CCNSignatureHelper.verify(proxy,
signature,
(digestAlgorithm == null) ? CCNDigestHelper.DEFAULT_DIGEST_ALGORITHM : digestAlgorithm,
publicKey);
return result;
}
public static boolean verify(byte[] proxy, byte [] signature, SignedInfo signedInfo,
String digestAlgorithm, KeyManager keyManager) throws InvalidKeyException, SignatureException, NoSuchAlgorithmException {
try {
if (null == keyManager)
keyManager = KeyManager.getDefaultKeyManager();
PublicKey publicKey = keyManager.getPublicKey(
signedInfo.getPublisherKeyID(),
signedInfo.getKeyLocator());
if (null == publicKey) {
throw new SignatureException("Cannot obtain public key to verify object. Publisher: " +
signedInfo.getPublisherKeyID() + " Key locator: " +
signedInfo.getKeyLocator());
}
return verify(proxy, signature, signedInfo, digestAlgorithm, publicKey);
} catch (IOException e) {
throw new SignatureException("IOException attempting to obtain public key to verify object. Key locator: " +
signedInfo.getKeyLocator() + " exception: " + e.getClass().getName() + ": " + e.getMessage(), e);
}
}
public byte [] computeProxy() throws CertificateEncodingException, ContentEncodingException {
// Given a witness and an object, compute the proxy.
if (null == content())
return null;
if ((null == signature()) || (null == signature().witness())) {
return null;
}
// Have to eventually handle various forms of witnesses...
// Need to take an algorithm to control the digest used.
byte[] blockDigest = CCNDigestHelper.digest(
prepareContent(name(), signedInfo(), content()));
return signature().computeProxy(blockDigest, true);
}
public byte [] prepareContent() throws ContentEncodingException {
return prepareContent(name(), signedInfo(), content());
}
public static byte [] prepareContent(ContentName name,
SignedInfo signedInfo,
byte [] content) throws ContentEncodingException {
return prepareContent(name, signedInfo, content, 0,
((null == content) ? 0 : content.length));
}
/**
* Prepare digest for signature.
* DKS TODO -- limit extra copies -- shouldn't be returning a byte array
* that is just digested.
* @return
*/
public static byte [] prepareContent(ContentName name,
SignedInfo signedInfo,
byte [] content, int offset, int length) throws ContentEncodingException {
if ((null == name) || (null == signedInfo)) {
Log.info("Name and signedInfo must not be null.");
throw new ContentEncodingException("prepareContent: name, signedInfo must not be null.");
}
// Do setup. Binary codec doesn't write a preamble or anything.
// If allow to pick, text encoder would sometimes write random stuff...
ByteArrayOutputStream baos = new ByteArrayOutputStream();
XMLEncoder encoder = XMLCodecFactory.getEncoder(BinaryXMLCodec.CODEC_NAME);
encoder.beginEncoding(baos);
// We include the tags in what we verify, to allow routers to merely
// take a chunk of data from the packet and sign/verify it en masse
name.encode(encoder);
signedInfo.encode(encoder);
// We treat content as a blob according to the binary codec. Want to always
// sign the same thing, plus it's really hard to do the automated codec
// stuff without doing a whole document, unless we do some serious
// rearranging.
encoder.writeElement(CCNProtocolDTags.Content, content, offset, length);
encoder.endEncoding();
return baos.toByteArray();
}
/**
* Encode this object and calculate the digest.
*/
protected byte[] calcDigest() {
MessageDigest md;
try {
md = MessageDigest.getInstance(CCNDigestHelper.DEFAULT_DIGEST_ALGORITHM);
DigestOutputStream dos = new DigestOutputStream(new NullOutputStream(), md);
encode(dos);
} catch (NoSuchAlgorithmException e) {
// Should never happen since we are using a default algorithm.
throw new RuntimeException(e);
} catch (ContentEncodingException e) {
// Should never happen since we are writing out to make a digest only.
throw new RuntimeException(e);
}
return md.digest();
}
/**
* Calculates a digest of the wire representation of this ContentObject.
* This is used as the implicit final name component.
* Note: the value is cached, so subsequent calls are fast.
*/
public byte [] digest() {
if (_digest == null)
_digest = calcDigest();
return _digest;
}
public int compareTo(ContentObject o) {
return name().compareTo(o.name());
}
/*
* Type-checkers for built-in types.
*/
public boolean isType(ContentType type) {
return signedInfo().getType().equals(type);
}
public boolean isData() {
return isType(ContentType.DATA);
}
public boolean isLink() {
return isType(ContentType.LINK);
}
public boolean isGone() {
return isType(ContentType.GONE);
}
public boolean isNACK() {
return isType(ContentType.NACK);
}
public boolean isKey() {
return isType(ContentType.KEY);
}
/**
* To aid debugging we output a human readable summary of this object here.
*/
public String toString() {
StringBuffer s = new StringBuffer();
s.append(String.format("CObj: name=%s, digest=%s, SI:%s len=%d, data=", _name,
DataUtils.printHexBytes(digest()), _signedInfo, _content.length));
int len = _content.length;
if (len > 16)
len = 16;
s.append(ContentName.componentPrintURI(_content, 0, len));
return s.toString();
}
}
| false | true | public static boolean verify(ContentObject object,
PublicKey publicKey) throws SignatureException, InvalidKeyException,
NoSuchAlgorithmException, ContentEncodingException {
if (null == publicKey) {
throw new SignatureException("Cannot verify object without public key -- public key cannot be null!");
}
// Start with the cheap part. Derive the content proxy that was signed. This is
// either the root of the MerkleHash tree, the content itself, or the digest of
// the content.
byte [] contentProxy = null;
try {
// Callers that think they don't need to recompute the signature can just compute
// the proxy and check.
// The proxy may be dependent on the whole object. If there is a proxy, signature
// is over that. Otherwise, signature is over hash of the content and name and signedInfo.
contentProxy = object.computeProxy();
} catch (CertificateEncodingException e) {
if (Log.isLoggable(Level.INFO))
Log.info("Encoding exception attempting to verify content digest for object: " + object.name() + ". Signature verification fails.");
return false;
}
boolean result;
if (null != contentProxy) {
result = CCNSignatureHelper.verify(contentProxy, object.signature().signature(), object.signature().digestAlgorithm(), publicKey);
} else {
result = verify(object.name(), object.signedInfo(), object.content(), object.signature(), publicKey);
}
if ((!result) && Log.isLoggable(Log.FAC_VERIFY, Level.WARNING)) {
String proxyString = null;
try {
proxyString = DataUtils.printHexBytes(CCNDigestHelper.digest(object.computeProxy()));
} catch (CertificateEncodingException e) {
proxyString = "<encoding error>";
}
Log.info("VERIFICATION FAILURE: " + object.name() + " timestamp: " + object.signedInfo().getTimestamp() + " content length: " + object.contentLength() +
" ephemeral digest: " + DataUtils.printBytes(object.digest()) +
" proxy sha256 digest: " + proxyString);
SystemConfiguration.outputDebugObject(object);
}
return result;
}
| public static boolean verify(ContentObject object,
PublicKey publicKey) throws SignatureException, InvalidKeyException,
NoSuchAlgorithmException, ContentEncodingException {
if (null == publicKey) {
throw new SignatureException("Cannot verify object without public key -- public key cannot be null!");
}
// Start with the cheap part. Derive the content proxy that was signed. This is
// either the root of the MerkleHash tree, the content itself, or the digest of
// the content.
byte [] contentProxy = null;
try {
// Callers that think they don't need to recompute the signature can just compute
// the proxy and check.
// The proxy may be dependent on the whole object. If there is a proxy, signature
// is over that. Otherwise, signature is over hash of the content and name and signedInfo.
contentProxy = object.computeProxy();
} catch (CertificateEncodingException e) {
if (Log.isLoggable(Level.INFO))
Log.info("Encoding exception attempting to verify content digest for object: " + object.name() + ". Signature verification fails.");
return false;
}
boolean result;
if (null != contentProxy) {
result = CCNSignatureHelper.verify(contentProxy, object.signature().signature(), object.signature().digestAlgorithm(), publicKey);
} else {
result = verify(object.name(), object.signedInfo(), object.content(), object.signature(), publicKey);
}
if ((!result) && Log.isLoggable(Log.FAC_VERIFY, Level.WARNING)) {
Log.info("VERIFICATION FAILURE: " + object.name() + " timestamp: " + object.signedInfo().getTimestamp() + " content length: " + object.contentLength() +
" ephemeral digest: " + DataUtils.printBytes(object.digest()) +
" to be signed sha256 digest: " + DataUtils.printHexBytes(CCNDigestHelper.digest(object.prepareContent())));
SystemConfiguration.outputDebugObject(object);
}
return result;
}
|
diff --git a/maven-scm-providers/maven-scm-provider-starteam/src/test/java/org/apache/maven/scm/provider/starteam/command/status/StarteamStatusConsumerTest.java b/maven-scm-providers/maven-scm-provider-starteam/src/test/java/org/apache/maven/scm/provider/starteam/command/status/StarteamStatusConsumerTest.java
index 4120e142..43d93a33 100644
--- a/maven-scm-providers/maven-scm-provider-starteam/src/test/java/org/apache/maven/scm/provider/starteam/command/status/StarteamStatusConsumerTest.java
+++ b/maven-scm-providers/maven-scm-provider-starteam/src/test/java/org/apache/maven/scm/provider/starteam/command/status/StarteamStatusConsumerTest.java
@@ -1,71 +1,71 @@
package org.apache.maven.scm.provider.starteam.command.status;
/*
* 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 java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import org.apache.maven.scm.ScmTestCase;
import org.apache.maven.scm.log.DefaultLog;
/**
* @author <a href="mailto:[email protected]">Dan T. Tran</a>
*/
public class StarteamStatusConsumerTest
extends ScmTestCase
{
// must match with the test file
private static final String WORKING_DIR = "/usr/scm-starteam/driver";
private File testFile;
public void setUp()
throws Exception
{
super.setUp();
testFile = getTestFile( "/src/test/resources/starteam/status/status.txt" );
}
public void testParse()
throws Exception
{
FileInputStream fis = new FileInputStream( testFile );
BufferedReader in = new BufferedReader( new InputStreamReader( fis ) );
String s = in.readLine();
StarteamStatusConsumer consumer = new StarteamStatusConsumer( new DefaultLog(), new File( WORKING_DIR ) );
while ( s != null )
{
consumer.consumeLine( s );
s = in.readLine();
}
- assertEquals( "Wrong number of entries returned", 4, consumer.getChangedFiles() );
+ assertEquals( "Wrong number of entries returned", 4, consumer.getChangedFiles().size() );
// TODO add more validation to the entries
}
}
| true | true | public void testParse()
throws Exception
{
FileInputStream fis = new FileInputStream( testFile );
BufferedReader in = new BufferedReader( new InputStreamReader( fis ) );
String s = in.readLine();
StarteamStatusConsumer consumer = new StarteamStatusConsumer( new DefaultLog(), new File( WORKING_DIR ) );
while ( s != null )
{
consumer.consumeLine( s );
s = in.readLine();
}
assertEquals( "Wrong number of entries returned", 4, consumer.getChangedFiles() );
// TODO add more validation to the entries
}
| public void testParse()
throws Exception
{
FileInputStream fis = new FileInputStream( testFile );
BufferedReader in = new BufferedReader( new InputStreamReader( fis ) );
String s = in.readLine();
StarteamStatusConsumer consumer = new StarteamStatusConsumer( new DefaultLog(), new File( WORKING_DIR ) );
while ( s != null )
{
consumer.consumeLine( s );
s = in.readLine();
}
assertEquals( "Wrong number of entries returned", 4, consumer.getChangedFiles().size() );
// TODO add more validation to the entries
}
|
diff --git a/java/uk/ltd/getahead/dwr/convert/ConverterUtil.java b/java/uk/ltd/getahead/dwr/convert/ConverterUtil.java
index fcfaccf3..de581e14 100644
--- a/java/uk/ltd/getahead/dwr/convert/ConverterUtil.java
+++ b/java/uk/ltd/getahead/dwr/convert/ConverterUtil.java
@@ -1,361 +1,361 @@
/*
* Copyright 2005 Joe Walker
*
* 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 uk.ltd.getahead.dwr.convert;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import uk.ltd.getahead.dwr.OutboundContext;
import uk.ltd.getahead.dwr.OutboundVariable;
import uk.ltd.getahead.dwr.util.JavascriptUtil;
import uk.ltd.getahead.dwr.util.LocalUtil;
/**
* A collection of utilities that are useful to more than one Converter
* @author Joe Walker [joe at getahead dot ltd dot uk]
*/
public class ConverterUtil
{
/**
* Generate an array declaration for a list of Outbound variables
* @param ov The OutboundVariable to declare
* @param ovs The list of contents of this array
*/
public static void addListInit(OutboundVariable ov, List ovs)
{
String varname = ov.getAssignCode();
StringBuffer buffer = new StringBuffer();
String init = getInitCodes(ovs);
if (init.length() == 0)
{
// Declare ourselves so recurrsion works
buffer.append("var "); //$NON-NLS-1$
buffer.append(varname);
- buffer.append("=[;"); //$NON-NLS-1$
+ buffer.append("=["); //$NON-NLS-1$
// Declare the non-recursive parts to the list
boolean first = true;
for (int i = 0; i < ovs.size(); i++)
{
OutboundVariable nested = (OutboundVariable) ovs.get(i);
if (!first)
{
buffer.append(',');
}
if (nested.getAssignCode() == varname)
{
// We'll fill it in later
buffer.append("null"); //$NON-NLS-1$
}
else
{
ovs.set(i, null);
buffer.append(nested.getAssignCode());
}
first = false;
}
buffer.append("];"); //$NON-NLS-1$
}
else
{
// Declare ourselves so recurrsion works
buffer.append("var "); //$NON-NLS-1$
buffer.append(varname);
buffer.append("=[];"); //$NON-NLS-1$
// First we output all the init code
buffer.append(init);
// Declare the non-recursive parts to the list
buffer.append(varname);
buffer.append('=');
buffer.append(varname);
buffer.append(".concat(["); //$NON-NLS-1$
boolean first = true;
for (int i = 0; i < ovs.size(); i++)
{
OutboundVariable nested = (OutboundVariable) ovs.get(i);
if (!first)
{
buffer.append(',');
}
if (nested.getAssignCode() == varname)
{
// We'll fill it in later
buffer.append("null"); //$NON-NLS-1$
}
else
{
ovs.set(i, null);
buffer.append(nested.getAssignCode());
}
first = false;
}
buffer.append("]);"); //$NON-NLS-1$
}
// And now the recursive parts
for (int i = 0; i < ovs.size(); i++)
{
OutboundVariable nested = (OutboundVariable) ovs.get(i);
if (nested != null)
{
buffer.append(varname);
buffer.append('[');
buffer.append(i);
buffer.append("]="); //$NON-NLS-1$
buffer.append(nested.getAssignCode());
buffer.append(';');
}
}
buffer.append("\r\n"); //$NON-NLS-1$
ov.setInitCode(buffer.toString());
}
/**
* Generate an map declaration for a map of Outbound variables
* @param ov The OutboundVariable to declare
* @param ovs The map of the converted contents
*/
public static void addMapInit(OutboundVariable ov, Map ovs)
{
String varname = ov.getAssignCode();
StringBuffer buffer = new StringBuffer();
String init = getInitCodes(ovs.values());
// If there is no init code, there is no recursion so we can go into
// compact JSON mode
if (init.length() == 0)
{
// First loop through is for the stuff we can embed
buffer.append("var "); //$NON-NLS-1$
buffer.append(varname);
buffer.append("={"); //$NON-NLS-1$
// And now declare our stuff
boolean first = true;
for (Iterator it = ovs.entrySet().iterator(); it.hasNext();)
{
Map.Entry entry = (Map.Entry) it.next();
String name = (String) entry.getKey();
OutboundVariable nested = (OutboundVariable) entry.getValue();
String assignCode = nested.getAssignCode();
// The compact JSON style syntax is only any good for simple names
// and when we are not recursive
if (LocalUtil.isSimpleName(name) && !assignCode.equals(varname))
{
if (!first)
{
buffer.append(',');
}
buffer.append(name);
buffer.append(':');
buffer.append(assignCode);
// we don't need to do this one the hard way
it.remove();
first = false;
}
}
buffer.append("};"); //$NON-NLS-1$
}
else
{
// Declare ourselves so recursion works
buffer.append("var "); //$NON-NLS-1$
buffer.append(varname);
buffer.append("={};"); //$NON-NLS-1$
buffer.append(init);
// And now declare our stuff
for (Iterator it = ovs.entrySet().iterator(); it.hasNext();)
{
Map.Entry entry = (Map.Entry) it.next();
String name = (String) entry.getKey();
OutboundVariable nested = (OutboundVariable) entry.getValue();
String assignCode = nested.getAssignCode();
// The semi-compact syntax is only any good for simple names
if (LocalUtil.isSimpleName(name) && !assignCode.equals(varname))
{
buffer.append(varname);
buffer.append('.');
buffer.append(name);
buffer.append('=');
buffer.append(nested.getAssignCode());
buffer.append(';');
it.remove();
}
}
}
// The next loop through is for everything that will not embed
for (Iterator it = ovs.entrySet().iterator(); it.hasNext();)
{
Map.Entry entry = (Map.Entry) it.next();
String name = (String) entry.getKey();
OutboundVariable nested = (OutboundVariable) entry.getValue();
buffer.append(varname);
buffer.append("['"); //$NON-NLS-1$
buffer.append(name);
buffer.append("']="); //$NON-NLS-1$
buffer.append(nested.getAssignCode());
buffer.append(';');
}
buffer.append("\r\n"); //$NON-NLS-1$
ov.setInitCode(buffer.toString());
}
/**
* Grab all the init codes together
* @param ovs The set of variables to marshall
* @return An init string
*/
private static String getInitCodes(Collection ovs)
{
StringBuffer init = new StringBuffer();
// Make sure the nested things are declared
for (Iterator it = ovs.iterator(); it.hasNext();)
{
OutboundVariable nested = (OutboundVariable) it.next();
init.append(nested.getInitCode());
}
return init.toString();
}
/**
* Generate a string declaration from a Java string. This includes deciding
* to inline the string if it is too short, or splitting it up if it is too
* long.
* @param output The Java string to convert
* @param outctx The conversion context.
* @return The converted OutboundVariable
*/
public static OutboundVariable addStringInit(String output, OutboundContext outctx)
{
String escaped = jsutil.escapeJavaScript(output);
// For short strings inline them
if (escaped.length() < INLINE_LENGTH)
{
return new OutboundVariable("", '\"' + escaped + '\"'); //$NON-NLS-1$
}
// For medium length strings do it in a separate variable
if (escaped.length() < WRAP_LENGTH)
{
OutboundVariable ov = outctx.createOutboundVariable(output);
String varname = ov.getAssignCode();
ov.setInitCode("var " + varname + "=\"" + escaped + "\";\r\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
return ov;
}
// For very long strings chop up the init into several parts
OutboundVariable ov = outctx.createOutboundVariable(output);
String varname = ov.getAssignCode();
StringBuffer initBody = new StringBuffer();
StringBuffer initEnd = new StringBuffer();
initEnd.append("var "); //$NON-NLS-1$
initEnd.append(varname);
initEnd.append('=');
int start = 0;
while (start < escaped.length())
{
String tempvar = outctx.getNextVariableName();
boolean last = false;
int end = start + WRAP_LENGTH;
if (end > escaped.length())
{
last = true;
end = escaped.length();
}
// If the last char is a \ then there is a chance of breaking
// an escape so we increment until the last char in not a \
// There is a potential bug here where the input string contains
// only escaped slashes (\\) in which case we will end up not
// breaking the string. Since this whole thing is a workaround
// and the solution is complex we are going to pass on it now.
while (!last && escaped.charAt(end - 1) == '\\' && end < escaped.length())
{
end++;
}
initBody.append("var "); //$NON-NLS-1$
initBody.append(tempvar);
initBody.append("=\""); //$NON-NLS-1$
initBody.append(escaped.substring(start, end));
initBody.append("\";\r\n"); //$NON-NLS-1$
initEnd.append(tempvar);
if (!last)
{
initEnd.append('+');
}
start = end;
}
initEnd.append(";\r\n"); //$NON-NLS-1$
initBody.append(initEnd.toString());
ov.setInitCode(initBody.toString());
return ov;
}
/**
* The length at which we stop inlining strings
*/
private static final int INLINE_LENGTH = 20;
/**
* Strings longer than this are chopped up into smaller strings
*/
private static final int WRAP_LENGTH = 128;
/**
* The means by which we strip comments
*/
private static JavascriptUtil jsutil = new JavascriptUtil();
}
| true | true | public static void addListInit(OutboundVariable ov, List ovs)
{
String varname = ov.getAssignCode();
StringBuffer buffer = new StringBuffer();
String init = getInitCodes(ovs);
if (init.length() == 0)
{
// Declare ourselves so recurrsion works
buffer.append("var "); //$NON-NLS-1$
buffer.append(varname);
buffer.append("=[;"); //$NON-NLS-1$
// Declare the non-recursive parts to the list
boolean first = true;
for (int i = 0; i < ovs.size(); i++)
{
OutboundVariable nested = (OutboundVariable) ovs.get(i);
if (!first)
{
buffer.append(',');
}
if (nested.getAssignCode() == varname)
{
// We'll fill it in later
buffer.append("null"); //$NON-NLS-1$
}
else
{
ovs.set(i, null);
buffer.append(nested.getAssignCode());
}
first = false;
}
buffer.append("];"); //$NON-NLS-1$
}
else
{
// Declare ourselves so recurrsion works
buffer.append("var "); //$NON-NLS-1$
buffer.append(varname);
buffer.append("=[];"); //$NON-NLS-1$
// First we output all the init code
buffer.append(init);
// Declare the non-recursive parts to the list
buffer.append(varname);
buffer.append('=');
buffer.append(varname);
buffer.append(".concat(["); //$NON-NLS-1$
boolean first = true;
for (int i = 0; i < ovs.size(); i++)
{
OutboundVariable nested = (OutboundVariable) ovs.get(i);
if (!first)
{
buffer.append(',');
}
if (nested.getAssignCode() == varname)
{
// We'll fill it in later
buffer.append("null"); //$NON-NLS-1$
}
else
{
ovs.set(i, null);
buffer.append(nested.getAssignCode());
}
first = false;
}
buffer.append("]);"); //$NON-NLS-1$
}
// And now the recursive parts
for (int i = 0; i < ovs.size(); i++)
{
OutboundVariable nested = (OutboundVariable) ovs.get(i);
if (nested != null)
{
buffer.append(varname);
buffer.append('[');
buffer.append(i);
buffer.append("]="); //$NON-NLS-1$
buffer.append(nested.getAssignCode());
buffer.append(';');
}
}
buffer.append("\r\n"); //$NON-NLS-1$
ov.setInitCode(buffer.toString());
}
| public static void addListInit(OutboundVariable ov, List ovs)
{
String varname = ov.getAssignCode();
StringBuffer buffer = new StringBuffer();
String init = getInitCodes(ovs);
if (init.length() == 0)
{
// Declare ourselves so recurrsion works
buffer.append("var "); //$NON-NLS-1$
buffer.append(varname);
buffer.append("=["); //$NON-NLS-1$
// Declare the non-recursive parts to the list
boolean first = true;
for (int i = 0; i < ovs.size(); i++)
{
OutboundVariable nested = (OutboundVariable) ovs.get(i);
if (!first)
{
buffer.append(',');
}
if (nested.getAssignCode() == varname)
{
// We'll fill it in later
buffer.append("null"); //$NON-NLS-1$
}
else
{
ovs.set(i, null);
buffer.append(nested.getAssignCode());
}
first = false;
}
buffer.append("];"); //$NON-NLS-1$
}
else
{
// Declare ourselves so recurrsion works
buffer.append("var "); //$NON-NLS-1$
buffer.append(varname);
buffer.append("=[];"); //$NON-NLS-1$
// First we output all the init code
buffer.append(init);
// Declare the non-recursive parts to the list
buffer.append(varname);
buffer.append('=');
buffer.append(varname);
buffer.append(".concat(["); //$NON-NLS-1$
boolean first = true;
for (int i = 0; i < ovs.size(); i++)
{
OutboundVariable nested = (OutboundVariable) ovs.get(i);
if (!first)
{
buffer.append(',');
}
if (nested.getAssignCode() == varname)
{
// We'll fill it in later
buffer.append("null"); //$NON-NLS-1$
}
else
{
ovs.set(i, null);
buffer.append(nested.getAssignCode());
}
first = false;
}
buffer.append("]);"); //$NON-NLS-1$
}
// And now the recursive parts
for (int i = 0; i < ovs.size(); i++)
{
OutboundVariable nested = (OutboundVariable) ovs.get(i);
if (nested != null)
{
buffer.append(varname);
buffer.append('[');
buffer.append(i);
buffer.append("]="); //$NON-NLS-1$
buffer.append(nested.getAssignCode());
buffer.append(';');
}
}
buffer.append("\r\n"); //$NON-NLS-1$
ov.setInitCode(buffer.toString());
}
|
diff --git a/src/demos/hwShadowmapsSimple/HWShadowmapsSimple.java b/src/demos/hwShadowmapsSimple/HWShadowmapsSimple.java
index 049bd3d..13f3997 100644
--- a/src/demos/hwShadowmapsSimple/HWShadowmapsSimple.java
+++ b/src/demos/hwShadowmapsSimple/HWShadowmapsSimple.java
@@ -1,836 +1,833 @@
/*
* Portions Copyright (C) 2003 Sun Microsystems, Inc.
* All rights reserved.
*/
/*
*
* COPYRIGHT NVIDIA CORPORATION 2003. ALL RIGHTS RESERVED.
* BY ACCESSING OR USING THIS SOFTWARE, YOU AGREE TO:
*
* 1) ACKNOWLEDGE NVIDIA'S EXCLUSIVE OWNERSHIP OF ALL RIGHTS
* IN AND TO THE SOFTWARE;
*
* 2) NOT MAKE OR DISTRIBUTE COPIES OF THE SOFTWARE WITHOUT
* INCLUDING THIS NOTICE AND AGREEMENT;
*
* 3) ACKNOWLEDGE THAT TO THE MAXIMUM EXTENT PERMITTED BY
* APPLICABLE LAW, THIS SOFTWARE IS PROVIDED *AS IS* AND
* THAT NVIDIA AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES,
* EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED
* TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE.
*
* IN NO EVENT SHALL NVIDIA OR ITS SUPPLIERS BE LIABLE FOR ANY
* SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES
* WHATSOEVER (INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS
* OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF BUSINESS
* INFORMATION, OR ANY OTHER PECUNIARY LOSS), INCLUDING ATTORNEYS'
* FEES, RELATING TO THE USE OF OR INABILITY TO USE THIS SOFTWARE,
* EVEN IF NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
*
*/
package demos.hwShadowmapsSimple;
import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import java.nio.*;
import java.util.*;
import javax.imageio.*;
import javax.swing.*;
import net.java.games.jogl.*;
import net.java.games.jogl.util.*;
import demos.util.*;
import gleem.*;
import gleem.linalg.*;
/** This demo is a simple illustration of ARB_shadow and ARB_depth_texture. <P>
Cass Everitt <BR>
12-11-00 <P>
hw_shadowmaps_simple (c) 2001 NVIDIA Corporation <P>
Ported to Java by Kenneth Russell
*/
public class HWShadowmapsSimple {
private volatile boolean quit;
private GLCanvas canvas;
private GLPbuffer pbuffer;
private GLUT glut;
private float[] light_ambient = { 0, 0, 0, 0 };
private float[] light_intensity = { 1, 1, 1, 1 };
private float[] light_pos = { 0, 0, 0, 1 };
static class Tweak {
String name;
float val;
float incr;
Tweak(String name, float val, float incr) {
this.name = name;
this.val = val;
this.incr = incr;
}
};
private java.util.List/*<Tweak>*/ tweaks = new ArrayList();
private static final int R_COORDINATE_SCALE = 0;
private static final int R_COORDINATE_BIAS = 1;
private static final int POLYGON_OFFSET_SCALE = 2;
private static final int POLYGON_OFFSET_BIAS = 3;
private int curr_tweak;
// Texture objects
private static final int TEX_SIZE = 1024;
private int decal;
private int light_image;
private int light_view_depth;
// Depth buffer format
private int depth_format;
private boolean fullyInitialized;
// Display mode
private static final int RENDER_SCENE_FROM_CAMERA_VIEW = 0;
private static final int RENDER_SCENE_FROM_CAMERA_VIEW_SHADOWED = 1;
private static final int RENDER_SCENE_FROM_LIGHT_VIEW = 2;
private static final int NUM_DISPLAY_MODES = 3;
private int displayMode = 1;
// Display lists
private int quad;
private int wirecube;
private int geometry;
// Shadowing light
private float lightshaper_fovy = 60.0f;
private float lightshaper_zNear = 0.5f;
private float lightshaper_zFar = 5.0f;
// Manipulators
private ExaminerViewer viewer;
private boolean doViewAll = true;
// private float zNear = 0.5f;
// private float zFar = 5.0f;
private float zNear = 0.5f;
private float zFar = 50.0f;
private HandleBoxManip object;
private HandleBoxManip spotlight;
private Mat4f cameraPerspective = new Mat4f();
private Mat4f cameraTransform = new Mat4f();
private Mat4f cameraInverseTransform = new Mat4f();
private Mat4f spotlightTransform = new Mat4f();
private Mat4f spotlightInverseTransform = new Mat4f();
private Mat4f objectTransform = new Mat4f();
public static void main(String[] args) {
new HWShadowmapsSimple().run(args);
}
public void run(String[] args) {
canvas = GLDrawableFactory.getFactory().createGLCanvas(new GLCapabilities());
canvas.addGLEventListener(new Listener());
Frame frame = new Frame("ARB_shadow Shadows");
frame.setLayout(new BorderLayout());
canvas.setSize(512, 512);
frame.add(canvas, BorderLayout.CENTER);
frame.pack();
frame.show();
canvas.requestFocus();
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
runExit();
}
});
}
//----------------------------------------------------------------------
// Internals only below this point
//
class Listener implements GLEventListener {
public void init(GLDrawable drawable) {
// init() might get called more than once if the GLCanvas is
// added and removed, but we only want to install the DebugGL
// pipeline once
// if (!(drawable.getGL() instanceof DebugGL)) {
// drawable.setGL(new DebugGL(drawable.getGL()));
// }
GL gl = drawable.getGL();
GLU glu = drawable.getGLU();
glut = new GLUT();
try {
checkExtension(gl, "GL_ARB_multitexture");
checkExtension(gl, "GL_ARB_depth_texture");
checkExtension(gl, "GL_ARB_shadow");
checkExtension(gl, "GL_ARB_pbuffer");
checkExtension(gl, "GL_ARB_pixel_format");
} catch (GLException e) {
e.printStackTrace();
throw(e);
}
gl.glClearColor(.5f, .5f, .5f, .5f);
decal = genTexture(gl);
gl.glBindTexture(GL.GL_TEXTURE_2D, decal);
BufferedImage img = readPNGImage("demos/data/images/decal_image.png");
makeRGBTexture(gl, glu, img, GL.GL_TEXTURE_2D, true);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR_MIPMAP_LINEAR);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR);
light_image = genTexture(gl);
gl.glBindTexture(GL.GL_TEXTURE_2D, light_image);
img = readPNGImage("demos/data/images/nvlogo_spot.png");
makeRGBTexture(gl, glu, img, GL.GL_TEXTURE_2D, true);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, GL.GL_CLAMP_TO_EDGE);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL.GL_CLAMP_TO_EDGE);
quad = gl.glGenLists(1);
gl.glNewList(quad, GL.GL_COMPILE);
gl.glPushMatrix();
gl.glRotatef(-90, 1, 0, 0);
gl.glScalef(4,4,4);
gl.glBegin(GL.GL_QUADS);
gl.glNormal3f(0, 0, 1);
gl.glVertex2f(-1, -1);
gl.glVertex2f(-1, 1);
gl.glVertex2f( 1, 1);
gl.glVertex2f( 1, -1);
gl.glEnd();
gl.glPopMatrix();
gl.glEndList();
wirecube = gl.glGenLists(1);
gl.glNewList(wirecube, GL.GL_COMPILE);
glut.glutWireCube(gl, 2);
gl.glEndList();
geometry = gl.glGenLists(1);
gl.glNewList(geometry, GL.GL_COMPILE);
gl.glPushMatrix();
- // gl.glTranslatef(0, .4f, 0);
- // FIXME
- // glutSolidTeapot(.5f);
- glut.glutSolidTorus(gl, 0.25f, 0.5f, 40, 20);
+ glut.glutSolidTeapot(gl, 0.8f);
gl.glPopMatrix();
gl.glEndList();
gl.glEnable(GL.GL_LIGHT0);
gl.glLightfv(GL.GL_LIGHT0, GL.GL_AMBIENT, light_ambient);
gl.glLightfv(GL.GL_LIGHT0, GL.GL_DIFFUSE, light_intensity);
gl.glLightfv(GL.GL_LIGHT0, GL.GL_SPECULAR, light_intensity);
gl.glEnable(GL.GL_DEPTH_TEST);
// init pbuffer
GLCapabilities caps = new GLCapabilities();
caps.setDoubleBuffered(false);
pbuffer = drawable.createOffscreenDrawable(caps, TEX_SIZE, TEX_SIZE);
pbuffer.addGLEventListener(new PbufferListener());
// Register the window with the ManipManager
ManipManager manager = ManipManager.getManipManager();
manager.registerWindow(drawable);
object = new HandleBoxManip();
object.setTranslation(new Vec3f(0, 0.7f, 1.8f));
object.setGeometryScale(new Vec3f(0.7f, 0.7f, 0.7f));
manager.showManipInWindow(object, drawable);
spotlight = new HandleBoxManip();
spotlight.setScale(new Vec3f(0.5f, 0.5f, 0.5f));
spotlight.setTranslation(new Vec3f(-0.25f, 2.35f, 5.0f));
spotlight.setRotation(new Rotf(Vec3f.X_AXIS, (float) Math.toRadians(-30.0f)));
manager.showManipInWindow(spotlight, drawable);
viewer = new ExaminerViewer(MouseButtonHelper.numMouseButtons());
viewer.attach(drawable, new BSphereProvider() {
public BSphere getBoundingSphere() {
return new BSphere(object.getTranslation(), 2.0f);
}
});
viewer.setOrientation(new Rotf(Vec3f.Y_AXIS, (float) Math.toRadians(45.0f)).times
(new Rotf(Vec3f.X_AXIS, (float) Math.toRadians(-15.0f))));
viewer.setVertFOV((float) Math.toRadians(lightshaper_fovy / 2.0f));
viewer.setZNear(zNear);
viewer.setZFar(zFar);
float bias = 1/((float) Math.pow(2.0,16.0)-1);
tweaks.add(new Tweak("r coordinate scale", 0.5f, bias));
tweaks.add(new Tweak("r coordinate bias", 0.5f, bias));
tweaks.add(new Tweak("polygon offset scale", 2.5f, 0.5f));
tweaks.add(new Tweak("polygon offset bias", 10.0f, 1.0f));
drawable.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
dispatchKey(e.getKeyChar());
canvas.repaint();
}
});
}
public void display(GLDrawable drawable) {
viewer.update();
// Grab these values once per render to avoid multithreading
// issues with their values being changed by manipulation from
// the AWT thread during the render
CameraParameters params = viewer.getCameraParameters();
cameraPerspective.set(params.getProjectionMatrix());
cameraInverseTransform.set(params.getModelviewMatrix());
cameraTransform.set(cameraInverseTransform);
cameraTransform.invertRigid();
spotlightTransform.set(spotlight.getTransform());
spotlightInverseTransform.set(spotlightTransform);
spotlightInverseTransform.invertRigid();
objectTransform.set(object.getTransform());
if (displayMode == RENDER_SCENE_FROM_CAMERA_VIEW_SHADOWED || !fullyInitialized) {
if (pbuffer != null) {
pbuffer.display();
}
}
if (!fullyInitialized) {
return;
}
GL gl = drawable.getGL();
GLU glu = drawable.getGLU();
gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);
if (doViewAll) {
viewer.viewAll(gl);
doViewAll = false;
// Immediately zap effects
gl.glMatrixMode(GL.GL_PROJECTION);
gl.glLoadIdentity();
gl.glMatrixMode(GL.GL_MODELVIEW);
gl.glLoadIdentity();
// Schedule repaint to clean up first bogus frame
canvas.repaint();
}
switch (displayMode) {
case RENDER_SCENE_FROM_CAMERA_VIEW: render_scene_from_camera_view(gl, glu, drawable, params); break;
case RENDER_SCENE_FROM_CAMERA_VIEW_SHADOWED: render_scene_from_camera_view_shadowed(gl, glu, drawable, params); break;
case RENDER_SCENE_FROM_LIGHT_VIEW: render_scene_from_light_view(gl, glu); break;
default: throw new RuntimeException("Illegal display mode " + displayMode);
}
}
// Unused routines
public void reshape(GLDrawable drawable, int x, int y, int width, int height) {}
public void displayChanged(GLDrawable drawable, boolean modeChanged, boolean deviceChanged) {}
//----------------------------------------------------------------------
// Internals only below this point
//
private void checkExtension(GL gl, String extensionName) {
if (!gl.isExtensionAvailable(extensionName)) {
String message = "Unable to initialize " + extensionName + " OpenGL extension";
JOptionPane.showMessageDialog(null, message, "Unavailable extension", JOptionPane.ERROR_MESSAGE);
throw new GLException(message);
}
}
private void dispatchKey(char k) {
switch (k) {
case 27:
case 'q':
runExit();
break;
case 'v':
doViewAll = true;
System.err.println("Forcing viewAll()");
break;
case ' ':
displayMode = (displayMode + 1) % NUM_DISPLAY_MODES;
System.err.println("Switching to display mode " + displayMode);
break;
// FIXME: add more key behaviors from original demo
default:
break;
}
}
}
class PbufferListener implements GLEventListener {
public void init(GLDrawable drawable) {
// init() might get called more than once if the GLCanvas is
// added and removed, but we only want to install the DebugGL
// pipeline once
// if (!(drawable.getGL() instanceof DebugGL)) {
// drawable.setGL(new DebugGL(drawable.getGL()));
// }
GL gl = drawable.getGL();
GLU glu = drawable.getGLU();
gl.glEnable(GL.GL_DEPTH_TEST);
int[] depth_bits = new int[1];
gl.glGetIntegerv(GL.GL_DEPTH_BITS, depth_bits);
if (depth_bits[0] == 16) depth_format = GL.GL_DEPTH_COMPONENT16_ARB;
else depth_format = GL.GL_DEPTH_COMPONENT24_ARB;
light_view_depth = genTexture(gl);
gl.glBindTexture(GL.GL_TEXTURE_2D, light_view_depth);
gl.glTexImage2D(GL.GL_TEXTURE_2D, 0, depth_format, TEX_SIZE, TEX_SIZE, 0,
GL.GL_DEPTH_COMPONENT, GL.GL_UNSIGNED_INT, (byte[]) null);
set_light_view_texture_parameters(gl);
fullyInitialized = true;
}
public void display(GLDrawable drawable) {
GL gl = drawable.getGL();
GLU glu = drawable.getGLU();
gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);
gl.glPolygonOffset(((Tweak) tweaks.get(POLYGON_OFFSET_SCALE)).val,
((Tweak) tweaks.get(POLYGON_OFFSET_BIAS)).val);
gl.glEnable(GL.GL_POLYGON_OFFSET_FILL);
render_scene_from_light_view(gl, glu);
gl.glDisable(GL.GL_POLYGON_OFFSET_FILL);
gl.glBindTexture(GL.GL_TEXTURE_2D, light_view_depth);
// trying different ways of getting the depth info over
gl.glCopyTexSubImage2D(GL.GL_TEXTURE_2D, 0, 0, 0, 0, 0, TEX_SIZE, TEX_SIZE);
}
// Unused routines
public void reshape(GLDrawable drawable, int x, int y, int width, int height) {}
public void displayChanged(GLDrawable drawable, boolean modeChanged, boolean deviceChanged) {}
}
private void set_light_view_texture_parameters(GL gl) {
gl.glBindTexture(GL.GL_TEXTURE_2D, light_view_depth);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, GL.GL_CLAMP_TO_EDGE);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL.GL_CLAMP_TO_EDGE);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_COMPARE_MODE_ARB, GL.GL_COMPARE_R_TO_TEXTURE_ARB);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_COMPARE_FUNC_ARB, GL.GL_LEQUAL);
}
private int genTexture(GL gl) {
int[] tmp = new int[1];
gl.glGenTextures(1, tmp);
return tmp[0];
}
private BufferedImage readPNGImage(String resourceName) {
try {
// Note: use of BufferedInputStream works around 4764639/4892246
BufferedImage img = ImageIO.read(new BufferedInputStream(getClass().getClassLoader().getResourceAsStream(resourceName)));
if (img == null) {
throw new RuntimeException("Error reading resource " + resourceName);
}
return img;
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private void makeRGBTexture(GL gl, GLU glu, BufferedImage img, int target, boolean mipmapped) {
ByteBuffer dest = null;
switch (img.getType()) {
case BufferedImage.TYPE_3BYTE_BGR:
case BufferedImage.TYPE_CUSTOM: {
byte[] data = ((DataBufferByte) img.getRaster().getDataBuffer()).getData();
dest = ByteBuffer.allocateDirect(data.length);
dest.order(ByteOrder.nativeOrder());
dest.put(data, 0, data.length);
break;
}
case BufferedImage.TYPE_INT_RGB: {
int[] data = ((DataBufferInt) img.getRaster().getDataBuffer()).getData();
dest = ByteBuffer.allocateDirect(data.length * BufferUtils.SIZEOF_INT);
dest.order(ByteOrder.nativeOrder());
dest.asIntBuffer().put(data, 0, data.length);
break;
}
default:
throw new RuntimeException("Unsupported image type " + img.getType());
}
if (mipmapped) {
glu.gluBuild2DMipmaps(target, GL.GL_RGB8, img.getWidth(), img.getHeight(), GL.GL_RGB,
GL.GL_UNSIGNED_BYTE, dest);
} else {
gl.glTexImage2D(target, 0, GL.GL_RGB, img.getWidth(), img.getHeight(), 0,
GL.GL_RGB, GL.GL_UNSIGNED_BYTE, dest);
}
}
private void eye_linear_texgen(GL gl) {
Mat4f m = new Mat4f();
m.makeIdent();
set_texgen_planes(gl, GL.GL_EYE_PLANE, m);
gl.glTexGeni(GL.GL_S, GL.GL_TEXTURE_GEN_MODE, GL.GL_EYE_LINEAR);
gl.glTexGeni(GL.GL_T, GL.GL_TEXTURE_GEN_MODE, GL.GL_EYE_LINEAR);
gl.glTexGeni(GL.GL_R, GL.GL_TEXTURE_GEN_MODE, GL.GL_EYE_LINEAR);
gl.glTexGeni(GL.GL_Q, GL.GL_TEXTURE_GEN_MODE, GL.GL_EYE_LINEAR);
}
private void obj_linear_texgen(GL gl) {
Mat4f m = new Mat4f();
m.makeIdent();
set_texgen_planes(gl, GL.GL_OBJECT_PLANE, m);
gl.glTexGeni(GL.GL_S, GL.GL_TEXTURE_GEN_MODE, GL.GL_OBJECT_LINEAR);
gl.glTexGeni(GL.GL_T, GL.GL_TEXTURE_GEN_MODE, GL.GL_OBJECT_LINEAR);
gl.glTexGeni(GL.GL_R, GL.GL_TEXTURE_GEN_MODE, GL.GL_OBJECT_LINEAR);
gl.glTexGeni(GL.GL_Q, GL.GL_TEXTURE_GEN_MODE, GL.GL_OBJECT_LINEAR);
}
private void set_texgen_planes(GL gl, int plane_type, Mat4f m) {
int[] coord = {GL.GL_S, GL.GL_T, GL.GL_R, GL.GL_Q};
float[] row = new float[4];
for(int i = 0; i < 4; i++) {
getRow(m, i, row);
gl.glTexGenfv(coord[i], plane_type, row);
}
}
private void texgen(GL gl, boolean enable) {
if(enable) {
gl.glEnable(GL.GL_TEXTURE_GEN_S);
gl.glEnable(GL.GL_TEXTURE_GEN_T);
gl.glEnable(GL.GL_TEXTURE_GEN_R);
gl.glEnable(GL.GL_TEXTURE_GEN_Q);
} else {
gl.glDisable(GL.GL_TEXTURE_GEN_S);
gl.glDisable(GL.GL_TEXTURE_GEN_T);
gl.glDisable(GL.GL_TEXTURE_GEN_R);
gl.glDisable(GL.GL_TEXTURE_GEN_Q);
}
}
private void render_light_frustum(GL gl) {
gl.glPushMatrix();
applyTransform(gl, cameraInverseTransform);
applyTransform(gl, spotlightTransform);
applyTransform(gl, perspectiveInverse(lightshaper_fovy, 1, lightshaper_zNear, lightshaper_zFar));
gl.glDisable(GL.GL_LIGHTING);
gl.glColor3f(1,1,0);
gl.glCallList(wirecube);
gl.glColor3f(1,1,1);
gl.glEnable(GL.GL_LIGHTING);
gl.glPopMatrix();
}
private void render_quad(GL gl) {
gl.glActiveTextureARB(GL.GL_TEXTURE0_ARB);
obj_linear_texgen(gl);
texgen(gl, true);
gl.glMatrixMode(GL.GL_TEXTURE);
gl.glLoadIdentity();
gl.glScalef(4,4,1);
gl.glMatrixMode(GL.GL_MODELVIEW);
gl.glDisable(GL.GL_LIGHTING);
gl.glBindTexture(GL.GL_TEXTURE_2D, decal);
gl.glEnable(GL.GL_TEXTURE_2D);
gl.glCallList(quad);
gl.glDisable(GL.GL_TEXTURE_2D);
gl.glEnable(GL.GL_LIGHTING);
texgen(gl, false);
gl.glMatrixMode(GL.GL_TEXTURE);
gl.glLoadIdentity();
gl.glMatrixMode(GL.GL_MODELVIEW);
}
private void render_scene(GL gl, Mat4f view, GLDrawable drawable, CameraParameters params) {
gl.glColor3f(1,1,1);
gl.glPushMatrix();
Mat4f inverseView = new Mat4f(view);
inverseView.invertRigid();
applyTransform(gl, inverseView);
gl.glPushMatrix();
render_quad(gl);
applyTransform(gl, objectTransform);
gl.glEnable(GL.GL_LIGHTING);
gl.glCallList(geometry);
gl.glDisable(GL.GL_LIGHTING);
gl.glPopMatrix();
gl.glPopMatrix();
}
private void render_manipulators(GL gl, Mat4f view, GLDrawable drawable, CameraParameters params) {
gl.glColor3f(1,1,1);
gl.glPushMatrix();
Mat4f inverseView = new Mat4f(view);
inverseView.invertRigid();
applyTransform(gl, inverseView);
if (params != null) {
ManipManager.getManipManager().updateCameraParameters(drawable, params);
ManipManager.getManipManager().render(drawable, gl);
}
gl.glPopMatrix();
}
private void render_scene_from_camera_view(GL gl, GLU glu, GLDrawable drawable, CameraParameters params) {
// place light
gl.glPushMatrix();
gl.glLoadIdentity();
applyTransform(gl, cameraInverseTransform);
applyTransform(gl, spotlightTransform);
gl.glLightfv(GL.GL_LIGHT0, GL.GL_POSITION, light_pos);
gl.glPopMatrix();
// spot image
gl.glActiveTextureARB(GL.GL_TEXTURE1_ARB);
gl.glPushMatrix();
applyTransform(gl, cameraInverseTransform);
eye_linear_texgen(gl);
texgen(gl, true);
gl.glPopMatrix();
gl.glMatrixMode(GL.GL_TEXTURE);
gl.glLoadIdentity();
gl.glTranslatef(.5f, .5f, .5f);
gl.glScalef(.5f, .5f, .5f);
glu.gluPerspective(lightshaper_fovy, 1, lightshaper_zNear, lightshaper_zFar);
applyTransform(gl, spotlightInverseTransform);
gl.glMatrixMode(GL.GL_MODELVIEW);
gl.glBindTexture(GL.GL_TEXTURE_2D, light_image);
gl.glEnable(GL.GL_TEXTURE_2D);
gl.glTexEnvi(GL.GL_TEXTURE_ENV, GL.GL_TEXTURE_ENV_MODE, GL.GL_MODULATE);
gl.glActiveTextureARB(GL.GL_TEXTURE0_ARB);
gl.glMatrixMode(GL.GL_PROJECTION);
gl.glLoadIdentity();
gl.glViewport(0, 0, canvas.getWidth(), canvas.getHeight());
applyTransform(gl, cameraPerspective);
gl.glMatrixMode(GL.GL_MODELVIEW);
render_scene(gl, cameraTransform, drawable, params);
gl.glActiveTextureARB(GL.GL_TEXTURE1_ARB);
gl.glDisable(GL.GL_TEXTURE_2D);
gl.glActiveTextureARB(GL.GL_TEXTURE0_ARB);
render_manipulators(gl, cameraTransform, drawable, params);
render_light_frustum(gl);
}
private void render_scene_from_camera_view_shadowed(GL gl, GLU glu, GLDrawable drawable, CameraParameters params) {
// place light
gl.glPushMatrix();
gl.glLoadIdentity();
applyTransform(gl, cameraInverseTransform);
applyTransform(gl, spotlightTransform);
gl.glLightfv(GL.GL_LIGHT0, GL.GL_POSITION, light_pos);
gl.glPopMatrix();
// spot image
gl.glActiveTextureARB(GL.GL_TEXTURE1_ARB);
gl.glPushMatrix();
applyTransform(gl, cameraInverseTransform);
eye_linear_texgen(gl);
texgen(gl, true);
gl.glPopMatrix();
gl.glMatrixMode(GL.GL_TEXTURE);
gl.glLoadIdentity();
gl.glTranslatef(.5f, .5f, .5f);
gl.glScalef(.5f, .5f, .5f);
glu.gluPerspective(lightshaper_fovy, 1, lightshaper_zNear, lightshaper_zFar);
applyTransform(gl, spotlightInverseTransform);
gl.glMatrixMode(GL.GL_MODELVIEW);
gl.glBindTexture(GL.GL_TEXTURE_2D, light_image);
gl.glEnable(GL.GL_TEXTURE_2D);
gl.glTexEnvi(GL.GL_TEXTURE_ENV, GL.GL_TEXTURE_ENV_MODE, GL.GL_MODULATE);
// depth compare
gl.glActiveTextureARB(GL.GL_TEXTURE2_ARB);
gl.glPushMatrix();
applyTransform(gl, cameraInverseTransform);
eye_linear_texgen(gl);
texgen(gl, true);
gl.glPopMatrix();
gl.glMatrixMode(GL.GL_TEXTURE);
gl.glLoadIdentity();
gl.glTranslatef(.5f, .5f, ((Tweak) tweaks.get(R_COORDINATE_SCALE)).val);
gl.glScalef(.5f, .5f, ((Tweak) tweaks.get(R_COORDINATE_BIAS)).val);
glu.gluPerspective(lightshaper_fovy, 1, lightshaper_zNear, lightshaper_zFar);
applyTransform(gl, spotlightInverseTransform);
gl.glMatrixMode(GL.GL_MODELVIEW);
gl.glBindTexture(GL.GL_TEXTURE_2D, light_view_depth);
gl.glEnable(GL.GL_TEXTURE_2D);
gl.glTexEnvi(GL.GL_TEXTURE_ENV, GL.GL_TEXTURE_ENV_MODE, GL.GL_MODULATE);
gl.glActiveTextureARB(GL.GL_TEXTURE0_ARB);
gl.glMatrixMode(GL.GL_PROJECTION);
gl.glLoadIdentity();
gl.glViewport(0, 0, canvas.getWidth(), canvas.getHeight());
applyTransform(gl, cameraPerspective);
gl.glMatrixMode(GL.GL_MODELVIEW);
render_scene(gl, cameraTransform, drawable, params);
gl.glActiveTextureARB(GL.GL_TEXTURE1_ARB);
gl.glDisable(GL.GL_TEXTURE_2D);
gl.glActiveTextureARB(GL.GL_TEXTURE2_ARB);
gl.glDisable(GL.GL_TEXTURE_2D);
gl.glActiveTextureARB(GL.GL_TEXTURE0_ARB);
render_manipulators(gl, cameraTransform, drawable, params);
render_light_frustum(gl);
}
private void largest_square_power_of_two_viewport(GL gl) {
Dimension dim = canvas.getSize();
float min = Math.min(dim.width, dim.height);
float log2min = (float) Math.log(min) / (float) Math.log(2.0);
float pow2 = (float) Math.floor(log2min);
int size = 1 << (int) pow2;
gl.glViewport(0, 0, size, size);
}
private void render_scene_from_light_view(GL gl, GLU glu) {
// place light
gl.glPushMatrix();
gl.glLoadIdentity();
gl.glLightfv(GL.GL_LIGHT0, GL.GL_POSITION, light_pos);
gl.glPopMatrix();
// spot image
gl.glActiveTextureARB(GL.GL_TEXTURE1_ARB);
gl.glPushMatrix();
eye_linear_texgen(gl);
texgen(gl, true);
gl.glPopMatrix();
gl.glMatrixMode(GL.GL_TEXTURE);
gl.glLoadIdentity();
gl.glTranslatef(.5f, .5f, .5f);
gl.glScalef(.5f, .5f, .5f);
glu.gluPerspective(lightshaper_fovy, 1, lightshaper_zNear, lightshaper_zFar);
gl.glMatrixMode(GL.GL_MODELVIEW);
gl.glBindTexture(GL.GL_TEXTURE_2D, light_image);
gl.glEnable(GL.GL_TEXTURE_2D);
gl.glTexEnvi(GL.GL_TEXTURE_ENV, GL.GL_TEXTURE_ENV_MODE, GL.GL_MODULATE);
gl.glActiveTextureARB(GL.GL_TEXTURE0_ARB);
gl.glViewport(0, 0, TEX_SIZE, TEX_SIZE);
gl.glMatrixMode(GL.GL_PROJECTION);
gl.glLoadIdentity();
glu.gluPerspective(lightshaper_fovy, 1, lightshaper_zNear, lightshaper_zFar);
gl.glMatrixMode(GL.GL_MODELVIEW);
if (displayMode == RENDER_SCENE_FROM_LIGHT_VIEW)
largest_square_power_of_two_viewport(gl);
render_scene(gl, spotlightTransform, null, null);
gl.glActiveTextureARB(GL.GL_TEXTURE1_ARB);
gl.glDisable(GL.GL_TEXTURE_2D);
gl.glActiveTextureARB(GL.GL_TEXTURE0_ARB);
}
private static void getRow(Mat4f m, int row, float[] out) {
out[0] = m.get(row, 0);
out[1] = m.get(row, 1);
out[2] = m.get(row, 2);
out[3] = m.get(row, 3);
}
private static void applyTransform(GL gl, Mat4f xform) {
float[] data = new float[16];
xform.getColumnMajorData(data);
gl.glMultMatrixf(data);
}
private static Mat4f perspectiveInverse(float fovy, float aspect, float zNear, float zFar) {
float tangent = (float) Math.tan(Math.toRadians(fovy / 2.0));
float y = tangent * zNear;
float x = aspect * y;
return frustumInverse(-x, x, -y, y, zNear, zFar);
}
private static Mat4f frustumInverse(float left, float right,
float bottom, float top,
float zNear, float zFar) {
Mat4f m = new Mat4f();
m.makeIdent();
m.set(0, 0, (right - left) / (2 * zNear));
m.set(0, 3, (right + left) / (2 * zNear));
m.set(1, 1, (top - bottom) / (2 * zNear));
m.set(1, 3, (top + bottom) / (2 * zNear));
m.set(2, 2, 0);
m.set(2, 3, -1);
m.set(3, 2, -(zFar - zNear) / (2 * zFar * zNear));
m.set(3, 3, (zFar + zNear) / (2 * zFar * zNear));
return m;
}
private void runExit() {
// Note: calling System.exit() synchronously inside the draw,
// reshape or init callbacks can lead to deadlocks on certain
// platforms (in particular, X11) because the JAWT's locking
// routines cause a global AWT lock to be grabbed. Run the
// exit routine in another thread.
new Thread(new Runnable() {
public void run() {
System.exit(0);
}
}).start();
}
}
| true | true | public void init(GLDrawable drawable) {
// init() might get called more than once if the GLCanvas is
// added and removed, but we only want to install the DebugGL
// pipeline once
// if (!(drawable.getGL() instanceof DebugGL)) {
// drawable.setGL(new DebugGL(drawable.getGL()));
// }
GL gl = drawable.getGL();
GLU glu = drawable.getGLU();
glut = new GLUT();
try {
checkExtension(gl, "GL_ARB_multitexture");
checkExtension(gl, "GL_ARB_depth_texture");
checkExtension(gl, "GL_ARB_shadow");
checkExtension(gl, "GL_ARB_pbuffer");
checkExtension(gl, "GL_ARB_pixel_format");
} catch (GLException e) {
e.printStackTrace();
throw(e);
}
gl.glClearColor(.5f, .5f, .5f, .5f);
decal = genTexture(gl);
gl.glBindTexture(GL.GL_TEXTURE_2D, decal);
BufferedImage img = readPNGImage("demos/data/images/decal_image.png");
makeRGBTexture(gl, glu, img, GL.GL_TEXTURE_2D, true);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR_MIPMAP_LINEAR);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR);
light_image = genTexture(gl);
gl.glBindTexture(GL.GL_TEXTURE_2D, light_image);
img = readPNGImage("demos/data/images/nvlogo_spot.png");
makeRGBTexture(gl, glu, img, GL.GL_TEXTURE_2D, true);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, GL.GL_CLAMP_TO_EDGE);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL.GL_CLAMP_TO_EDGE);
quad = gl.glGenLists(1);
gl.glNewList(quad, GL.GL_COMPILE);
gl.glPushMatrix();
gl.glRotatef(-90, 1, 0, 0);
gl.glScalef(4,4,4);
gl.glBegin(GL.GL_QUADS);
gl.glNormal3f(0, 0, 1);
gl.glVertex2f(-1, -1);
gl.glVertex2f(-1, 1);
gl.glVertex2f( 1, 1);
gl.glVertex2f( 1, -1);
gl.glEnd();
gl.glPopMatrix();
gl.glEndList();
wirecube = gl.glGenLists(1);
gl.glNewList(wirecube, GL.GL_COMPILE);
glut.glutWireCube(gl, 2);
gl.glEndList();
geometry = gl.glGenLists(1);
gl.glNewList(geometry, GL.GL_COMPILE);
gl.glPushMatrix();
// gl.glTranslatef(0, .4f, 0);
// FIXME
// glutSolidTeapot(.5f);
glut.glutSolidTorus(gl, 0.25f, 0.5f, 40, 20);
gl.glPopMatrix();
gl.glEndList();
gl.glEnable(GL.GL_LIGHT0);
gl.glLightfv(GL.GL_LIGHT0, GL.GL_AMBIENT, light_ambient);
gl.glLightfv(GL.GL_LIGHT0, GL.GL_DIFFUSE, light_intensity);
gl.glLightfv(GL.GL_LIGHT0, GL.GL_SPECULAR, light_intensity);
gl.glEnable(GL.GL_DEPTH_TEST);
// init pbuffer
GLCapabilities caps = new GLCapabilities();
caps.setDoubleBuffered(false);
pbuffer = drawable.createOffscreenDrawable(caps, TEX_SIZE, TEX_SIZE);
pbuffer.addGLEventListener(new PbufferListener());
// Register the window with the ManipManager
ManipManager manager = ManipManager.getManipManager();
manager.registerWindow(drawable);
object = new HandleBoxManip();
object.setTranslation(new Vec3f(0, 0.7f, 1.8f));
object.setGeometryScale(new Vec3f(0.7f, 0.7f, 0.7f));
manager.showManipInWindow(object, drawable);
spotlight = new HandleBoxManip();
spotlight.setScale(new Vec3f(0.5f, 0.5f, 0.5f));
spotlight.setTranslation(new Vec3f(-0.25f, 2.35f, 5.0f));
spotlight.setRotation(new Rotf(Vec3f.X_AXIS, (float) Math.toRadians(-30.0f)));
manager.showManipInWindow(spotlight, drawable);
viewer = new ExaminerViewer(MouseButtonHelper.numMouseButtons());
viewer.attach(drawable, new BSphereProvider() {
public BSphere getBoundingSphere() {
return new BSphere(object.getTranslation(), 2.0f);
}
});
viewer.setOrientation(new Rotf(Vec3f.Y_AXIS, (float) Math.toRadians(45.0f)).times
(new Rotf(Vec3f.X_AXIS, (float) Math.toRadians(-15.0f))));
viewer.setVertFOV((float) Math.toRadians(lightshaper_fovy / 2.0f));
viewer.setZNear(zNear);
viewer.setZFar(zFar);
float bias = 1/((float) Math.pow(2.0,16.0)-1);
tweaks.add(new Tweak("r coordinate scale", 0.5f, bias));
tweaks.add(new Tweak("r coordinate bias", 0.5f, bias));
tweaks.add(new Tweak("polygon offset scale", 2.5f, 0.5f));
tweaks.add(new Tweak("polygon offset bias", 10.0f, 1.0f));
drawable.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
dispatchKey(e.getKeyChar());
canvas.repaint();
}
});
}
| public void init(GLDrawable drawable) {
// init() might get called more than once if the GLCanvas is
// added and removed, but we only want to install the DebugGL
// pipeline once
// if (!(drawable.getGL() instanceof DebugGL)) {
// drawable.setGL(new DebugGL(drawable.getGL()));
// }
GL gl = drawable.getGL();
GLU glu = drawable.getGLU();
glut = new GLUT();
try {
checkExtension(gl, "GL_ARB_multitexture");
checkExtension(gl, "GL_ARB_depth_texture");
checkExtension(gl, "GL_ARB_shadow");
checkExtension(gl, "GL_ARB_pbuffer");
checkExtension(gl, "GL_ARB_pixel_format");
} catch (GLException e) {
e.printStackTrace();
throw(e);
}
gl.glClearColor(.5f, .5f, .5f, .5f);
decal = genTexture(gl);
gl.glBindTexture(GL.GL_TEXTURE_2D, decal);
BufferedImage img = readPNGImage("demos/data/images/decal_image.png");
makeRGBTexture(gl, glu, img, GL.GL_TEXTURE_2D, true);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR_MIPMAP_LINEAR);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR);
light_image = genTexture(gl);
gl.glBindTexture(GL.GL_TEXTURE_2D, light_image);
img = readPNGImage("demos/data/images/nvlogo_spot.png");
makeRGBTexture(gl, glu, img, GL.GL_TEXTURE_2D, true);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_S, GL.GL_CLAMP_TO_EDGE);
gl.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_WRAP_T, GL.GL_CLAMP_TO_EDGE);
quad = gl.glGenLists(1);
gl.glNewList(quad, GL.GL_COMPILE);
gl.glPushMatrix();
gl.glRotatef(-90, 1, 0, 0);
gl.glScalef(4,4,4);
gl.glBegin(GL.GL_QUADS);
gl.glNormal3f(0, 0, 1);
gl.glVertex2f(-1, -1);
gl.glVertex2f(-1, 1);
gl.glVertex2f( 1, 1);
gl.glVertex2f( 1, -1);
gl.glEnd();
gl.glPopMatrix();
gl.glEndList();
wirecube = gl.glGenLists(1);
gl.glNewList(wirecube, GL.GL_COMPILE);
glut.glutWireCube(gl, 2);
gl.glEndList();
geometry = gl.glGenLists(1);
gl.glNewList(geometry, GL.GL_COMPILE);
gl.glPushMatrix();
glut.glutSolidTeapot(gl, 0.8f);
gl.glPopMatrix();
gl.glEndList();
gl.glEnable(GL.GL_LIGHT0);
gl.glLightfv(GL.GL_LIGHT0, GL.GL_AMBIENT, light_ambient);
gl.glLightfv(GL.GL_LIGHT0, GL.GL_DIFFUSE, light_intensity);
gl.glLightfv(GL.GL_LIGHT0, GL.GL_SPECULAR, light_intensity);
gl.glEnable(GL.GL_DEPTH_TEST);
// init pbuffer
GLCapabilities caps = new GLCapabilities();
caps.setDoubleBuffered(false);
pbuffer = drawable.createOffscreenDrawable(caps, TEX_SIZE, TEX_SIZE);
pbuffer.addGLEventListener(new PbufferListener());
// Register the window with the ManipManager
ManipManager manager = ManipManager.getManipManager();
manager.registerWindow(drawable);
object = new HandleBoxManip();
object.setTranslation(new Vec3f(0, 0.7f, 1.8f));
object.setGeometryScale(new Vec3f(0.7f, 0.7f, 0.7f));
manager.showManipInWindow(object, drawable);
spotlight = new HandleBoxManip();
spotlight.setScale(new Vec3f(0.5f, 0.5f, 0.5f));
spotlight.setTranslation(new Vec3f(-0.25f, 2.35f, 5.0f));
spotlight.setRotation(new Rotf(Vec3f.X_AXIS, (float) Math.toRadians(-30.0f)));
manager.showManipInWindow(spotlight, drawable);
viewer = new ExaminerViewer(MouseButtonHelper.numMouseButtons());
viewer.attach(drawable, new BSphereProvider() {
public BSphere getBoundingSphere() {
return new BSphere(object.getTranslation(), 2.0f);
}
});
viewer.setOrientation(new Rotf(Vec3f.Y_AXIS, (float) Math.toRadians(45.0f)).times
(new Rotf(Vec3f.X_AXIS, (float) Math.toRadians(-15.0f))));
viewer.setVertFOV((float) Math.toRadians(lightshaper_fovy / 2.0f));
viewer.setZNear(zNear);
viewer.setZFar(zFar);
float bias = 1/((float) Math.pow(2.0,16.0)-1);
tweaks.add(new Tweak("r coordinate scale", 0.5f, bias));
tweaks.add(new Tweak("r coordinate bias", 0.5f, bias));
tweaks.add(new Tweak("polygon offset scale", 2.5f, 0.5f));
tweaks.add(new Tweak("polygon offset bias", 10.0f, 1.0f));
drawable.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
dispatchKey(e.getKeyChar());
canvas.repaint();
}
});
}
|
diff --git a/v4/java/android/support/v4/widget/DrawerLayout.java b/v4/java/android/support/v4/widget/DrawerLayout.java
index c5772de..0b923e7 100644
--- a/v4/java/android/support/v4/widget/DrawerLayout.java
+++ b/v4/java/android/support/v4/widget/DrawerLayout.java
@@ -1,1591 +1,1592 @@
/*
* Copyright (C) 2013 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.support.v4.widget;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Parcel;
import android.os.Parcelable;
import android.os.SystemClock;
import android.support.v4.view.AccessibilityDelegateCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.view.KeyEventCompat;
import android.support.v4.view.MotionEventCompat;
import android.support.v4.view.ViewCompat;
import android.support.v4.view.ViewGroupCompat;
import android.support.v4.view.accessibility.AccessibilityNodeInfoCompat;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.accessibility.AccessibilityEvent;
/**
* DrawerLayout acts as a top-level container for window content that allows for
* interactive "drawer" views to be pulled out from the edge of the window.
*
* <p>Drawer positioning and layout is controlled using the <code>android:layout_gravity</code>
* attribute on child views corresponding to which side of the view you want the drawer
* to emerge from: left or right. (Or start/end on platform versions that support layout direction.)
* </p>
*
* <p>To use a DrawerLayout, position your primary content view as the first child with
* a width and height of <code>match_parent</code>. Add drawers as child views after the main
* content view and set the <code>layout_gravity</code> appropriately. Drawers commonly use
* <code>match_parent</code> for height with a fixed width.</p>
*
* <p>{@link DrawerListener} can be used to monitor the state and motion of drawer views.
* Avoid performing expensive operations such as layout during animation as it can cause
* stuttering; try to perform expensive operations during the {@link #STATE_IDLE} state.
* {@link SimpleDrawerListener} offers default/no-op implementations of each callback method.</p>
*
* <p>As per the Android Design guide, any drawers positioned to the left/start should
* always contain content for navigating around the application, whereas any drawers
* positioned to the right/end should always contain actions to take on the current content.
* This preserves the same navigation left, actions right structure present in the Action Bar
* and elsewhere.</p>
*/
public class DrawerLayout extends ViewGroup {
private static final String TAG = "DrawerLayout";
/**
* Indicates that any drawers are in an idle, settled state. No animation is in progress.
*/
public static final int STATE_IDLE = ViewDragHelper.STATE_IDLE;
/**
* Indicates that a drawer is currently being dragged by the user.
*/
public static final int STATE_DRAGGING = ViewDragHelper.STATE_DRAGGING;
/**
* Indicates that a drawer is in the process of settling to a final position.
*/
public static final int STATE_SETTLING = ViewDragHelper.STATE_SETTLING;
/**
* The drawer is unlocked.
*/
public static final int LOCK_MODE_UNLOCKED = 0;
/**
* The drawer is locked closed. The user may not open it, though
* the app may open it programmatically.
*/
public static final int LOCK_MODE_LOCKED_CLOSED = 1;
/**
* The drawer is locked open. The user may not close it, though the app
* may close it programmatically.
*/
public static final int LOCK_MODE_LOCKED_OPEN = 2;
private static final int MIN_DRAWER_MARGIN = 64; // dp
private static final int DEFAULT_SCRIM_COLOR = 0x99000000;
/**
* Length of time to delay before peeking the drawer.
*/
private static final int PEEK_DELAY = 160; // ms
/**
* Minimum velocity that will be detected as a fling
*/
private static final int MIN_FLING_VELOCITY = 400; // dips per second
/**
* Experimental feature.
*/
private static final boolean ALLOW_EDGE_LOCK = false;
private static final boolean CHILDREN_DISALLOW_INTERCEPT = true;
private static final float TOUCH_SLOP_SENSITIVITY = 1.f;
private static final int[] LAYOUT_ATTRS = new int[] {
android.R.attr.layout_gravity
};
private int mMinDrawerMargin;
private int mScrimColor = DEFAULT_SCRIM_COLOR;
private float mScrimOpacity;
private Paint mScrimPaint = new Paint();
private final ViewDragHelper mLeftDragger;
private final ViewDragHelper mRightDragger;
private final ViewDragCallback mLeftCallback;
private final ViewDragCallback mRightCallback;
private int mDrawerState;
private boolean mInLayout;
private boolean mFirstLayout = true;
private int mLockModeLeft;
private int mLockModeRight;
private boolean mDisallowInterceptRequested;
private boolean mChildrenCanceledTouch;
private DrawerListener mListener;
private float mInitialMotionX;
private float mInitialMotionY;
private Drawable mShadowLeft;
private Drawable mShadowRight;
/**
* Listener for monitoring events about drawers.
*/
public interface DrawerListener {
/**
* Called when a drawer's position changes.
* @param drawerView The child view that was moved
* @param slideOffset The new offset of this drawer within its range, from 0-1
*/
public void onDrawerSlide(View drawerView, float slideOffset);
/**
* Called when a drawer has settled in a completely open state.
* The drawer is interactive at this point.
*
* @param drawerView Drawer view that is now open
*/
public void onDrawerOpened(View drawerView);
/**
* Called when a drawer has settled in a completely closed state.
*
* @param drawerView Drawer view that is now closed
*/
public void onDrawerClosed(View drawerView);
/**
* Called when the drawer motion state changes. The new state will
* be one of {@link #STATE_IDLE}, {@link #STATE_DRAGGING} or {@link #STATE_SETTLING}.
*
* @param newState The new drawer motion state
*/
public void onDrawerStateChanged(int newState);
}
/**
* Stub/no-op implementations of all methods of {@link DrawerListener}.
* Override this if you only care about a few of the available callback methods.
*/
public static abstract class SimpleDrawerListener implements DrawerListener {
@Override
public void onDrawerSlide(View drawerView, float slideOffset) {
}
@Override
public void onDrawerOpened(View drawerView) {
}
@Override
public void onDrawerClosed(View drawerView) {
}
@Override
public void onDrawerStateChanged(int newState) {
}
}
public DrawerLayout(Context context) {
this(context, null);
}
public DrawerLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public DrawerLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
final float density = getResources().getDisplayMetrics().density;
mMinDrawerMargin = (int) (MIN_DRAWER_MARGIN * density + 0.5f);
final float minVel = MIN_FLING_VELOCITY * density;
mLeftCallback = new ViewDragCallback(Gravity.LEFT);
mRightCallback = new ViewDragCallback(Gravity.RIGHT);
mLeftDragger = ViewDragHelper.create(this, TOUCH_SLOP_SENSITIVITY, mLeftCallback);
mLeftDragger.setEdgeTrackingEnabled(ViewDragHelper.EDGE_LEFT);
mLeftDragger.setMinVelocity(minVel);
mLeftCallback.setDragger(mLeftDragger);
mRightDragger = ViewDragHelper.create(this, TOUCH_SLOP_SENSITIVITY, mRightCallback);
mRightDragger.setEdgeTrackingEnabled(ViewDragHelper.EDGE_RIGHT);
mRightDragger.setMinVelocity(minVel);
mRightCallback.setDragger(mRightDragger);
// So that we can catch the back button
setFocusableInTouchMode(true);
ViewCompat.setAccessibilityDelegate(this, new AccessibilityDelegate());
ViewGroupCompat.setMotionEventSplittingEnabled(this, false);
}
/**
* Set a simple drawable used for the left or right shadow.
* The drawable provided must have a nonzero intrinsic width.
*
* @param shadowDrawable Shadow drawable to use at the edge of a drawer
* @param gravity Which drawer the shadow should apply to
*/
public void setDrawerShadow(Drawable shadowDrawable, int gravity) {
/*
* TODO Someone someday might want to set more complex drawables here.
* They're probably nuts, but we might want to consider registering callbacks,
* setting states, etc. properly.
*/
final int absGravity = GravityCompat.getAbsoluteGravity(gravity,
ViewCompat.getLayoutDirection(this));
if ((absGravity & Gravity.LEFT) == Gravity.LEFT) {
mShadowLeft = shadowDrawable;
invalidate();
}
if ((absGravity & Gravity.RIGHT) == Gravity.RIGHT) {
mShadowRight = shadowDrawable;
invalidate();
}
}
/**
* Set a simple drawable used for the left or right shadow.
* The drawable provided must have a nonzero intrinsic width.
*
* @param resId Resource id of a shadow drawable to use at the edge of a drawer
* @param gravity Which drawer the shadow should apply to
*/
public void setDrawerShadow(int resId, int gravity) {
setDrawerShadow(getResources().getDrawable(resId), gravity);
}
/**
* Set a color to use for the scrim that obscures primary content while a drawer is open.
*
* @param color Color to use in 0xAARRGGBB format.
*/
public void setScrimColor(int color) {
mScrimColor = color;
invalidate();
}
/**
* Set a listener to be notified of drawer events.
*
* @param listener Listener to notify when drawer events occur
* @see DrawerListener
*/
public void setDrawerListener(DrawerListener listener) {
mListener = listener;
}
/**
* Enable or disable interaction with all drawers.
*
* <p>This allows the application to restrict the user's ability to open or close
* any drawer within this layout. DrawerLayout will still respond to calls to
* {@link #openDrawer(int)}, {@link #closeDrawer(int)} and friends if a drawer is locked.</p>
*
* <p>Locking drawers open or closed will implicitly open or close
* any drawers as appropriate.</p>
*
* @param lockMode The new lock mode for the given drawer. One of {@link #LOCK_MODE_UNLOCKED},
* {@link #LOCK_MODE_LOCKED_CLOSED} or {@link #LOCK_MODE_LOCKED_OPEN}.
*/
public void setDrawerLockMode(int lockMode) {
setDrawerLockMode(lockMode, Gravity.LEFT);
setDrawerLockMode(lockMode, Gravity.RIGHT);
}
/**
* Enable or disable interaction with the given drawer.
*
* <p>This allows the application to restrict the user's ability to open or close
* the given drawer. DrawerLayout will still respond to calls to {@link #openDrawer(int)},
* {@link #closeDrawer(int)} and friends if a drawer is locked.</p>
*
* <p>Locking a drawer open or closed will implicitly open or close
* that drawer as appropriate.</p>
*
* @param lockMode The new lock mode for the given drawer. One of {@link #LOCK_MODE_UNLOCKED},
* {@link #LOCK_MODE_LOCKED_CLOSED} or {@link #LOCK_MODE_LOCKED_OPEN}.
* @param edgeGravity Gravity.LEFT, RIGHT, START or END.
* Expresses which drawer to change the mode for.
*
* @see #LOCK_MODE_UNLOCKED
* @see #LOCK_MODE_LOCKED_CLOSED
* @see #LOCK_MODE_LOCKED_OPEN
*/
public void setDrawerLockMode(int lockMode, int edgeGravity) {
final int absGrav = GravityCompat.getAbsoluteGravity(edgeGravity,
ViewCompat.getLayoutDirection(this));
if (absGrav == Gravity.LEFT) {
mLockModeLeft = lockMode;
} else if (absGrav == Gravity.RIGHT) {
mLockModeRight = lockMode;
}
if (lockMode != LOCK_MODE_UNLOCKED) {
// Cancel interaction in progress
final ViewDragHelper helper = absGrav == Gravity.LEFT ? mLeftDragger : mRightDragger;
helper.cancel();
}
switch (lockMode) {
case LOCK_MODE_LOCKED_OPEN:
final View toOpen = findDrawerWithGravity(absGrav);
if (toOpen != null) {
openDrawer(toOpen);
}
break;
case LOCK_MODE_LOCKED_CLOSED:
final View toClose = findDrawerWithGravity(absGrav);
if (toClose != null) {
closeDrawer(toClose);
}
break;
// default: do nothing
}
}
/**
* Enable or disable interaction with the given drawer.
*
* <p>This allows the application to restrict the user's ability to open or close
* the given drawer. DrawerLayout will still respond to calls to {@link #openDrawer(int)},
* {@link #closeDrawer(int)} and friends if a drawer is locked.</p>
*
* <p>Locking a drawer open or closed will implicitly open or close
* that drawer as appropriate.</p>
*
* @param lockMode The new lock mode for the given drawer. One of {@link #LOCK_MODE_UNLOCKED},
* {@link #LOCK_MODE_LOCKED_CLOSED} or {@link #LOCK_MODE_LOCKED_OPEN}.
* @param drawerView The drawer view to change the lock mode for
*
* @see #LOCK_MODE_UNLOCKED
* @see #LOCK_MODE_LOCKED_CLOSED
* @see #LOCK_MODE_LOCKED_OPEN
*/
public void setDrawerLockMode(int lockMode, View drawerView) {
if (!isDrawerView(drawerView)) {
throw new IllegalArgumentException("View " + drawerView + " is not a " +
"drawer with appropriate layout_gravity");
}
setDrawerLockMode(lockMode, getDrawerViewGravity(drawerView));
}
/**
* Check the lock mode of the drawer with the given gravity.
*
* @param edgeGravity Gravity of the drawer to check
* @return one of {@link #LOCK_MODE_UNLOCKED}, {@link #LOCK_MODE_LOCKED_CLOSED} or
* {@link #LOCK_MODE_LOCKED_OPEN}.
*/
public int getDrawerLockMode(int edgeGravity) {
final int absGrav = GravityCompat.getAbsoluteGravity(edgeGravity,
ViewCompat.getLayoutDirection(this));
if (absGrav == Gravity.LEFT) {
return mLockModeLeft;
} else if (absGrav == Gravity.RIGHT) {
return mLockModeRight;
}
return LOCK_MODE_UNLOCKED;
}
/**
* Check the lock mode of the given drawer view.
*
* @param drawerView Drawer view to check lock mode
* @return one of {@link #LOCK_MODE_UNLOCKED}, {@link #LOCK_MODE_LOCKED_CLOSED} or
* {@link #LOCK_MODE_LOCKED_OPEN}.
*/
public int getDrawerLockMode(View drawerView) {
final int gravity = getDrawerViewGravity(drawerView);
if (gravity == Gravity.LEFT) {
return mLockModeLeft;
} else if (gravity == Gravity.RIGHT) {
return mLockModeRight;
}
return LOCK_MODE_UNLOCKED;
}
/**
* Resolve the shared state of all drawers from the component ViewDragHelpers.
* Should be called whenever a ViewDragHelper's state changes.
*/
void updateDrawerState(int forGravity, int activeState, View activeDrawer) {
final int leftState = mLeftDragger.getViewDragState();
final int rightState = mRightDragger.getViewDragState();
final int state;
if (leftState == STATE_DRAGGING || rightState == STATE_DRAGGING) {
state = STATE_DRAGGING;
} else if (leftState == STATE_SETTLING || rightState == STATE_SETTLING) {
state = STATE_SETTLING;
} else {
state = STATE_IDLE;
}
if (activeDrawer != null && activeState == STATE_IDLE) {
final LayoutParams lp = (LayoutParams) activeDrawer.getLayoutParams();
if (lp.onScreen == 0) {
dispatchOnDrawerClosed(activeDrawer);
} else if (lp.onScreen == 1) {
dispatchOnDrawerOpened(activeDrawer);
}
}
if (state != mDrawerState) {
mDrawerState = state;
if (mListener != null) {
mListener.onDrawerStateChanged(state);
}
}
}
void dispatchOnDrawerClosed(View drawerView) {
final LayoutParams lp = (LayoutParams) drawerView.getLayoutParams();
if (lp.knownOpen) {
lp.knownOpen = false;
if (mListener != null) {
mListener.onDrawerClosed(drawerView);
}
sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
}
}
void dispatchOnDrawerOpened(View drawerView) {
final LayoutParams lp = (LayoutParams) drawerView.getLayoutParams();
if (!lp.knownOpen) {
lp.knownOpen = true;
if (mListener != null) {
mListener.onDrawerOpened(drawerView);
}
drawerView.sendAccessibilityEvent(AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED);
}
}
void dispatchOnDrawerSlide(View drawerView, float slideOffset) {
if (mListener != null) {
mListener.onDrawerSlide(drawerView, slideOffset);
}
}
void setDrawerViewOffset(View drawerView, float slideOffset) {
final LayoutParams lp = (LayoutParams) drawerView.getLayoutParams();
if (slideOffset == lp.onScreen) {
return;
}
lp.onScreen = slideOffset;
dispatchOnDrawerSlide(drawerView, slideOffset);
}
float getDrawerViewOffset(View drawerView) {
return ((LayoutParams) drawerView.getLayoutParams()).onScreen;
}
int getDrawerViewGravity(View drawerView) {
final int gravity = ((LayoutParams) drawerView.getLayoutParams()).gravity;
return GravityCompat.getAbsoluteGravity(gravity, ViewCompat.getLayoutDirection(drawerView));
}
boolean checkDrawerViewGravity(View drawerView, int checkFor) {
final int absGrav = getDrawerViewGravity(drawerView);
return (absGrav & checkFor) == checkFor;
}
View findOpenDrawer() {
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
if (((LayoutParams) child.getLayoutParams()).knownOpen) {
return child;
}
}
return null;
}
void moveDrawerToOffset(View drawerView, float slideOffset) {
final float oldOffset = getDrawerViewOffset(drawerView);
final int width = drawerView.getWidth();
final int oldPos = (int) (width * oldOffset);
final int newPos = (int) (width * slideOffset);
final int dx = newPos - oldPos;
drawerView.offsetLeftAndRight(checkDrawerViewGravity(drawerView, Gravity.LEFT) ? dx : -dx);
setDrawerViewOffset(drawerView, slideOffset);
}
View findDrawerWithGravity(int gravity) {
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
final int childGravity = getDrawerViewGravity(child);
if ((childGravity & Gravity.HORIZONTAL_GRAVITY_MASK) ==
(gravity & Gravity.HORIZONTAL_GRAVITY_MASK)) {
return child;
}
}
return null;
}
/**
* Simple gravity to string - only supports LEFT and RIGHT for debugging output.
*
* @param gravity Absolute gravity value
* @return LEFT or RIGHT as appropriate, or a hex string
*/
static String gravityToString(int gravity) {
if ((gravity & Gravity.LEFT) == Gravity.LEFT) {
return "LEFT";
}
if ((gravity & Gravity.RIGHT) == Gravity.RIGHT) {
return "RIGHT";
}
return Integer.toHexString(gravity);
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
mFirstLayout = true;
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
mFirstLayout = true;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
if (widthMode != MeasureSpec.EXACTLY || heightMode != MeasureSpec.EXACTLY) {
if (isInEditMode()) {
// Don't crash the layout editor. Consume all of the space if specified
// or pick a magic number from thin air otherwise.
// TODO Better communication with tools of this bogus state.
// It will crash on a real device.
if (widthMode == MeasureSpec.AT_MOST) {
widthMode = MeasureSpec.EXACTLY;
} else if (widthMode == MeasureSpec.UNSPECIFIED) {
widthMode = MeasureSpec.EXACTLY;
widthSize = 300;
}
if (heightMode == MeasureSpec.AT_MOST) {
heightMode = MeasureSpec.EXACTLY;
}
else if (heightMode == MeasureSpec.UNSPECIFIED) {
heightMode = MeasureSpec.EXACTLY;
heightSize = 300;
}
} else {
throw new IllegalArgumentException(
"DrawerLayout must be measured with MeasureSpec.EXACTLY.");
}
}
setMeasuredDimension(widthSize, heightSize);
// Gravity value for each drawer we've seen. Only one of each permitted.
int foundDrawers = 0;
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
if (child.getVisibility() == GONE) {
continue;
}
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (isContentView(child)) {
// Content views get measured at exactly the layout's size.
final int contentWidthSpec = MeasureSpec.makeMeasureSpec(
widthSize - lp.leftMargin - lp.rightMargin, MeasureSpec.EXACTLY);
final int contentHeightSpec = MeasureSpec.makeMeasureSpec(
heightSize - lp.topMargin - lp.bottomMargin, MeasureSpec.EXACTLY);
child.measure(contentWidthSpec, contentHeightSpec);
} else if (isDrawerView(child)) {
final int childGravity =
getDrawerViewGravity(child) & Gravity.HORIZONTAL_GRAVITY_MASK;
if ((foundDrawers & childGravity) != 0) {
throw new IllegalStateException("Child drawer has absolute gravity " +
gravityToString(childGravity) + " but this " + TAG + " already has a " +
"drawer view along that edge");
}
final int drawerWidthSpec = getChildMeasureSpec(widthMeasureSpec,
mMinDrawerMargin + lp.leftMargin + lp.rightMargin,
lp.width);
final int drawerHeightSpec = getChildMeasureSpec(heightMeasureSpec,
lp.topMargin + lp.bottomMargin,
lp.height);
child.measure(drawerWidthSpec, drawerHeightSpec);
} else {
throw new IllegalStateException("Child " + child + " at index " + i +
" does not have a valid layout_gravity - must be Gravity.LEFT, " +
"Gravity.RIGHT or Gravity.NO_GRAVITY");
}
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
mInLayout = true;
final int width = r - l;
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
if (child.getVisibility() == GONE) {
continue;
}
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (isContentView(child)) {
child.layout(lp.leftMargin, lp.topMargin,
lp.leftMargin + child.getMeasuredWidth(),
lp.topMargin + child.getMeasuredHeight());
} else { // Drawer, if it wasn't onMeasure would have thrown an exception.
final int childWidth = child.getMeasuredWidth();
final int childHeight = child.getMeasuredHeight();
int childLeft;
final float newOffset;
if (checkDrawerViewGravity(child, Gravity.LEFT)) {
childLeft = -childWidth + (int) (childWidth * lp.onScreen);
newOffset = (float) (childWidth + childLeft) / childWidth;
} else { // Right; onMeasure checked for us.
childLeft = width - (int) (childWidth * lp.onScreen);
newOffset = (float) (width - childLeft) / childWidth;
}
final boolean changeOffset = newOffset != lp.onScreen;
final int vgrav = lp.gravity & Gravity.VERTICAL_GRAVITY_MASK;
switch (vgrav) {
default:
case Gravity.TOP: {
- child.layout(childLeft, lp.topMargin, childLeft + childWidth, childHeight);
+ child.layout(childLeft, lp.topMargin, childLeft + childWidth,
+ lp.topMargin + childHeight);
break;
}
case Gravity.BOTTOM: {
final int height = b - t;
child.layout(childLeft,
height - lp.bottomMargin - child.getMeasuredHeight(),
childLeft + childWidth,
height - lp.bottomMargin);
break;
}
case Gravity.CENTER_VERTICAL: {
final int height = b - t;
int childTop = (height - childHeight) / 2;
// Offset for margins. If things don't fit right because of
// bad measurement before, oh well.
if (childTop < lp.topMargin) {
childTop = lp.topMargin;
} else if (childTop + childHeight > height - lp.bottomMargin) {
childTop = height - lp.bottomMargin - childHeight;
}
child.layout(childLeft, childTop, childLeft + childWidth,
childTop + childHeight);
break;
}
}
if (changeOffset) {
setDrawerViewOffset(child, newOffset);
}
final int newVisibility = lp.onScreen > 0 ? VISIBLE : INVISIBLE;
if (child.getVisibility() != newVisibility) {
child.setVisibility(newVisibility);
}
}
}
mInLayout = false;
mFirstLayout = false;
}
@Override
public void requestLayout() {
if (!mInLayout) {
super.requestLayout();
}
}
@Override
public void computeScroll() {
final int childCount = getChildCount();
float scrimOpacity = 0;
for (int i = 0; i < childCount; i++) {
final float onscreen = ((LayoutParams) getChildAt(i).getLayoutParams()).onScreen;
scrimOpacity = Math.max(scrimOpacity, onscreen);
}
mScrimOpacity = scrimOpacity;
// "|" used on purpose; both need to run.
if (mLeftDragger.continueSettling(true) | mRightDragger.continueSettling(true)) {
ViewCompat.postInvalidateOnAnimation(this);
}
}
private static boolean hasOpaqueBackground(View v) {
final Drawable bg = v.getBackground();
if (bg != null) {
return bg.getOpacity() == PixelFormat.OPAQUE;
}
return false;
}
@Override
protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
final int height = getHeight();
final boolean drawingContent = isContentView(child);
int clipLeft = 0, clipRight = getWidth();
final int restoreCount = canvas.save();
if (drawingContent) {
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View v = getChildAt(i);
if (v == child || v.getVisibility() != VISIBLE ||
!hasOpaqueBackground(v) || !isDrawerView(v) ||
v.getHeight() < height) {
continue;
}
if (checkDrawerViewGravity(v, Gravity.LEFT)) {
final int vright = v.getRight();
if (vright > clipLeft) clipLeft = vright;
} else {
final int vleft = v.getLeft();
if (vleft < clipRight) clipRight = vleft;
}
}
canvas.clipRect(clipLeft, 0, clipRight, getHeight());
}
final boolean result = super.drawChild(canvas, child, drawingTime);
canvas.restoreToCount(restoreCount);
if (mScrimOpacity > 0 && drawingContent) {
final int baseAlpha = (mScrimColor & 0xff000000) >>> 24;
final int imag = (int) (baseAlpha * mScrimOpacity);
final int color = imag << 24 | (mScrimColor & 0xffffff);
mScrimPaint.setColor(color);
canvas.drawRect(clipLeft, 0, clipRight, getHeight(), mScrimPaint);
} else if (mShadowLeft != null && checkDrawerViewGravity(child, Gravity.LEFT)) {
final int shadowWidth = mShadowLeft.getIntrinsicWidth();
final int childRight = child.getRight();
final int drawerPeekDistance = mLeftDragger.getEdgeSize();
final float alpha =
Math.max(0, Math.min((float) childRight / drawerPeekDistance, 1.f));
mShadowLeft.setBounds(childRight, child.getTop(),
childRight + shadowWidth, child.getBottom());
mShadowLeft.setAlpha((int) (0xff * alpha));
mShadowLeft.draw(canvas);
} else if (mShadowRight != null && checkDrawerViewGravity(child, Gravity.RIGHT)) {
final int shadowWidth = mShadowRight.getIntrinsicWidth();
final int childLeft = child.getLeft();
final int showing = getWidth() - childLeft;
final int drawerPeekDistance = mRightDragger.getEdgeSize();
final float alpha =
Math.max(0, Math.min((float) showing / drawerPeekDistance, 1.f));
mShadowRight.setBounds(childLeft - shadowWidth, child.getTop(),
childLeft, child.getBottom());
mShadowRight.setAlpha((int) (0xff * alpha));
mShadowRight.draw(canvas);
}
return result;
}
boolean isContentView(View child) {
return ((LayoutParams) child.getLayoutParams()).gravity == Gravity.NO_GRAVITY;
}
boolean isDrawerView(View child) {
final int gravity = ((LayoutParams) child.getLayoutParams()).gravity;
final int absGravity = GravityCompat.getAbsoluteGravity(gravity,
ViewCompat.getLayoutDirection(child));
return (absGravity & (Gravity.LEFT | Gravity.RIGHT)) != 0;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
final int action = MotionEventCompat.getActionMasked(ev);
// "|" used deliberately here; both methods should be invoked.
final boolean interceptForDrag = mLeftDragger.shouldInterceptTouchEvent(ev) |
mRightDragger.shouldInterceptTouchEvent(ev);
boolean interceptForTap = false;
switch (action) {
case MotionEvent.ACTION_DOWN: {
final float x = ev.getX();
final float y = ev.getY();
mInitialMotionX = x;
mInitialMotionY = y;
if (mScrimOpacity > 0 &&
isContentView(mLeftDragger.findTopChildUnder((int) x, (int) y))) {
interceptForTap = true;
}
mDisallowInterceptRequested = false;
mChildrenCanceledTouch = false;
break;
}
case MotionEvent.ACTION_MOVE: {
// If we cross the touch slop, don't perform the delayed peek for an edge touch.
if (mLeftDragger.checkTouchSlop(ViewDragHelper.DIRECTION_ALL)) {
mLeftCallback.removeCallbacks();
mRightCallback.removeCallbacks();
}
break;
}
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP: {
closeDrawers(true);
mDisallowInterceptRequested = false;
mChildrenCanceledTouch = false;
}
}
return interceptForDrag || interceptForTap || hasPeekingDrawer() || mChildrenCanceledTouch;
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
mLeftDragger.processTouchEvent(ev);
mRightDragger.processTouchEvent(ev);
final int action = ev.getAction();
boolean wantTouchEvents = true;
switch (action & MotionEventCompat.ACTION_MASK) {
case MotionEvent.ACTION_DOWN: {
final float x = ev.getX();
final float y = ev.getY();
mInitialMotionX = x;
mInitialMotionY = y;
mDisallowInterceptRequested = false;
mChildrenCanceledTouch = false;
break;
}
case MotionEvent.ACTION_UP: {
final float x = ev.getX();
final float y = ev.getY();
boolean peekingOnly = true;
final View touchedView = mLeftDragger.findTopChildUnder((int) x, (int) y);
if (touchedView != null && isContentView(touchedView)) {
final float dx = x - mInitialMotionX;
final float dy = y - mInitialMotionY;
final int slop = mLeftDragger.getTouchSlop();
if (dx * dx + dy * dy < slop * slop) {
// Taps close a dimmed open drawer but only if it isn't locked open.
final View openDrawer = findOpenDrawer();
if (openDrawer != null) {
peekingOnly = getDrawerLockMode(openDrawer) == LOCK_MODE_LOCKED_OPEN;
}
}
}
closeDrawers(peekingOnly);
mDisallowInterceptRequested = false;
break;
}
case MotionEvent.ACTION_CANCEL: {
closeDrawers(true);
mDisallowInterceptRequested = false;
mChildrenCanceledTouch = false;
break;
}
}
return wantTouchEvents;
}
public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) {
if (CHILDREN_DISALLOW_INTERCEPT ||
(!mLeftDragger.isEdgeTouched(ViewDragHelper.EDGE_LEFT) &&
!mRightDragger.isEdgeTouched(ViewDragHelper.EDGE_RIGHT))) {
// If we have an edge touch we want to skip this and track it for later instead.
super.requestDisallowInterceptTouchEvent(disallowIntercept);
}
mDisallowInterceptRequested = disallowIntercept;
if (disallowIntercept) {
closeDrawers(true);
}
}
/**
* Close all currently open drawer views by animating them out of view.
*/
public void closeDrawers() {
closeDrawers(false);
}
void closeDrawers(boolean peekingOnly) {
boolean needsInvalidate = false;
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (!isDrawerView(child) || (peekingOnly && !lp.isPeeking)) {
continue;
}
final int childWidth = child.getWidth();
if (checkDrawerViewGravity(child, Gravity.LEFT)) {
needsInvalidate |= mLeftDragger.smoothSlideViewTo(child,
-childWidth, child.getTop());
} else {
needsInvalidate |= mRightDragger.smoothSlideViewTo(child,
getWidth(), child.getTop());
}
lp.isPeeking = false;
}
mLeftCallback.removeCallbacks();
mRightCallback.removeCallbacks();
if (needsInvalidate) {
invalidate();
}
}
/**
* Open the specified drawer view by animating it into view.
*
* @param drawerView Drawer view to open
*/
public void openDrawer(View drawerView) {
if (!isDrawerView(drawerView)) {
throw new IllegalArgumentException("View " + drawerView + " is not a sliding drawer");
}
if (mFirstLayout) {
final LayoutParams lp = (LayoutParams) drawerView.getLayoutParams();
lp.onScreen = 1.f;
lp.knownOpen = true;
} else {
if (checkDrawerViewGravity(drawerView, Gravity.LEFT)) {
mLeftDragger.smoothSlideViewTo(drawerView, 0, drawerView.getTop());
} else {
mRightDragger.smoothSlideViewTo(drawerView, getWidth() - drawerView.getWidth(),
drawerView.getTop());
}
}
invalidate();
}
/**
* Open the specified drawer by animating it out of view.
*
* @param gravity Gravity.LEFT to move the left drawer or Gravity.RIGHT for the right.
* GravityCompat.START or GravityCompat.END may also be used.
*/
public void openDrawer(int gravity) {
final int absGravity = GravityCompat.getAbsoluteGravity(gravity,
ViewCompat.getLayoutDirection(this));
final View drawerView = findDrawerWithGravity(absGravity);
if (drawerView == null) {
throw new IllegalArgumentException("No drawer view found with absolute gravity " +
gravityToString(absGravity));
}
openDrawer(drawerView);
}
/**
* Close the specified drawer view by animating it into view.
*
* @param drawerView Drawer view to close
*/
public void closeDrawer(View drawerView) {
if (!isDrawerView(drawerView)) {
throw new IllegalArgumentException("View " + drawerView + " is not a sliding drawer");
}
if (mFirstLayout) {
final LayoutParams lp = (LayoutParams) drawerView.getLayoutParams();
lp.onScreen = 0.f;
lp.knownOpen = false;
} else {
if (checkDrawerViewGravity(drawerView, Gravity.LEFT)) {
mLeftDragger.smoothSlideViewTo(drawerView, -drawerView.getWidth(),
drawerView.getTop());
} else {
mRightDragger.smoothSlideViewTo(drawerView, getWidth(), drawerView.getTop());
}
}
invalidate();
}
/**
* Close the specified drawer by animating it out of view.
*
* @param gravity Gravity.LEFT to move the left drawer or Gravity.RIGHT for the right.
* GravityCompat.START or GravityCompat.END may also be used.
*/
public void closeDrawer(int gravity) {
final int absGravity = GravityCompat.getAbsoluteGravity(gravity,
ViewCompat.getLayoutDirection(this));
final View drawerView = findDrawerWithGravity(absGravity);
if (drawerView == null) {
throw new IllegalArgumentException("No drawer view found with absolute gravity " +
gravityToString(absGravity));
}
closeDrawer(drawerView);
}
/**
* Check if the given drawer view is currently in an open state.
* To be considered "open" the drawer must have settled into its fully
* visible state. To check for partial visibility use
* {@link #isDrawerVisible(android.view.View)}.
*
* @param drawer Drawer view to check
* @return true if the given drawer view is in an open state
* @see #isDrawerVisible(android.view.View)
*/
public boolean isDrawerOpen(View drawer) {
if (!isDrawerView(drawer)) {
throw new IllegalArgumentException("View " + drawer + " is not a drawer");
}
return ((LayoutParams) drawer.getLayoutParams()).knownOpen;
}
/**
* Check if the given drawer view is currently in an open state.
* To be considered "open" the drawer must have settled into its fully
* visible state. If there is no drawer with the given gravity this method
* will return false.
*
* @param drawerGravity Gravity of the drawer to check
* @return true if the given drawer view is in an open state
*/
public boolean isDrawerOpen(int drawerGravity) {
final View drawerView = findDrawerWithGravity(drawerGravity);
if (drawerView != null) {
return isDrawerOpen(drawerView);
}
return false;
}
/**
* Check if a given drawer view is currently visible on-screen. The drawer
* may be only peeking onto the screen, fully extended, or anywhere inbetween.
*
* @param drawer Drawer view to check
* @return true if the given drawer is visible on-screen
* @see #isDrawerOpen(android.view.View)
*/
public boolean isDrawerVisible(View drawer) {
if (!isDrawerView(drawer)) {
throw new IllegalArgumentException("View " + drawer + " is not a drawer");
}
return ((LayoutParams) drawer.getLayoutParams()).onScreen > 0;
}
/**
* Check if a given drawer view is currently visible on-screen. The drawer
* may be only peeking onto the screen, fully extended, or anywhere inbetween.
* If there is no drawer with the given gravity this method will return false.
*
* @param drawerGravity Gravity of the drawer to check
* @return true if the given drawer is visible on-screen
*/
public boolean isDrawerVisible(int drawerGravity) {
final View drawerView = findDrawerWithGravity(drawerGravity);
if (drawerView != null) {
return isDrawerVisible(drawerView);
}
return false;
}
private boolean hasPeekingDrawer() {
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final LayoutParams lp = (LayoutParams) getChildAt(i).getLayoutParams();
if (lp.isPeeking) {
return true;
}
}
return false;
}
@Override
protected ViewGroup.LayoutParams generateDefaultLayoutParams() {
return new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
}
@Override
protected ViewGroup.LayoutParams generateLayoutParams(ViewGroup.LayoutParams p) {
return p instanceof LayoutParams
? new LayoutParams((LayoutParams) p)
: p instanceof ViewGroup.MarginLayoutParams
? new LayoutParams((MarginLayoutParams) p)
: new LayoutParams(p);
}
@Override
protected boolean checkLayoutParams(ViewGroup.LayoutParams p) {
return p instanceof LayoutParams && super.checkLayoutParams(p);
}
@Override
public ViewGroup.LayoutParams generateLayoutParams(AttributeSet attrs) {
return new LayoutParams(getContext(), attrs);
}
private boolean hasVisibleDrawer() {
return findVisibleDrawer() != null;
}
private View findVisibleDrawer() {
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
if (isDrawerView(child) && isDrawerVisible(child)) {
return child;
}
}
return null;
}
void cancelChildViewTouch() {
// Cancel child touches
if (!mChildrenCanceledTouch) {
final long now = SystemClock.uptimeMillis();
final MotionEvent cancelEvent = MotionEvent.obtain(now, now,
MotionEvent.ACTION_CANCEL, 0.0f, 0.0f, 0);
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
getChildAt(i).dispatchTouchEvent(cancelEvent);
}
cancelEvent.recycle();
mChildrenCanceledTouch = true;
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && hasVisibleDrawer()) {
KeyEventCompat.startTracking(event);
return true;
}
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
final View visibleDrawer = findVisibleDrawer();
if (visibleDrawer != null && getDrawerLockMode(visibleDrawer) == LOCK_MODE_UNLOCKED) {
closeDrawers();
}
return visibleDrawer != null;
}
return super.onKeyUp(keyCode, event);
}
@Override
protected void onRestoreInstanceState(Parcelable state) {
final SavedState ss = (SavedState) state;
super.onRestoreInstanceState(ss.getSuperState());
if (ss.openDrawerGravity != Gravity.NO_GRAVITY) {
final View toOpen = findDrawerWithGravity(ss.openDrawerGravity);
if (toOpen != null) {
openDrawer(toOpen);
}
}
setDrawerLockMode(ss.lockModeLeft, Gravity.LEFT);
setDrawerLockMode(ss.lockModeRight, Gravity.RIGHT);
}
@Override
protected Parcelable onSaveInstanceState() {
final Parcelable superState = super.onSaveInstanceState();
final SavedState ss = new SavedState(superState);
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
if (!isDrawerView(child)) {
continue;
}
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (lp.knownOpen) {
ss.openDrawerGravity = lp.gravity;
// Only one drawer can be open at a time.
break;
}
}
ss.lockModeLeft = mLockModeLeft;
ss.lockModeRight = mLockModeRight;
return ss;
}
/**
* State persisted across instances
*/
protected static class SavedState extends BaseSavedState {
int openDrawerGravity = Gravity.NO_GRAVITY;
int lockModeLeft = LOCK_MODE_UNLOCKED;
int lockModeRight = LOCK_MODE_UNLOCKED;
public SavedState(Parcel in) {
super(in);
openDrawerGravity = in.readInt();
}
public SavedState(Parcelable superState) {
super(superState);
}
@Override
public void writeToParcel(Parcel dest, int flags) {
super.writeToParcel(dest, flags);
dest.writeInt(openDrawerGravity);
}
public static final Parcelable.Creator<SavedState> CREATOR =
new Parcelable.Creator<SavedState>() {
@Override
public SavedState createFromParcel(Parcel source) {
return new SavedState(source);
}
@Override
public SavedState[] newArray(int size) {
return new SavedState[size];
}
};
}
private class ViewDragCallback extends ViewDragHelper.Callback {
private final int mGravity;
private ViewDragHelper mDragger;
private final Runnable mPeekRunnable = new Runnable() {
@Override public void run() {
peekDrawer();
}
};
public ViewDragCallback(int gravity) {
mGravity = gravity;
}
public void setDragger(ViewDragHelper dragger) {
mDragger = dragger;
}
public void removeCallbacks() {
DrawerLayout.this.removeCallbacks(mPeekRunnable);
}
@Override
public boolean tryCaptureView(View child, int pointerId) {
// Only capture views where the gravity matches what we're looking for.
// This lets us use two ViewDragHelpers, one for each side drawer.
return isDrawerView(child) && checkDrawerViewGravity(child, mGravity) &&
getDrawerLockMode(child) == LOCK_MODE_UNLOCKED;
}
@Override
public void onViewDragStateChanged(int state) {
updateDrawerState(mGravity, state, mDragger.getCapturedView());
}
@Override
public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) {
float offset;
final int childWidth = changedView.getWidth();
// This reverses the positioning shown in onLayout.
if (checkDrawerViewGravity(changedView, Gravity.LEFT)) {
offset = (float) (childWidth + left) / childWidth;
} else {
final int width = getWidth();
offset = (float) (width - left) / childWidth;
}
setDrawerViewOffset(changedView, offset);
changedView.setVisibility(offset == 0 ? INVISIBLE : VISIBLE);
invalidate();
}
@Override
public void onViewCaptured(View capturedChild, int activePointerId) {
final LayoutParams lp = (LayoutParams) capturedChild.getLayoutParams();
lp.isPeeking = false;
closeOtherDrawer();
}
private void closeOtherDrawer() {
final int otherGrav = mGravity == Gravity.LEFT ? Gravity.RIGHT : Gravity.LEFT;
final View toClose = findDrawerWithGravity(otherGrav);
if (toClose != null) {
closeDrawer(toClose);
}
}
@Override
public void onViewReleased(View releasedChild, float xvel, float yvel) {
// Offset is how open the drawer is, therefore left/right values
// are reversed from one another.
final float offset = getDrawerViewOffset(releasedChild);
final int childWidth = releasedChild.getWidth();
int left;
if (checkDrawerViewGravity(releasedChild, Gravity.LEFT)) {
left = xvel > 0 || xvel == 0 && offset > 0.5f ? 0 : -childWidth;
} else {
final int width = getWidth();
left = xvel < 0 || xvel == 0 && offset < 0.5f ? width - childWidth : width;
}
mDragger.settleCapturedViewAt(left, releasedChild.getTop());
invalidate();
}
@Override
public void onEdgeTouched(int edgeFlags, int pointerId) {
postDelayed(mPeekRunnable, PEEK_DELAY);
}
private void peekDrawer() {
final View toCapture;
final int childLeft;
final int peekDistance = mDragger.getEdgeSize();
final boolean leftEdge = mGravity == Gravity.LEFT;
if (leftEdge) {
toCapture = findDrawerWithGravity(Gravity.LEFT);
childLeft = (toCapture != null ? -toCapture.getWidth() : 0) + peekDistance;
} else {
toCapture = findDrawerWithGravity(Gravity.RIGHT);
childLeft = getWidth() - peekDistance;
}
// Only peek if it would mean making the drawer more visible and the drawer isn't locked
if (toCapture != null && ((leftEdge && toCapture.getLeft() < childLeft) ||
(!leftEdge && toCapture.getLeft() > childLeft)) &&
getDrawerLockMode(toCapture) == LOCK_MODE_UNLOCKED) {
final LayoutParams lp = (LayoutParams) toCapture.getLayoutParams();
mDragger.smoothSlideViewTo(toCapture, childLeft, toCapture.getTop());
lp.isPeeking = true;
invalidate();
closeOtherDrawer();
cancelChildViewTouch();
}
}
@Override
public boolean onEdgeLock(int edgeFlags) {
if (ALLOW_EDGE_LOCK) {
final View drawer = findDrawerWithGravity(mGravity);
if (drawer != null && !isDrawerOpen(drawer)) {
closeDrawer(drawer);
}
return true;
}
return false;
}
@Override
public void onEdgeDragStarted(int edgeFlags, int pointerId) {
final View toCapture;
if ((edgeFlags & ViewDragHelper.EDGE_LEFT) == ViewDragHelper.EDGE_LEFT) {
toCapture = findDrawerWithGravity(Gravity.LEFT);
} else {
toCapture = findDrawerWithGravity(Gravity.RIGHT);
}
if (toCapture != null && getDrawerLockMode(toCapture) == LOCK_MODE_UNLOCKED) {
mDragger.captureChildView(toCapture, pointerId);
}
}
@Override
public int getViewHorizontalDragRange(View child) {
return child.getWidth();
}
@Override
public int clampViewPositionHorizontal(View child, int left, int dx) {
if (checkDrawerViewGravity(child, Gravity.LEFT)) {
return Math.max(-child.getWidth(), Math.min(left, 0));
} else {
final int width = getWidth();
return Math.max(width - child.getWidth(), Math.min(left, width));
}
}
@Override
public int clampViewPositionVertical(View child, int top, int dy) {
return child.getTop();
}
}
public static class LayoutParams extends ViewGroup.MarginLayoutParams {
public int gravity = Gravity.NO_GRAVITY;
float onScreen;
boolean isPeeking;
boolean knownOpen;
public LayoutParams(Context c, AttributeSet attrs) {
super(c, attrs);
final TypedArray a = c.obtainStyledAttributes(attrs, LAYOUT_ATTRS);
this.gravity = a.getInt(0, Gravity.NO_GRAVITY);
a.recycle();
}
public LayoutParams(int width, int height) {
super(width, height);
}
public LayoutParams(int width, int height, int gravity) {
this(width, height);
this.gravity = gravity;
}
public LayoutParams(LayoutParams source) {
super(source);
this.gravity = source.gravity;
}
public LayoutParams(ViewGroup.LayoutParams source) {
super(source);
}
public LayoutParams(ViewGroup.MarginLayoutParams source) {
super(source);
}
}
class AccessibilityDelegate extends AccessibilityDelegateCompat {
private final Rect mTmpRect = new Rect();
@Override
public void onInitializeAccessibilityNodeInfo(View host, AccessibilityNodeInfoCompat info) {
final AccessibilityNodeInfoCompat superNode = AccessibilityNodeInfoCompat.obtain(info);
super.onInitializeAccessibilityNodeInfo(host, superNode);
info.setSource(host);
final ViewParent parent = ViewCompat.getParentForAccessibility(host);
if (parent instanceof View) {
info.setParent((View) parent);
}
copyNodeInfoNoChildren(info, superNode);
superNode.recycle();
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
if (!filter(child)) {
info.addChild(child);
}
}
}
@Override
public boolean onRequestSendAccessibilityEvent(ViewGroup host, View child,
AccessibilityEvent event) {
if (!filter(child)) {
return super.onRequestSendAccessibilityEvent(host, child, event);
}
return false;
}
public boolean filter(View child) {
final View openDrawer = findOpenDrawer();
return openDrawer != null && openDrawer != child;
}
/**
* This should really be in AccessibilityNodeInfoCompat, but there unfortunately
* seem to be a few elements that are not easily cloneable using the underlying API.
* Leave it private here as it's not general-purpose useful.
*/
private void copyNodeInfoNoChildren(AccessibilityNodeInfoCompat dest,
AccessibilityNodeInfoCompat src) {
final Rect rect = mTmpRect;
src.getBoundsInParent(rect);
dest.setBoundsInParent(rect);
src.getBoundsInScreen(rect);
dest.setBoundsInScreen(rect);
dest.setVisibleToUser(src.isVisibleToUser());
dest.setPackageName(src.getPackageName());
dest.setClassName(src.getClassName());
dest.setContentDescription(src.getContentDescription());
dest.setEnabled(src.isEnabled());
dest.setClickable(src.isClickable());
dest.setFocusable(src.isFocusable());
dest.setFocused(src.isFocused());
dest.setAccessibilityFocused(src.isAccessibilityFocused());
dest.setSelected(src.isSelected());
dest.setLongClickable(src.isLongClickable());
dest.addAction(src.getActions());
}
}
}
| true | true | protected void onLayout(boolean changed, int l, int t, int r, int b) {
mInLayout = true;
final int width = r - l;
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
if (child.getVisibility() == GONE) {
continue;
}
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (isContentView(child)) {
child.layout(lp.leftMargin, lp.topMargin,
lp.leftMargin + child.getMeasuredWidth(),
lp.topMargin + child.getMeasuredHeight());
} else { // Drawer, if it wasn't onMeasure would have thrown an exception.
final int childWidth = child.getMeasuredWidth();
final int childHeight = child.getMeasuredHeight();
int childLeft;
final float newOffset;
if (checkDrawerViewGravity(child, Gravity.LEFT)) {
childLeft = -childWidth + (int) (childWidth * lp.onScreen);
newOffset = (float) (childWidth + childLeft) / childWidth;
} else { // Right; onMeasure checked for us.
childLeft = width - (int) (childWidth * lp.onScreen);
newOffset = (float) (width - childLeft) / childWidth;
}
final boolean changeOffset = newOffset != lp.onScreen;
final int vgrav = lp.gravity & Gravity.VERTICAL_GRAVITY_MASK;
switch (vgrav) {
default:
case Gravity.TOP: {
child.layout(childLeft, lp.topMargin, childLeft + childWidth, childHeight);
break;
}
case Gravity.BOTTOM: {
final int height = b - t;
child.layout(childLeft,
height - lp.bottomMargin - child.getMeasuredHeight(),
childLeft + childWidth,
height - lp.bottomMargin);
break;
}
case Gravity.CENTER_VERTICAL: {
final int height = b - t;
int childTop = (height - childHeight) / 2;
// Offset for margins. If things don't fit right because of
// bad measurement before, oh well.
if (childTop < lp.topMargin) {
childTop = lp.topMargin;
} else if (childTop + childHeight > height - lp.bottomMargin) {
childTop = height - lp.bottomMargin - childHeight;
}
child.layout(childLeft, childTop, childLeft + childWidth,
childTop + childHeight);
break;
}
}
if (changeOffset) {
setDrawerViewOffset(child, newOffset);
}
final int newVisibility = lp.onScreen > 0 ? VISIBLE : INVISIBLE;
if (child.getVisibility() != newVisibility) {
child.setVisibility(newVisibility);
}
}
}
mInLayout = false;
mFirstLayout = false;
}
| protected void onLayout(boolean changed, int l, int t, int r, int b) {
mInLayout = true;
final int width = r - l;
final int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
final View child = getChildAt(i);
if (child.getVisibility() == GONE) {
continue;
}
final LayoutParams lp = (LayoutParams) child.getLayoutParams();
if (isContentView(child)) {
child.layout(lp.leftMargin, lp.topMargin,
lp.leftMargin + child.getMeasuredWidth(),
lp.topMargin + child.getMeasuredHeight());
} else { // Drawer, if it wasn't onMeasure would have thrown an exception.
final int childWidth = child.getMeasuredWidth();
final int childHeight = child.getMeasuredHeight();
int childLeft;
final float newOffset;
if (checkDrawerViewGravity(child, Gravity.LEFT)) {
childLeft = -childWidth + (int) (childWidth * lp.onScreen);
newOffset = (float) (childWidth + childLeft) / childWidth;
} else { // Right; onMeasure checked for us.
childLeft = width - (int) (childWidth * lp.onScreen);
newOffset = (float) (width - childLeft) / childWidth;
}
final boolean changeOffset = newOffset != lp.onScreen;
final int vgrav = lp.gravity & Gravity.VERTICAL_GRAVITY_MASK;
switch (vgrav) {
default:
case Gravity.TOP: {
child.layout(childLeft, lp.topMargin, childLeft + childWidth,
lp.topMargin + childHeight);
break;
}
case Gravity.BOTTOM: {
final int height = b - t;
child.layout(childLeft,
height - lp.bottomMargin - child.getMeasuredHeight(),
childLeft + childWidth,
height - lp.bottomMargin);
break;
}
case Gravity.CENTER_VERTICAL: {
final int height = b - t;
int childTop = (height - childHeight) / 2;
// Offset for margins. If things don't fit right because of
// bad measurement before, oh well.
if (childTop < lp.topMargin) {
childTop = lp.topMargin;
} else if (childTop + childHeight > height - lp.bottomMargin) {
childTop = height - lp.bottomMargin - childHeight;
}
child.layout(childLeft, childTop, childLeft + childWidth,
childTop + childHeight);
break;
}
}
if (changeOffset) {
setDrawerViewOffset(child, newOffset);
}
final int newVisibility = lp.onScreen > 0 ? VISIBLE : INVISIBLE;
if (child.getVisibility() != newVisibility) {
child.setVisibility(newVisibility);
}
}
}
mInLayout = false;
mFirstLayout = false;
}
|
diff --git a/errai-cdi/errai-cdi-client/src/main/java/org/jboss/errai/enterprise/client/cdi/CDIClientBootstrap.java b/errai-cdi/errai-cdi-client/src/main/java/org/jboss/errai/enterprise/client/cdi/CDIClientBootstrap.java
index 61d76c45e..f29d9c455 100644
--- a/errai-cdi/errai-cdi-client/src/main/java/org/jboss/errai/enterprise/client/cdi/CDIClientBootstrap.java
+++ b/errai-cdi/errai-cdi-client/src/main/java/org/jboss/errai/enterprise/client/cdi/CDIClientBootstrap.java
@@ -1,124 +1,125 @@
/*
* Copyright 2011 JBoss, by Red Hat, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jboss.errai.enterprise.client.cdi;
import org.jboss.errai.bus.client.ErraiBus;
import org.jboss.errai.bus.client.api.BusErrorCallback;
import org.jboss.errai.bus.client.api.ClientMessageBus;
import org.jboss.errai.bus.client.api.base.MessageBuilder;
import org.jboss.errai.bus.client.api.base.NoSubscribersToDeliverTo;
import org.jboss.errai.bus.client.api.messaging.Message;
import org.jboss.errai.bus.client.api.messaging.MessageCallback;
import org.jboss.errai.bus.client.framework.ClientMessageBusImpl;
import org.jboss.errai.bus.client.util.BusToolsCli;
import org.jboss.errai.common.client.api.extension.InitVotes;
import org.jboss.errai.common.client.protocols.MessageParts;
import org.jboss.errai.common.client.util.LogUtil;
import org.jboss.errai.enterprise.client.cdi.api.CDI;
import org.jboss.errai.enterprise.client.cdi.events.BusReadyEvent;
import com.google.gwt.core.client.EntryPoint;
/**
* The GWT entry point for the Errai CDI module.
*
* @author Mike Brock <[email protected]>
* @author Christian Sadilek <[email protected]>
*/
public class CDIClientBootstrap implements EntryPoint {
static final ClientMessageBusImpl bus = (ClientMessageBusImpl) ErraiBus.get();
final static Runnable initRemoteCdiSubsystem = new Runnable() {
@Override
public void run() {
LogUtil.log("CDI subsystem syncing with server ...");
BusErrorCallback serverDispatchErrorCallback = new BusErrorCallback() {
@Override
public boolean error(Message message, Throwable throwable) {
try {
throw throwable;
}
catch (NoSubscribersToDeliverTo e) {
LogUtil.log("Server did not subscribe to " + CDI.SERVER_DISPATCHER_SUBJECT +
". To activate the full Errai CDI functionality, make sure that Errai's Weld " +
- "integration module has been deployed.");
+ "integration module has been deployed on the server.");
+ CDI.activate();
return false;
}
catch (Throwable t) {
return true;
}
}
};
MessageBuilder.createMessage().toSubject(CDI.SERVER_DISPATCHER_SUBJECT)
.command(CDICommands.AttachRemote)
.errorsHandledBy(serverDispatchErrorCallback)
.sendNowWith(bus);
CDI.fireEvent(new BusReadyEvent());
}
@Override
public String toString() {
return "BusReadyEvent";
}
};
final static Runnable declareServices = new Runnable() {
final ClientMessageBusImpl bus = (ClientMessageBusImpl) ErraiBus.get();
@Override
public void run() {
if (!bus.isSubscribed(CDI.CLIENT_DISPATCHER_SUBJECT)) {
LogUtil.log("declare CDI dispatch service");
bus.subscribe(CDI.CLIENT_DISPATCHER_SUBJECT, new MessageCallback() {
@Override
public void callback(final Message message) {
switch (CDICommands.valueOf(message.getCommandType())) {
case AttachRemote:
CDI.activate(message.get(String.class, MessageParts.RemoteServices).split(","));
break;
case RemoteSubscribe:
CDI.addRemoteEventTypes(message.get(String[].class, MessageParts.Value));
break;
case CDIEvent:
CDI.consumeEventFromMessage(message);
break;
}
}
});
}
}
};
@Override
public void onModuleLoad() {
InitVotes.registerPersistentPreInitCallback(declareServices);
InitVotes.waitFor(CDI.class);
if (BusToolsCli.isRemoteCommunicationEnabled()) {
InitVotes.registerPersistentDependencyCallback(ClientMessageBus.class, initRemoteCdiSubsystem);
}
else {
CDI.activate();
CDI.fireEvent(new BusReadyEvent());
}
}
}
| true | true | public void run() {
LogUtil.log("CDI subsystem syncing with server ...");
BusErrorCallback serverDispatchErrorCallback = new BusErrorCallback() {
@Override
public boolean error(Message message, Throwable throwable) {
try {
throw throwable;
}
catch (NoSubscribersToDeliverTo e) {
LogUtil.log("Server did not subscribe to " + CDI.SERVER_DISPATCHER_SUBJECT +
". To activate the full Errai CDI functionality, make sure that Errai's Weld " +
"integration module has been deployed.");
return false;
}
catch (Throwable t) {
return true;
}
}
};
MessageBuilder.createMessage().toSubject(CDI.SERVER_DISPATCHER_SUBJECT)
.command(CDICommands.AttachRemote)
.errorsHandledBy(serverDispatchErrorCallback)
.sendNowWith(bus);
CDI.fireEvent(new BusReadyEvent());
}
| public void run() {
LogUtil.log("CDI subsystem syncing with server ...");
BusErrorCallback serverDispatchErrorCallback = new BusErrorCallback() {
@Override
public boolean error(Message message, Throwable throwable) {
try {
throw throwable;
}
catch (NoSubscribersToDeliverTo e) {
LogUtil.log("Server did not subscribe to " + CDI.SERVER_DISPATCHER_SUBJECT +
". To activate the full Errai CDI functionality, make sure that Errai's Weld " +
"integration module has been deployed on the server.");
CDI.activate();
return false;
}
catch (Throwable t) {
return true;
}
}
};
MessageBuilder.createMessage().toSubject(CDI.SERVER_DISPATCHER_SUBJECT)
.command(CDICommands.AttachRemote)
.errorsHandledBy(serverDispatchErrorCallback)
.sendNowWith(bus);
CDI.fireEvent(new BusReadyEvent());
}
|
diff --git a/src/rajawali/primitives/Cube.java b/src/rajawali/primitives/Cube.java
index 00a605b3..580772d8 100644
--- a/src/rajawali/primitives/Cube.java
+++ b/src/rajawali/primitives/Cube.java
@@ -1,112 +1,112 @@
package rajawali.primitives;
import rajawali.BaseObject3D;
public class Cube extends BaseObject3D {
private float mSize;
private boolean mIsSkybox;
public Cube(float size) {
super();
mSize = size;
mHasCubemapTexture = false;
init();
}
public Cube(float size, boolean isSkybox) {
super();
mIsSkybox = isSkybox;
mSize = size;
mHasCubemapTexture = true;
init();
}
public Cube(float size, boolean isSkybox, boolean hasCubemapTexture) {
super();
mIsSkybox = isSkybox;
mSize = size;
mHasCubemapTexture = hasCubemapTexture;
init();
}
private void init()
{
float halfSize = mSize * .5f;
float[] vertices = {
halfSize, halfSize, halfSize, -halfSize, halfSize, halfSize, -halfSize,-halfSize, halfSize, halfSize,-halfSize, halfSize, //0-1-halfSize-3 front
halfSize, halfSize, halfSize, halfSize,-halfSize, halfSize, halfSize,-halfSize,-halfSize, halfSize, halfSize,-halfSize,//0-3-4-5 right
halfSize,-halfSize,-halfSize, -halfSize,-halfSize,-halfSize, -halfSize, halfSize,-halfSize, halfSize, halfSize,-halfSize,//4-7-6-5 back
-halfSize, halfSize, halfSize, -halfSize, halfSize,-halfSize, -halfSize,-halfSize,-halfSize, -halfSize,-halfSize, halfSize,//1-6-7-halfSize left
halfSize, halfSize, halfSize, halfSize, halfSize,-halfSize, -halfSize, halfSize,-halfSize, -halfSize, halfSize, halfSize, //top
halfSize,-halfSize, halfSize, -halfSize,-halfSize, halfSize, -halfSize,-halfSize,-halfSize, halfSize,-halfSize,-halfSize,//bottom
};
float t = 1;
float[] textureCoords = {
0, 1, 1, 1, 1, 0, 0, 0, // front
0, 1, 1, 1, 1, 0, 0, 0, // up
0, 1, 1, 1, 1, 0, 0, 0, // back
0, 1, 1, 1, 1, 0, 0, 0, // down
0, 1, 1, 1, 1, 0, 0, 0, // right
0, 1, 1, 1, 1, 0, 0, 0, // left
};
float[] skyboxTextureCoords = {
-t,t,t, t,t,t, t,-t,t, -t,-t,t, // front
t,t,-t, t,-t,-t, t,-t,t, t,t,t, // up
-t,-t,-t, t,-t,-t, t,t,-t, -t,t,-t, // back
-t,t,-t, -t,t,t, -t,-t,t,-t,-t,-t, // down
-t,t,t, -t,t,-t, t,t,-t, t,t,t, // right
-t,-t,t, t,-t,t, t,-t,-t, -t,-t,-t, // left
};
float[] skybox2TextureCoords = {
.25f, .3333f, .5f, .3333f, .5f, .6666f, .25f, .6666f, // front
.25f, .3333f, .25f, .6666f, 0, .6666f, 0, .3333f, // left
1, .6666f, .75f, .6666f, .75f, .3333f, 1, .3333f, // back
.5f, .3333f, .75f, .3333f, .75f, .6666f, .5f, .6666f, // right
.25f, .3333f, .25f, 0, .5f, 0, .5f, .3333f, // up
.25f, .6666f, .5f, .6666f, .5f, 1, .25f, 1 // down
};
if(mIsSkybox && !mHasCubemapTexture)
skyboxTextureCoords = skybox2TextureCoords;
float[] colors = {
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
};
float n = 1;
float[] normals = {
0, 0, n, 0, 0, n, 0, 0, n, 0, 0, n, //front
n, 0, 0, n, 0, 0, n, 0, 0, n, 0, 0, // right
0, 0,-n, 0, 0,-n, 0, 0,-n, 0, 0,-n, //back
-n, 0, 0, -n, 0, 0, -n, 0, 0, -n, 0, 0, // left
0, n, 0, 0, n, 0, 0, n, 0, 0, n, 0, // top
0,-n, 0, 0,-n, 0, 0,-n, 0, 0,-n, 0, // bottom
};
int[] indices = {
0,1,2, 0,2,3,
4,5,6, 4,6,7,
8,9,10, 8,10,11,
12,13,14, 12,14,15,
16,17,18, 16,18,19,
20,21,22, 20,22,23,
};
int[] skyboxIndices = {
2,1,0, 3,2,0,
6,5,4, 7,6,4,
10,9,8, 11, 10, 8,
14, 13, 12, 15, 14, 12,
18, 17, 16, 19, 18, 16,
22, 21, 20, 23, 22, 20
};
- setData(vertices, normals, mIsSkybox ? skyboxTextureCoords : textureCoords, colors, mIsSkybox && mHasCubemapTexture ? skyboxIndices : indices);
+ setData(vertices, normals, mIsSkybox || mHasCubemapTexture ? skyboxTextureCoords : textureCoords, colors, mIsSkybox && mHasCubemapTexture ? skyboxIndices : indices);
}
}
| true | true | private void init()
{
float halfSize = mSize * .5f;
float[] vertices = {
halfSize, halfSize, halfSize, -halfSize, halfSize, halfSize, -halfSize,-halfSize, halfSize, halfSize,-halfSize, halfSize, //0-1-halfSize-3 front
halfSize, halfSize, halfSize, halfSize,-halfSize, halfSize, halfSize,-halfSize,-halfSize, halfSize, halfSize,-halfSize,//0-3-4-5 right
halfSize,-halfSize,-halfSize, -halfSize,-halfSize,-halfSize, -halfSize, halfSize,-halfSize, halfSize, halfSize,-halfSize,//4-7-6-5 back
-halfSize, halfSize, halfSize, -halfSize, halfSize,-halfSize, -halfSize,-halfSize,-halfSize, -halfSize,-halfSize, halfSize,//1-6-7-halfSize left
halfSize, halfSize, halfSize, halfSize, halfSize,-halfSize, -halfSize, halfSize,-halfSize, -halfSize, halfSize, halfSize, //top
halfSize,-halfSize, halfSize, -halfSize,-halfSize, halfSize, -halfSize,-halfSize,-halfSize, halfSize,-halfSize,-halfSize,//bottom
};
float t = 1;
float[] textureCoords = {
0, 1, 1, 1, 1, 0, 0, 0, // front
0, 1, 1, 1, 1, 0, 0, 0, // up
0, 1, 1, 1, 1, 0, 0, 0, // back
0, 1, 1, 1, 1, 0, 0, 0, // down
0, 1, 1, 1, 1, 0, 0, 0, // right
0, 1, 1, 1, 1, 0, 0, 0, // left
};
float[] skyboxTextureCoords = {
-t,t,t, t,t,t, t,-t,t, -t,-t,t, // front
t,t,-t, t,-t,-t, t,-t,t, t,t,t, // up
-t,-t,-t, t,-t,-t, t,t,-t, -t,t,-t, // back
-t,t,-t, -t,t,t, -t,-t,t,-t,-t,-t, // down
-t,t,t, -t,t,-t, t,t,-t, t,t,t, // right
-t,-t,t, t,-t,t, t,-t,-t, -t,-t,-t, // left
};
float[] skybox2TextureCoords = {
.25f, .3333f, .5f, .3333f, .5f, .6666f, .25f, .6666f, // front
.25f, .3333f, .25f, .6666f, 0, .6666f, 0, .3333f, // left
1, .6666f, .75f, .6666f, .75f, .3333f, 1, .3333f, // back
.5f, .3333f, .75f, .3333f, .75f, .6666f, .5f, .6666f, // right
.25f, .3333f, .25f, 0, .5f, 0, .5f, .3333f, // up
.25f, .6666f, .5f, .6666f, .5f, 1, .25f, 1 // down
};
if(mIsSkybox && !mHasCubemapTexture)
skyboxTextureCoords = skybox2TextureCoords;
float[] colors = {
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
};
float n = 1;
float[] normals = {
0, 0, n, 0, 0, n, 0, 0, n, 0, 0, n, //front
n, 0, 0, n, 0, 0, n, 0, 0, n, 0, 0, // right
0, 0,-n, 0, 0,-n, 0, 0,-n, 0, 0,-n, //back
-n, 0, 0, -n, 0, 0, -n, 0, 0, -n, 0, 0, // left
0, n, 0, 0, n, 0, 0, n, 0, 0, n, 0, // top
0,-n, 0, 0,-n, 0, 0,-n, 0, 0,-n, 0, // bottom
};
int[] indices = {
0,1,2, 0,2,3,
4,5,6, 4,6,7,
8,9,10, 8,10,11,
12,13,14, 12,14,15,
16,17,18, 16,18,19,
20,21,22, 20,22,23,
};
int[] skyboxIndices = {
2,1,0, 3,2,0,
6,5,4, 7,6,4,
10,9,8, 11, 10, 8,
14, 13, 12, 15, 14, 12,
18, 17, 16, 19, 18, 16,
22, 21, 20, 23, 22, 20
};
setData(vertices, normals, mIsSkybox ? skyboxTextureCoords : textureCoords, colors, mIsSkybox && mHasCubemapTexture ? skyboxIndices : indices);
}
| private void init()
{
float halfSize = mSize * .5f;
float[] vertices = {
halfSize, halfSize, halfSize, -halfSize, halfSize, halfSize, -halfSize,-halfSize, halfSize, halfSize,-halfSize, halfSize, //0-1-halfSize-3 front
halfSize, halfSize, halfSize, halfSize,-halfSize, halfSize, halfSize,-halfSize,-halfSize, halfSize, halfSize,-halfSize,//0-3-4-5 right
halfSize,-halfSize,-halfSize, -halfSize,-halfSize,-halfSize, -halfSize, halfSize,-halfSize, halfSize, halfSize,-halfSize,//4-7-6-5 back
-halfSize, halfSize, halfSize, -halfSize, halfSize,-halfSize, -halfSize,-halfSize,-halfSize, -halfSize,-halfSize, halfSize,//1-6-7-halfSize left
halfSize, halfSize, halfSize, halfSize, halfSize,-halfSize, -halfSize, halfSize,-halfSize, -halfSize, halfSize, halfSize, //top
halfSize,-halfSize, halfSize, -halfSize,-halfSize, halfSize, -halfSize,-halfSize,-halfSize, halfSize,-halfSize,-halfSize,//bottom
};
float t = 1;
float[] textureCoords = {
0, 1, 1, 1, 1, 0, 0, 0, // front
0, 1, 1, 1, 1, 0, 0, 0, // up
0, 1, 1, 1, 1, 0, 0, 0, // back
0, 1, 1, 1, 1, 0, 0, 0, // down
0, 1, 1, 1, 1, 0, 0, 0, // right
0, 1, 1, 1, 1, 0, 0, 0, // left
};
float[] skyboxTextureCoords = {
-t,t,t, t,t,t, t,-t,t, -t,-t,t, // front
t,t,-t, t,-t,-t, t,-t,t, t,t,t, // up
-t,-t,-t, t,-t,-t, t,t,-t, -t,t,-t, // back
-t,t,-t, -t,t,t, -t,-t,t,-t,-t,-t, // down
-t,t,t, -t,t,-t, t,t,-t, t,t,t, // right
-t,-t,t, t,-t,t, t,-t,-t, -t,-t,-t, // left
};
float[] skybox2TextureCoords = {
.25f, .3333f, .5f, .3333f, .5f, .6666f, .25f, .6666f, // front
.25f, .3333f, .25f, .6666f, 0, .6666f, 0, .3333f, // left
1, .6666f, .75f, .6666f, .75f, .3333f, 1, .3333f, // back
.5f, .3333f, .75f, .3333f, .75f, .6666f, .5f, .6666f, // right
.25f, .3333f, .25f, 0, .5f, 0, .5f, .3333f, // up
.25f, .6666f, .5f, .6666f, .5f, 1, .25f, 1 // down
};
if(mIsSkybox && !mHasCubemapTexture)
skyboxTextureCoords = skybox2TextureCoords;
float[] colors = {
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
};
float n = 1;
float[] normals = {
0, 0, n, 0, 0, n, 0, 0, n, 0, 0, n, //front
n, 0, 0, n, 0, 0, n, 0, 0, n, 0, 0, // right
0, 0,-n, 0, 0,-n, 0, 0,-n, 0, 0,-n, //back
-n, 0, 0, -n, 0, 0, -n, 0, 0, -n, 0, 0, // left
0, n, 0, 0, n, 0, 0, n, 0, 0, n, 0, // top
0,-n, 0, 0,-n, 0, 0,-n, 0, 0,-n, 0, // bottom
};
int[] indices = {
0,1,2, 0,2,3,
4,5,6, 4,6,7,
8,9,10, 8,10,11,
12,13,14, 12,14,15,
16,17,18, 16,18,19,
20,21,22, 20,22,23,
};
int[] skyboxIndices = {
2,1,0, 3,2,0,
6,5,4, 7,6,4,
10,9,8, 11, 10, 8,
14, 13, 12, 15, 14, 12,
18, 17, 16, 19, 18, 16,
22, 21, 20, 23, 22, 20
};
setData(vertices, normals, mIsSkybox || mHasCubemapTexture ? skyboxTextureCoords : textureCoords, colors, mIsSkybox && mHasCubemapTexture ? skyboxIndices : indices);
}
|
diff --git a/src/cc/co/evenprime/bukkit/nocheat/checks/moving/MovingCheckListener.java b/src/cc/co/evenprime/bukkit/nocheat/checks/moving/MovingCheckListener.java
index 8c43935..048288a 100644
--- a/src/cc/co/evenprime/bukkit/nocheat/checks/moving/MovingCheckListener.java
+++ b/src/cc/co/evenprime/bukkit/nocheat/checks/moving/MovingCheckListener.java
@@ -1,344 +1,344 @@
package cc.co.evenprime.bukkit.nocheat.checks.moving;
import java.util.LinkedList;
import java.util.List;
import org.bukkit.Location;
import org.bukkit.block.Block;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.BlockPlaceEvent;
import org.bukkit.event.player.PlayerChangedWorldEvent;
import org.bukkit.event.player.PlayerMoveEvent;
import org.bukkit.event.player.PlayerPortalEvent;
import org.bukkit.event.player.PlayerRespawnEvent;
import org.bukkit.event.player.PlayerTeleportEvent;
import org.bukkit.event.player.PlayerVelocityEvent;
import org.bukkit.util.Vector;
import com.bukkit.gemo.utils.UtilPermissions;
import cc.co.evenprime.bukkit.nocheat.EventManager;
import cc.co.evenprime.bukkit.nocheat.NoCheat;
import cc.co.evenprime.bukkit.nocheat.NoCheatPlayer;
import cc.co.evenprime.bukkit.nocheat.checks.CheckUtil;
import cc.co.evenprime.bukkit.nocheat.config.ConfigurationCacheStore;
import cc.co.evenprime.bukkit.nocheat.config.Permissions;
import cc.co.evenprime.bukkit.nocheat.data.PreciseLocation;
/**
* Central location to listen to events that are relevant for the moving checks
*
*/
public class MovingCheckListener implements Listener, EventManager {
private final MorePacketsCheck morePacketsCheck;
private final FlyingCheck flyingCheck;
private final RunningCheck runningCheck;
private final NoCheat plugin;
public MovingCheckListener(NoCheat plugin) {
flyingCheck = new FlyingCheck(plugin);
runningCheck = new RunningCheck(plugin);
morePacketsCheck = new MorePacketsCheck(plugin);
this.plugin = plugin;
}
/**
* A workaround for players placing blocks below them getting pushed off the
* block by NoCheat.
*
* It essentially moves the "setbackpoint" to the top of the newly placed
* block, therefore tricking NoCheat into thinking the player was already on
* top of that block and should be allowed to stay there
*
* @param event
* The BlockPlaceEvent
*/
@EventHandler(priority = EventPriority.MONITOR)
public void blockPlace(final BlockPlaceEvent event) {
// Block wasn't placed, so we don't care
if (event.isCancelled())
return;
final NoCheatPlayer player = plugin.getPlayer(event.getPlayer());
final MovingConfig config = MovingCheck.getConfig(player);
// If the player is allowed to fly anyway, the workaround is not needed
// It's kind of expensive (looking up block types) therefore it makes
// sense to avoid it
if (config.allowFlying || !config.runflyCheck || UtilPermissions.playerCanUseCommand(event.getPlayer(), Permissions.MOVING_FLYING) || UtilPermissions.playerCanUseCommand(event.getPlayer(), Permissions.MOVING_RUNFLY)) {
return;
}
// Get the player-specific stored data that applies here
final MovingData data = MovingCheck.getData(player);
final Block block = event.getBlockPlaced();
if (block == null || !data.runflySetBackPoint.isSet()) {
return;
}
// Keep some results of "expensive calls
final Location l = player.getPlayer().getLocation();
final int playerX = l.getBlockX();
final int playerY = l.getBlockY();
final int playerZ = l.getBlockZ();
final int blockY = block.getY();
// Was the block below the player?
if (Math.abs(playerX - block.getX()) <= 1 && Math.abs(playerZ - block.getZ()) <= 1 && playerY - blockY >= 0 && playerY - blockY <= 2) {
// yes
final int type = CheckUtil.getType(block.getTypeId());
if (CheckUtil.isSolid(type) || CheckUtil.isLiquid(type)) {
if (blockY + 1 >= data.runflySetBackPoint.y) {
data.runflySetBackPoint.y = (blockY + 1);
data.jumpPhase = 0;
}
}
}
}
/**
* If a player gets teleported, it may have two reasons. Either it was
* NoCheat or another plugin. If it was NoCheat, the target location should
* match the "data.teleportTo" value.
*
* On teleports, reset some movement related data that gets invalid
*
* @param event
* The PlayerTeleportEvent
*/
@EventHandler(priority = EventPriority.HIGHEST)
public void teleport(final PlayerTeleportEvent event) {
NoCheatPlayer player = plugin.getPlayer(event.getPlayer());
final MovingData data = MovingCheck.getData(player);
// If it was a teleport initialized by NoCheat, do it anyway
// even if another plugin said "no"
if (data.teleportTo.isSet() && data.teleportTo.equals(event.getTo())) {
event.setCancelled(false);
} else {
// Only if it wasn't NoCheat, drop data from morepackets check.
// If it was NoCheat, we don't want players to exploit the
// runfly check teleporting to get rid of the "morepackets"
// data.
data.clearMorePacketsData();
}
// Always drop data from runfly check, as it always loses its validity
// after teleports. Always!
data.teleportTo.reset();
data.clearRunFlyData();
return;
}
/**
* Just for security, if a player switches between worlds, reset the runfly
* and morepackets checks data, because it is definitely invalid now
*
* @param event
* The PlayerChangedWorldEvent
*/
@EventHandler(priority = EventPriority.MONITOR)
public void worldChange(final PlayerChangedWorldEvent event) {
// Maybe this helps with people teleporting through multiverse portals
// having problems?
final MovingData data = MovingCheck.getData(plugin.getPlayer(event.getPlayer()));
data.teleportTo.reset();
data.clearRunFlyData();
data.clearMorePacketsData();
}
/**
* When a player uses a portal, all information related to the moving checks
* becomes invalid.
*
* @param event
*/
@EventHandler(priority = EventPriority.MONITOR)
public void portal(final PlayerPortalEvent event) {
final MovingData data = MovingCheck.getData(plugin.getPlayer(event.getPlayer()));
data.clearMorePacketsData();
data.clearRunFlyData();
}
/**
* When a player respawns, all information related to the moving checks
* becomes invalid.
*
* @param event
*/
@EventHandler(priority = EventPriority.MONITOR)
public void respawn(final PlayerRespawnEvent event) {
final MovingData data = MovingCheck.getData(plugin.getPlayer(event.getPlayer()));
data.clearMorePacketsData();
data.clearRunFlyData();
}
/**
* When a player moves, he will be checked for various suspicious behaviour.
*
* @param event
* The PlayerMoveEvent
*/
@EventHandler(priority = EventPriority.LOW)
public void move(final PlayerMoveEvent event) {
// Don't care for vehicles
if (event.isCancelled() || event.getPlayer().isInsideVehicle())
return;
// Don't care for movements that are very high distance or to another
// world (such that it is very likely the event data was modified by
// another plugin before we got it)
if (!event.getFrom().getWorld().equals(event.getTo().getWorld()) || event.getFrom().distanceSquared(event.getTo()) > 400) {
return;
}
final NoCheatPlayer player = plugin.getPlayer(event.getPlayer());
final MovingConfig cc = MovingCheck.getConfig(player);
final MovingData data = MovingCheck.getData(player);
- if (event.getPlayer().getAllowFlight()) {
+ if (event.getPlayer().isOp() || event.getPlayer().getAllowFlight()) {
data.teleportTo.set(event.getTo());
data.to.set(event.getTo());
data.runflySetBackPoint.set(event.getTo());
return;
}
// Advance various counters and values that change per movement
// tick. They are needed to decide on how fast a player may
// move.
tickVelocities(data);
// Remember locations
data.from.set(event.getFrom());
final Location to = event.getTo();
data.to.set(to);
PreciseLocation newTo = null;
/** RUNFLY CHECK SECTION **/
// If the player isn't handled by runfly checks
if (!cc.runflyCheck || event.getPlayer().getAllowFlight()) {
// Just because he is allowed now, doesn't mean he will always
// be. So forget data about the player related to moving
data.clearRunFlyData();
} else if (event.getPlayer().getAllowFlight()) {
// Only do the limited flying check
newTo = flyingCheck.check(player, data, cc);
} else {
// Go for the full treatment
newTo = runningCheck.check(player, data, cc);
}
/** MOREPACKETS CHECK SECTION **/
if (!cc.morePacketsCheck || event.getPlayer().getAllowFlight()) {
data.clearMorePacketsData();
} else if (newTo == null) {
newTo = morePacketsCheck.check(player, data, cc);
}
// Did one of the check(s) decide we need a new "to"-location?
if (newTo != null) {
// Compose a new location based on coordinates of "newTo" and
// viewing direction of "event.getTo()" to allow the player to
// look somewhere else despite getting pulled back by NoCheat
event.setTo(new Location(player.getPlayer().getWorld(), newTo.x, newTo.y, newTo.z, to.getYaw(), to.getPitch()));
// remember where we send the player to
data.teleportTo.set(newTo);
}
}
/**
* Just try to estimate velocities over time Not very precise, but works
* good enough most of the time.
*
* @param data
*/
private void tickVelocities(MovingData data) {
/******** DO GENERAL DATA MODIFICATIONS ONCE FOR EACH EVENT *****/
if (data.horizVelocityCounter > 0) {
data.horizVelocityCounter--;
} else if (data.horizFreedom > 0.001) {
data.horizFreedom *= 0.90;
}
if (data.vertVelocity <= 0.1) {
data.vertVelocityCounter--;
}
if (data.vertVelocityCounter > 0) {
data.vertFreedom += data.vertVelocity;
data.vertVelocity *= 0.90;
} else if (data.vertFreedom > 0.001) {
// Counter has run out, now reduce the vert freedom over time
data.vertFreedom *= 0.93;
}
}
/**
* Player got a velocity packet. The server can't keep track of actual
* velocity values (by design), so we have to try and do that ourselves.
* Very rough estimates.
*
* @param event
* The PlayerVelocityEvent
*/
@EventHandler(priority = EventPriority.MONITOR)
public void velocity(final PlayerVelocityEvent event) {
if (event.isCancelled())
return;
final MovingData data = MovingCheck.getData(plugin.getPlayer(event.getPlayer()));
final Vector v = event.getVelocity();
double newVal = v.getY();
if (newVal >= 0.0D) {
data.vertVelocity += newVal;
data.vertFreedom += data.vertVelocity;
}
data.vertVelocityCounter = 50;
newVal = Math.sqrt(Math.pow(v.getX(), 2) + Math.pow(v.getZ(), 2));
if (newVal > 0.0D) {
data.horizFreedom += newVal;
data.horizVelocityCounter = 30;
}
}
public List<String> getActiveChecks(ConfigurationCacheStore cc) {
LinkedList<String> s = new LinkedList<String>();
MovingConfig m = MovingCheck.getConfig(cc);
if (m.runflyCheck) {
if (!m.allowFlying) {
s.add("moving.runfly");
if (m.sneakingCheck)
s.add("moving.sneaking");
if (m.nofallCheck)
s.add("moving.nofall");
} else
s.add("moving.flying");
}
if (m.morePacketsCheck)
s.add("moving.morepackets");
return s;
}
}
| true | true | public void move(final PlayerMoveEvent event) {
// Don't care for vehicles
if (event.isCancelled() || event.getPlayer().isInsideVehicle())
return;
// Don't care for movements that are very high distance or to another
// world (such that it is very likely the event data was modified by
// another plugin before we got it)
if (!event.getFrom().getWorld().equals(event.getTo().getWorld()) || event.getFrom().distanceSquared(event.getTo()) > 400) {
return;
}
final NoCheatPlayer player = plugin.getPlayer(event.getPlayer());
final MovingConfig cc = MovingCheck.getConfig(player);
final MovingData data = MovingCheck.getData(player);
if (event.getPlayer().getAllowFlight()) {
data.teleportTo.set(event.getTo());
data.to.set(event.getTo());
data.runflySetBackPoint.set(event.getTo());
return;
}
// Advance various counters and values that change per movement
// tick. They are needed to decide on how fast a player may
// move.
tickVelocities(data);
// Remember locations
data.from.set(event.getFrom());
final Location to = event.getTo();
data.to.set(to);
PreciseLocation newTo = null;
/** RUNFLY CHECK SECTION **/
// If the player isn't handled by runfly checks
if (!cc.runflyCheck || event.getPlayer().getAllowFlight()) {
// Just because he is allowed now, doesn't mean he will always
// be. So forget data about the player related to moving
data.clearRunFlyData();
} else if (event.getPlayer().getAllowFlight()) {
// Only do the limited flying check
newTo = flyingCheck.check(player, data, cc);
} else {
// Go for the full treatment
newTo = runningCheck.check(player, data, cc);
}
/** MOREPACKETS CHECK SECTION **/
if (!cc.morePacketsCheck || event.getPlayer().getAllowFlight()) {
data.clearMorePacketsData();
} else if (newTo == null) {
newTo = morePacketsCheck.check(player, data, cc);
}
// Did one of the check(s) decide we need a new "to"-location?
if (newTo != null) {
// Compose a new location based on coordinates of "newTo" and
// viewing direction of "event.getTo()" to allow the player to
// look somewhere else despite getting pulled back by NoCheat
event.setTo(new Location(player.getPlayer().getWorld(), newTo.x, newTo.y, newTo.z, to.getYaw(), to.getPitch()));
// remember where we send the player to
data.teleportTo.set(newTo);
}
}
| public void move(final PlayerMoveEvent event) {
// Don't care for vehicles
if (event.isCancelled() || event.getPlayer().isInsideVehicle())
return;
// Don't care for movements that are very high distance or to another
// world (such that it is very likely the event data was modified by
// another plugin before we got it)
if (!event.getFrom().getWorld().equals(event.getTo().getWorld()) || event.getFrom().distanceSquared(event.getTo()) > 400) {
return;
}
final NoCheatPlayer player = plugin.getPlayer(event.getPlayer());
final MovingConfig cc = MovingCheck.getConfig(player);
final MovingData data = MovingCheck.getData(player);
if (event.getPlayer().isOp() || event.getPlayer().getAllowFlight()) {
data.teleportTo.set(event.getTo());
data.to.set(event.getTo());
data.runflySetBackPoint.set(event.getTo());
return;
}
// Advance various counters and values that change per movement
// tick. They are needed to decide on how fast a player may
// move.
tickVelocities(data);
// Remember locations
data.from.set(event.getFrom());
final Location to = event.getTo();
data.to.set(to);
PreciseLocation newTo = null;
/** RUNFLY CHECK SECTION **/
// If the player isn't handled by runfly checks
if (!cc.runflyCheck || event.getPlayer().getAllowFlight()) {
// Just because he is allowed now, doesn't mean he will always
// be. So forget data about the player related to moving
data.clearRunFlyData();
} else if (event.getPlayer().getAllowFlight()) {
// Only do the limited flying check
newTo = flyingCheck.check(player, data, cc);
} else {
// Go for the full treatment
newTo = runningCheck.check(player, data, cc);
}
/** MOREPACKETS CHECK SECTION **/
if (!cc.morePacketsCheck || event.getPlayer().getAllowFlight()) {
data.clearMorePacketsData();
} else if (newTo == null) {
newTo = morePacketsCheck.check(player, data, cc);
}
// Did one of the check(s) decide we need a new "to"-location?
if (newTo != null) {
// Compose a new location based on coordinates of "newTo" and
// viewing direction of "event.getTo()" to allow the player to
// look somewhere else despite getting pulled back by NoCheat
event.setTo(new Location(player.getPlayer().getWorld(), newTo.x, newTo.y, newTo.z, to.getYaw(), to.getPitch()));
// remember where we send the player to
data.teleportTo.set(newTo);
}
}
|
diff --git a/src/main/ed/appserver/jxp/Parser.java b/src/main/ed/appserver/jxp/Parser.java
index aa9a2e6b0..5287497ab 100644
--- a/src/main/ed/appserver/jxp/Parser.java
+++ b/src/main/ed/appserver/jxp/Parser.java
@@ -1,182 +1,184 @@
// Parser.java
package ed.appserver.jxp;
import java.io.*;
import java.util.*;
import ed.io.*;
import ed.util.*;
public class Parser {
static List<Block> parse( JxpSource s )
throws IOException {
String data = s.getContent();
int lastline = 1;
int line = 1;
final boolean isTemplate = s.getName().endsWith( ".html" );
Block.Type curType = s.getName().endsWith( ".jxp" ) || s.getName().endsWith( ".html" ) ? Block.Type.HTML : Block.Type.CODE;
StringBuilder buf = new StringBuilder();
boolean newLine = true;
char lastChar = '\n';
char codeOpening = ' ';
int numBrackets = 0;
List<Block> blocks = new ArrayList<Block>();
if ( isTemplate )
blocks.add( Block.create( Block.Type.CODE , "var obj = arguments[0];\n" , -1 ) );
for ( int i=0; i<data.length(); i++ ){
lastChar = i == 0 ? '\n' : data.charAt( i - 1 );
char c = data.charAt( i );
if ( c == '\n' )
line++;
newLine = lastChar == '\n';
if ( curType == Block.Type.WIKI && data.startsWith( "</wiki>" , i ) ){
blocks.add( Block.create( curType , buf.toString() , lastline ) );
buf.setLength( 0 );
lastline = line;
curType = Block.Type.HTML;
i += 6;
continue;
}
if ( curType == Block.Type.HTML ){
if ( data.startsWith( "<wiki>" , i ) ){
blocks.add( Block.create( curType , buf.toString() , lastline ) );
buf.setLength( 0 );
lastline = line;
curType = Block.Type.WIKI;
i += 5;
continue;
}
if ( isTemplate && c == '$' ){
blocks.add( Block.create( curType , buf.toString() , lastline ) );
buf.setLength( 0 );
i++;
int end = i;
int parens = 0;
for ( ; end < data.length(); end ++ ){
char temp = data.charAt( end );
if ( temp == '(' ){
parens++;
continue;
}
if ( temp == ')' ){
parens--;
continue;
}
if ( ( Character.isWhitespace( temp )
- || ! ( Character.isLetterOrDigit( temp ) || temp == '_' )
+ || ! ( Character.isLetterOrDigit( temp )
+ || temp == '.'
+ || temp == '_' )
|| temp == '\''
|| temp == '"'
|| temp == '>'
|| temp == '<' )
&& parens == 0 )
break;
}
blocks.add( Block.create( Block.Type.OUTPUT , "obj." + data.substring( i , end ) , lastline ) );
i = end - 1;
curType = Block.Type.HTML;
continue;
}
if (
( newLine && c == '{' )
||
( c == '<' &&
i + 1 < data.length() &&
data.charAt( i + 1 ) == '%' )
) {
codeOpening = c;
numBrackets = 0;
blocks.add( Block.create( curType , buf.toString() , lastline ) );
buf.setLength( 0 );
lastline = line;
curType = Block.Type.CODE;
if ( c == '<' )
i++;
if ( i + 1 < data.length() &&
data.charAt( i + 1 ) == '=' ){
i++;
curType = Block.Type.OUTPUT;
}
continue;
}
}
if ( curType == Block.Type.CODE ||
curType == Block.Type.OUTPUT ){
if ( c == '"' ){
buf.append( c );
i++;
for ( ; i<data.length(); i++ ){
c = data.charAt( i );
buf.append( c );
if ( c == '"' )
break;
}
continue;
}
if ( ( numBrackets == 0 && codeOpening == '{' && c == '}' )
||
( codeOpening == '<' &&
c == '%' &&
i + 1 < data.length() &&
data.charAt( i + 1 ) == '>' )
) {
blocks.add( Block.create( curType , buf.toString() , lastline ) );
lastline = line;
buf.setLength( 0 );
if ( codeOpening == '<' )
i++;
curType = Block.Type.HTML;
continue;
}
if ( codeOpening == '{' ){
if ( c == '}' && numBrackets > 0 )
numBrackets --;
if ( c == '{' )
numBrackets++;
}
}
buf.append( c );
}
blocks.add( Block.create( curType , buf.toString() , lastline ) );
return blocks;
}
public static void main( String args[] )
throws Exception {
System.out.println( parse( JxpSource.getSource( new File( "crap/www/index.jxp" ) ) ) );
}
}
| true | true | static List<Block> parse( JxpSource s )
throws IOException {
String data = s.getContent();
int lastline = 1;
int line = 1;
final boolean isTemplate = s.getName().endsWith( ".html" );
Block.Type curType = s.getName().endsWith( ".jxp" ) || s.getName().endsWith( ".html" ) ? Block.Type.HTML : Block.Type.CODE;
StringBuilder buf = new StringBuilder();
boolean newLine = true;
char lastChar = '\n';
char codeOpening = ' ';
int numBrackets = 0;
List<Block> blocks = new ArrayList<Block>();
if ( isTemplate )
blocks.add( Block.create( Block.Type.CODE , "var obj = arguments[0];\n" , -1 ) );
for ( int i=0; i<data.length(); i++ ){
lastChar = i == 0 ? '\n' : data.charAt( i - 1 );
char c = data.charAt( i );
if ( c == '\n' )
line++;
newLine = lastChar == '\n';
if ( curType == Block.Type.WIKI && data.startsWith( "</wiki>" , i ) ){
blocks.add( Block.create( curType , buf.toString() , lastline ) );
buf.setLength( 0 );
lastline = line;
curType = Block.Type.HTML;
i += 6;
continue;
}
if ( curType == Block.Type.HTML ){
if ( data.startsWith( "<wiki>" , i ) ){
blocks.add( Block.create( curType , buf.toString() , lastline ) );
buf.setLength( 0 );
lastline = line;
curType = Block.Type.WIKI;
i += 5;
continue;
}
if ( isTemplate && c == '$' ){
blocks.add( Block.create( curType , buf.toString() , lastline ) );
buf.setLength( 0 );
i++;
int end = i;
int parens = 0;
for ( ; end < data.length(); end ++ ){
char temp = data.charAt( end );
if ( temp == '(' ){
parens++;
continue;
}
if ( temp == ')' ){
parens--;
continue;
}
if ( ( Character.isWhitespace( temp )
|| ! ( Character.isLetterOrDigit( temp ) || temp == '_' )
|| temp == '\''
|| temp == '"'
|| temp == '>'
|| temp == '<' )
&& parens == 0 )
break;
}
blocks.add( Block.create( Block.Type.OUTPUT , "obj." + data.substring( i , end ) , lastline ) );
i = end - 1;
curType = Block.Type.HTML;
continue;
}
if (
( newLine && c == '{' )
||
( c == '<' &&
i + 1 < data.length() &&
data.charAt( i + 1 ) == '%' )
) {
codeOpening = c;
numBrackets = 0;
blocks.add( Block.create( curType , buf.toString() , lastline ) );
buf.setLength( 0 );
lastline = line;
curType = Block.Type.CODE;
if ( c == '<' )
i++;
if ( i + 1 < data.length() &&
data.charAt( i + 1 ) == '=' ){
i++;
curType = Block.Type.OUTPUT;
}
continue;
}
}
if ( curType == Block.Type.CODE ||
curType == Block.Type.OUTPUT ){
if ( c == '"' ){
buf.append( c );
i++;
for ( ; i<data.length(); i++ ){
c = data.charAt( i );
buf.append( c );
if ( c == '"' )
break;
}
continue;
}
if ( ( numBrackets == 0 && codeOpening == '{' && c == '}' )
||
( codeOpening == '<' &&
c == '%' &&
i + 1 < data.length() &&
data.charAt( i + 1 ) == '>' )
) {
blocks.add( Block.create( curType , buf.toString() , lastline ) );
lastline = line;
buf.setLength( 0 );
if ( codeOpening == '<' )
i++;
curType = Block.Type.HTML;
continue;
}
if ( codeOpening == '{' ){
if ( c == '}' && numBrackets > 0 )
numBrackets --;
if ( c == '{' )
numBrackets++;
}
}
buf.append( c );
}
blocks.add( Block.create( curType , buf.toString() , lastline ) );
return blocks;
}
| static List<Block> parse( JxpSource s )
throws IOException {
String data = s.getContent();
int lastline = 1;
int line = 1;
final boolean isTemplate = s.getName().endsWith( ".html" );
Block.Type curType = s.getName().endsWith( ".jxp" ) || s.getName().endsWith( ".html" ) ? Block.Type.HTML : Block.Type.CODE;
StringBuilder buf = new StringBuilder();
boolean newLine = true;
char lastChar = '\n';
char codeOpening = ' ';
int numBrackets = 0;
List<Block> blocks = new ArrayList<Block>();
if ( isTemplate )
blocks.add( Block.create( Block.Type.CODE , "var obj = arguments[0];\n" , -1 ) );
for ( int i=0; i<data.length(); i++ ){
lastChar = i == 0 ? '\n' : data.charAt( i - 1 );
char c = data.charAt( i );
if ( c == '\n' )
line++;
newLine = lastChar == '\n';
if ( curType == Block.Type.WIKI && data.startsWith( "</wiki>" , i ) ){
blocks.add( Block.create( curType , buf.toString() , lastline ) );
buf.setLength( 0 );
lastline = line;
curType = Block.Type.HTML;
i += 6;
continue;
}
if ( curType == Block.Type.HTML ){
if ( data.startsWith( "<wiki>" , i ) ){
blocks.add( Block.create( curType , buf.toString() , lastline ) );
buf.setLength( 0 );
lastline = line;
curType = Block.Type.WIKI;
i += 5;
continue;
}
if ( isTemplate && c == '$' ){
blocks.add( Block.create( curType , buf.toString() , lastline ) );
buf.setLength( 0 );
i++;
int end = i;
int parens = 0;
for ( ; end < data.length(); end ++ ){
char temp = data.charAt( end );
if ( temp == '(' ){
parens++;
continue;
}
if ( temp == ')' ){
parens--;
continue;
}
if ( ( Character.isWhitespace( temp )
|| ! ( Character.isLetterOrDigit( temp )
|| temp == '.'
|| temp == '_' )
|| temp == '\''
|| temp == '"'
|| temp == '>'
|| temp == '<' )
&& parens == 0 )
break;
}
blocks.add( Block.create( Block.Type.OUTPUT , "obj." + data.substring( i , end ) , lastline ) );
i = end - 1;
curType = Block.Type.HTML;
continue;
}
if (
( newLine && c == '{' )
||
( c == '<' &&
i + 1 < data.length() &&
data.charAt( i + 1 ) == '%' )
) {
codeOpening = c;
numBrackets = 0;
blocks.add( Block.create( curType , buf.toString() , lastline ) );
buf.setLength( 0 );
lastline = line;
curType = Block.Type.CODE;
if ( c == '<' )
i++;
if ( i + 1 < data.length() &&
data.charAt( i + 1 ) == '=' ){
i++;
curType = Block.Type.OUTPUT;
}
continue;
}
}
if ( curType == Block.Type.CODE ||
curType == Block.Type.OUTPUT ){
if ( c == '"' ){
buf.append( c );
i++;
for ( ; i<data.length(); i++ ){
c = data.charAt( i );
buf.append( c );
if ( c == '"' )
break;
}
continue;
}
if ( ( numBrackets == 0 && codeOpening == '{' && c == '}' )
||
( codeOpening == '<' &&
c == '%' &&
i + 1 < data.length() &&
data.charAt( i + 1 ) == '>' )
) {
blocks.add( Block.create( curType , buf.toString() , lastline ) );
lastline = line;
buf.setLength( 0 );
if ( codeOpening == '<' )
i++;
curType = Block.Type.HTML;
continue;
}
if ( codeOpening == '{' ){
if ( c == '}' && numBrackets > 0 )
numBrackets --;
if ( c == '{' )
numBrackets++;
}
}
buf.append( c );
}
blocks.add( Block.create( curType , buf.toString() , lastline ) );
return blocks;
}
|
diff --git a/src/com/trendrr/oss/networking/strest/StrestSynchronousRequest.java b/src/com/trendrr/oss/networking/strest/StrestSynchronousRequest.java
index 55b7284..b85e51b 100644
--- a/src/com/trendrr/oss/networking/strest/StrestSynchronousRequest.java
+++ b/src/com/trendrr/oss/networking/strest/StrestSynchronousRequest.java
@@ -1,89 +1,89 @@
/**
*
*/
package com.trendrr.oss.networking.strest;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.trendrr.oss.exceptions.TrendrrTimeoutException;
/**
*
* Allows us to do synchronous requests
*
* @author Dustin Norlander
* @created Mar 15, 2011
*
*/
class StrestSynchronousRequest implements StrestRequestCallback{
protected static Log log = LogFactory.getLog(StrestSynchronousRequest.class);
Semaphore lock = new Semaphore(1, true);
StrestResponse response;
Throwable error;
public StrestSynchronousRequest() {
try {
//take the only semaphore
lock.acquire(1);
} catch (InterruptedException e) {
log.error("Caught", e);
}
}
public StrestResponse awaitResponse(long timeoutMillis) throws Throwable {
try {
//try to aquire a semaphore, none is available so we wait.
- if (timeoutMillis > 0) {
+ if (timeoutMillis <= 0) {
lock.acquire(1);
} else {
if (!lock.tryAcquire(timeoutMillis, TimeUnit.MILLISECONDS)) {
throw new TrendrrTimeoutException("Waited for " + timeoutMillis + " millis for a response");
}
}
} catch (InterruptedException e) {
log.error("Caught", e);
throw e;
}
if (this.error != null) {
throw this.error;
}
return this.response;
}
/* (non-Javadoc)
* @see com.trendrr.oss.networking.strest.StrestCallback#messageRecieved(com.trendrr.oss.networking.strest.StrestResponse)
*/
@Override
public void response(StrestResponse response) {
this.response = response;
//release the single semaphore.
lock.release(1);
}
/* (non-Javadoc)
* @see com.trendrr.oss.networking.strest.StrestCallback#txnComplete()
*/
@Override
public void txnComplete(String txnId) {
//do nothing. txn should always be complete!
}
/* (non-Javadoc)
* @see com.trendrr.oss.networking.strest.StrestCallback#error(java.lang.Throwable)
*/
@Override
public void error(Throwable x) {
this.error = x;
//release the single semaphore.
lock.release(1);
}
}
| true | true | public StrestResponse awaitResponse(long timeoutMillis) throws Throwable {
try {
//try to aquire a semaphore, none is available so we wait.
if (timeoutMillis > 0) {
lock.acquire(1);
} else {
if (!lock.tryAcquire(timeoutMillis, TimeUnit.MILLISECONDS)) {
throw new TrendrrTimeoutException("Waited for " + timeoutMillis + " millis for a response");
}
}
} catch (InterruptedException e) {
log.error("Caught", e);
throw e;
}
if (this.error != null) {
throw this.error;
}
return this.response;
}
| public StrestResponse awaitResponse(long timeoutMillis) throws Throwable {
try {
//try to aquire a semaphore, none is available so we wait.
if (timeoutMillis <= 0) {
lock.acquire(1);
} else {
if (!lock.tryAcquire(timeoutMillis, TimeUnit.MILLISECONDS)) {
throw new TrendrrTimeoutException("Waited for " + timeoutMillis + " millis for a response");
}
}
} catch (InterruptedException e) {
log.error("Caught", e);
throw e;
}
if (this.error != null) {
throw this.error;
}
return this.response;
}
|
diff --git a/bpm/bonita-bpm-integration-tests/bonita-integration-local-tests/src/main/java/org/bonitasoft/engine/TestShades.java b/bpm/bonita-bpm-integration-tests/bonita-integration-local-tests/src/main/java/org/bonitasoft/engine/TestShades.java
index cf9d6fd5fa..1c70d8cda6 100644
--- a/bpm/bonita-bpm-integration-tests/bonita-integration-local-tests/src/main/java/org/bonitasoft/engine/TestShades.java
+++ b/bpm/bonita-bpm-integration-tests/bonita-integration-local-tests/src/main/java/org/bonitasoft/engine/TestShades.java
@@ -1,91 +1,92 @@
package org.bonitasoft.engine;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.bonitasoft.engine.io.IOUtil;
import org.junit.Test;
public class TestShades {
@Test
public void testShades() throws IOException {
String version = System.getProperty("bonita.version");// works in maven
if (version == null) {
// when running tests in eclipse get it from the pom.xml
File file = new File("pom.xml");
String pomContent = IOUtil.read(file);
Pattern pattern = Pattern.compile("<version>(.*)</version>");
Matcher matcher = pattern.matcher(pomContent);
matcher.find();
version = matcher.group(1);
}
String thePom = getPom(version);
File file = new File("shadeTester");
file.mkdir();
String outputOfMaven;
try {
File file2 = new File(file, "pom.xml");
IOUtil.write(file2, thePom);
System.out.println("building " + file2.getAbsolutePath());
+ System.out.println("Run mvn in " + file.getAbsolutePath());
Process exec = Runtime.getRuntime().exec("mvn dependency:tree", new String[] {}, file);
InputStream inputStream = exec.getInputStream();
exec.getOutputStream().close();
exec.getErrorStream().close();
outputOfMaven = IOUtil.read(inputStream);
System.out.println(outputOfMaven);
} finally {
- IOUtil.deleteDir(file);
+ // IOUtil.deleteDir(file);
}
assertTrue("build was not successfull", outputOfMaven.contains("BUILD SUCCESS"));
outputOfMaven = outputOfMaven.replaceAll("bonitasoft.engine:bonita-server", "");
outputOfMaven = outputOfMaven.replaceAll("bonitasoft.engine:bonita-client", "");
outputOfMaven = outputOfMaven.replaceAll("bonitasoft.engine:bonita-common", "");
if (outputOfMaven.contains("bonitasoft")) {
String str = "bonitasoft";
int indexOf = outputOfMaven.indexOf(str);
String part1 = outputOfMaven.substring(indexOf - 50, indexOf - 1);
String part2 = outputOfMaven.substring(indexOf - 1, indexOf + str.length());
String part3 = outputOfMaven.substring(indexOf + str.length(), indexOf + str.length() + 50);
fail("the dependency tree contains other modules than server/client/common: \"" + part1 + " =====>>>>>" + part2 + " <<<<<=====" + part3);
}
}
private String getPom(final String version) {
String pom = "<project xmlns=\"http://maven.apache.org/POM/4.0.0\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n";
pom += " xsi:schemaLocation=\"http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n";
pom += "<modelVersion>4.0.0</modelVersion>\n";
pom += "<groupId>test</groupId>\n";
pom += "<artifactId>shadeTester</artifactId>\n";
pom += "<version>0.0.1-SNAPSHOT</version>\n";
pom += "<dependencies>\n";
pom += generateDependencies(version);
pom += " </dependencies>\n";
pom += "</project> \n";
return pom;
}
protected String generateDependencies(final String version) {
String pom2 = generateDependency("bonita-server", "org.bonitasoft.engine", version);
pom2 += generateDependency("bonita-client", "org.bonitasoft.engine", version);
return pom2;
}
protected String generateDependency(final String artifactId, final String groupId, final String version) {
String dep = "<dependency>\n";
dep += "<artifactId>" + artifactId + "</artifactId>\n";
dep += "<groupId>" + groupId + "</groupId>\n";
dep += "<version>" + version + "</version>\n";
dep += "</dependency>\n";
return dep;
}
}
| false | true | public void testShades() throws IOException {
String version = System.getProperty("bonita.version");// works in maven
if (version == null) {
// when running tests in eclipse get it from the pom.xml
File file = new File("pom.xml");
String pomContent = IOUtil.read(file);
Pattern pattern = Pattern.compile("<version>(.*)</version>");
Matcher matcher = pattern.matcher(pomContent);
matcher.find();
version = matcher.group(1);
}
String thePom = getPom(version);
File file = new File("shadeTester");
file.mkdir();
String outputOfMaven;
try {
File file2 = new File(file, "pom.xml");
IOUtil.write(file2, thePom);
System.out.println("building " + file2.getAbsolutePath());
Process exec = Runtime.getRuntime().exec("mvn dependency:tree", new String[] {}, file);
InputStream inputStream = exec.getInputStream();
exec.getOutputStream().close();
exec.getErrorStream().close();
outputOfMaven = IOUtil.read(inputStream);
System.out.println(outputOfMaven);
} finally {
IOUtil.deleteDir(file);
}
assertTrue("build was not successfull", outputOfMaven.contains("BUILD SUCCESS"));
outputOfMaven = outputOfMaven.replaceAll("bonitasoft.engine:bonita-server", "");
outputOfMaven = outputOfMaven.replaceAll("bonitasoft.engine:bonita-client", "");
outputOfMaven = outputOfMaven.replaceAll("bonitasoft.engine:bonita-common", "");
if (outputOfMaven.contains("bonitasoft")) {
String str = "bonitasoft";
int indexOf = outputOfMaven.indexOf(str);
String part1 = outputOfMaven.substring(indexOf - 50, indexOf - 1);
String part2 = outputOfMaven.substring(indexOf - 1, indexOf + str.length());
String part3 = outputOfMaven.substring(indexOf + str.length(), indexOf + str.length() + 50);
fail("the dependency tree contains other modules than server/client/common: \"" + part1 + " =====>>>>>" + part2 + " <<<<<=====" + part3);
}
}
| public void testShades() throws IOException {
String version = System.getProperty("bonita.version");// works in maven
if (version == null) {
// when running tests in eclipse get it from the pom.xml
File file = new File("pom.xml");
String pomContent = IOUtil.read(file);
Pattern pattern = Pattern.compile("<version>(.*)</version>");
Matcher matcher = pattern.matcher(pomContent);
matcher.find();
version = matcher.group(1);
}
String thePom = getPom(version);
File file = new File("shadeTester");
file.mkdir();
String outputOfMaven;
try {
File file2 = new File(file, "pom.xml");
IOUtil.write(file2, thePom);
System.out.println("building " + file2.getAbsolutePath());
System.out.println("Run mvn in " + file.getAbsolutePath());
Process exec = Runtime.getRuntime().exec("mvn dependency:tree", new String[] {}, file);
InputStream inputStream = exec.getInputStream();
exec.getOutputStream().close();
exec.getErrorStream().close();
outputOfMaven = IOUtil.read(inputStream);
System.out.println(outputOfMaven);
} finally {
// IOUtil.deleteDir(file);
}
assertTrue("build was not successfull", outputOfMaven.contains("BUILD SUCCESS"));
outputOfMaven = outputOfMaven.replaceAll("bonitasoft.engine:bonita-server", "");
outputOfMaven = outputOfMaven.replaceAll("bonitasoft.engine:bonita-client", "");
outputOfMaven = outputOfMaven.replaceAll("bonitasoft.engine:bonita-common", "");
if (outputOfMaven.contains("bonitasoft")) {
String str = "bonitasoft";
int indexOf = outputOfMaven.indexOf(str);
String part1 = outputOfMaven.substring(indexOf - 50, indexOf - 1);
String part2 = outputOfMaven.substring(indexOf - 1, indexOf + str.length());
String part3 = outputOfMaven.substring(indexOf + str.length(), indexOf + str.length() + 50);
fail("the dependency tree contains other modules than server/client/common: \"" + part1 + " =====>>>>>" + part2 + " <<<<<=====" + part3);
}
}
|
diff --git a/src/main/java/com/in6k/mypal/controller/TransactionController.java b/src/main/java/com/in6k/mypal/controller/TransactionController.java
index 7823cf4..6ebf4d2 100644
--- a/src/main/java/com/in6k/mypal/controller/TransactionController.java
+++ b/src/main/java/com/in6k/mypal/controller/TransactionController.java
@@ -1,177 +1,177 @@
package com.in6k.mypal.controller;
import com.in6k.mypal.dao.TransactionDao;
import com.in6k.mypal.dao.UserDao;
import com.in6k.mypal.domain.Transaction;
import com.in6k.mypal.domain.User;
import com.in6k.mypal.service.CreditCard.IncreaseBalanсe;
import com.in6k.mypal.service.CreditCard.ValidCreditCard;
import com.in6k.mypal.service.Inviter;
import com.in6k.mypal.service.SessionValidService;
import com.in6k.mypal.service.TransactionValidator;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Collection;
import java.util.List;
@Controller
@RequestMapping(value = "/transaction")
public class TransactionController {
@RequestMapping(value = "/create", method = RequestMethod.GET)
public String creationForm(ModelMap model, HttpServletRequest request) {
HttpSession session = request.getSession();
User userSession = (User) session.getAttribute("LoggedUser");
if (userSession == null) {
return "redirect:/login";
}
model.addAttribute("sess", userSession);
model.addAttribute("balance", UserDao.getBalance(userSession));
return "transaction/create";
}
@RequestMapping(value = "/create", method = RequestMethod.POST)
public String create(HttpServletRequest request, ModelMap model) throws IOException {
TransactionValidator transactionValidator = new TransactionValidator();
HttpSession session = request.getSession();
User userSession = (User) session.getAttribute("LoggedUser");
transactionValidator.setCredit(userSession);
User debitUser = UserDao.getByEmail(request.getParameter("debit"));
transactionValidator.setDebit(debitUser);
transactionValidator.setInputSum(request.getParameter("sum"));
if (UserDao.getBalance(userSession) > Double.parseDouble(request.getParameter("sum")) && debitUser == null) {
Inviter.sendEmail(userSession.getFirstName(), request.getParameter("debit"), Integer.parseInt(request.getParameter("sum")));
}
if (transactionValidator.validate().size() == 0) {
Transaction transaction = new Transaction();
transaction.setDebit(transactionValidator.getDebit());
transaction.setCredit(transactionValidator.getCredit());
transaction.setSum(transactionValidator.getSum());
TransactionDao.create(transaction);
- return "transaction/create";
+ return "redirect:/transaction/create";
}
- return "transaction/create";
+ return "redirect:/transaction/create";
}
@RequestMapping(value = "/history")
public String history(ModelMap model, HttpServletRequest request) throws IOException, SQLException {
HttpSession session = request.getSession();
User userSession = (User) session.getAttribute("LoggedUser");
if (userSession == null) {
return "redirect:/login";
}
model.addAttribute("sess", userSession);
model.addAttribute("balance", UserDao.getBalance(userSession));
model.addAttribute("transactions", TransactionDao.findAllForUser(userSession));
return "transaction/list";
}
@RequestMapping(value = "/list")
public String list(ModelMap model, HttpServletRequest request) throws IOException, SQLException {
HttpSession session = request.getSession();
User userSession = (User) session.getAttribute("LoggedUser");
if (userSession == null) {
return "redirect:/login";
}
model.addAttribute("sess", userSession);
//model.addAttribute("transactions", TransactionDao.list());
model.addAttribute("transactions", TransactionDao.list());
return "transaction/list";
}
@RequestMapping(value = "/delete")
public String delete(@RequestParam("id") int id) throws SQLException {
TransactionDao.delete(id);
return "transaction/list";
}
@RequestMapping(value = "/create/creditfromcard", method = RequestMethod.POST)
public String createTransactionDebetFromCard(HttpServletRequest request,
@RequestParam("card_number") String cardNumber, @RequestParam("expiry_date") String expiryDate,
@RequestParam("name_on_card") String nameOnCard, @RequestParam("sum") String sum,
@RequestParam("cvv") String cvv, @RequestParam("id_Account") int id,
ModelMap model) throws IOException {
HttpSession session = request.getSession();
ValidCreditCard isValidCard = new ValidCreditCard();
List validateCardInfo = isValidCard.validateCardInfo(cardNumber, sum);
if ((validateCardInfo.size()>0)){
model.addAttribute("validateCardInfo", validateCardInfo);
return "creditcard/create";
}
boolean fromCard = true;
IncreaseBalanсe.moneyFromCreditCard(cardNumber, sum, SessionValidService.ValidUser(session).getId(), fromCard);
return "creditcard/create";
}
@RequestMapping(value = "/create/creditfromcard", method = RequestMethod.GET)
public String creationFormDebetFromCard(HttpServletRequest request, ModelMap model){
HttpSession session = request.getSession();
if (SessionValidService.ValidUser(session) == null) {
return "redirect:/login";
}
return "creditcard/create";
}
@RequestMapping(value = "/create/debitedtothecard", method = RequestMethod.GET)
public String creationDebitedToTheCard(HttpServletRequest request, ModelMap model){
HttpSession session = request.getSession();
if (SessionValidService.ValidUser(session) == null) {
return "redirect:/login";
}
return "creditcard/transfer";
}
@RequestMapping(value = "/create/debitedtothecard", method = RequestMethod.POST)
public String createTransactionDebitedToTheCard(HttpServletRequest request,
@RequestParam("card_number") String cardNumber,
@RequestParam("sum") String sum,
@RequestParam("id_Account") int id, ModelMap model){
HttpSession session = request.getSession();
ValidCreditCard isValidCard = new ValidCreditCard();
List validateCardInfo = isValidCard.validateCardInfo(cardNumber, sum);
if ((validateCardInfo.size()>0)){
model.addAttribute("validateCardInfo", validateCardInfo);
return "creditcard/transfer";
}
boolean fromCard = false;
IncreaseBalanсe.moneyFromCreditCard(cardNumber, sum, SessionValidService.ValidUser(session).getId(), fromCard);
return "creditcard/transfer";
}
}
| false | true | public String create(HttpServletRequest request, ModelMap model) throws IOException {
TransactionValidator transactionValidator = new TransactionValidator();
HttpSession session = request.getSession();
User userSession = (User) session.getAttribute("LoggedUser");
transactionValidator.setCredit(userSession);
User debitUser = UserDao.getByEmail(request.getParameter("debit"));
transactionValidator.setDebit(debitUser);
transactionValidator.setInputSum(request.getParameter("sum"));
if (UserDao.getBalance(userSession) > Double.parseDouble(request.getParameter("sum")) && debitUser == null) {
Inviter.sendEmail(userSession.getFirstName(), request.getParameter("debit"), Integer.parseInt(request.getParameter("sum")));
}
if (transactionValidator.validate().size() == 0) {
Transaction transaction = new Transaction();
transaction.setDebit(transactionValidator.getDebit());
transaction.setCredit(transactionValidator.getCredit());
transaction.setSum(transactionValidator.getSum());
TransactionDao.create(transaction);
return "transaction/create";
}
return "transaction/create";
}
| public String create(HttpServletRequest request, ModelMap model) throws IOException {
TransactionValidator transactionValidator = new TransactionValidator();
HttpSession session = request.getSession();
User userSession = (User) session.getAttribute("LoggedUser");
transactionValidator.setCredit(userSession);
User debitUser = UserDao.getByEmail(request.getParameter("debit"));
transactionValidator.setDebit(debitUser);
transactionValidator.setInputSum(request.getParameter("sum"));
if (UserDao.getBalance(userSession) > Double.parseDouble(request.getParameter("sum")) && debitUser == null) {
Inviter.sendEmail(userSession.getFirstName(), request.getParameter("debit"), Integer.parseInt(request.getParameter("sum")));
}
if (transactionValidator.validate().size() == 0) {
Transaction transaction = new Transaction();
transaction.setDebit(transactionValidator.getDebit());
transaction.setCredit(transactionValidator.getCredit());
transaction.setSum(transactionValidator.getSum());
TransactionDao.create(transaction);
return "redirect:/transaction/create";
}
return "redirect:/transaction/create";
}
|
diff --git a/src/com/android/settings/wifi/AdvancedWifiSettings.java b/src/com/android/settings/wifi/AdvancedWifiSettings.java
index fc1b128a4..c213512bb 100644
--- a/src/com/android/settings/wifi/AdvancedWifiSettings.java
+++ b/src/com/android/settings/wifi/AdvancedWifiSettings.java
@@ -1,198 +1,200 @@
/*
* Copyright (C) 2011 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.settings.wifi;
import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.preference.CheckBoxPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceScreen;
import android.provider.Settings;
import android.provider.Settings.Secure;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
import com.android.settings.R;
import com.android.settings.SettingsPreferenceFragment;
import com.android.settings.Utils;
public class AdvancedWifiSettings extends SettingsPreferenceFragment
implements Preference.OnPreferenceChangeListener {
private static final String TAG = "AdvancedWifiSettings";
private static final String KEY_MAC_ADDRESS = "mac_address";
private static final String KEY_CURRENT_IP_ADDRESS = "current_ip_address";
private static final String KEY_FREQUENCY_BAND = "frequency_band";
private static final String KEY_NOTIFY_OPEN_NETWORKS = "notify_open_networks";
private static final String KEY_SLEEP_POLICY = "sleep_policy";
private static final String KEY_ENABLE_WIFI_WATCHDOG = "wifi_enable_watchdog_service";
private WifiManager mWifiManager;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.wifi_advanced_settings);
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
}
@Override
public void onResume() {
super.onResume();
initPreferences();
refreshWifiInfo();
}
private void initPreferences() {
CheckBoxPreference notifyOpenNetworks =
(CheckBoxPreference) findPreference(KEY_NOTIFY_OPEN_NETWORKS);
notifyOpenNetworks.setChecked(Secure.getInt(getContentResolver(),
Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 0) == 1);
notifyOpenNetworks.setEnabled(mWifiManager.isWifiEnabled());
CheckBoxPreference watchdogEnabled =
(CheckBoxPreference) findPreference(KEY_ENABLE_WIFI_WATCHDOG);
- watchdogEnabled.setChecked(Secure.getInt(getContentResolver(),
- Secure.WIFI_WATCHDOG_ON, 1) == 1);
+ if (watchdogEnabled != null) {
+ watchdogEnabled.setChecked(Secure.getInt(getContentResolver(),
+ Secure.WIFI_WATCHDOG_ON, 1) == 1);
- //TODO: Bring this back after changing watchdog behavior
- getPreferenceScreen().removePreference(watchdogEnabled);
+ //TODO: Bring this back after changing watchdog behavior
+ getPreferenceScreen().removePreference(watchdogEnabled);
+ }
ListPreference frequencyPref = (ListPreference) findPreference(KEY_FREQUENCY_BAND);
if (mWifiManager.isDualBandSupported()) {
frequencyPref.setOnPreferenceChangeListener(this);
int value = mWifiManager.getFrequencyBand();
if (value != -1) {
frequencyPref.setValue(String.valueOf(value));
} else {
Log.e(TAG, "Failed to fetch frequency band");
}
} else {
if (frequencyPref != null) {
// null if it has already been removed before resume
getPreferenceScreen().removePreference(frequencyPref);
}
}
ListPreference sleepPolicyPref = (ListPreference) findPreference(KEY_SLEEP_POLICY);
if (sleepPolicyPref != null) {
if (Utils.isWifiOnly(getActivity())) {
sleepPolicyPref.setEntries(R.array.wifi_sleep_policy_entries_wifi_only);
}
sleepPolicyPref.setOnPreferenceChangeListener(this);
int value = Settings.System.getInt(getContentResolver(),
Settings.System.WIFI_SLEEP_POLICY,
Settings.System.WIFI_SLEEP_POLICY_NEVER);
String stringValue = String.valueOf(value);
sleepPolicyPref.setValue(stringValue);
updateSleepPolicySummary(sleepPolicyPref, stringValue);
}
}
private void updateSleepPolicySummary(Preference sleepPolicyPref, String value) {
if (value != null) {
String[] values = getResources().getStringArray(R.array.wifi_sleep_policy_values);
final int summaryArrayResId = Utils.isWifiOnly(getActivity()) ?
R.array.wifi_sleep_policy_entries_wifi_only : R.array.wifi_sleep_policy_entries;
String[] summaries = getResources().getStringArray(summaryArrayResId);
for (int i = 0; i < values.length; i++) {
if (value.equals(values[i])) {
if (i < summaries.length) {
sleepPolicyPref.setSummary(summaries[i]);
return;
}
}
}
}
sleepPolicyPref.setSummary("");
Log.e(TAG, "Invalid sleep policy value: " + value);
}
@Override
public boolean onPreferenceTreeClick(PreferenceScreen screen, Preference preference) {
String key = preference.getKey();
if (KEY_NOTIFY_OPEN_NETWORKS.equals(key)) {
Secure.putInt(getContentResolver(),
Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON,
((CheckBoxPreference) preference).isChecked() ? 1 : 0);
} else if (KEY_ENABLE_WIFI_WATCHDOG.equals(key)) {
Secure.putInt(getContentResolver(),
Secure.WIFI_WATCHDOG_ON,
((CheckBoxPreference) preference).isChecked() ? 1 : 0);
} else {
return super.onPreferenceTreeClick(screen, preference);
}
return true;
}
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
String key = preference.getKey();
if (KEY_FREQUENCY_BAND.equals(key)) {
try {
mWifiManager.setFrequencyBand(Integer.parseInt((String) newValue), true);
} catch (NumberFormatException e) {
Toast.makeText(getActivity(), R.string.wifi_setting_frequency_band_error,
Toast.LENGTH_SHORT).show();
return false;
}
}
if (KEY_SLEEP_POLICY.equals(key)) {
try {
String stringValue = (String) newValue;
Settings.System.putInt(getContentResolver(), Settings.System.WIFI_SLEEP_POLICY,
Integer.parseInt(stringValue));
updateSleepPolicySummary(preference, stringValue);
} catch (NumberFormatException e) {
Toast.makeText(getActivity(), R.string.wifi_setting_sleep_policy_error,
Toast.LENGTH_SHORT).show();
return false;
}
}
return true;
}
private void refreshWifiInfo() {
WifiInfo wifiInfo = mWifiManager.getConnectionInfo();
Preference wifiMacAddressPref = findPreference(KEY_MAC_ADDRESS);
String macAddress = wifiInfo == null ? null : wifiInfo.getMacAddress();
wifiMacAddressPref.setSummary(!TextUtils.isEmpty(macAddress) ? macAddress
: getActivity().getString(R.string.status_unavailable));
Preference wifiIpAddressPref = findPreference(KEY_CURRENT_IP_ADDRESS);
String ipAddress = Utils.getWifiIpAddresses(getActivity());
wifiIpAddressPref.setSummary(ipAddress == null ?
getActivity().getString(R.string.status_unavailable) : ipAddress);
}
}
| false | true | private void initPreferences() {
CheckBoxPreference notifyOpenNetworks =
(CheckBoxPreference) findPreference(KEY_NOTIFY_OPEN_NETWORKS);
notifyOpenNetworks.setChecked(Secure.getInt(getContentResolver(),
Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 0) == 1);
notifyOpenNetworks.setEnabled(mWifiManager.isWifiEnabled());
CheckBoxPreference watchdogEnabled =
(CheckBoxPreference) findPreference(KEY_ENABLE_WIFI_WATCHDOG);
watchdogEnabled.setChecked(Secure.getInt(getContentResolver(),
Secure.WIFI_WATCHDOG_ON, 1) == 1);
//TODO: Bring this back after changing watchdog behavior
getPreferenceScreen().removePreference(watchdogEnabled);
ListPreference frequencyPref = (ListPreference) findPreference(KEY_FREQUENCY_BAND);
if (mWifiManager.isDualBandSupported()) {
frequencyPref.setOnPreferenceChangeListener(this);
int value = mWifiManager.getFrequencyBand();
if (value != -1) {
frequencyPref.setValue(String.valueOf(value));
} else {
Log.e(TAG, "Failed to fetch frequency band");
}
} else {
if (frequencyPref != null) {
// null if it has already been removed before resume
getPreferenceScreen().removePreference(frequencyPref);
}
}
ListPreference sleepPolicyPref = (ListPreference) findPreference(KEY_SLEEP_POLICY);
if (sleepPolicyPref != null) {
if (Utils.isWifiOnly(getActivity())) {
sleepPolicyPref.setEntries(R.array.wifi_sleep_policy_entries_wifi_only);
}
sleepPolicyPref.setOnPreferenceChangeListener(this);
int value = Settings.System.getInt(getContentResolver(),
Settings.System.WIFI_SLEEP_POLICY,
Settings.System.WIFI_SLEEP_POLICY_NEVER);
String stringValue = String.valueOf(value);
sleepPolicyPref.setValue(stringValue);
updateSleepPolicySummary(sleepPolicyPref, stringValue);
}
}
| private void initPreferences() {
CheckBoxPreference notifyOpenNetworks =
(CheckBoxPreference) findPreference(KEY_NOTIFY_OPEN_NETWORKS);
notifyOpenNetworks.setChecked(Secure.getInt(getContentResolver(),
Secure.WIFI_NETWORKS_AVAILABLE_NOTIFICATION_ON, 0) == 1);
notifyOpenNetworks.setEnabled(mWifiManager.isWifiEnabled());
CheckBoxPreference watchdogEnabled =
(CheckBoxPreference) findPreference(KEY_ENABLE_WIFI_WATCHDOG);
if (watchdogEnabled != null) {
watchdogEnabled.setChecked(Secure.getInt(getContentResolver(),
Secure.WIFI_WATCHDOG_ON, 1) == 1);
//TODO: Bring this back after changing watchdog behavior
getPreferenceScreen().removePreference(watchdogEnabled);
}
ListPreference frequencyPref = (ListPreference) findPreference(KEY_FREQUENCY_BAND);
if (mWifiManager.isDualBandSupported()) {
frequencyPref.setOnPreferenceChangeListener(this);
int value = mWifiManager.getFrequencyBand();
if (value != -1) {
frequencyPref.setValue(String.valueOf(value));
} else {
Log.e(TAG, "Failed to fetch frequency band");
}
} else {
if (frequencyPref != null) {
// null if it has already been removed before resume
getPreferenceScreen().removePreference(frequencyPref);
}
}
ListPreference sleepPolicyPref = (ListPreference) findPreference(KEY_SLEEP_POLICY);
if (sleepPolicyPref != null) {
if (Utils.isWifiOnly(getActivity())) {
sleepPolicyPref.setEntries(R.array.wifi_sleep_policy_entries_wifi_only);
}
sleepPolicyPref.setOnPreferenceChangeListener(this);
int value = Settings.System.getInt(getContentResolver(),
Settings.System.WIFI_SLEEP_POLICY,
Settings.System.WIFI_SLEEP_POLICY_NEVER);
String stringValue = String.valueOf(value);
sleepPolicyPref.setValue(stringValue);
updateSleepPolicySummary(sleepPolicyPref, stringValue);
}
}
|
diff --git a/swag-webapp/src/main/java/at/ac/tuwien/swag/webapp/in/map/GameMap.java b/swag-webapp/src/main/java/at/ac/tuwien/swag/webapp/in/map/GameMap.java
index 422ce95..f9478e9 100644
--- a/swag-webapp/src/main/java/at/ac/tuwien/swag/webapp/in/map/GameMap.java
+++ b/swag-webapp/src/main/java/at/ac/tuwien/swag/webapp/in/map/GameMap.java
@@ -1,164 +1,171 @@
package at.ac.tuwien.swag.webapp.in.map;
import java.util.List;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.markup.html.AjaxFallbackLink;
import org.apache.wicket.behavior.SimpleAttributeModifier;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.list.ListItem;
import org.apache.wicket.markup.html.list.ListView;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.IModel;
import at.ac.tuwien.swag.model.domain.MapUser;
import at.ac.tuwien.swag.model.domain.Square;
import at.ac.tuwien.swag.webapp.SwagWebSession;
public class GameMap extends Panel {
private static final long serialVersionUID = -2473064801663338918L;
private ListView<List<Square>> gameMaplistView;
private IModel<List<List<Square>>> gameMapList;
private MapUser mapUser;
private MapModalWindow mapModalWindow;
public GameMap(String id, MapUser mapUser, IModel<List<List<Square>>> gameMapList) {
super(id);
this.mapUser = mapUser;
this.gameMapList = gameMapList;
this.setOutputMarkupId(true);
this.setupGameMapView();
this.add(gameMaplistView);
this.setupMapModalWindow();
this.add(mapModalWindow);
}
private void setupMapModalWindow() {
// The ModalWindow, showing some choices for the user to select.
mapModalWindow = new MapModalWindow("modalwindow"){
private static final long serialVersionUID = 6244873170722607468L;
void onSelect(AjaxRequestTarget target, String selection) {
// Handle Select action
// close(target);
}
void onCancel(AjaxRequestTarget target) {
// Handle Cancel action
// close(target);
}
@Override
void onSettle(AjaxRequestTarget target, long squareId) {
close(target);
}
};
}
private void setupGameMapView() {
gameMaplistView = new ListView<List<Square>>("gameMap", gameMapList) {
private static final long serialVersionUID = 7083713778515545799L;
@Override
protected void populateItem(ListItem<List<Square>> row) {
List<Square> rowList = row.getModelObject();
ListView<Square> rowListView = new ListView<Square>("row", rowList) {
private static final long serialVersionUID = 3054181382288233598L;
@Override
protected void populateItem(ListItem<Square> squareList) {
final Square square = squareList.getModelObject();
Label label = null;
if(checkIfMySquare(square)) {
label = new Label("square", "X: " + square.getCoordX() + " AAAAA Y: " + square.getCoordY());
if (checkIfBaseBuildings(square)) {
label = new Label("square", "BASEOWNEDBYME");
label.add(new SimpleAttributeModifier("class", "baseSquare"));
}
if (square.getIsHomeBase()) {
label = new Label("square", "HOMEBASE");
label.add(new SimpleAttributeModifier("class", "homeBaseSquare"));
}
} else {
if (square.getIsHomeBase()) {
label = new Label("square", "FOREIGN-HOMEBASE");
label.add(new SimpleAttributeModifier("class", "homeBaseSquare"));
}
if (checkIfBaseBuildings(square)) {
label = new Label("square", "X: " + square.getCoordX() +" Y: lalala" + square.getCoordY());
label.add(new SimpleAttributeModifier("class", "baseSquare"));
- }else {
+ }
+ if(!square.getIsHomeBase()&& !checkIfBaseBuildings(square)){
label =new Label("square", "X: " + square.getCoordX() + " EMPTY Y: " + square.getCoordY());
}
}
squareList.add(label);
/////////////////////////////////////////// MODAL WINDOW ////////////////////////////////////////////////
AjaxFallbackLink<String> squareLink = new AjaxFallbackLink<String>("squareLink") {
private static final long serialVersionUID = -2641432580203719830L;
@Override
public void onClick(AjaxRequestTarget target) {
// Sets current selected squareId
SwagWebSession session = (SwagWebSession) getSession();
session.setSelectedSquareId(square.getId());
if(checkIfMySquare(square)) {
mapModalWindow.loadBasePanel();
}else{
+ if (square.getIsHomeBase()) {
+ mapModalWindow.loadForeignSquareModalPanel();
+ }
if(checkIfBaseBuildings(square)){
mapModalWindow.loadForeignSquareModalPanel();
- }else { mapModalWindow.loadEmptySquareModalPanel(); }
+ }
+ if(!square.getIsHomeBase()&& !checkIfBaseBuildings(square)){
+ mapModalWindow.loadEmptySquareModalPanel();
+ }
}
mapModalWindow.show(target);
}
};
/////////////////////////////////////////// MODAL WINDOW ////////////////////////////////////////////////
squareLink.setOutputMarkupId(true);
squareList.add(squareLink);
label.setOutputMarkupId(true);
squareLink.add(label);
}
};
row.add(rowListView);
}
};
}
/**
*
* @param sq
* @return
*/
private boolean checkIfBaseBuildings(Square sq) {
if (sq.getBuildings() == null || sq.getBuildings().isEmpty()) {
return false;
}
return true;
}
/**
*
* @param sq
* @return
*/
private boolean checkIfMySquare(Square sq) {
if (mapUser != null && mapUser.getSquares().contains(sq)) {
return true;
}
return false;
}
}
| false | true | private void setupGameMapView() {
gameMaplistView = new ListView<List<Square>>("gameMap", gameMapList) {
private static final long serialVersionUID = 7083713778515545799L;
@Override
protected void populateItem(ListItem<List<Square>> row) {
List<Square> rowList = row.getModelObject();
ListView<Square> rowListView = new ListView<Square>("row", rowList) {
private static final long serialVersionUID = 3054181382288233598L;
@Override
protected void populateItem(ListItem<Square> squareList) {
final Square square = squareList.getModelObject();
Label label = null;
if(checkIfMySquare(square)) {
label = new Label("square", "X: " + square.getCoordX() + " AAAAA Y: " + square.getCoordY());
if (checkIfBaseBuildings(square)) {
label = new Label("square", "BASEOWNEDBYME");
label.add(new SimpleAttributeModifier("class", "baseSquare"));
}
if (square.getIsHomeBase()) {
label = new Label("square", "HOMEBASE");
label.add(new SimpleAttributeModifier("class", "homeBaseSquare"));
}
} else {
if (square.getIsHomeBase()) {
label = new Label("square", "FOREIGN-HOMEBASE");
label.add(new SimpleAttributeModifier("class", "homeBaseSquare"));
}
if (checkIfBaseBuildings(square)) {
label = new Label("square", "X: " + square.getCoordX() +" Y: lalala" + square.getCoordY());
label.add(new SimpleAttributeModifier("class", "baseSquare"));
}else {
label =new Label("square", "X: " + square.getCoordX() + " EMPTY Y: " + square.getCoordY());
}
}
squareList.add(label);
/////////////////////////////////////////// MODAL WINDOW ////////////////////////////////////////////////
AjaxFallbackLink<String> squareLink = new AjaxFallbackLink<String>("squareLink") {
private static final long serialVersionUID = -2641432580203719830L;
@Override
public void onClick(AjaxRequestTarget target) {
// Sets current selected squareId
SwagWebSession session = (SwagWebSession) getSession();
session.setSelectedSquareId(square.getId());
if(checkIfMySquare(square)) {
mapModalWindow.loadBasePanel();
}else{
if(checkIfBaseBuildings(square)){
mapModalWindow.loadForeignSquareModalPanel();
}else { mapModalWindow.loadEmptySquareModalPanel(); }
}
mapModalWindow.show(target);
}
};
/////////////////////////////////////////// MODAL WINDOW ////////////////////////////////////////////////
squareLink.setOutputMarkupId(true);
squareList.add(squareLink);
label.setOutputMarkupId(true);
squareLink.add(label);
}
};
row.add(rowListView);
}
};
}
| private void setupGameMapView() {
gameMaplistView = new ListView<List<Square>>("gameMap", gameMapList) {
private static final long serialVersionUID = 7083713778515545799L;
@Override
protected void populateItem(ListItem<List<Square>> row) {
List<Square> rowList = row.getModelObject();
ListView<Square> rowListView = new ListView<Square>("row", rowList) {
private static final long serialVersionUID = 3054181382288233598L;
@Override
protected void populateItem(ListItem<Square> squareList) {
final Square square = squareList.getModelObject();
Label label = null;
if(checkIfMySquare(square)) {
label = new Label("square", "X: " + square.getCoordX() + " AAAAA Y: " + square.getCoordY());
if (checkIfBaseBuildings(square)) {
label = new Label("square", "BASEOWNEDBYME");
label.add(new SimpleAttributeModifier("class", "baseSquare"));
}
if (square.getIsHomeBase()) {
label = new Label("square", "HOMEBASE");
label.add(new SimpleAttributeModifier("class", "homeBaseSquare"));
}
} else {
if (square.getIsHomeBase()) {
label = new Label("square", "FOREIGN-HOMEBASE");
label.add(new SimpleAttributeModifier("class", "homeBaseSquare"));
}
if (checkIfBaseBuildings(square)) {
label = new Label("square", "X: " + square.getCoordX() +" Y: lalala" + square.getCoordY());
label.add(new SimpleAttributeModifier("class", "baseSquare"));
}
if(!square.getIsHomeBase()&& !checkIfBaseBuildings(square)){
label =new Label("square", "X: " + square.getCoordX() + " EMPTY Y: " + square.getCoordY());
}
}
squareList.add(label);
/////////////////////////////////////////// MODAL WINDOW ////////////////////////////////////////////////
AjaxFallbackLink<String> squareLink = new AjaxFallbackLink<String>("squareLink") {
private static final long serialVersionUID = -2641432580203719830L;
@Override
public void onClick(AjaxRequestTarget target) {
// Sets current selected squareId
SwagWebSession session = (SwagWebSession) getSession();
session.setSelectedSquareId(square.getId());
if(checkIfMySquare(square)) {
mapModalWindow.loadBasePanel();
}else{
if (square.getIsHomeBase()) {
mapModalWindow.loadForeignSquareModalPanel();
}
if(checkIfBaseBuildings(square)){
mapModalWindow.loadForeignSquareModalPanel();
}
if(!square.getIsHomeBase()&& !checkIfBaseBuildings(square)){
mapModalWindow.loadEmptySquareModalPanel();
}
}
mapModalWindow.show(target);
}
};
/////////////////////////////////////////// MODAL WINDOW ////////////////////////////////////////////////
squareLink.setOutputMarkupId(true);
squareList.add(squareLink);
label.setOutputMarkupId(true);
squareLink.add(label);
}
};
row.add(rowListView);
}
};
}
|
diff --git a/src/ProjectControl/src/org/cvut/wa2/projectcontrol/CreateSubtaskServlet.java b/src/ProjectControl/src/org/cvut/wa2/projectcontrol/CreateSubtaskServlet.java
index 395ddcb..0365838 100644
--- a/src/ProjectControl/src/org/cvut/wa2/projectcontrol/CreateSubtaskServlet.java
+++ b/src/ProjectControl/src/org/cvut/wa2/projectcontrol/CreateSubtaskServlet.java
@@ -1,52 +1,53 @@
package org.cvut.wa2.projectcontrol;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.cvut.wa2.projectcontrol.DAO.TaskDAO;
import org.cvut.wa2.projectcontrol.DAO.TeamDAO;
import org.cvut.wa2.projectcontrol.entities.CompositeTask;
import org.cvut.wa2.projectcontrol.entities.Team;
import org.cvut.wa2.projectcontrol.entities.TeamMember;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
public class CreateSubtaskServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
UserService userService = UserServiceFactory.getUserService();
RequestDispatcher disp = null;
if (userService.isUserLoggedIn()) {
String taskName = (String) req.getParameter("taskName");
CompositeTask ct = TaskDAO.getTask(taskName);
Team team = TeamDAO.getTeam(ct.getOwner());
List<String> listOfEmails = new ArrayList<String>();
for (TeamMember mem : team.getMembers()) {
listOfEmails.add(mem.getName());
}
req.setAttribute("emails", listOfEmails);
+ req.setAttribute("taskName", taskName);
disp = req.getRequestDispatcher("CreateSubtask.jsp");
disp.forward(req, resp);
} else {
disp = req.getRequestDispatcher("/projectcontrol");
disp.forward(req, resp);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doGet(req, resp);
}
}
| true | true | protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
UserService userService = UserServiceFactory.getUserService();
RequestDispatcher disp = null;
if (userService.isUserLoggedIn()) {
String taskName = (String) req.getParameter("taskName");
CompositeTask ct = TaskDAO.getTask(taskName);
Team team = TeamDAO.getTeam(ct.getOwner());
List<String> listOfEmails = new ArrayList<String>();
for (TeamMember mem : team.getMembers()) {
listOfEmails.add(mem.getName());
}
req.setAttribute("emails", listOfEmails);
disp = req.getRequestDispatcher("CreateSubtask.jsp");
disp.forward(req, resp);
} else {
disp = req.getRequestDispatcher("/projectcontrol");
disp.forward(req, resp);
}
}
| protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
UserService userService = UserServiceFactory.getUserService();
RequestDispatcher disp = null;
if (userService.isUserLoggedIn()) {
String taskName = (String) req.getParameter("taskName");
CompositeTask ct = TaskDAO.getTask(taskName);
Team team = TeamDAO.getTeam(ct.getOwner());
List<String> listOfEmails = new ArrayList<String>();
for (TeamMember mem : team.getMembers()) {
listOfEmails.add(mem.getName());
}
req.setAttribute("emails", listOfEmails);
req.setAttribute("taskName", taskName);
disp = req.getRequestDispatcher("CreateSubtask.jsp");
disp.forward(req, resp);
} else {
disp = req.getRequestDispatcher("/projectcontrol");
disp.forward(req, resp);
}
}
|
diff --git a/src/edu/ucla/cens/awserver/validator/AbstractAnnotatingValidator.java b/src/edu/ucla/cens/awserver/validator/AbstractAnnotatingValidator.java
index 042869c7..2fa0ed22 100644
--- a/src/edu/ucla/cens/awserver/validator/AbstractAnnotatingValidator.java
+++ b/src/edu/ucla/cens/awserver/validator/AbstractAnnotatingValidator.java
@@ -1,25 +1,25 @@
package edu.ucla.cens.awserver.validator;
/**
* Abstract base class for Validators which need to annotate an AwRequest as part of their processing.
*
* @author selsky
*/
public abstract class AbstractAnnotatingValidator implements Validator {
private AwRequestAnnotator _annotator;
/**
* @throws IllegalArgumentException if the provided AnnotateAwRequestStrategy is null
*/
public AbstractAnnotatingValidator(AwRequestAnnotator annotator) {
if(null == annotator) {
- throw new IllegalArgumentException("an AwRequestAnnotationStrategy is required");
+ throw new IllegalArgumentException("a non-null annotator is required");
}
_annotator = annotator;
}
protected AwRequestAnnotator getAnnotator() {
return _annotator;
}
}
| true | true | public AbstractAnnotatingValidator(AwRequestAnnotator annotator) {
if(null == annotator) {
throw new IllegalArgumentException("an AwRequestAnnotationStrategy is required");
}
_annotator = annotator;
}
| public AbstractAnnotatingValidator(AwRequestAnnotator annotator) {
if(null == annotator) {
throw new IllegalArgumentException("a non-null annotator is required");
}
_annotator = annotator;
}
|
diff --git a/modules/highlevel/hookApprove/src/dk/statsbiblioteket/doms/bitstorage/highlevel/HookApprove.java b/modules/highlevel/hookApprove/src/dk/statsbiblioteket/doms/bitstorage/highlevel/HookApprove.java
index 2ca942c..90efc6e 100644
--- a/modules/highlevel/hookApprove/src/dk/statsbiblioteket/doms/bitstorage/highlevel/HookApprove.java
+++ b/modules/highlevel/hookApprove/src/dk/statsbiblioteket/doms/bitstorage/highlevel/HookApprove.java
@@ -1,389 +1,390 @@
/*
* $Id$
* $Revision$
* $Date$
* $Author$
*
* The DOMS project.
* Copyright (C) 2007-2010 The State and University Library
*
* 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 dk.statsbiblioteket.doms.bitstorage.highlevel;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.fcrepo.server.proxy.AbstractInvocationHandler;
import org.fcrepo.server.management.ManagementModule;
import org.fcrepo.server.access.Access;
import org.fcrepo.server.access.ObjectProfile;
import org.fcrepo.server.Server;
import org.fcrepo.server.Context;
import org.fcrepo.server.errors.ModuleInitializationException;
import org.fcrepo.server.errors.ServerInitializationException;
import org.fcrepo.common.Constants;
import javax.xml.namespace.QName;
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
import java.io.File;
import java.net.URL;
import java.net.MalformedURLException;
import java.util.List;
import java.util.LinkedList;
/**
* Hooks the modifyObject method, so that when a file object is set to Active
* the file is published. Published means that the publish method from
* HighLevelBitstorage is invoked on the object, which moves the file from
* temporary bitstorage to permanent.
*
* @see HighlevelBitstorageSoapWebservice#publish(String)
* <p/>
* author: abr
* reviewer: jrg
*/
public class HookApprove extends AbstractInvocationHandler {
/**
* Logger for this class.
*/
private static Log LOG = LogFactory.getLog(HookApprove.class);
/**
* The service name of the bitstorage service. Nessesary for soap
* operations. Should not ever change
*/
public static final QName SERVICENAME =
new QName(
"http://highlevel.bitstorage.doms.statsbiblioteket.dk/",
"HighlevelBitstorageSoapWebserviceService");
/**
* The name of the api method to hook
*/
public static final String HOOKEDMETHOD = "modifyObject";
/**
* The boolean stating if the initialization steps have been taken
*/
private boolean initialised = false;
/**
* The bitstorage client
*/
private HighlevelBitstorageSoapWebservice bitstorageClient;
/**
* The Fedora Management module
*/
private ManagementModule managementModule;
/**
* The Fedora Access Module
*/
private Access accessModule;
/**
* The Fedora Server module
*/
private Server serverModule;
/**
* The list of content models that are hooked. An object must have
* one of these for the invoke method to attempt to publish the object
*/
private List<String> filemodels;
/**
* The init method, called before the first invocation of the method.
* Synchronized, to avoid problems with dual inits.
* Cannot be made as a constructor, as it depends on the presense of other
* Fedora modules.
* Reads these parameters from management module section in fedora.fcfg.
* See the supplied insertToFedora.fcfg for how to set these parameters.
* <ul>
* <li>dk.statsbiblioteket.doms.bitstorage.highlevel.hookapprove.filecmodel
* The pid of the file content model. Only objects with this content model
* will be published when set to Active.
* <li>dk.statsbiblioteket.doms.bitstorage.highlevel.hookapprove.
* webservicelocation
* The location of the wsdl for the highlevel bitstorage service
* </ul>
*
* @throws ModuleInitializationException If some Fedora module is not
* initiatialized yet
* @throws ServerInitializationException If the Fedora server is not
* initialized yet
* @throws MalformedURLException If the webservice location is set
* to an incorrect url
* @throws FileCouldNotBePublishedException
* catchall exception of something
* failed, but did not throw it's own
* exception
*/
public synchronized void init() throws
ModuleInitializationException,
ServerInitializationException,
MalformedURLException,
FileCouldNotBePublishedException {
if (initialised) {
return;
}
serverModule = Server.getInstance(new File(Constants.FEDORA_HOME),
false);
filemodels = new LinkedList<String>();
//get the management module
managementModule = getManagement();
if (managementModule == null) {
throw new FileCouldNotBePublishedException("Could not get the "
+ "management module "
+ "from fedora");
}
//get the access module
accessModule = getAccess();
if (accessModule == null) {
throw new FileCouldNotBePublishedException("Could not get the "
+ "Access module from "
+ "Fedora");
}
//read the parameters from the management module
String fileContentModel = managementModule.getParameter(
"dk.statsbiblioteket.doms.bitstorage.highlevel.hookapprove."
+ "filecmodel");
if (fileContentModel != null) {
filemodels.add(fileContentModel);
} else {
LOG.warn(
"No dk.statsbiblioteket.doms.bitstorage.highlevel."
+ "hookapprove.filecmodel specified,"
+ " disabling hookapprove");
}
String webservicelocation = managementModule.getParameter(
"dk.statsbiblioteket.doms.bitstorage.highlevel.hookapprove."
+ "webservicelocation");
if (webservicelocation == null) {
webservicelocation = "http://localhost:8080/ecm/validate/";//TODO
LOG.info(
"No dk.statsbiblioteket.doms.bitstorage.highlevel."
+ "hookapprove.webservicelocation specified,"
+ " using default location: " + webservicelocation);
}
//create the bitstorage client
URL wsdl;
wsdl = new URL(webservicelocation);
bitstorageClient
= new HighlevelBitstorageSoapWebserviceService(wsdl,
SERVICENAME)
.getHighlevelBitstorageSoapWebservicePort();
initialised = true;
}
/**
* Utility method to get the Access Module from the Server module
*
* @return the Access Module
*/
private Access getAccess() {
Access module = (Access) serverModule.getModule(
"org.fcrepo.server.access.Access");
if (module == null) {
module = (Access) serverModule.getModule(
"fedora.server.access.Access");
}
return module;
}
/**
* Utility method to get the Management Module from the Server module
*
* @return the Management module
*/
private ManagementModule getManagement() {
ManagementModule module = (ManagementModule) serverModule.getModule(
"org.fcrepo.server.management.Management");
if (module == null) {
module = (ManagementModule) serverModule.getModule(
"fedora.server.management.Management");
}
return module;
}
/**
* If the Method is modifyObject AND object to be modified has the
* specified content model AND is set to the Active state, then attempt to
* publish file via the bitstorage system. If the file cannot be published,
* the modification to the object is undone (but will leave a trail in the
* object log).
*
* @param proxy Unknown, probably this object
* @param method The method to invoke
* @param args the arguments to the method, the array depends on which
* method is invoked. For modifyObject, the list is
* <ul>
* <li>0: Context context The calling context
* <li>1: String pid the pid of the object
* <li>2: String State the new state of the object
* <li>3: String label the new label of the object
* <li>4: String ownerID the new ownerID of the object
* <li>5: String logmessage the logmessage of the change
* </ul>
* Parameter 2-4 can be null, which means no change.
* @return the method return type
* @throws Throwable
*/
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
try {
init();
if (!HOOKEDMETHOD.equals(method.getName())) {
//this calls the next proxy in the chain, and does nothing
// here
//target is a magical variable set to the next proxy
return method.invoke(target, args);
}
//If the call does not change the state to active, pass through
String state = (String) args[2];
if (!(state != null && state.startsWith("A"))) {
//startsWith to catch both "A" and "Active"
return method.invoke(target, args);
}
//so, we have a modify object that changes state to A
//Get at few relevant variables from the arguments
Context context = (Context) args[0];//call context
String pid = args[1].toString();
//Get profile to check if the object has the correct content model
// and save the profile for rollback
ObjectProfile profile = accessModule.getObjectProfile(context,
pid,
null);
//Do the change, to see if it was allowed
Object returnValue = method.invoke(target, args);
//If we are here, the change committed without exceptions thrown
try {
if (isFileObject(profile)) {//is this a file object?
if (!profile.objectState.startsWith("A")) {
//object was not already active
bitstorageClient.publish(pid);
//publish moves the file from temporary bitstorage to
//permanent bitstorage
//milestone, any fails beyound this must rollback
}
}
return returnValue;
} catch (Exception e) {
//something broke in publishing, so undo the state operation
//rollback
String old_state = profile.objectState;
String old_label = null;
if (args[3] != null) {//label
//label changed
old_label = profile.objectLabel;
}
String old_ownerid = null;
if (args[4] != null) {//ownerid
//ownerid changed
old_ownerid = profile.objectOwnerId;
}
//commit the rollback.
// TODO perform this directly on the Management, instead?
Object new_return = method.invoke(
target,
context,
pid,
old_state,
old_label,
old_ownerid,
"Undoing state change because file could not be"
- + " published");
+ + " published",
+ null);
//discard rollback returnvalue
throw new FileCouldNotBePublishedException(
"The file in '" + pid + "' could not be published. "
+ "State change rolled back.",
e);
}
} catch (InvocationTargetException e) {
//if the invoke method failed, throw the original exception on
throw e.getCause();
}//if anything else failed, let it pass
}
/**
* Utility method to determine if the object is a file object
*
* @param profile the object profile
* @return true if the object has the specified content model
* @see #filemodels
*/
private boolean isFileObject(ObjectProfile profile) {
for (String model : profile.objectModels) {
if (model == null) {
continue;
}
model = ensurePid(model);
if (filemodels.contains(model)) {
return true;
}
}
return false;
}
/**
* Utility method to remove info:fedora/ prefix from pids, if they have
* them
*
* @param pid the pid to clean
* @return if the pid starts with info:fedora/ return the pid without this
* prefix, otherwise just return the unchanged pid
*/
private String ensurePid(String pid) {
if (pid.startsWith("info:fedora/")) {
return pid.substring("info:fedora/".length());
}
return pid;
}
}
| true | true | public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
try {
init();
if (!HOOKEDMETHOD.equals(method.getName())) {
//this calls the next proxy in the chain, and does nothing
// here
//target is a magical variable set to the next proxy
return method.invoke(target, args);
}
//If the call does not change the state to active, pass through
String state = (String) args[2];
if (!(state != null && state.startsWith("A"))) {
//startsWith to catch both "A" and "Active"
return method.invoke(target, args);
}
//so, we have a modify object that changes state to A
//Get at few relevant variables from the arguments
Context context = (Context) args[0];//call context
String pid = args[1].toString();
//Get profile to check if the object has the correct content model
// and save the profile for rollback
ObjectProfile profile = accessModule.getObjectProfile(context,
pid,
null);
//Do the change, to see if it was allowed
Object returnValue = method.invoke(target, args);
//If we are here, the change committed without exceptions thrown
try {
if (isFileObject(profile)) {//is this a file object?
if (!profile.objectState.startsWith("A")) {
//object was not already active
bitstorageClient.publish(pid);
//publish moves the file from temporary bitstorage to
//permanent bitstorage
//milestone, any fails beyound this must rollback
}
}
return returnValue;
} catch (Exception e) {
//something broke in publishing, so undo the state operation
//rollback
String old_state = profile.objectState;
String old_label = null;
if (args[3] != null) {//label
//label changed
old_label = profile.objectLabel;
}
String old_ownerid = null;
if (args[4] != null) {//ownerid
//ownerid changed
old_ownerid = profile.objectOwnerId;
}
//commit the rollback.
// TODO perform this directly on the Management, instead?
Object new_return = method.invoke(
target,
context,
pid,
old_state,
old_label,
old_ownerid,
"Undoing state change because file could not be"
+ " published");
//discard rollback returnvalue
throw new FileCouldNotBePublishedException(
"The file in '" + pid + "' could not be published. "
+ "State change rolled back.",
e);
}
} catch (InvocationTargetException e) {
//if the invoke method failed, throw the original exception on
throw e.getCause();
}//if anything else failed, let it pass
}
| public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
try {
init();
if (!HOOKEDMETHOD.equals(method.getName())) {
//this calls the next proxy in the chain, and does nothing
// here
//target is a magical variable set to the next proxy
return method.invoke(target, args);
}
//If the call does not change the state to active, pass through
String state = (String) args[2];
if (!(state != null && state.startsWith("A"))) {
//startsWith to catch both "A" and "Active"
return method.invoke(target, args);
}
//so, we have a modify object that changes state to A
//Get at few relevant variables from the arguments
Context context = (Context) args[0];//call context
String pid = args[1].toString();
//Get profile to check if the object has the correct content model
// and save the profile for rollback
ObjectProfile profile = accessModule.getObjectProfile(context,
pid,
null);
//Do the change, to see if it was allowed
Object returnValue = method.invoke(target, args);
//If we are here, the change committed without exceptions thrown
try {
if (isFileObject(profile)) {//is this a file object?
if (!profile.objectState.startsWith("A")) {
//object was not already active
bitstorageClient.publish(pid);
//publish moves the file from temporary bitstorage to
//permanent bitstorage
//milestone, any fails beyound this must rollback
}
}
return returnValue;
} catch (Exception e) {
//something broke in publishing, so undo the state operation
//rollback
String old_state = profile.objectState;
String old_label = null;
if (args[3] != null) {//label
//label changed
old_label = profile.objectLabel;
}
String old_ownerid = null;
if (args[4] != null) {//ownerid
//ownerid changed
old_ownerid = profile.objectOwnerId;
}
//commit the rollback.
// TODO perform this directly on the Management, instead?
Object new_return = method.invoke(
target,
context,
pid,
old_state,
old_label,
old_ownerid,
"Undoing state change because file could not be"
+ " published",
null);
//discard rollback returnvalue
throw new FileCouldNotBePublishedException(
"The file in '" + pid + "' could not be published. "
+ "State change rolled back.",
e);
}
} catch (InvocationTargetException e) {
//if the invoke method failed, throw the original exception on
throw e.getCause();
}//if anything else failed, let it pass
}
|
diff --git a/TravelGates/src/com/ghomerr/travelgates/TravelGates.java b/TravelGates/src/com/ghomerr/travelgates/TravelGates.java
index 738b02c..7403529 100644
--- a/TravelGates/src/com/ghomerr/travelgates/TravelGates.java
+++ b/TravelGates/src/com/ghomerr/travelgates/TravelGates.java
@@ -1,2922 +1,2922 @@
package com.ghomerr.travelgates;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Properties;
import java.util.logging.Logger;
import org.bukkit.ChatColor;
import org.bukkit.Chunk;
import org.bukkit.DyeColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.TreeSpecies;
import org.bukkit.World;
import org.bukkit.WorldCreator;
import org.bukkit.block.BlockFace;
import org.bukkit.command.PluginCommand;
import org.bukkit.entity.Player;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import ru.tehkode.permissions.PermissionManager;
import ru.tehkode.permissions.bukkit.PermissionsEx;
import com.ghomerr.travelgates.constants.TravelGatesConstants;
import com.ghomerr.travelgates.enums.TravelGatesCommands;
import com.ghomerr.travelgates.enums.TravelGatesConfigurations;
import com.ghomerr.travelgates.enums.TravelGatesOptions;
import com.ghomerr.travelgates.enums.TravelGatesPermissionsNodes;
import com.ghomerr.travelgates.enums.TravelGatesWorldType;
import com.ghomerr.travelgates.listeners.TravelGatesCommandExecutor;
import com.ghomerr.travelgates.listeners.TravelGatesPlayerListener;
import com.ghomerr.travelgates.listeners.TravelGatesPortalListener;
import com.ghomerr.travelgates.listeners.TravelGatesSignListener;
import com.ghomerr.travelgates.messages.TravelGatesMessages;
import com.ghomerr.travelgates.messages.TravelGatesMessagesManager;
import com.ghomerr.travelgates.objects.TravelGatesOptionsContainer;
import com.ghomerr.travelgates.objects.TravelGatesTeleportBlock;
import com.ghomerr.travelgates.utils.TravelGatesUtils;
import com.nijiko.permissions.PermissionHandler;
import com.nijikokun.bukkit.Permissions.Permissions;
public class TravelGates extends JavaPlugin
{
private static final Logger _LOGGER = Logger.getLogger(TravelGatesConstants.MINECRAFT);
// Misc
private boolean _pluginEnabled = false;
private PluginManager _pm = null;
// config
private String _language = TravelGatesConstants.DEFAULT_LANGUAGE;
private boolean _usePermissions = false;
private boolean _teleportWithSign = true;
private boolean _teleportWithPortal = false;
private boolean _clearAllInventory = false;
private boolean _protectAdminInventory = false;
private boolean _autosave = false;
private boolean _isDebugEnabled = false;
private TravelGatesTeleportBlock _tpBlock = new TravelGatesTeleportBlock();
// messages
private TravelGatesMessagesManager _messages = null;
private String _portalSignOnState = null;
private String _portalSignOffState = null;
// Cache
private HashMap<String, String> _mapShortLocationsByDest = new HashMap<String, String>();
private HashMap<String, Location> _mapLocationsByDest = new HashMap<String, Location>();
private HashMap<String, String> _mapDestinationsByShortLoc = new HashMap<String, String>();
private HashMap<String, TravelGatesOptionsContainer> _mapOptionsByDest = new HashMap<String, TravelGatesOptionsContainer>();
private HashMap<String, Integer> _mapMaterialIdByName = new HashMap<String, Integer>();
private HashMap<String, DyeColor> _mapDyeColorByName = new HashMap<String, DyeColor>();
private HashMap<String, TreeSpecies> _mapTreeSpeciesByName = new HashMap<String, TreeSpecies>();
private HashSet<String> _setAdditionalWorlds = new HashSet<String>();
// Files and data
private Properties _configData = new Properties();
private File _configFile = null;
private Properties _destinationsData = new Properties();
private File _destinationsFile = null;
private Properties _restrictionsData = new Properties();
private File _restrictionsFile = null;
// Permissions
private boolean _useNativePermissions = false;
private boolean _usePermissionsBukkit = false;
private boolean _usePermissionsEx = false;
private PermissionHandler _permHandler = null;
private PermissionManager _permManager = null;
// Listeners
public TravelGatesPlayerListener playerListener = null;
public TravelGatesPortalListener portalListener = null;
public TravelGatesSignListener portalSignListener = null;
// Constants
private final String _tag = TravelGatesConstants.PLUGIN_TAG;
private final String _debug = TravelGatesConstants.DEBUG_TAG;
public void onEnable()
{
super.onEnable();
// Must be done before loadXXX() methods !
_pm = getServer().getPluginManager();
// Load Configuration
_pluginEnabled = loadConfiguration();
if (_pluginEnabled)
{
// Must be loaded before loadConfiguration()
_pluginEnabled = _pluginEnabled && loadAdditionalWorld();
_pluginEnabled = _pluginEnabled && loadMessages();
_pluginEnabled = _pluginEnabled && loadPermissions();
_pluginEnabled = _pluginEnabled && loadDestinations();
}
if (!_pluginEnabled)
{
_LOGGER.severe(_tag + " Plugin loading failed. All commands are disabled.");
}
else
{
playerListener = new TravelGatesPlayerListener(this);
portalListener = new TravelGatesPortalListener(this);
portalSignListener = new TravelGatesSignListener(this);
final TravelGatesCommandExecutor commandeExecutor = new TravelGatesCommandExecutor(this);
// Register commands
for (final String cmd : TravelGatesCommands.TRAVELGATES.list())
{
final PluginCommand pluginCmd = this.getCommand(cmd);
if (pluginCmd != null)
{
pluginCmd.setExecutor(commandeExecutor);
}
else
{
_LOGGER.severe(_tag + " Command " + cmd + " could not be added.");
}
}
}
// End
_LOGGER.info(_tag + " Plugin loading done. There are " + _mapShortLocationsByDest.size() + " destinations loaded.");
}
public void onDisable()
{
super.onDisable();
saveAll();
_LOGGER.info(_tag + " Plugin unloading done.");
}
public boolean saveConfiguration()
{
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " Start saveConfiguration()");
}
boolean saveSuccess = saveFile(_configFile, _configData, TravelGatesConstants.CONFIG_FILE_NAME);
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " End saveConfiguration : " + saveSuccess);
}
return saveSuccess;
}
public boolean saveDestinations()
{
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " Start saveDestinations()");
}
boolean saveSuccess = saveFile(_destinationsFile, _destinationsData, TravelGatesConstants.DEST_FILE_NAME);
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " End saveDestinations : " + saveSuccess);
}
return saveSuccess;
}
public boolean saveRestrictions()
{
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " Start saveRestrictions()");
}
boolean saveSuccess = saveFile(_restrictionsFile, _restrictionsData, TravelGatesConstants.RESTRICTIONS_FILE_NAME);
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " End saveRestrictions : " + saveSuccess);
}
return saveSuccess;
}
public boolean saveData()
{
return saveDestinations() && saveRestrictions();
}
public boolean saveAll()
{
return saveConfiguration() && saveData();
}
private boolean saveFile(final File file, final Properties data, final String fileName)
{
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " Start saveFile : " + fileName);
}
boolean ret = false;
if (file != null && file.exists())
{
if (data != null && !data.isEmpty())
{
FileOutputStream out = null;
try
{
out = new FileOutputStream(file);
}
catch (final FileNotFoundException ex)
{
_LOGGER.severe(_tag + " File " + fileName + " not found. ");
ex.printStackTrace();
}
try
{
data.store(out, null);
out.close();
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " End saveFile : " + true);
}
ret = true;
}
catch (final IOException ex)
{
_LOGGER.severe(_tag + " " + fileName + " file update failed !");
ex.printStackTrace();
}
}
else
{
_LOGGER.info(_tag + " No data to save in " + fileName);
ret = true;
}
}
else
{
_LOGGER.severe(_tag + " File " + fileName + " doesn't exist !");
}
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " End saveFile : " + ret);
}
return ret;
}
public boolean isPluginEnabled()
{
return _pluginEnabled;
}
public void addDestination(final Player player, final String destination, final Location loc, final TravelGatesOptionsContainer container)
{
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " Start addDestination(destination=" + destination + ", container=" + container + ", player=" + player + ")");
}
final String shortLoc = TravelGatesUtils.locationToShortString(loc);
String fullLoc = TravelGatesUtils.locationToFullString(loc);
final String lowerCaseDest = destination.toLowerCase();
_mapShortLocationsByDest.put(lowerCaseDest, shortLoc);
_mapLocationsByDest.put(lowerCaseDest, TravelGatesUtils.shortStringToLocation(shortLoc, getServer().getWorlds()));
_mapDestinationsByShortLoc.put(shortLoc, lowerCaseDest);
fullLoc = fullLoc + TravelGatesConstants.DELIMITER + container.getOptionsForData();
_destinationsData.put(lowerCaseDest, fullLoc);
if (container.has(TravelGatesOptions.RESTRICTION))
{
_restrictionsData.put(destination, container.getRestrictionsListString());
}
if (container.has(TravelGatesOptions.SAVE) || _autosave)
{
final boolean saved = saveData();
if (saved)
{
player.sendMessage(ChatColor.GREEN + _messages.get(TravelGatesMessages.SAVE_DONE));
}
else
{
player.sendMessage(ChatColor.RED + _messages.get(TravelGatesMessages.SAVE_FAILED));
}
}
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " End addDestination");
}
}
public Location getLocationFromPosition(final Player player, final Location playerLoc, final String position)
{
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " Start getLocationFromPosition(player=" + player + ", playerLoc=" + playerLoc + ", position=" + position + ")");
}
Location destinationLocation = null;
if (TravelGatesUtils.stringIsBlank(position))
{
destinationLocation = playerLoc;
}
else
{
final String[] positionData = position.split(TravelGatesConstants.DELIMITER);
final int numberOfItems = positionData.length;
if (numberOfItems == 3)
{
try
{
final World world = player.getWorld();
destinationLocation = TravelGatesUtils.getDestinationLocation(world, positionData, playerLoc,
TravelGatesConstants.POSITION_WITHOUT_WORLD);
}
catch (final Throwable th)
{
player.sendMessage(ChatColor.RED + _messages.get(TravelGatesMessages.WRONG_POSITION_VALUE));
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " Exception caught : ");
}
th.printStackTrace();
}
}
else if (numberOfItems == 4)
{
try
{
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " World name : " + positionData[0]);
}
final World world = getServer().getWorld(positionData[0]);
destinationLocation = TravelGatesUtils.getDestinationLocation(world, positionData, playerLoc,
TravelGatesConstants.POSITION_WITH_WORLD);
}
catch (final Throwable th)
{
player.sendMessage(ChatColor.RED + _messages.get(TravelGatesMessages.WRONG_POSITION_VALUE));
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " Exception caught : ");
}
th.printStackTrace();
}
}
else
{
player.sendMessage(ChatColor.RED + _messages.get(TravelGatesMessages.WRONG_POSITION_VALUE));
}
}
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " End getLocationFromPosition : " + destinationLocation);
}
return destinationLocation;
}
public void deleteDestination(final String destination, final boolean save, final Player player)
{
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " Start deleteDestination(destination=" + destination + ")");
}
final String lowerCaseDest = destination.toLowerCase();
_destinationsData.remove(lowerCaseDest);
_restrictionsData.remove(lowerCaseDest);
_mapDestinationsByShortLoc.remove(_mapShortLocationsByDest.get(lowerCaseDest));
_mapLocationsByDest.remove(lowerCaseDest);
_mapShortLocationsByDest.remove(lowerCaseDest);
_mapOptionsByDest.get(lowerCaseDest).clear();
_mapOptionsByDest.remove(lowerCaseDest);
if (save || _autosave)
{
final boolean saved = saveData();
if (saved)
{
player.sendMessage(ChatColor.GREEN + _messages.get(TravelGatesMessages.SAVE_DONE));
}
else
{
player.sendMessage(ChatColor.RED + _messages.get(TravelGatesMessages.SAVE_FAILED));
}
}
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " End deleteDestination");
}
}
public boolean hasDestination(final String destination)
{
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " Start hasDestination(destination=" + destination + ")");
}
final boolean hasDest = _mapShortLocationsByDest.containsKey(destination.toLowerCase());
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " End hasDestination : " + hasDest);
}
return hasDest;
}
public boolean hasLocation(final Location loc)
{
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " Start hasLocation(loc=" + loc + ")");
}
final String shortLoc = TravelGatesUtils.locationToShortString(loc);
final boolean hasLoc = hasShortLocation(shortLoc); // _shortLocations.containsValue(shortLoc);
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " End hasLocation : " + hasLoc);
}
return hasLoc;
}
public boolean hasShortLocation(final String shortLoc)
{
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " Start hasShortLocation(loc=" + shortLoc + ")");
}
final boolean hasShortLoc = _mapDestinationsByShortLoc.containsKey(shortLoc);
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " End hasShortLocation : " + hasShortLoc);
}
return hasShortLoc;
}
public String getDestinationsList()
{
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " Start destList()");
}
final StringBuilder strBuild = new StringBuilder();
strBuild.append(_messages.get(TravelGatesMessages.AVAILABLE_DESTINATIONS));
final int initLength = strBuild.length();
for (final String dest : _mapShortLocationsByDest.keySet())
{
strBuild.append(" ").append(ChatColor.AQUA).append(dest).append(ChatColor.YELLOW).append(TravelGatesConstants.DELIMITER);
}
final int endLength = strBuild.length();
if (initLength < endLength)
{
strBuild.deleteCharAt(endLength - 1);
}
else
{
strBuild.append(ChatColor.AQUA).append(_messages.get(TravelGatesMessages.NONE));
}
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " End destList : " + strBuild.toString());
}
return strBuild.toString();
}
public String getRestrictionsList(final String destination)
{
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " Start restrictionsList(destination=" + destination + ")");
}
final String lowerCaseDest = destination.toLowerCase();
final StringBuilder strBuild = new StringBuilder();
strBuild.append(_messages.get(TravelGatesMessages.RESTRICTED_DESTINATIONS_ARE, ChatColor.AQUA + lowerCaseDest + ChatColor.YELLOW));
final int initLength = strBuild.length();
final HashSet<String> restrictedDests = _mapOptionsByDest.get(destination).getRestrictionsList();
if (restrictedDests != null)
{
for (final String dest : restrictedDests)
{
strBuild.append(" ").append(ChatColor.AQUA).append(dest).append(ChatColor.YELLOW).append(TravelGatesConstants.DELIMITER);
}
}
final int endLength = strBuild.length();
if (initLength < endLength)
{
strBuild.deleteCharAt(endLength - 1);
}
else
{
strBuild.append(ChatColor.AQUA).append(" ").append(_messages.get(TravelGatesMessages.ALL));
}
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " End restrictionsList : " + strBuild.toString());
}
return strBuild.toString();
}
public String getDestinationsDetailsList()
{
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " Start destDetailedList()");
}
final StringBuilder strBuild = new StringBuilder();
strBuild.append(_messages.get(TravelGatesMessages.AVAILABLE_DESTINATIONS));
final int initLength = strBuild.length();
for (final String dest : _mapShortLocationsByDest.keySet())
{
strBuild.append(getDestinationDetails(dest));
}
final int endLength = strBuild.length();
if (initLength == endLength)
{
strBuild.append(ChatColor.AQUA).append(_messages.get(TravelGatesMessages.NONE));
}
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " End destDetailedList : " + strBuild.toString());
}
return strBuild.toString();
}
public String getDestinationDetails(final String dest)
{
final StringBuilder strBuild = new StringBuilder();
if (strBuild.length() > 0)
{
strBuild.append(TravelGatesConstants.DELIMITER).append(" ");
}
final boolean inventoryCleared = getOptionOfDestination(dest, TravelGatesOptions.INVENTORY);
final String msgInventory = (inventoryCleared) ? ChatColor.RED + _messages.get(TravelGatesMessages.INVENTORY_CLEAR) : ChatColor.GREEN
+ _messages.get(TravelGatesMessages.INVENTORY_KEEP);
final boolean isAdminTP = getOptionOfDestination(dest, TravelGatesOptions.ADMINTP);
final String msgAdmin = (isAdminTP) ? ChatColor.RED + _messages.get(TravelGatesMessages.ADMIN_TP) : ChatColor.GREEN
+ _messages.get(TravelGatesMessages.FREE_TP);
final boolean isRestricted = getOptionOfDestination(dest, TravelGatesOptions.RESTRICTION);
final String msgRestrictions = (isRestricted) ? ChatColor.RED + _messages.get(TravelGatesMessages.DEST_RESTRICTED) : ChatColor.GREEN
+ _messages.get(TravelGatesMessages.DEST_FREE);
strBuild.append(ChatColor.AQUA).append(dest).append(ChatColor.YELLOW).append("=(").append(ChatColor.GREEN)
.append(_mapShortLocationsByDest.get((String) dest).toLowerCase()).append(ChatColor.YELLOW).append(")[").append(msgAdmin)
.append(ChatColor.YELLOW).append(TravelGatesConstants.DELIMITER).append(msgInventory).append(ChatColor.YELLOW)
.append(TravelGatesConstants.DELIMITER).append(msgRestrictions).append(ChatColor.YELLOW).append("]");
return strBuild.toString();
}
public String getCurrentConfiguration()
{
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " Start getCurrentConfiguration()");
}
final StringBuilder strBuild = new StringBuilder();
strBuild.append(ChatColor.YELLOW).append(_messages.get(TravelGatesMessages.CURRENT_CONFIG));
for (final Object o : _configData.keySet())
{
final String key = o.toString();
final String value = _configData.getProperty(key);
final Boolean boolValue = new Boolean(value);
if (TravelGatesConfigurations.LANGUAGE.value().equalsIgnoreCase(key))
{
strBuild.append(" ").append(ChatColor.AQUA).append(TravelGatesConfigurations.LANGUAGE.value()).append(ChatColor.YELLOW).append("=")
.append(ChatColor.WHITE).append(_language);
}
else if (TravelGatesConfigurations.TPBLOCK.value().equalsIgnoreCase(key))
{
strBuild.append(" ").append(ChatColor.AQUA).append(TravelGatesConfigurations.TPBLOCK.value()).append(ChatColor.YELLOW).append("=")
.append(ChatColor.WHITE).append(_tpBlock);
}
else if (TravelGatesConfigurations.WORLDS.value().equalsIgnoreCase(key))
{
strBuild.append(" ").append(ChatColor.AQUA).append(TravelGatesConfigurations.WORLDS.value()).append(ChatColor.YELLOW).append("=")
.append(ChatColor.WHITE).append(getListOfAdditionnalWorld());
}
else
{
strBuild.append(" ").append(ChatColor.AQUA).append(key).append(ChatColor.YELLOW).append("=")
.append((boolValue.booleanValue()) ? ChatColor.GREEN : ChatColor.RED).append(value);
}
}
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " End getCurrentConfiguration : " + strBuild.toString());
}
return strBuild.toString();
}
public TravelGatesOptionsContainer getOptionsOfDestination(final String destination)
{
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " Start getOptionsOfDestination(destination=" + destination + ")");
}
final TravelGatesOptionsContainer container = _mapOptionsByDest.get(destination.toLowerCase());
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " End getOptionsOfDestination : " + container);
}
return container;
}
public boolean getOptionOfDestination(final String destination, final TravelGatesOptions option)
{
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " Start getOptionOfDestination(destination=" + destination + ", option=" + option + ")");
}
String lowerDest = null;
boolean optionValue = false;
try
{
lowerDest = destination.toLowerCase();
}
catch (final Throwable th)
{
_LOGGER.severe(_tag + " Exception caught while getting lower case of destination : " + destination);
th.printStackTrace();
}
if (lowerDest != null)
{
final TravelGatesOptionsContainer container = _mapOptionsByDest.get(lowerDest);
optionValue = container.has(option);
}
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " End getOptionOfDestination : " + optionValue);
}
return optionValue;
}
public void setOptionOfDestination(final String destination, final TravelGatesOptions option, final boolean newValue)
{
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " Start setOptionOfDestination(destination=" + destination + ", option=" + option + ", newValue=" + newValue + ")");
}
final TravelGatesOptionsContainer container = _mapOptionsByDest.get(destination.toLowerCase());
container.set(option, newValue);
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " End setOptionOfDestination");
}
}
public String getShortLoc(final String destination)
{
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " Start getShortLoc(destination=" + destination + ")");
}
final String shortLoc = _mapShortLocationsByDest.get(destination.toLowerCase());
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " End getShortLoc : " + shortLoc);
}
return shortLoc;
}
public Location getLocation(final String destination)
{
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " Start getLocation(destination=" + destination + ")");
}
final Location loc = _mapLocationsByDest.get(destination.toLowerCase());
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " End getLocation : " + loc);
}
return loc;
}
public String getFullLoc(final String destination)
{
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " Start getFullLoc(destination=" + destination + ")");
}
final String fullLoc = _destinationsData.getProperty(destination.toLowerCase());
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " End getFullLoc : " + fullLoc);
}
return fullLoc;
}
public String getDestination(final Location location)
{
String dest = null;
final String shortLoc = TravelGatesUtils.locationToShortString(location);
dest = getDestination(shortLoc);
return dest;
}
public String getDestination(final String shortLoc)
{
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " Start getDestination(shortLoc=" + shortLoc + ")");
}
String dest = null;
dest = _mapDestinationsByShortLoc.get(shortLoc);
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " End getDestination : " + dest);
}
return dest;
}
public String getDestPattern()
{
return TravelGatesConstants.DESTINATION_NAME_PATTERN;
}
public boolean teleportPlayerToDest(final String dest, final Player player, final boolean destHasBeenChecked,
final boolean ignorePlayerLocation, final String portalDestinationShortLoc)
{
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " Start teleportPlayerToDest(dest=" + dest + ", player=" + player + ", destHasBeenChecked=" + destHasBeenChecked
+ ", ignorePlayerLocation=" + ignorePlayerLocation + ")");
}
final String destination = dest.toLowerCase();
if (ignorePlayerLocation || destHasBeenChecked || hasDestination(destination))
{
final String fullLoc = getFullLoc(destination);
final String shortLoc = getShortLoc(destination);
if (getOptionOfDestination(destination, TravelGatesOptions.ADMINTP))
{
if (!hasPermission(player, TravelGatesPermissionsNodes.ADMINTP))
{
player.sendMessage(ChatColor.RED + _messages.get(TravelGatesMessages.ONLY_ADMIN_TP));
return false;
}
}
final Location playerLocation = player.getLocation();
final String playerShortLoc = TravelGatesUtils.locationToShortString(playerLocation);
final boolean targetAndCurrentLocationAreDifferent = !shortLoc.equalsIgnoreCase(playerShortLoc);
final boolean playerIsOnExistingDestination = hasShortLocation(playerShortLoc);
boolean playerNotOnTeleportBlock = false;
String nearestDestinationShortLocation = null;
if (!ignorePlayerLocation)
{
if (playerIsOnExistingDestination || portalDestinationShortLoc != null)
{
if (portalDestinationShortLoc == null && _tpBlock.isEnabled() && !_tpBlock.isTPBlock(player.getWorld().getBlockAt(playerLocation).getRelative(BlockFace.DOWN)))
{
playerNotOnTeleportBlock = true;
}
if (playerIsOnExistingDestination)
{
nearestDestinationShortLocation = playerShortLoc;
}
else if (portalDestinationShortLoc != null)
{
nearestDestinationShortLocation = portalDestinationShortLoc;
}
}
else
{
if (_tpBlock.isEnabled())
{
if (_isDebugEnabled)
{
_LOGGER.info("#0 : Not on dest and tp block enabled");
}
final World currWorld = player.getWorld();
if (_isDebugEnabled)
{
_LOGGER.info("#0-bis : currWorld = " + currWorld);
_LOGGER.info("#0-ters : type block = " + currWorld.getBlockAt(playerLocation).getRelative(BlockFace.DOWN).getType());
}
playerNotOnTeleportBlock = !_tpBlock.isTPBlock(currWorld.getBlockAt(playerLocation).getRelative(BlockFace.DOWN));
if (_isDebugEnabled)
{
_LOGGER.info("#1 : playerNotOnTeleportBlock = " + playerNotOnTeleportBlock);
}
if (!playerNotOnTeleportBlock)
{
// Search the locations in the current player's
// world
ArrayList<Location> rightWorldsList = new ArrayList<Location>();
for (final Object key : _mapLocationsByDest.keySet())
{
final Location loc = _mapLocationsByDest.get(key);
if (_isDebugEnabled)
{
_LOGGER.info("#1bis : key = " + key + " ; playerLocation.getWorld()=" + playerLocation.getWorld()
+ " ; loc.getWorld()= " + loc.getWorld());
}
if (playerLocation.getWorld() == loc.getWorld())
{
rightWorldsList.add(loc);
}
}
if (_isDebugEnabled)
{
_LOGGER.info("#2 : rightWorldsList size = " + rightWorldsList.size());
}
if (!rightWorldsList.isEmpty())
{
// Search the locations at the same height
ArrayList<Location> rightHeightList = new ArrayList<Location>();
for (final Location loc : rightWorldsList)
{
if (loc.getBlockY() == playerLocation.getBlockY())
{
rightHeightList.add(loc);
}
}
if (_isDebugEnabled)
{
_LOGGER.info("#3 : rightHeightList size = " + rightHeightList.size());
}
if (!rightHeightList.isEmpty())
{
// Search the nearest destination from
// the
// Player's location
Location nearestDestinationLocation = null;
int lastMinX = TravelGatesConstants.MAX_COORDINATE;
int lastMinZ = TravelGatesConstants.MAX_COORDINATE;
if (_isDebugEnabled)
{
_LOGGER.info("#3-a : nearestDestinationLocation = " + nearestDestinationLocation);
}
for (final Location loc : rightHeightList)
{
if (_isDebugEnabled)
{
_LOGGER.info("#3-b : loc = " + loc);
}
if (nearestDestinationLocation == null)
{
lastMinX = TravelGatesUtils.getCoordinateDiff(loc.getBlockX(), playerLocation.getBlockX());
lastMinZ = TravelGatesUtils.getCoordinateDiff(loc.getBlockZ(), playerLocation.getBlockZ());
nearestDestinationLocation = loc;
if (_isDebugEnabled)
{
_LOGGER.info("#3-c : lastMinX = " + lastMinX + " ; lastMinZ = " + lastMinZ);
}
}
else
{
final int xDiff = TravelGatesUtils.getCoordinateDiff(loc.getBlockX(), playerLocation.getBlockX());
final int zDiff = TravelGatesUtils.getCoordinateDiff(loc.getBlockZ(), playerLocation.getBlockZ());
if (_isDebugEnabled)
{
_LOGGER.info("#3-d : xDiff = " + xDiff + " ; zDiff = " + zDiff);
_LOGGER.info("#3-e : lastMinX = " + lastMinX + " ; lastMinZ = " + lastMinZ);
}
if (xDiff + zDiff <= lastMinX + lastMinZ)
{
lastMinX = xDiff;
lastMinZ = zDiff;
nearestDestinationLocation = loc;
}
}
if (_isDebugEnabled)
{
_LOGGER.info("#3-f : nearestDestinationLocation = " + nearestDestinationLocation);
}
}
if (_isDebugEnabled)
{
_LOGGER.info("#4 : nearestDestinationLocation = " + nearestDestinationLocation);
}
if (nearestDestinationLocation != null)
{
int pX = playerLocation.getBlockX();
int pZ = playerLocation.getBlockZ();
if (_isDebugEnabled)
{
_LOGGER.info("#5 : pX = " + pX + " ; pZ = " + pZ);
}
final int dX = nearestDestinationLocation.getBlockX();
final int dZ = nearestDestinationLocation.getBlockZ();
if (_isDebugEnabled)
{
_LOGGER.info("#6 : dX = " + dX + " ; dZ = " + dZ);
}
int xDiff = TravelGatesUtils.getCoordinateDiff(dX, pX);
int zDiff = TravelGatesUtils.getCoordinateDiff(dZ, pZ);
if (_isDebugEnabled)
{
_LOGGER.info("#7 : xDiff = " + xDiff + " ; zDiff = " + zDiff);
}
// The nearest destination is at 5
// blocks max from the player
if (xDiff <= TravelGatesConstants.MAX_TARGET_RANGE && zDiff <= TravelGatesConstants.MAX_TARGET_RANGE)
{
final int offsetX = ((pX - dX) > 0) ? -1 : 1;
final int offsetZ = ((pZ - dZ) > 0) ? -1 : 1;
if (_isDebugEnabled)
{
_LOGGER.info("#8 : offsetX = " + offsetX + " ; offsetZ = " + offsetZ);
}
final int heightOfBeneathBlock = playerLocation.getBlockY() - 1;
if (_isDebugEnabled)
{
_LOGGER.info("#9 : heightOfBeneathBlock = " + heightOfBeneathBlock);
}
// Is blocks between player and
// the
// nearest destination are TP
// blocks
// ?
while (xDiff > 0 && !playerNotOnTeleportBlock)
{
pX += offsetX;
playerNotOnTeleportBlock = !_tpBlock.isTPBlock(currWorld.getBlockAt(pX, heightOfBeneathBlock, pZ));
xDiff = TravelGatesUtils.getCoordinateDiff(dX, pX);
if (_isDebugEnabled)
{
_LOGGER.info("#10 : pX = " + pX + " ; xDiff = " + xDiff + " ; playerNotOnTeleportBlock = "
+ playerNotOnTeleportBlock);
}
}
if (!playerNotOnTeleportBlock)
{
while (zDiff > 0 && !playerNotOnTeleportBlock)
{
pZ += offsetZ;
playerNotOnTeleportBlock = !_tpBlock
.isTPBlock(currWorld.getBlockAt(pX, heightOfBeneathBlock, pZ));
zDiff = TravelGatesUtils.getCoordinateDiff(dZ, pZ);
if (_isDebugEnabled)
{
_LOGGER.info("#11 : pZ = " + pZ + " ; zDiff = " + zDiff + " ; playerNotOnTeleportBlock = "
+ playerNotOnTeleportBlock);
}
}
// Get the short loc of the
// nearest destination
if (!playerNotOnTeleportBlock)
{
nearestDestinationShortLocation = TravelGatesUtils
.locationToShortString(nearestDestinationLocation);
}
}
}
else
{
playerNotOnTeleportBlock = true;
}
}
else
{
playerNotOnTeleportBlock = true;
}
}
else
{
playerNotOnTeleportBlock = true;
}
}
else
{
playerNotOnTeleportBlock = true;
}
}
}
}
}
if (_isDebugEnabled)
{
_LOGGER.info("#12 : playerNotOnTeleportBlock = " + playerNotOnTeleportBlock);
_LOGGER.info("#13 : nearestDestinationShortLocation = " + nearestDestinationShortLocation);
}
if (_tpBlock.isEnabled() && playerNotOnTeleportBlock)
{
player.sendMessage(ChatColor.RED
+ _messages.get(TravelGatesMessages.NOT_STANDING_ON_TPBLOCK, ChatColor.YELLOW + _tpBlock.toString() + ChatColor.RED));
return false;
}
if (ignorePlayerLocation || targetAndCurrentLocationAreDifferent
- && (playerIsOnExistingDestination || !playerNotOnTeleportBlock && _tpBlock.isEnabled()))
+ && (nearestDestinationShortLocation != null || !playerNotOnTeleportBlock && _tpBlock.isEnabled()))
{
final String currentDest = _mapDestinationsByShortLoc.get(nearestDestinationShortLocation);
if (_isDebugEnabled)
{
_LOGGER.info("#14 : currentDest = " + currentDest);
}
if (!ignorePlayerLocation)
{
if (currentDest != null && getOptionOfDestination(currentDest, TravelGatesOptions.RESTRICTION))
{
final TravelGatesOptionsContainer container = _mapOptionsByDest.get(currentDest);
if (container != null && !container.isDestinationAllowed(destination))
{
player.sendMessage(ChatColor.RED
+ _messages.get(TravelGatesMessages.DESTINATION_IS_RESTRICTED, ChatColor.AQUA + currentDest + ChatColor.RED,
ChatColor.AQUA + destination + ChatColor.RED));
return false;
}
}
else if (currentDest == null)
{
player.sendMessage(ChatColor.RED + _messages.get(TravelGatesMessages.NO_STANDING_ON_DESTINATION));
return false;
}
}
final Location targetLocation = TravelGatesUtils.fullStringToLocation(fullLoc, player.getServer().getWorlds());
if (targetLocation.getWorld() != null)
{
player.teleport(targetLocation);
}
else
{
player.sendMessage(ChatColor.RED
+ _messages.get(TravelGatesMessages.TELEPORT_CANCELLED_WORLD_UNLOADED, ChatColor.AQUA + destination + ChatColor.RED));
return false;
}
if (ignorePlayerLocation)
{
_LOGGER.info(_tag + " " + player.getName() + " has forced the travel from " + playerShortLoc + " to " + destination);
}
else
{
_LOGGER.info(_tag + " " + player.getName() + " has travelled from " + currentDest + " to " + destination);
}
final boolean inventoryCleared = getOptionOfDestination(destination, TravelGatesOptions.INVENTORY);
// System.out.println("inventoryCleared=" + inventoryCleared + "; _protectAdminInventory=" + _protectAdminInventory
// + "; perm=" + hasPermission(player, TravelGatesPermissionsNodes.PROTECTADMININV));
if (!inventoryCleared || isProtectedInventory(player))
{
player.sendMessage(ChatColor.YELLOW
+ _messages.get(TravelGatesMessages.YOU_ARE_ARRIVED_AT, ChatColor.AQUA + destination + ChatColor.YELLOW)
+ ChatColor.GREEN + _messages.get(TravelGatesMessages.INVENTORY_KEPT));
}
else
{
String inventoryMessage = "";
final PlayerInventory inventory = player.getInventory();
if (_clearAllInventory)
{
inventory.setArmorContents(null);
inventoryMessage = _messages.get(TravelGatesMessages.ALL_INVENTORY_LOST);
}
else
{
inventoryMessage = _messages.get(TravelGatesMessages.INVENTORY_LOST);
}
inventory.clear();
player.sendMessage(ChatColor.YELLOW
+ _messages.get(TravelGatesMessages.YOU_ARE_ARRIVED_AT, ChatColor.AQUA + destination + ChatColor.YELLOW) + ChatColor.RED
+ inventoryMessage);
}
// If the arrival chunk is unloaded, it will be forced to load
final Chunk arrivalChunk = player.getWorld().getChunkAt(targetLocation);
if (!arrivalChunk.isLoaded())
{
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " The " + destination + "'s chunk was not loaded at " + targetLocation);
}
arrivalChunk.load();
}
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " End teleportPlayerToDest : true");
}
return true;
}
else
{
if (!targetAndCurrentLocationAreDifferent)
{
player.sendMessage(ChatColor.RED
+ _messages.get(TravelGatesMessages.YOURE_ALREADY_AT, ChatColor.AQUA + destination + ChatColor.RED));
}
else if (!playerIsOnExistingDestination)
{
player.sendMessage(ChatColor.RED
+ _messages.get(TravelGatesMessages.YOU_CANT_GO_THERE, ChatColor.AQUA + destination + ChatColor.RED));
}
}
}
else
{
player.sendMessage(ChatColor.RED
+ _messages.get(TravelGatesMessages.DESTINATION_DOESNT_EXIST, ChatColor.AQUA + destination + ChatColor.RED));
}
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " End teleportPlayerToDest : false");
}
return false;
}
public String getMessage(final TravelGatesMessages message, final String... vars)
{
return _messages.get(message, vars);
}
public boolean usePermissions()
{
return _usePermissions;
}
private boolean loadDestinations()
{
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " Start loadDestinations()");
}
boolean ret = false;
boolean isfileCreated = false;
_destinationsFile = new File(TravelGatesConstants.PLUGIN_FILE_PATH);
if (!_destinationsFile.exists())
{
try
{
final File rootDir = new File(TravelGatesConstants.PLUGIN_ROOT_PATH);
isfileCreated = rootDir.mkdir();
isfileCreated &= _destinationsFile.createNewFile();
_destinationsFile.setReadable(true, false);
_destinationsFile.setWritable(true, false);
_destinationsFile.setExecutable(true, false);
}
catch (final IOException ioex)
{
_LOGGER.severe(_tag + " Destinations file creation failed !");
ioex.printStackTrace();
}
}
else
{
isfileCreated = true;
}
if (!isfileCreated)
{
_LOGGER.severe(_tag + " Destinations file creation failed !");
}
else
{
FileInputStream in = null;
try
{
in = new FileInputStream(_destinationsFile);
}
catch (final FileNotFoundException ex)
{
_LOGGER.info(_tag + " Destinations file failed to be read : ");
ex.printStackTrace();
}
if (in != null)
{
try
{
_destinationsData.load(in);
in.close();
}
catch (final IOException ex)
{
_LOGGER.severe(_tag + " Error while reading the Destinations file.");
ex.printStackTrace();
}
if (!_destinationsData.isEmpty())
{
for (final Object key : _destinationsData.keySet())
{
final String dest = String.valueOf(key).toLowerCase();
final String fullString = _destinationsData.getProperty(dest);
final String shortLoc = TravelGatesUtils.fullStringToShortString(fullString);
_mapShortLocationsByDest.put(dest, shortLoc);
_mapLocationsByDest.put(dest, TravelGatesUtils.shortStringToLocation(shortLoc, getServer().getWorlds()));
_mapDestinationsByShortLoc.put(shortLoc, dest);
final TravelGatesOptionsContainer container = new TravelGatesOptionsContainer(this, fullString.substring(1 + fullString
.lastIndexOf(TravelGatesConstants.DELIMITER)));
_mapOptionsByDest.put(dest, container);
}
loadRestrictions();
}
ret = true;
}
else
{
_LOGGER.info(_tag + " Destinations file could not be loaded.");
}
}
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " End loadDestinations : " + ret);
}
return ret;
}
private void loadRestrictions()
{
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " Start loadRestrictions()");
}
_restrictionsFile = new File(TravelGatesConstants.PLUGIN_RESTRICTIONS_FILE_PATH);
if (_restrictionsFile.exists())
{
FileInputStream in = null;
try
{
in = new FileInputStream(_restrictionsFile);
}
catch (final FileNotFoundException ex)
{
_LOGGER.info(_tag + " Restrictions file not found.");
ex.printStackTrace();
return;
}
if (in != null)
{
try
{
_restrictionsData.load(in);
in.close();
}
catch (final IOException ex)
{
_LOGGER.severe(_tag + " Error while reading the Restrictions file.");
ex.printStackTrace();
}
if (!_restrictionsData.isEmpty())
{
for (final Object key : _restrictionsData.keySet())
{
final String dest = String.valueOf(key).toLowerCase();
final TravelGatesOptionsContainer optionsContainer = _mapOptionsByDest.get(dest);
if (optionsContainer.has(TravelGatesOptions.RESTRICTION))
{
optionsContainer.setRestrictionsList(_restrictionsData.getProperty(dest));
}
}
}
}
}
else
{
_LOGGER.info(_tag + " Restrictions file not found. New file created with the name : " + TravelGatesConstants.RESTRICTIONS_FILE_NAME);
try
{
_restrictionsFile.createNewFile();
_restrictionsFile.setReadable(true, false);
_restrictionsFile.setWritable(true, false);
_restrictionsFile.setExecutable(true, false);
}
catch (final IOException e)
{
_LOGGER.severe(_tag + " Unable to create Restriction file: ");
e.printStackTrace();
}
}
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " End loadRestrictions");
}
}
private boolean loadConfiguration()
{
_configFile = new File(TravelGatesConstants.PLUGIN_CONFIG_PATH);
if (_configFile.exists())
{
FileInputStream in = null;
try
{
in = new FileInputStream(_configFile);
}
catch (final Throwable ex)
{
_LOGGER.severe(_tag + " Unable to create a stream to read the configuration file.");
ex.printStackTrace();
return false;
}
if (in != null)
{
// LOAD CONFIGURATIONS
try
{
_configData.load(in);
in.close();
}
catch (final IOException ex)
{
_LOGGER.severe(_tag + " Error while loading the Configuration file.");
ex.printStackTrace();
return false;
}
// DEBUG
try
{
final String debugEnabled = _configData.getProperty(TravelGatesConfigurations.DEBUG.value());
if (TravelGatesUtils.stringIsNotBlank(debugEnabled))
{
_isDebugEnabled = Boolean.parseBoolean(debugEnabled.toLowerCase());
TravelGatesUtils.setDebugState(_isDebugEnabled);
}
else
{
_LOGGER.warning(_tag + " Debug configuration not found.");
}
_LOGGER.info(_tag + " Debug configuration set to : " + _isDebugEnabled);
}
catch (final Throwable th)
{
_LOGGER.severe(_tag + " Debug configuration reading failed.");
th.printStackTrace();
return false;
}
// LANGUAGE
try
{
final String language = _configData.getProperty(TravelGatesConfigurations.LANGUAGE.value());
if (TravelGatesUtils.stringIsNotBlank(language))
{
_language = language.toLowerCase();
}
else
{
_LOGGER.warning(_tag + " Language configuration not found.");
}
_LOGGER.info(_tag + " Language configuration set to : " + _language);
}
catch (final Throwable th)
{
_LOGGER.severe(_tag + " Language configuration reading failed.");
th.printStackTrace();
return false;
}
// USE PERMISSIONS
try
{
final String usePermissions = _configData.getProperty(TravelGatesConfigurations.USEPERMISSIONS.value());
if (TravelGatesUtils.stringIsNotBlank(usePermissions))
{
_usePermissions = Boolean.parseBoolean(usePermissions.toLowerCase());
}
else
{
_LOGGER.warning(_tag + " Permissions configuration not found.");
}
_LOGGER.info(_tag + " Permissions configuration set to : " + _usePermissions);
}
catch (final Throwable th)
{
_LOGGER.severe(_tag + " Permissions configuration reading failed.");
th.printStackTrace();
return false;
}
// TELEPORT MODES
try
{
final String teleportWithSign = _configData.getProperty(TravelGatesConfigurations.TELEPORTWITHSIGN.value());
final String teleportWithPortal = _configData.getProperty(TravelGatesConfigurations.TELEPORTWITHPORTAL.value());
if (TravelGatesUtils.stringIsNotBlank(teleportWithSign))
{
_teleportWithSign = Boolean.parseBoolean(teleportWithSign.toLowerCase());
}
else
{
_LOGGER.warning(_tag + " Sign teleportation configuration not found.");
}
if (TravelGatesUtils.stringIsNotBlank(teleportWithPortal))
{
_teleportWithPortal = Boolean.parseBoolean(teleportWithPortal.toLowerCase());
}
else
{
_LOGGER.warning(_tag + " Portal teleportation configuration not found.");
}
_LOGGER.info(_tag + " Teleport modes configuration set to : sign=" + _teleportWithSign + ", portal=" + _teleportWithPortal);
}
catch (final Throwable th)
{
_LOGGER.severe(_tag + " Teleport modes configuration reading failed.");
th.printStackTrace();
return false;
}
// CLEAR ALL INVENTORY
try
{
final String clearAllInventory = _configData.getProperty(TravelGatesConfigurations.CLEARALLINVENTORY.value());
if (TravelGatesUtils.stringIsNotBlank(clearAllInventory))
{
_clearAllInventory = Boolean.parseBoolean(clearAllInventory.toLowerCase());
}
else
{
_LOGGER.warning(_tag + " Clear all inventory configuration not found.");
}
_LOGGER.info(_tag + " Clear all inventory configuration set to : " + _clearAllInventory);
}
catch (final Throwable th)
{
_LOGGER.severe(_tag + " Clear all inventory configuration reading failed.");
th.printStackTrace();
return false;
}
// PROTECT ADMIN INVENTORY
try
{
final String protectAdminInventory =
_configData.getProperty(TravelGatesConfigurations.PROTECTADMININVENTORY.value());
if (TravelGatesUtils.stringIsNotBlank(protectAdminInventory))
{
_protectAdminInventory = Boolean.parseBoolean(protectAdminInventory.toLowerCase());
}
else
{
_LOGGER.warning(_tag + " Protect admin inventory configuration not found.");
}
_LOGGER.info(_tag + " Protect admin inventory configuration set to : " + _protectAdminInventory);
}
catch (final Throwable th)
{
_LOGGER.severe(_tag + " Protect admin inventory configuration reading failed.");
th.printStackTrace();
return false;
}
// AUTO SAVE
try
{
final String autosave = _configData.getProperty(TravelGatesConfigurations.AUTOSAVE.value());
if (TravelGatesUtils.stringIsNotBlank(autosave))
{
_autosave = Boolean.parseBoolean(autosave.toLowerCase());
}
else
{
_LOGGER.warning(_tag + " Autosave configuration not found.");
}
_LOGGER.info(_tag + " Autosave configuration set to : " + _autosave);
}
catch (final Throwable th)
{
_LOGGER.severe(_tag + " Autosave configuration reading failed.");
th.printStackTrace();
return false;
}
// TP BLOCK
try
{
final String tpblock = _configData.getProperty(TravelGatesConfigurations.TPBLOCK.value());
if (TravelGatesUtils.stringIsNotBlank(tpblock))
{
loadMaterialTypes();
configTeleportBlock(tpblock, false);
}
else
{
_LOGGER.warning(_tag + " TP Block configuration not found.");
}
_LOGGER.info(_tag + " TP Block configuration set to : " + _tpBlock);
}
catch (final Throwable th)
{
_LOGGER.severe(_tag + " TP Block configuration reading failed.");
th.printStackTrace();
return false;
}
// ADDITIONAL WORLDS
try
{
final String worlds = _configData.getProperty(TravelGatesConfigurations.WORLDS.value());
if (TravelGatesUtils.stringIsNotBlank(worlds))
{
final String[] worldsList = worlds.split(TravelGatesConstants.DELIMITER);
for (final String world : worldsList)
{
_setAdditionalWorlds.add(world);
}
}
else
{
_LOGGER.warning(_tag + " Additional Worlds configuration not found.");
}
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " Additional Worlds configuration loaded with : " + _setAdditionalWorlds.size() + " worlds.");
}
}
catch (final Throwable th)
{
_LOGGER.severe(_tag + " Additional Worlds configuration reading failed.");
th.printStackTrace();
return false;
}
}
}
else
{
_LOGGER.info(_tag + " Configuration file not found. New file created with the name : " + TravelGatesConstants.CONFIG_FILE_NAME);
try
{
_configFile.createNewFile();
_configFile.setReadable(true, false);
_configFile.setWritable(true, false);
_configFile.setExecutable(true, false);
// Add default config
_configData.put(TravelGatesConfigurations.AUTOSAVE.value(), String.valueOf(_autosave));
_configData.put(TravelGatesConfigurations.CLEARALLINVENTORY.value(), String.valueOf(_clearAllInventory));
_configData.put(TravelGatesConfigurations.PROTECTADMININVENTORY.value(), String.valueOf(_protectAdminInventory));
_configData.put(TravelGatesConfigurations.DEBUG.value(), String.valueOf(_isDebugEnabled));
_configData.put(TravelGatesConfigurations.LANGUAGE.value(), _language);
_configData.put(TravelGatesConfigurations.TELEPORTWITHPORTAL.value(), String.valueOf(_teleportWithPortal));
_configData.put(TravelGatesConfigurations.TELEPORTWITHSIGN.value(), String.valueOf(_teleportWithSign));
_configData.put(TravelGatesConfigurations.TPBLOCK.value(), _tpBlock.toString());
_configData.put(TravelGatesConfigurations.USEPERMISSIONS.value(), String.valueOf(_usePermissions));
}
catch (IOException e)
{
_LOGGER.severe(_tag + " Unable to create Configuration file: ");
e.printStackTrace();
return false;
}
}
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " End loadConfiguration");
}
return true;
}
private boolean loadMessages()
{
_messages = new TravelGatesMessagesManager(this, _language);
if (_messages != null)
{
_portalSignOnState = _messages.get(TravelGatesMessages.ON);
_portalSignOffState = _messages.get(TravelGatesMessages.OFF);
return true;
}
return false;
}
private boolean loadPermissions()
{
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " Start loadPermissions()");
}
try
{
if (_usePermissions)
{
// Search PermissionsBukkit plugin
Plugin permPlugin = _pm.getPlugin(TravelGatesConstants.PLUGIN_PERMISSIONS_BUKKIT);
if (permPlugin != null)
{
if (permPlugin.isEnabled())
{
_usePermissionsBukkit = true;
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " " + permPlugin.getDescription().getFullName() + " will be used to manage Permissions.");
}
}
else
{
_usePermissionsBukkit = forcePermissionsPluginLoading(permPlugin);
_usePermissions = _usePermissionsBukkit;
}
}
else
{
// Search PermissionsEx plugin
permPlugin = _pm.getPlugin(TravelGatesConstants.PLUGIN_PERMISSIONS_EX);
if (permPlugin != null)
{
if (!permPlugin.isEnabled())
{
_usePermissions = forcePermissionsPluginLoading(permPlugin);
}
if (_usePermissions)
{
_permManager = PermissionsEx.getPermissionManager();
if (_permManager != null)
{
_usePermissionsEx = true;
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " " + permPlugin.getDescription().getFullName() + " will be used to manage Permissions.");
}
}
else
{
_usePermissions = false;
_LOGGER.warning(_tag + " " + permPlugin.getDescription().getFullName()
+ " has not been loaded correctly. Permissions disabled.");
}
}
}
else
{
// Search Permissions 2x/3x plugin
permPlugin = _pm.getPlugin(TravelGatesConstants.PLUGIN_PERMISSONS);
if (permPlugin != null)
{
if (!permPlugin.isEnabled())
{
_usePermissions = forcePermissionsPluginLoading(permPlugin);
}
if (_usePermissions)
{
_permHandler = ((Permissions) permPlugin).getHandler();
if (_permHandler != null)
{
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " " + permPlugin.getDescription().getFullName()
+ " will be used to manage Permissions.");
}
}
else
{
_usePermissions = false;
_LOGGER.warning(_tag + " " + permPlugin.getDescription().getFullName()
+ " has not been loaded correctly. Permissions disabled.");
}
}
}
else
{
// Use Native Bukkit's Permission is used
_useNativePermissions = true;
_LOGGER.info(_debug
+ " Bukkit's Native Permissions system is used. Do not forget to fill the permissions.yml file of your server.");
}
}
}
}
}
catch (final Throwable th)
{
_usePermissions = false;
_LOGGER.severe(_tag + " Permissions loading has failed. Permissions disabled.");
th.printStackTrace();
return false;
}
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " End loadPermissions");
}
return true;
}
private void loadMaterialTypes()
{
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " Start loadMaterialTypes()");
}
for (final Material mat : Material.values())
{
switch (mat)
{
case BEDROCK:
case BOOKSHELF:
case BRICK:
case CLAY:
case COAL_ORE:
case COBBLESTONE:
case DIAMOND_BLOCK:
case DIAMOND_ORE:
case DIRT:
case ENDER_STONE:
case FURNACE:
case GLASS:
case GLOWING_REDSTONE_ORE:
case GLOWSTONE:
case GOLD_BLOCK:
case GOLD_ORE:
case GRASS:
case GRAVEL:
case ICE:
case IRON_BLOCK:
case IRON_ORE:
case JACK_O_LANTERN:
case JUKEBOX:
case LAPIS_BLOCK:
case LAPIS_ORE:
case LOG:
case MELON_BLOCK:
case MOSSY_COBBLESTONE:
case MYCEL:
case NETHER_BRICK:
case NETHERRACK:
case NOTE_BLOCK:
case OBSIDIAN:
case PUMPKIN:
case REDSTONE:
case SAND:
case SANDSTONE:
case SMOOTH_BRICK:
case SNOW_BLOCK:
case SOUL_SAND:
case SPONGE:
case STONE:
case TNT:
case WOOD:
case WOOL:
case WORKBENCH:
_mapMaterialIdByName.put(mat.name().toLowerCase(), new Integer(mat.getId()));
}
}
for (final DyeColor color : DyeColor.values())
{
_mapDyeColorByName.put(color.name().toLowerCase(), color);
}
for (final TreeSpecies species : TreeSpecies.values())
{
_mapTreeSpeciesByName.put(species.name().toLowerCase(), species);
}
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " _materialTypeMap has " + _mapMaterialIdByName.size() + " elements.");
_LOGGER.info(_debug + " _colorMap has " + _mapDyeColorByName.size() + " elements.");
_LOGGER.info(_debug + " _treeSpeciesMap has " + _mapTreeSpeciesByName.size() + " elements.");
}
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " End loadMaterialTypes");
}
}
private boolean forcePermissionsPluginLoading(final Plugin permPlugin)
{
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " Start forcePermissionsPluginLoading(plugin=" + permPlugin.getDescription().getFullName() + ")");
}
boolean pluginLoaded = false;
try
{
_pm.enablePlugin(permPlugin);
if (permPlugin.isEnabled())
{
pluginLoaded = true;
}
}
catch (final Throwable th)
{
_LOGGER.warning(_tag + " " + permPlugin.getDescription().getFullName() + " could not have been forced to load. Permissions disabled.");
th.printStackTrace();
}
if (pluginLoaded)
{
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " " + permPlugin.getDescription().getFullName()
+ " has been forced to load and will be used to manage Permissions.");
}
}
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " End forcePermissionsPluginLoading : " + pluginLoaded);
}
return pluginLoaded;
}
public boolean hasPermission(final Player player, final TravelGatesPermissionsNodes permissionNode)
{
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " Start hasPermission(player=" + player + ", permissionNode=" + permissionNode + ")");
}
boolean hasPerm = false;
try
{
if (_usePermissions)
{
if (_usePermissionsBukkit || _useNativePermissions)
{
hasPerm = player.hasPermission(permissionNode.getNode());
}
else if (_usePermissionsEx)
{
hasPerm = _permManager.has(player, permissionNode.getNode());
}
else
{
hasPerm = _permHandler.has(player, permissionNode.getNode());
}
}
else
{
if (permissionNode.isAdminOnly())
{
if (player.isOp())
{
hasPerm = true;
}
}
else
{
hasPerm = true;
}
}
}
catch (final Throwable th)
{
_LOGGER.severe(_tag + " Permissions access has failed. Permissions disabled.");
th.printStackTrace();
_usePermissions = false;
}
if (!hasPerm)
{
player.sendMessage(ChatColor.RED + _messages.get(TravelGatesMessages.USER_NOT_ALLOWED));
}
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " End hasPermission : " + hasPerm);
}
return hasPerm;
}
public boolean updateDestination(final String destination, final TravelGatesOptionsContainer container, final Player player)
{
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " Start updateDestination(destination=" + destination + ", container=" + container + ", player=" + player + ")");
}
boolean optionsUpdated = false;
String fullStringLocation = null;
if (container.has(TravelGatesOptions.POSITION))
{
final Location newLocation = getLocationFromPosition(player, player.getLocation(), container.getPosition());
if (newLocation != null)
{
fullStringLocation = TravelGatesUtils.locationToFullString(newLocation) + TravelGatesConstants.DELIMITER;
final String shortStringLocation = TravelGatesUtils.locationToShortString(newLocation);
final String oldShortLoc = _mapShortLocationsByDest.get(destination);
_mapDestinationsByShortLoc.remove(oldShortLoc);
_mapDestinationsByShortLoc.put(shortStringLocation, destination);
_mapShortLocationsByDest.put(destination, shortStringLocation);
_mapLocationsByDest.put(destination, TravelGatesUtils.shortStringToLocation(shortStringLocation, getServer().getWorlds()));
}
else
{
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " End updateDestination : " + false);
}
return false;
}
}
else
{
fullStringLocation = _destinationsData.getProperty(destination);
fullStringLocation = fullStringLocation.substring(0, fullStringLocation.lastIndexOf(TravelGatesConstants.DELIMITER) + 1);
}
fullStringLocation += container.getOptionsForData();
_destinationsData.put(destination, fullStringLocation);
if (!container.has(TravelGatesOptions.RESTRICTION))
{
_restrictionsData.remove(destination);
}
else
{
_restrictionsData.put(destination, container.getRestrictionsListString());
}
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " New details : " + _destinationsData.getProperty(destination));
}
if (container.has(TravelGatesOptions.SAVE) || _autosave)
{
final boolean saved = saveData();
optionsUpdated = saved;
if (saved)
{
player.sendMessage(ChatColor.GREEN + _messages.get(TravelGatesMessages.SAVE_DONE));
}
else
{
player.sendMessage(ChatColor.RED + _messages.get(TravelGatesMessages.SAVE_FAILED));
}
}
else
{
optionsUpdated = true;
}
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " End updateDestination : " + optionsUpdated);
}
return optionsUpdated;
}
public boolean isDebugEnabled()
{
return _isDebugEnabled;
}
public TravelGatesTeleportBlock getTeleportBlock()
{
return _tpBlock;
}
public void toggleDebugState()
{
_isDebugEnabled = !_isDebugEnabled;
TravelGatesUtils.setDebugState(_isDebugEnabled);
_configData.put(TravelGatesConfigurations.DEBUG.value(), String.valueOf(_isDebugEnabled));
if (_autosave)
{
saveConfiguration();
}
_LOGGER.info(_tag + " DEBUG MODE : " + ((_isDebugEnabled) ? "ENABLED" : "DISABLED"));
}
public boolean togglePermissionsState()
{
_usePermissions = !_usePermissions;
if (_usePermissions)
{
loadPermissions();
}
_configData.put(TravelGatesConfigurations.USEPERMISSIONS.value(), String.valueOf(_usePermissions));
if (_autosave)
{
saveConfiguration();
}
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " USE PERMISSIONS : " + ((_usePermissions) ? "ENABLED" : "DISABLED"));
}
return _usePermissions;
}
public boolean toggleSignTeleportState()
{
_teleportWithSign = !_teleportWithSign;
_configData.put(TravelGatesConfigurations.TELEPORTWITHSIGN.value(), String.valueOf(_teleportWithSign));
if (_autosave)
{
saveConfiguration();
}
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " TELEPORT WITH SIGN : " + ((_teleportWithSign) ? "ENABLED" : "DISABLED"));
}
return _teleportWithSign;
}
public boolean togglePortalTeleportState()
{
_teleportWithPortal = !_teleportWithPortal;
_configData.put(TravelGatesConfigurations.TELEPORTWITHPORTAL.value(), String.valueOf(_teleportWithPortal));
if (_autosave)
{
saveConfiguration();
}
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " TELEPORT WITH PORTAL : " + ((_teleportWithPortal) ? "ENABLED" : "DISABLED"));
}
return _teleportWithPortal;
}
public boolean toggleClearAllInventoryState()
{
_clearAllInventory = !_clearAllInventory;
_configData.put(TravelGatesConfigurations.CLEARALLINVENTORY.value(), String.valueOf(_clearAllInventory));
if (_autosave)
{
saveConfiguration();
}
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " CLEAR ALL INVENTORY : " + ((_clearAllInventory) ? "ENABLED" : "DISABLED"));
}
return _clearAllInventory;
}
public boolean toggleProtectAdminInventoryState()
{
_protectAdminInventory = !_protectAdminInventory;
_configData.put(TravelGatesConfigurations.PROTECTADMININVENTORY.value(), String.valueOf(_protectAdminInventory));
if (_autosave)
{
saveConfiguration();
}
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " PROTECT ADMIN INVENTORY : " + ((_protectAdminInventory) ? "ENABLED" : "DISABLED"));
}
return _protectAdminInventory;
}
public boolean toggleTeleportBlockState()
{
_tpBlock.toggleState();
_configData.put(TravelGatesConfigurations.TPBLOCK.value(), _tpBlock.toString());
if (_autosave)
{
saveConfiguration();
}
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " TELEPORT BLOCK : " + _tpBlock);
}
return _tpBlock.isEnabled();
}
public boolean toggleAutoSaveState()
{
_autosave = !_autosave;
_configData.put(TravelGatesConfigurations.AUTOSAVE.value(), String.valueOf(_autosave));
if (_autosave)
{
saveConfiguration();
}
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " AUTO SAVE : " + ((_autosave) ? "ENABLED" : "DISABLED"));
}
return _autosave;
}
public boolean isSignTeleportEnabled()
{
return _teleportWithSign;
}
public boolean isPortalTeleportEnabled()
{
return _teleportWithPortal;
}
public String getListOfWorlds()
{
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " Start getListOfWorlds()");
}
final StringBuilder strBld = new StringBuilder();
strBld.append(ChatColor.YELLOW).append(_messages.get(TravelGatesMessages.AVAILABLE_WORLDS_ARE)).append(" ");
final int initialSize = strBld.length();
for (final World world : this.getServer().getWorlds())
{
if (strBld.length() != initialSize)
{
strBld.append(ChatColor.YELLOW).append(TravelGatesConstants.DELIMITER).append(" ");
}
strBld.append(ChatColor.AQUA).append(world.getName());
}
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " End getListOfWorlds : " + strBld.toString());
}
return strBld.toString();
}
public final String getPortalSignOnState()
{
return _portalSignOnState;
}
public final String getPortalSignOffState()
{
return _portalSignOffState;
}
public PluginManager getPM()
{
return _pm;
}
public boolean configTeleportBlock(final String tpblock, final boolean save)
{
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " Start configTeleportBlock(tpblock=" + tpblock + ")");
}
boolean result = false;
String[] split = tpblock.split(TravelGatesConstants.DELIMITER);
if (split.length >= 1)
{
final String material = split[0];
final Integer typeId = _mapMaterialIdByName.get(material.toLowerCase());
if (typeId != null)
{
final Material type = Material.getMaterial(typeId);
// Ticket #18: default values for Wool and Log materials
if (split.length == 1)
{
switch (type)
{
case WOOL:
_tpBlock.setColor(DyeColor.WHITE);
break;
case LOG:
_tpBlock.setSpecies(TreeSpecies.GENERIC);
break;
}
}
_tpBlock.setType(type);
_tpBlock.setEnabled(true);
result = true;
}
else
{
_LOGGER.severe(_tag + " Material " + material + " is not expected to be used as a TP Block.");
}
}
// Ticket #18: stop if result is false
if (result && split.length >= 2)
{
final String data = split[1];
// Ticket #18: check if data is given by id
Byte rawData = null;
if (TravelGatesUtils.stringIsNotBlank(data) && data.matches(TravelGatesConstants.INTEGER_PATTERN))
{
rawData = Byte.parseByte(data);
}
switch (_tpBlock.type())
{
case WOOL:
DyeColor color = null;
if (rawData != null)
{
// Ticket #18: color found by data id
color = DyeColor.getByWoolData(rawData);
}
else
{
color = _mapDyeColorByName.get(data.toLowerCase());
}
if (color != null)
{
_tpBlock.setColor(color);
}
else
{
_tpBlock.setEnabled(false);
result = false;
_LOGGER.severe(_tag + " TP Block data: " + data + " is invalid for WOOL Material.");
}
break;
case LOG:
TreeSpecies species = null;
if (rawData != null)
{
// Ticket #18: species found by data id
species = TreeSpecies.getByData(rawData);
}
else
{
species = _mapTreeSpeciesByName.get(data.toLowerCase());
}
if (species != null)
{
_tpBlock.setSpecies(species);
}
else
{
_tpBlock.setEnabled(false);
result = false;
_LOGGER.severe(_tag + " TP Block data: " + data + " is invalid for LOG Material.");
}
break;
default:
_LOGGER.severe(_tag + " " + _tpBlock.type() + " is not configured to have data.");
_tpBlock.setEnabled(false);
result = false;
break;
}
}
// Ticket #18: do not save when errors occurred
if (result && save)
{
_configData.put(TravelGatesConfigurations.TPBLOCK.value(), _tpBlock.toString());
if (_autosave)
{
saveConfiguration();
}
}
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " End configTeleportBlock : " + result);
}
return result;
}
public TravelGatesOptionsContainer createDestinationOptions(final String destination, final String options)
{
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " Start createDestinationOptions(destination=" + destination + ", options=" + options + ")");
}
TravelGatesOptionsContainer optionsContainer = null;
if (TravelGatesUtils.stringIsNotBlank(options))
{
String inputOptions = null;
if (options.startsWith(TravelGatesConstants.OPTION_PREFIX))
{
inputOptions = options.substring(1);
}
else
{
inputOptions = options;
}
optionsContainer = _mapOptionsByDest.get(destination.toLowerCase());
if (optionsContainer == null)
{
optionsContainer = new TravelGatesOptionsContainer(this);
_mapOptionsByDest.put(destination.toLowerCase(), optionsContainer);
}
// FIXME : Bug pour (2000,?,2000�
while (inputOptions.length() > 0)
{
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " inputOptions = " + inputOptions);
}
final String strOption = inputOptions.substring(0, 1);
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " strOption = " + strOption);
}
final TravelGatesOptions option = TravelGatesOptions.get(strOption);
if (option != null && option.isDestinationOption())
{
switch (option)
{
case POSITION:
final int startPosIndex = inputOptions.indexOf(TravelGatesConstants.START_POSITION);
final int endPosIndex = inputOptions.indexOf(TravelGatesConstants.END_POSITION);
if (!optionsContainer.has(option))
{
optionsContainer.set(option, true);
if (startPosIndex > 0 && endPosIndex > 0)
{
final String pos = inputOptions.substring(startPosIndex + 1, endPosIndex);
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " pos = " + pos);
}
optionsContainer.setPosition(pos);
inputOptions = inputOptions.substring(endPosIndex + 1);
}
else
{
optionsContainer.setPosition("");
inputOptions = inputOptions.substring(1);
}
}
break;
case RESTRICTION:
final int startResIndex = inputOptions.indexOf(TravelGatesConstants.START_RESTRICTIONS);
final int endResIndex = inputOptions.indexOf(TravelGatesConstants.END_RESTRICTIONS);
if (startResIndex > 0 && endResIndex > 0)
{
final String res = inputOptions.substring(startResIndex + 1, endResIndex);
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " res = " + res);
}
optionsContainer.setRestrictionsList(res);
inputOptions = inputOptions.substring(endResIndex + 1);
}
else
{
optionsContainer.clearRestrictionsList();
inputOptions = inputOptions.substring(1);
}
break;
default:
optionsContainer.set(option, !optionsContainer.has(option)); // toggle existing options
inputOptions = inputOptions.substring(1);
}
}
}
}
else
{
optionsContainer = new TravelGatesOptionsContainer(this);
}
_mapOptionsByDest.put(destination.toLowerCase(), optionsContainer);
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " End createDestinationOptions : " + optionsContainer);
}
return optionsContainer;
}
public String getWorldState(final World world, final String name)
{
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " Start getWorldState(world=" + world + ", name=" + name + ")");
}
String state = null;
// world unloaded or not found
if (world != null)
{
state = ChatColor.YELLOW
+ _messages.get(TravelGatesMessages.WORLD_STATE, ChatColor.AQUA + world.getName() + ChatColor.YELLOW,
ChatColor.GREEN + _messages.get(TravelGatesMessages.WORLD_LOADED) + ChatColor.YELLOW);
}
// world loaded
else
{
state = ChatColor.YELLOW
+ _messages.get(TravelGatesMessages.WORLD_STATE, ChatColor.AQUA + name + ChatColor.YELLOW,
ChatColor.RED + _messages.get(TravelGatesMessages.WORLD_UNLOADED) + ChatColor.YELLOW);
}
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " Start getWorldState : " + state);
}
return state;
}
public String getWorldState(final String worldName)
{
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " Start getWorldState(worldName=" + worldName + ")");
}
final World world = getServer().getWorld(worldName);
return getWorldState(world, worldName);
}
public World loadWorld(final String worldName, final String worldType)
{
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " Start loadWorld(worldName=" + worldName + ", worldType=" + worldType + ")");
}
World newWorld = getServer().getWorld(worldName);
if (newWorld == null)
{
final TravelGatesWorldType type = TravelGatesWorldType.getWorldType(worldType);
WorldCreator worldFactory = new WorldCreator(worldName);
worldFactory = worldFactory.environment(type.getEnv());
newWorld = getServer().createWorld(worldFactory);
if (!_setAdditionalWorlds.contains(worldName))
{
_setAdditionalWorlds.add(worldName);
_configData.put(TravelGatesConfigurations.WORLDS.value(), getListOfAdditionnalWorld());
if (_autosave)
{
saveConfig();
}
}
}
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " End loadWorld : " + newWorld);
}
return newWorld;
}
public World unloadWorld(final String worldName)
{
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " Start unloadWorld(worldName=" + worldName + ")");
}
World unloadedWorld = null;
final boolean unloaded = getServer().unloadWorld(worldName, true);
if (!unloaded)
{
unloadedWorld = getServer().getWorld(worldName);
}
else
{
if (_setAdditionalWorlds.contains(worldName))
{
_setAdditionalWorlds.remove(worldName);
_configData.put(TravelGatesConfigurations.WORLDS.value(), getListOfAdditionnalWorld());
if (_autosave)
{
saveConfig();
}
}
}
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " Start unloadWorld : " + unloadedWorld);
}
return unloadedWorld;
}
public String getAllWorldsFromServerDirectory()
{
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " Start getAllWorldsFromServerDirectory()");
}
final StringBuilder strBld = new StringBuilder();
strBld.append(ChatColor.YELLOW).append(_messages.get(TravelGatesMessages.WORLDS_IN_SERVER_DIR)).append(" ");
final int initialSize = strBld.length();
try
{
final File serverDir = new File(".");
final FilenameFilter filter = new FilenameFilter() {
public boolean accept(File file, String name)
{
return !name.startsWith(".") && !name.equals(TravelGatesConstants.PLUGINS_DIRECTORY);
}
};
for (final String el : serverDir.list(filter))
{
final File file = new File(el);
if (file.exists() && file.isDirectory())
{
if (strBld.length() != initialSize)
{
strBld.append(ChatColor.YELLOW).append(TravelGatesConstants.DELIMITER).append(" ");
}
final World world = getServer().getWorld(el);
if (world == null)
{
strBld.append(ChatColor.RED);
}
else
{
strBld.append(ChatColor.GREEN);
}
strBld.append(el);
}
}
}
catch (final Throwable th)
{
_LOGGER.severe(_tag + " Error while listing worlds in the server directory.");
th.printStackTrace();
strBld.append(ChatColor.RED).append(_messages.get(TravelGatesMessages.ERROR));
}
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " End getAllWorldsFromServerDirectory : " + strBld.toString());
}
return strBld.toString();
}
private boolean loadAdditionalWorld()
{
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " Start loadAdditionalWorld()");
}
if (!_setAdditionalWorlds.isEmpty())
{
final ArrayList<String> worldListToRemove = new ArrayList<String>();
for (final String worldName : _setAdditionalWorlds)
{
final File worldDir = new File(worldName);
if (worldDir.exists() && worldDir.isDirectory())
{
World world = getServer().getWorld(worldName);
if (world == null)
{
WorldCreator worldFactory = new WorldCreator(worldName);
world = getServer().createWorld(worldFactory);
if (world != null)
{
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " World " + worldName + " has been loaded.");
}
}
else
{
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " World " + worldName + " has not be loaded.");
}
}
}
else
{
worldListToRemove.add(worldName);
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " World " + worldName + " is already loaded.");
}
}
}
else
{
worldListToRemove.add(worldName);
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " World " + worldName + " does not exist in the server directory or is invalid.");
}
}
}
// Fix: remove worlds after working on it
if (!worldListToRemove.isEmpty())
{
_setAdditionalWorlds.removeAll(worldListToRemove);
}
_configData.put(TravelGatesConfigurations.WORLDS.value(), getListOfAdditionnalWorld());
}
else
{
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " No additional world to load.");
}
}
_LOGGER.info(_tag + " Additional Worlds configuration set to : " + _setAdditionalWorlds.size() + " additional worlds loaded.");
return true;
}
public String getListOfAdditionnalWorld()
{
final StringBuilder strBld = new StringBuilder();
for (final String world : _setAdditionalWorlds)
{
if (strBld.length() > 0)
{
strBld.append(TravelGatesConstants.DELIMITER);
}
strBld.append(world);
}
return strBld.toString();
}
public boolean isProtectedInventory(final Player player)
{
return _protectAdminInventory && hasPermission(player, TravelGatesPermissionsNodes.PROTECTADMININV);
}
}
| true | true | public boolean teleportPlayerToDest(final String dest, final Player player, final boolean destHasBeenChecked,
final boolean ignorePlayerLocation, final String portalDestinationShortLoc)
{
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " Start teleportPlayerToDest(dest=" + dest + ", player=" + player + ", destHasBeenChecked=" + destHasBeenChecked
+ ", ignorePlayerLocation=" + ignorePlayerLocation + ")");
}
final String destination = dest.toLowerCase();
if (ignorePlayerLocation || destHasBeenChecked || hasDestination(destination))
{
final String fullLoc = getFullLoc(destination);
final String shortLoc = getShortLoc(destination);
if (getOptionOfDestination(destination, TravelGatesOptions.ADMINTP))
{
if (!hasPermission(player, TravelGatesPermissionsNodes.ADMINTP))
{
player.sendMessage(ChatColor.RED + _messages.get(TravelGatesMessages.ONLY_ADMIN_TP));
return false;
}
}
final Location playerLocation = player.getLocation();
final String playerShortLoc = TravelGatesUtils.locationToShortString(playerLocation);
final boolean targetAndCurrentLocationAreDifferent = !shortLoc.equalsIgnoreCase(playerShortLoc);
final boolean playerIsOnExistingDestination = hasShortLocation(playerShortLoc);
boolean playerNotOnTeleportBlock = false;
String nearestDestinationShortLocation = null;
if (!ignorePlayerLocation)
{
if (playerIsOnExistingDestination || portalDestinationShortLoc != null)
{
if (portalDestinationShortLoc == null && _tpBlock.isEnabled() && !_tpBlock.isTPBlock(player.getWorld().getBlockAt(playerLocation).getRelative(BlockFace.DOWN)))
{
playerNotOnTeleportBlock = true;
}
if (playerIsOnExistingDestination)
{
nearestDestinationShortLocation = playerShortLoc;
}
else if (portalDestinationShortLoc != null)
{
nearestDestinationShortLocation = portalDestinationShortLoc;
}
}
else
{
if (_tpBlock.isEnabled())
{
if (_isDebugEnabled)
{
_LOGGER.info("#0 : Not on dest and tp block enabled");
}
final World currWorld = player.getWorld();
if (_isDebugEnabled)
{
_LOGGER.info("#0-bis : currWorld = " + currWorld);
_LOGGER.info("#0-ters : type block = " + currWorld.getBlockAt(playerLocation).getRelative(BlockFace.DOWN).getType());
}
playerNotOnTeleportBlock = !_tpBlock.isTPBlock(currWorld.getBlockAt(playerLocation).getRelative(BlockFace.DOWN));
if (_isDebugEnabled)
{
_LOGGER.info("#1 : playerNotOnTeleportBlock = " + playerNotOnTeleportBlock);
}
if (!playerNotOnTeleportBlock)
{
// Search the locations in the current player's
// world
ArrayList<Location> rightWorldsList = new ArrayList<Location>();
for (final Object key : _mapLocationsByDest.keySet())
{
final Location loc = _mapLocationsByDest.get(key);
if (_isDebugEnabled)
{
_LOGGER.info("#1bis : key = " + key + " ; playerLocation.getWorld()=" + playerLocation.getWorld()
+ " ; loc.getWorld()= " + loc.getWorld());
}
if (playerLocation.getWorld() == loc.getWorld())
{
rightWorldsList.add(loc);
}
}
if (_isDebugEnabled)
{
_LOGGER.info("#2 : rightWorldsList size = " + rightWorldsList.size());
}
if (!rightWorldsList.isEmpty())
{
// Search the locations at the same height
ArrayList<Location> rightHeightList = new ArrayList<Location>();
for (final Location loc : rightWorldsList)
{
if (loc.getBlockY() == playerLocation.getBlockY())
{
rightHeightList.add(loc);
}
}
if (_isDebugEnabled)
{
_LOGGER.info("#3 : rightHeightList size = " + rightHeightList.size());
}
if (!rightHeightList.isEmpty())
{
// Search the nearest destination from
// the
// Player's location
Location nearestDestinationLocation = null;
int lastMinX = TravelGatesConstants.MAX_COORDINATE;
int lastMinZ = TravelGatesConstants.MAX_COORDINATE;
if (_isDebugEnabled)
{
_LOGGER.info("#3-a : nearestDestinationLocation = " + nearestDestinationLocation);
}
for (final Location loc : rightHeightList)
{
if (_isDebugEnabled)
{
_LOGGER.info("#3-b : loc = " + loc);
}
if (nearestDestinationLocation == null)
{
lastMinX = TravelGatesUtils.getCoordinateDiff(loc.getBlockX(), playerLocation.getBlockX());
lastMinZ = TravelGatesUtils.getCoordinateDiff(loc.getBlockZ(), playerLocation.getBlockZ());
nearestDestinationLocation = loc;
if (_isDebugEnabled)
{
_LOGGER.info("#3-c : lastMinX = " + lastMinX + " ; lastMinZ = " + lastMinZ);
}
}
else
{
final int xDiff = TravelGatesUtils.getCoordinateDiff(loc.getBlockX(), playerLocation.getBlockX());
final int zDiff = TravelGatesUtils.getCoordinateDiff(loc.getBlockZ(), playerLocation.getBlockZ());
if (_isDebugEnabled)
{
_LOGGER.info("#3-d : xDiff = " + xDiff + " ; zDiff = " + zDiff);
_LOGGER.info("#3-e : lastMinX = " + lastMinX + " ; lastMinZ = " + lastMinZ);
}
if (xDiff + zDiff <= lastMinX + lastMinZ)
{
lastMinX = xDiff;
lastMinZ = zDiff;
nearestDestinationLocation = loc;
}
}
if (_isDebugEnabled)
{
_LOGGER.info("#3-f : nearestDestinationLocation = " + nearestDestinationLocation);
}
}
if (_isDebugEnabled)
{
_LOGGER.info("#4 : nearestDestinationLocation = " + nearestDestinationLocation);
}
if (nearestDestinationLocation != null)
{
int pX = playerLocation.getBlockX();
int pZ = playerLocation.getBlockZ();
if (_isDebugEnabled)
{
_LOGGER.info("#5 : pX = " + pX + " ; pZ = " + pZ);
}
final int dX = nearestDestinationLocation.getBlockX();
final int dZ = nearestDestinationLocation.getBlockZ();
if (_isDebugEnabled)
{
_LOGGER.info("#6 : dX = " + dX + " ; dZ = " + dZ);
}
int xDiff = TravelGatesUtils.getCoordinateDiff(dX, pX);
int zDiff = TravelGatesUtils.getCoordinateDiff(dZ, pZ);
if (_isDebugEnabled)
{
_LOGGER.info("#7 : xDiff = " + xDiff + " ; zDiff = " + zDiff);
}
// The nearest destination is at 5
// blocks max from the player
if (xDiff <= TravelGatesConstants.MAX_TARGET_RANGE && zDiff <= TravelGatesConstants.MAX_TARGET_RANGE)
{
final int offsetX = ((pX - dX) > 0) ? -1 : 1;
final int offsetZ = ((pZ - dZ) > 0) ? -1 : 1;
if (_isDebugEnabled)
{
_LOGGER.info("#8 : offsetX = " + offsetX + " ; offsetZ = " + offsetZ);
}
final int heightOfBeneathBlock = playerLocation.getBlockY() - 1;
if (_isDebugEnabled)
{
_LOGGER.info("#9 : heightOfBeneathBlock = " + heightOfBeneathBlock);
}
// Is blocks between player and
// the
// nearest destination are TP
// blocks
// ?
while (xDiff > 0 && !playerNotOnTeleportBlock)
{
pX += offsetX;
playerNotOnTeleportBlock = !_tpBlock.isTPBlock(currWorld.getBlockAt(pX, heightOfBeneathBlock, pZ));
xDiff = TravelGatesUtils.getCoordinateDiff(dX, pX);
if (_isDebugEnabled)
{
_LOGGER.info("#10 : pX = " + pX + " ; xDiff = " + xDiff + " ; playerNotOnTeleportBlock = "
+ playerNotOnTeleportBlock);
}
}
if (!playerNotOnTeleportBlock)
{
while (zDiff > 0 && !playerNotOnTeleportBlock)
{
pZ += offsetZ;
playerNotOnTeleportBlock = !_tpBlock
.isTPBlock(currWorld.getBlockAt(pX, heightOfBeneathBlock, pZ));
zDiff = TravelGatesUtils.getCoordinateDiff(dZ, pZ);
if (_isDebugEnabled)
{
_LOGGER.info("#11 : pZ = " + pZ + " ; zDiff = " + zDiff + " ; playerNotOnTeleportBlock = "
+ playerNotOnTeleportBlock);
}
}
// Get the short loc of the
// nearest destination
if (!playerNotOnTeleportBlock)
{
nearestDestinationShortLocation = TravelGatesUtils
.locationToShortString(nearestDestinationLocation);
}
}
}
else
{
playerNotOnTeleportBlock = true;
}
}
else
{
playerNotOnTeleportBlock = true;
}
}
else
{
playerNotOnTeleportBlock = true;
}
}
else
{
playerNotOnTeleportBlock = true;
}
}
}
}
}
if (_isDebugEnabled)
{
_LOGGER.info("#12 : playerNotOnTeleportBlock = " + playerNotOnTeleportBlock);
_LOGGER.info("#13 : nearestDestinationShortLocation = " + nearestDestinationShortLocation);
}
if (_tpBlock.isEnabled() && playerNotOnTeleportBlock)
{
player.sendMessage(ChatColor.RED
+ _messages.get(TravelGatesMessages.NOT_STANDING_ON_TPBLOCK, ChatColor.YELLOW + _tpBlock.toString() + ChatColor.RED));
return false;
}
if (ignorePlayerLocation || targetAndCurrentLocationAreDifferent
&& (playerIsOnExistingDestination || !playerNotOnTeleportBlock && _tpBlock.isEnabled()))
{
final String currentDest = _mapDestinationsByShortLoc.get(nearestDestinationShortLocation);
if (_isDebugEnabled)
{
_LOGGER.info("#14 : currentDest = " + currentDest);
}
if (!ignorePlayerLocation)
{
if (currentDest != null && getOptionOfDestination(currentDest, TravelGatesOptions.RESTRICTION))
{
final TravelGatesOptionsContainer container = _mapOptionsByDest.get(currentDest);
if (container != null && !container.isDestinationAllowed(destination))
{
player.sendMessage(ChatColor.RED
+ _messages.get(TravelGatesMessages.DESTINATION_IS_RESTRICTED, ChatColor.AQUA + currentDest + ChatColor.RED,
ChatColor.AQUA + destination + ChatColor.RED));
return false;
}
}
else if (currentDest == null)
{
player.sendMessage(ChatColor.RED + _messages.get(TravelGatesMessages.NO_STANDING_ON_DESTINATION));
return false;
}
}
final Location targetLocation = TravelGatesUtils.fullStringToLocation(fullLoc, player.getServer().getWorlds());
if (targetLocation.getWorld() != null)
{
player.teleport(targetLocation);
}
else
{
player.sendMessage(ChatColor.RED
+ _messages.get(TravelGatesMessages.TELEPORT_CANCELLED_WORLD_UNLOADED, ChatColor.AQUA + destination + ChatColor.RED));
return false;
}
if (ignorePlayerLocation)
{
_LOGGER.info(_tag + " " + player.getName() + " has forced the travel from " + playerShortLoc + " to " + destination);
}
else
{
_LOGGER.info(_tag + " " + player.getName() + " has travelled from " + currentDest + " to " + destination);
}
final boolean inventoryCleared = getOptionOfDestination(destination, TravelGatesOptions.INVENTORY);
// System.out.println("inventoryCleared=" + inventoryCleared + "; _protectAdminInventory=" + _protectAdminInventory
// + "; perm=" + hasPermission(player, TravelGatesPermissionsNodes.PROTECTADMININV));
if (!inventoryCleared || isProtectedInventory(player))
{
player.sendMessage(ChatColor.YELLOW
+ _messages.get(TravelGatesMessages.YOU_ARE_ARRIVED_AT, ChatColor.AQUA + destination + ChatColor.YELLOW)
+ ChatColor.GREEN + _messages.get(TravelGatesMessages.INVENTORY_KEPT));
}
else
{
String inventoryMessage = "";
final PlayerInventory inventory = player.getInventory();
if (_clearAllInventory)
{
inventory.setArmorContents(null);
inventoryMessage = _messages.get(TravelGatesMessages.ALL_INVENTORY_LOST);
}
else
{
inventoryMessage = _messages.get(TravelGatesMessages.INVENTORY_LOST);
}
inventory.clear();
player.sendMessage(ChatColor.YELLOW
+ _messages.get(TravelGatesMessages.YOU_ARE_ARRIVED_AT, ChatColor.AQUA + destination + ChatColor.YELLOW) + ChatColor.RED
+ inventoryMessage);
}
// If the arrival chunk is unloaded, it will be forced to load
final Chunk arrivalChunk = player.getWorld().getChunkAt(targetLocation);
if (!arrivalChunk.isLoaded())
{
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " The " + destination + "'s chunk was not loaded at " + targetLocation);
}
arrivalChunk.load();
}
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " End teleportPlayerToDest : true");
}
return true;
}
else
{
if (!targetAndCurrentLocationAreDifferent)
{
player.sendMessage(ChatColor.RED
+ _messages.get(TravelGatesMessages.YOURE_ALREADY_AT, ChatColor.AQUA + destination + ChatColor.RED));
}
else if (!playerIsOnExistingDestination)
{
player.sendMessage(ChatColor.RED
+ _messages.get(TravelGatesMessages.YOU_CANT_GO_THERE, ChatColor.AQUA + destination + ChatColor.RED));
}
}
}
else
{
player.sendMessage(ChatColor.RED
+ _messages.get(TravelGatesMessages.DESTINATION_DOESNT_EXIST, ChatColor.AQUA + destination + ChatColor.RED));
}
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " End teleportPlayerToDest : false");
}
return false;
}
| public boolean teleportPlayerToDest(final String dest, final Player player, final boolean destHasBeenChecked,
final boolean ignorePlayerLocation, final String portalDestinationShortLoc)
{
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " Start teleportPlayerToDest(dest=" + dest + ", player=" + player + ", destHasBeenChecked=" + destHasBeenChecked
+ ", ignorePlayerLocation=" + ignorePlayerLocation + ")");
}
final String destination = dest.toLowerCase();
if (ignorePlayerLocation || destHasBeenChecked || hasDestination(destination))
{
final String fullLoc = getFullLoc(destination);
final String shortLoc = getShortLoc(destination);
if (getOptionOfDestination(destination, TravelGatesOptions.ADMINTP))
{
if (!hasPermission(player, TravelGatesPermissionsNodes.ADMINTP))
{
player.sendMessage(ChatColor.RED + _messages.get(TravelGatesMessages.ONLY_ADMIN_TP));
return false;
}
}
final Location playerLocation = player.getLocation();
final String playerShortLoc = TravelGatesUtils.locationToShortString(playerLocation);
final boolean targetAndCurrentLocationAreDifferent = !shortLoc.equalsIgnoreCase(playerShortLoc);
final boolean playerIsOnExistingDestination = hasShortLocation(playerShortLoc);
boolean playerNotOnTeleportBlock = false;
String nearestDestinationShortLocation = null;
if (!ignorePlayerLocation)
{
if (playerIsOnExistingDestination || portalDestinationShortLoc != null)
{
if (portalDestinationShortLoc == null && _tpBlock.isEnabled() && !_tpBlock.isTPBlock(player.getWorld().getBlockAt(playerLocation).getRelative(BlockFace.DOWN)))
{
playerNotOnTeleportBlock = true;
}
if (playerIsOnExistingDestination)
{
nearestDestinationShortLocation = playerShortLoc;
}
else if (portalDestinationShortLoc != null)
{
nearestDestinationShortLocation = portalDestinationShortLoc;
}
}
else
{
if (_tpBlock.isEnabled())
{
if (_isDebugEnabled)
{
_LOGGER.info("#0 : Not on dest and tp block enabled");
}
final World currWorld = player.getWorld();
if (_isDebugEnabled)
{
_LOGGER.info("#0-bis : currWorld = " + currWorld);
_LOGGER.info("#0-ters : type block = " + currWorld.getBlockAt(playerLocation).getRelative(BlockFace.DOWN).getType());
}
playerNotOnTeleportBlock = !_tpBlock.isTPBlock(currWorld.getBlockAt(playerLocation).getRelative(BlockFace.DOWN));
if (_isDebugEnabled)
{
_LOGGER.info("#1 : playerNotOnTeleportBlock = " + playerNotOnTeleportBlock);
}
if (!playerNotOnTeleportBlock)
{
// Search the locations in the current player's
// world
ArrayList<Location> rightWorldsList = new ArrayList<Location>();
for (final Object key : _mapLocationsByDest.keySet())
{
final Location loc = _mapLocationsByDest.get(key);
if (_isDebugEnabled)
{
_LOGGER.info("#1bis : key = " + key + " ; playerLocation.getWorld()=" + playerLocation.getWorld()
+ " ; loc.getWorld()= " + loc.getWorld());
}
if (playerLocation.getWorld() == loc.getWorld())
{
rightWorldsList.add(loc);
}
}
if (_isDebugEnabled)
{
_LOGGER.info("#2 : rightWorldsList size = " + rightWorldsList.size());
}
if (!rightWorldsList.isEmpty())
{
// Search the locations at the same height
ArrayList<Location> rightHeightList = new ArrayList<Location>();
for (final Location loc : rightWorldsList)
{
if (loc.getBlockY() == playerLocation.getBlockY())
{
rightHeightList.add(loc);
}
}
if (_isDebugEnabled)
{
_LOGGER.info("#3 : rightHeightList size = " + rightHeightList.size());
}
if (!rightHeightList.isEmpty())
{
// Search the nearest destination from
// the
// Player's location
Location nearestDestinationLocation = null;
int lastMinX = TravelGatesConstants.MAX_COORDINATE;
int lastMinZ = TravelGatesConstants.MAX_COORDINATE;
if (_isDebugEnabled)
{
_LOGGER.info("#3-a : nearestDestinationLocation = " + nearestDestinationLocation);
}
for (final Location loc : rightHeightList)
{
if (_isDebugEnabled)
{
_LOGGER.info("#3-b : loc = " + loc);
}
if (nearestDestinationLocation == null)
{
lastMinX = TravelGatesUtils.getCoordinateDiff(loc.getBlockX(), playerLocation.getBlockX());
lastMinZ = TravelGatesUtils.getCoordinateDiff(loc.getBlockZ(), playerLocation.getBlockZ());
nearestDestinationLocation = loc;
if (_isDebugEnabled)
{
_LOGGER.info("#3-c : lastMinX = " + lastMinX + " ; lastMinZ = " + lastMinZ);
}
}
else
{
final int xDiff = TravelGatesUtils.getCoordinateDiff(loc.getBlockX(), playerLocation.getBlockX());
final int zDiff = TravelGatesUtils.getCoordinateDiff(loc.getBlockZ(), playerLocation.getBlockZ());
if (_isDebugEnabled)
{
_LOGGER.info("#3-d : xDiff = " + xDiff + " ; zDiff = " + zDiff);
_LOGGER.info("#3-e : lastMinX = " + lastMinX + " ; lastMinZ = " + lastMinZ);
}
if (xDiff + zDiff <= lastMinX + lastMinZ)
{
lastMinX = xDiff;
lastMinZ = zDiff;
nearestDestinationLocation = loc;
}
}
if (_isDebugEnabled)
{
_LOGGER.info("#3-f : nearestDestinationLocation = " + nearestDestinationLocation);
}
}
if (_isDebugEnabled)
{
_LOGGER.info("#4 : nearestDestinationLocation = " + nearestDestinationLocation);
}
if (nearestDestinationLocation != null)
{
int pX = playerLocation.getBlockX();
int pZ = playerLocation.getBlockZ();
if (_isDebugEnabled)
{
_LOGGER.info("#5 : pX = " + pX + " ; pZ = " + pZ);
}
final int dX = nearestDestinationLocation.getBlockX();
final int dZ = nearestDestinationLocation.getBlockZ();
if (_isDebugEnabled)
{
_LOGGER.info("#6 : dX = " + dX + " ; dZ = " + dZ);
}
int xDiff = TravelGatesUtils.getCoordinateDiff(dX, pX);
int zDiff = TravelGatesUtils.getCoordinateDiff(dZ, pZ);
if (_isDebugEnabled)
{
_LOGGER.info("#7 : xDiff = " + xDiff + " ; zDiff = " + zDiff);
}
// The nearest destination is at 5
// blocks max from the player
if (xDiff <= TravelGatesConstants.MAX_TARGET_RANGE && zDiff <= TravelGatesConstants.MAX_TARGET_RANGE)
{
final int offsetX = ((pX - dX) > 0) ? -1 : 1;
final int offsetZ = ((pZ - dZ) > 0) ? -1 : 1;
if (_isDebugEnabled)
{
_LOGGER.info("#8 : offsetX = " + offsetX + " ; offsetZ = " + offsetZ);
}
final int heightOfBeneathBlock = playerLocation.getBlockY() - 1;
if (_isDebugEnabled)
{
_LOGGER.info("#9 : heightOfBeneathBlock = " + heightOfBeneathBlock);
}
// Is blocks between player and
// the
// nearest destination are TP
// blocks
// ?
while (xDiff > 0 && !playerNotOnTeleportBlock)
{
pX += offsetX;
playerNotOnTeleportBlock = !_tpBlock.isTPBlock(currWorld.getBlockAt(pX, heightOfBeneathBlock, pZ));
xDiff = TravelGatesUtils.getCoordinateDiff(dX, pX);
if (_isDebugEnabled)
{
_LOGGER.info("#10 : pX = " + pX + " ; xDiff = " + xDiff + " ; playerNotOnTeleportBlock = "
+ playerNotOnTeleportBlock);
}
}
if (!playerNotOnTeleportBlock)
{
while (zDiff > 0 && !playerNotOnTeleportBlock)
{
pZ += offsetZ;
playerNotOnTeleportBlock = !_tpBlock
.isTPBlock(currWorld.getBlockAt(pX, heightOfBeneathBlock, pZ));
zDiff = TravelGatesUtils.getCoordinateDiff(dZ, pZ);
if (_isDebugEnabled)
{
_LOGGER.info("#11 : pZ = " + pZ + " ; zDiff = " + zDiff + " ; playerNotOnTeleportBlock = "
+ playerNotOnTeleportBlock);
}
}
// Get the short loc of the
// nearest destination
if (!playerNotOnTeleportBlock)
{
nearestDestinationShortLocation = TravelGatesUtils
.locationToShortString(nearestDestinationLocation);
}
}
}
else
{
playerNotOnTeleportBlock = true;
}
}
else
{
playerNotOnTeleportBlock = true;
}
}
else
{
playerNotOnTeleportBlock = true;
}
}
else
{
playerNotOnTeleportBlock = true;
}
}
}
}
}
if (_isDebugEnabled)
{
_LOGGER.info("#12 : playerNotOnTeleportBlock = " + playerNotOnTeleportBlock);
_LOGGER.info("#13 : nearestDestinationShortLocation = " + nearestDestinationShortLocation);
}
if (_tpBlock.isEnabled() && playerNotOnTeleportBlock)
{
player.sendMessage(ChatColor.RED
+ _messages.get(TravelGatesMessages.NOT_STANDING_ON_TPBLOCK, ChatColor.YELLOW + _tpBlock.toString() + ChatColor.RED));
return false;
}
if (ignorePlayerLocation || targetAndCurrentLocationAreDifferent
&& (nearestDestinationShortLocation != null || !playerNotOnTeleportBlock && _tpBlock.isEnabled()))
{
final String currentDest = _mapDestinationsByShortLoc.get(nearestDestinationShortLocation);
if (_isDebugEnabled)
{
_LOGGER.info("#14 : currentDest = " + currentDest);
}
if (!ignorePlayerLocation)
{
if (currentDest != null && getOptionOfDestination(currentDest, TravelGatesOptions.RESTRICTION))
{
final TravelGatesOptionsContainer container = _mapOptionsByDest.get(currentDest);
if (container != null && !container.isDestinationAllowed(destination))
{
player.sendMessage(ChatColor.RED
+ _messages.get(TravelGatesMessages.DESTINATION_IS_RESTRICTED, ChatColor.AQUA + currentDest + ChatColor.RED,
ChatColor.AQUA + destination + ChatColor.RED));
return false;
}
}
else if (currentDest == null)
{
player.sendMessage(ChatColor.RED + _messages.get(TravelGatesMessages.NO_STANDING_ON_DESTINATION));
return false;
}
}
final Location targetLocation = TravelGatesUtils.fullStringToLocation(fullLoc, player.getServer().getWorlds());
if (targetLocation.getWorld() != null)
{
player.teleport(targetLocation);
}
else
{
player.sendMessage(ChatColor.RED
+ _messages.get(TravelGatesMessages.TELEPORT_CANCELLED_WORLD_UNLOADED, ChatColor.AQUA + destination + ChatColor.RED));
return false;
}
if (ignorePlayerLocation)
{
_LOGGER.info(_tag + " " + player.getName() + " has forced the travel from " + playerShortLoc + " to " + destination);
}
else
{
_LOGGER.info(_tag + " " + player.getName() + " has travelled from " + currentDest + " to " + destination);
}
final boolean inventoryCleared = getOptionOfDestination(destination, TravelGatesOptions.INVENTORY);
// System.out.println("inventoryCleared=" + inventoryCleared + "; _protectAdminInventory=" + _protectAdminInventory
// + "; perm=" + hasPermission(player, TravelGatesPermissionsNodes.PROTECTADMININV));
if (!inventoryCleared || isProtectedInventory(player))
{
player.sendMessage(ChatColor.YELLOW
+ _messages.get(TravelGatesMessages.YOU_ARE_ARRIVED_AT, ChatColor.AQUA + destination + ChatColor.YELLOW)
+ ChatColor.GREEN + _messages.get(TravelGatesMessages.INVENTORY_KEPT));
}
else
{
String inventoryMessage = "";
final PlayerInventory inventory = player.getInventory();
if (_clearAllInventory)
{
inventory.setArmorContents(null);
inventoryMessage = _messages.get(TravelGatesMessages.ALL_INVENTORY_LOST);
}
else
{
inventoryMessage = _messages.get(TravelGatesMessages.INVENTORY_LOST);
}
inventory.clear();
player.sendMessage(ChatColor.YELLOW
+ _messages.get(TravelGatesMessages.YOU_ARE_ARRIVED_AT, ChatColor.AQUA + destination + ChatColor.YELLOW) + ChatColor.RED
+ inventoryMessage);
}
// If the arrival chunk is unloaded, it will be forced to load
final Chunk arrivalChunk = player.getWorld().getChunkAt(targetLocation);
if (!arrivalChunk.isLoaded())
{
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " The " + destination + "'s chunk was not loaded at " + targetLocation);
}
arrivalChunk.load();
}
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " End teleportPlayerToDest : true");
}
return true;
}
else
{
if (!targetAndCurrentLocationAreDifferent)
{
player.sendMessage(ChatColor.RED
+ _messages.get(TravelGatesMessages.YOURE_ALREADY_AT, ChatColor.AQUA + destination + ChatColor.RED));
}
else if (!playerIsOnExistingDestination)
{
player.sendMessage(ChatColor.RED
+ _messages.get(TravelGatesMessages.YOU_CANT_GO_THERE, ChatColor.AQUA + destination + ChatColor.RED));
}
}
}
else
{
player.sendMessage(ChatColor.RED
+ _messages.get(TravelGatesMessages.DESTINATION_DOESNT_EXIST, ChatColor.AQUA + destination + ChatColor.RED));
}
if (_isDebugEnabled)
{
_LOGGER.info(_debug + " End teleportPlayerToDest : false");
}
return false;
}
|
diff --git a/sobiohazardous/minestrappolation/extramobdrops/bridge/EMDBridgeRecipes.java b/sobiohazardous/minestrappolation/extramobdrops/bridge/EMDBridgeRecipes.java
index 23950341..2df056d7 100644
--- a/sobiohazardous/minestrappolation/extramobdrops/bridge/EMDBridgeRecipes.java
+++ b/sobiohazardous/minestrappolation/extramobdrops/bridge/EMDBridgeRecipes.java
@@ -1,53 +1,53 @@
package sobiohazardous.minestrappolation.extramobdrops.bridge;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import sobiohazardous.minestrappolation.extramobdrops.ExtraMobDrops;
import cpw.mods.fml.common.Loader;
import cpw.mods.fml.common.registry.GameRegistry;
public class EMDBridgeRecipes
{
public static void loadBridgeRecipes() throws Exception
{
if(Loader.isModLoaded("ExtraOres"))
{
GameRegistry.addShapelessRecipe(new ItemStack(ExtraMobDrops.hornSandstone), new Object[]
{
- ExtraMobDrops.horn, ExtraMobDrops.horn, sobiohazardous.minestrappolation.extraores.ExtraOres.SandstoneSword
+ ExtraMobDrops.horn, ExtraMobDrops.horn, sobiohazardous.minestrappolation.extraores.lib.EOItemManager.SandstoneSword
});
GameRegistry.addShapelessRecipe(new ItemStack(ExtraMobDrops.hornGranite), new Object[]
{
- ExtraMobDrops.horn, ExtraMobDrops.horn, sobiohazardous.minestrappolation.extraores.ExtraOres.GraniteSword
+ ExtraMobDrops.horn, ExtraMobDrops.horn, sobiohazardous.minestrappolation.extraores.lib.EOItemManager.GraniteSword
});
GameRegistry.addShapelessRecipe(new ItemStack(ExtraMobDrops.hornCopper), new Object[]
{
- ExtraMobDrops.horn, ExtraMobDrops.horn, sobiohazardous.minestrappolation.extraores.ExtraOres.CopperSword
+ ExtraMobDrops.horn, ExtraMobDrops.horn, sobiohazardous.minestrappolation.extraores.lib.EOItemManager.CopperSword
});
GameRegistry.addShapelessRecipe(new ItemStack(ExtraMobDrops.hornSteel), new Object[]
{
- ExtraMobDrops.horn, ExtraMobDrops.horn, sobiohazardous.minestrappolation.extraores.ExtraOres.SteelSword
+ ExtraMobDrops.horn, ExtraMobDrops.horn, sobiohazardous.minestrappolation.extraores.lib.EOItemManager.SteelSword
});
GameRegistry.addShapelessRecipe(new ItemStack(ExtraMobDrops.hornBronze), new Object[]
{
- ExtraMobDrops.horn, ExtraMobDrops.horn, sobiohazardous.minestrappolation.extraores.ExtraOres.BronzeSword
+ ExtraMobDrops.horn, ExtraMobDrops.horn, sobiohazardous.minestrappolation.extraores.lib.EOItemManager.BronzeSword
});
GameRegistry.addShapelessRecipe(new ItemStack(ExtraMobDrops.hornMeurodite), new Object[]
{
- ExtraMobDrops.horn, ExtraMobDrops.horn, sobiohazardous.minestrappolation.extraores.ExtraOres.meuroditeSword
+ ExtraMobDrops.horn, ExtraMobDrops.horn, sobiohazardous.minestrappolation.extraores.lib.EOItemManager.meuroditeSword
});
GameRegistry.addShapelessRecipe(new ItemStack(ExtraMobDrops.hornTorite), new Object[]
{
- ExtraMobDrops.horn, ExtraMobDrops.horn, sobiohazardous.minestrappolation.extraores.ExtraOres.ToriteSword
+ ExtraMobDrops.horn, ExtraMobDrops.horn, sobiohazardous.minestrappolation.extraores.lib.EOItemManager.ToriteSword
});
GameRegistry.addShapelessRecipe(new ItemStack(ExtraMobDrops.hornBlazium), new Object[]
{
- ExtraMobDrops.horn, ExtraMobDrops.horn, sobiohazardous.minestrappolation.extraores.ExtraOres.BlaziumSword
+ ExtraMobDrops.horn, ExtraMobDrops.horn, sobiohazardous.minestrappolation.extraores.lib.EOItemManager.BlaziumSword
});
GameRegistry.addShapelessRecipe(new ItemStack(ExtraMobDrops.hornTitanium), new Object[]
{
- ExtraMobDrops.horn, ExtraMobDrops.horn, sobiohazardous.minestrappolation.extraores.ExtraOres.TitaniumSword
+ ExtraMobDrops.horn, ExtraMobDrops.horn, sobiohazardous.minestrappolation.extraores.lib.EOItemManager.TitaniumSword
});
}
}
}
| false | true | public static void loadBridgeRecipes() throws Exception
{
if(Loader.isModLoaded("ExtraOres"))
{
GameRegistry.addShapelessRecipe(new ItemStack(ExtraMobDrops.hornSandstone), new Object[]
{
ExtraMobDrops.horn, ExtraMobDrops.horn, sobiohazardous.minestrappolation.extraores.ExtraOres.SandstoneSword
});
GameRegistry.addShapelessRecipe(new ItemStack(ExtraMobDrops.hornGranite), new Object[]
{
ExtraMobDrops.horn, ExtraMobDrops.horn, sobiohazardous.minestrappolation.extraores.ExtraOres.GraniteSword
});
GameRegistry.addShapelessRecipe(new ItemStack(ExtraMobDrops.hornCopper), new Object[]
{
ExtraMobDrops.horn, ExtraMobDrops.horn, sobiohazardous.minestrappolation.extraores.ExtraOres.CopperSword
});
GameRegistry.addShapelessRecipe(new ItemStack(ExtraMobDrops.hornSteel), new Object[]
{
ExtraMobDrops.horn, ExtraMobDrops.horn, sobiohazardous.minestrappolation.extraores.ExtraOres.SteelSword
});
GameRegistry.addShapelessRecipe(new ItemStack(ExtraMobDrops.hornBronze), new Object[]
{
ExtraMobDrops.horn, ExtraMobDrops.horn, sobiohazardous.minestrappolation.extraores.ExtraOres.BronzeSword
});
GameRegistry.addShapelessRecipe(new ItemStack(ExtraMobDrops.hornMeurodite), new Object[]
{
ExtraMobDrops.horn, ExtraMobDrops.horn, sobiohazardous.minestrappolation.extraores.ExtraOres.meuroditeSword
});
GameRegistry.addShapelessRecipe(new ItemStack(ExtraMobDrops.hornTorite), new Object[]
{
ExtraMobDrops.horn, ExtraMobDrops.horn, sobiohazardous.minestrappolation.extraores.ExtraOres.ToriteSword
});
GameRegistry.addShapelessRecipe(new ItemStack(ExtraMobDrops.hornBlazium), new Object[]
{
ExtraMobDrops.horn, ExtraMobDrops.horn, sobiohazardous.minestrappolation.extraores.ExtraOres.BlaziumSword
});
GameRegistry.addShapelessRecipe(new ItemStack(ExtraMobDrops.hornTitanium), new Object[]
{
ExtraMobDrops.horn, ExtraMobDrops.horn, sobiohazardous.minestrappolation.extraores.ExtraOres.TitaniumSword
});
}
}
| public static void loadBridgeRecipes() throws Exception
{
if(Loader.isModLoaded("ExtraOres"))
{
GameRegistry.addShapelessRecipe(new ItemStack(ExtraMobDrops.hornSandstone), new Object[]
{
ExtraMobDrops.horn, ExtraMobDrops.horn, sobiohazardous.minestrappolation.extraores.lib.EOItemManager.SandstoneSword
});
GameRegistry.addShapelessRecipe(new ItemStack(ExtraMobDrops.hornGranite), new Object[]
{
ExtraMobDrops.horn, ExtraMobDrops.horn, sobiohazardous.minestrappolation.extraores.lib.EOItemManager.GraniteSword
});
GameRegistry.addShapelessRecipe(new ItemStack(ExtraMobDrops.hornCopper), new Object[]
{
ExtraMobDrops.horn, ExtraMobDrops.horn, sobiohazardous.minestrappolation.extraores.lib.EOItemManager.CopperSword
});
GameRegistry.addShapelessRecipe(new ItemStack(ExtraMobDrops.hornSteel), new Object[]
{
ExtraMobDrops.horn, ExtraMobDrops.horn, sobiohazardous.minestrappolation.extraores.lib.EOItemManager.SteelSword
});
GameRegistry.addShapelessRecipe(new ItemStack(ExtraMobDrops.hornBronze), new Object[]
{
ExtraMobDrops.horn, ExtraMobDrops.horn, sobiohazardous.minestrappolation.extraores.lib.EOItemManager.BronzeSword
});
GameRegistry.addShapelessRecipe(new ItemStack(ExtraMobDrops.hornMeurodite), new Object[]
{
ExtraMobDrops.horn, ExtraMobDrops.horn, sobiohazardous.minestrappolation.extraores.lib.EOItemManager.meuroditeSword
});
GameRegistry.addShapelessRecipe(new ItemStack(ExtraMobDrops.hornTorite), new Object[]
{
ExtraMobDrops.horn, ExtraMobDrops.horn, sobiohazardous.minestrappolation.extraores.lib.EOItemManager.ToriteSword
});
GameRegistry.addShapelessRecipe(new ItemStack(ExtraMobDrops.hornBlazium), new Object[]
{
ExtraMobDrops.horn, ExtraMobDrops.horn, sobiohazardous.minestrappolation.extraores.lib.EOItemManager.BlaziumSword
});
GameRegistry.addShapelessRecipe(new ItemStack(ExtraMobDrops.hornTitanium), new Object[]
{
ExtraMobDrops.horn, ExtraMobDrops.horn, sobiohazardous.minestrappolation.extraores.lib.EOItemManager.TitaniumSword
});
}
}
|
diff --git a/programs/slammer/gui/UtilitiesPanel.java b/programs/slammer/gui/UtilitiesPanel.java
index a6f35d18..c2829e97 100644
--- a/programs/slammer/gui/UtilitiesPanel.java
+++ b/programs/slammer/gui/UtilitiesPanel.java
@@ -1,620 +1,624 @@
/* This file is in the public domain. */
package slammer.gui;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.border.*;
import java.io.*;
import java.util.*;
import slammer.*;
import slammer.analysis.*;
class UtilitiesPanel extends JPanel implements ActionListener
{
public final static int SELECT_CMGS = 1;
public final static int SELECT_GSCM = 2;
public final static int SELECT_MULT = 3;
public final static int SELECT_REDIGIT = 4;
public final static int SELECT_BRACKET = 5;
public final static int SELECT_TRIM = 6;
SlammerTabbedPane parent;
JRadioButton cmgs = new JRadioButton("<html>Convert cm/s<sup>2</sup> to g's</html>");
JRadioButton gscm = new JRadioButton("<html>Convert g's to cm/s<sup>2</sup></html>");
JRadioButton mult = new JRadioButton("Multiply by a constant");
JRadioButton redigit = new JRadioButton("Redigitize");
JRadioButton bracket = new JRadioButton("Bracket records");
JRadioButton trim = new JRadioButton("Trim records");
ButtonGroup group = new ButtonGroup();
JFileChooser fcs = new JFileChooser();
JFileChooser fcd = new JFileChooser();
JLabel source = new JLabel("Source files and directories");
JLabel dest = new JLabel("Destination file or directory (leave blank to overwrite source file)");
JLabel constant1 = new JLabel(" ");
JLabel constant1Pre = new JLabel("");
JLabel constant1Post = new JLabel("");
JLabel constant2 = new JLabel(" ");
JLabel constant2Pre = new JLabel("");
JLabel constant2Post = new JLabel("");
JLabel constant3 = new JLabel(" ");
JLabel constant3Pre = new JLabel("");
JLabel constant3Post = new JLabel("");
JTextField sourcef = new JTextField(50);
JTextField destf = new JTextField(50);
JTextField constant1f = new JTextField(5);
JTextField constant2f = new JTextField(5);
JTextField constant3f = new JTextField(5);
JButton sourceb = new JButton("Browse...");
JButton destb = new JButton("Browse...");
JButton go = new JButton("Execute");
JTextField skip = new JTextField("0", 4);
JCheckBox overwrite = new JCheckBox("Overwrite files without prompting");
JEditorPane pane = new JEditorPane();
JScrollPane spane = new JScrollPane(pane);
int global_overwrite = OVW_NONE;
public final static int OVW_NONE = 0;
public final static int OVW_OVERWRITE = 1;
public final static int OVW_SKIP = 2;
public UtilitiesPanel(SlammerTabbedPane parent)
{
this.parent = parent;
fcs.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
fcs.setMultiSelectionEnabled(true);
sourcef.setEditable(false);
fcd.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
cmgs.setActionCommand("change");
gscm.setActionCommand("change");
mult.setActionCommand("change");
redigit.setActionCommand("change");
bracket.setActionCommand("change");
trim.setActionCommand("change");
cmgs.addActionListener(this);
gscm.addActionListener(this);
mult.addActionListener(this);
redigit.addActionListener(this);
bracket.addActionListener(this);
trim.addActionListener(this);
group.add(cmgs);
group.add(gscm);
group.add(mult);
group.add(redigit);
group.add(bracket);
group.add(trim);
sourceb.setActionCommand("source");
sourceb.addActionListener(this);
destb.setActionCommand("dest");
destb.addActionListener(this);
go.setActionCommand("go");
go.addActionListener(this);
constant1f.setEditable(false);
constant2f.setEditable(false);
constant3f.setEditable(false);
pane.setEditable(false);
pane.setContentType("text/html");
GridBagLayout gridbag = new GridBagLayout();
GridBagConstraints c = new GridBagConstraints();
setLayout(gridbag);
Insets top = new Insets(10, 0, 0, 0);
Insets none = new Insets(0, 0, 0, 0);
Border b = BorderFactory.createCompoundBorder(
BorderFactory.createEmptyBorder(0, 0, 0, 5),
BorderFactory.createMatteBorder(0, 0, 0, 1, Color.BLACK)
);
int x = 0;
int y = 0;
JPanel panel = new JPanel(new GridLayout(0, 1));
panel.add(cmgs);
panel.add(gscm);
panel.add(mult);
panel.add(redigit);
panel.add(bracket);
panel.add(trim);
c.gridx = x++;
c.gridy = y;
c.gridheight = 12;
c.anchor = GridBagConstraints.NORTHWEST;
gridbag.setConstraints(panel, c);
add(panel);
c.gridx = x++;
c.fill = GridBagConstraints.BOTH;
JLabel label = new JLabel(" ");
label.setBorder(b);
gridbag.setConstraints(label, c);
add(label);
c.gridheight = 1;
c.insets = none;
c.gridx = x++;
c.gridy = y++;
gridbag.setConstraints(source, c);
add(source);
c.gridy = y++;
c.weightx = 1;
c.fill = GridBagConstraints.BOTH;
gridbag.setConstraints(sourcef, c);
add(sourcef);
c.gridx = x--;
c.weightx = 0;
gridbag.setConstraints(sourceb, c);
add(sourceb);
c.gridx = x++;
c.gridy = y++;
c.insets = top;
gridbag.setConstraints(dest, c);
add(dest);
c.gridy = y++;
c.insets = none;
gridbag.setConstraints(destf, c);
add(destf);
c.gridx = x--;
gridbag.setConstraints(destb, c);
add(destb);
c.gridx = x++;
c.gridy = y++;
c.gridwidth = 2;
c.insets = top;
gridbag.setConstraints(constant1, c);
add(constant1);
c.gridy = y++;
c.insets = none;
panel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
panel.add(constant1Pre);
panel.add(constant1f);
panel.add(constant1Post);
gridbag.setConstraints(panel, c);
add(panel);
c.gridy = y++;
c.insets = top;
gridbag.setConstraints(constant2, c);
add(constant2);
c.gridy = y++;
c.insets = none;
panel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
panel.add(constant2Pre);
panel.add(constant2f);
panel.add(constant2Post);
gridbag.setConstraints(panel, c);
add(panel);
c.gridy = y++;
c.insets = top;
gridbag.setConstraints(constant3, c);
add(constant3);
c.gridy = y++;
c.insets = none;
panel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
panel.add(constant3Pre);
panel.add(constant3f);
panel.add(constant3Post);
gridbag.setConstraints(panel, c);
add(panel);
c.gridy = y++;
c.insets = top;
panel = new JPanel(new FlowLayout(FlowLayout.LEFT, 0, 0));
panel.add(new JLabel("Delete the first "));
panel.add(skip);
panel.add(new JLabel(" lines of the source file (use this to delete header data)"));
gridbag.setConstraints(panel, c);
add(panel);
c.gridy = y++;
gridbag.setConstraints(overwrite, c);
add(overwrite);
c.gridy = y++;
c.fill = GridBagConstraints.NONE;
c.insets = new Insets(10, 0, 10, 0);
gridbag.setConstraints(go, c);
add(go);
c.gridx = 0;
c.gridy = y;
c.insets = none;
c.gridwidth = 4;
c.weightx = 1;
c.weighty = 1;
c.fill = GridBagConstraints.BOTH;
gridbag.setConstraints(spane, c);
add(spane);
}
public void actionPerformed(java.awt.event.ActionEvent e)
{
try
{
String command = e.getActionCommand();
if(command.equals("dest"))
{
if(fcd.showSaveDialog(this) == JFileChooser.APPROVE_OPTION)
{
destf.setText(fcd.getSelectedFile().getAbsolutePath());
}
}
else if(command.equals("source"))
{
if(fcs.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
{
File files[] = fcs.getSelectedFiles();
String sf = "";
for(int i = 0; i < files.length; i++)
{
if(i > 0)
sf += ", ";
sf += files[i].getAbsolutePath();
}
sourcef.setText(sf);
}
}
else if(command.equals("change"))
{
constant1f.setText("");
constant1f.setEditable(false);
constant1.setText(" ");
constant1Pre.setText("");
constant1Post.setText("");
constant2f.setText("");
constant2f.setEditable(false);
constant2.setText(" ");
constant2Pre.setText("");
constant2Post.setText("");
constant3f.setText("");
constant3f.setEditable(false);
constant3.setText(" ");
constant3Pre.setText("");
constant3Post.setText("");
if(cmgs.isSelected() || gscm.isSelected())
{
if(cmgs.isSelected())
pane.setText("This program converts a file containing a sequence of accelerations in units of cm/s/s into a file containing a sequence of accelerations in units of g. The program simply divides each value of cm/s/s by 980.665 to obtain values in terms of g. Both the input and output file or directory must be specified or selected using the browser.");
else
pane.setText("This program converts a file containing a sequence of accelerations in units of g into a file containing a sequence of accelerations in units of cm/s/s. The program simply multiplies each value by 980.665 to obtain values in cm/s/s. Both the input and output file or directory must be specified or selected using the browser.");
}
else if(mult.isSelected())
{
constant1.setText("Constant");
constant1f.setEditable(true);
pane.setText("This program multiplies the values in a file by a user-specified constant. Both the input and output file or directory must be specified or selected using the browser. The constant is specified in the \"Constant\" field.");
}
else if(redigit.isSelected())
{
constant1.setText("Digitization interval (s)");
constant1f.setEditable(true);
pane.setText("This program converts a time file (a file containing paired time and acceleration values) into a file containing a sequence of acceleration values having a constant time spacing (digitization interval) using an interpolation algorithm. The input and output files or directories must be specified or selected using the browser. The digitization interval for the output file must be specified in the indicated field; any value can be selected by the user, but values of 0.01-0.05 generally are appropriate. The output file is in the format necessary to be imported into the program, but it must have units of g.");
}
else if(bracket.isSelected())
{
constant1Pre.setText("Bracket record between values of ");
constant1Post.setText(" (in units of source file)");
constant1f.setEditable(true);
constant2Pre.setText("Retain ");
constant2Post.setText(" points to each side for lead-in and -out time");
constant2f.setEditable(true);
constant2f.setText("0");
pane.setText("This program removes points from a record from the beginning and end of the file that have values less than that specified in the input box.");
}
else if(trim.isSelected())
{
constant1Pre.setText("Remove data before ");
constant1Post.setText(" seconds");
constant1f.setEditable(true);
constant2Pre.setText("Remove data after ");
constant2Post.setText(" seconds");
constant2f.setEditable(true);
constant3.setText("Digitization interval (s)");
constant3f.setEditable(true);
pane.setText("This program saves all data within (inclusive) the specified range. If the file is shorter than the specified range, the file will simply be copied to the destination.");
}
}
else if(command.equals("go"))
{
File sources[], source, dest, d;
String temp;
sources = fcs.getSelectedFiles();
if(sources == null || sources.length == 0)
{
GUIUtils.popupError("No sources specified.");
return;
}
temp = destf.getText();
if(temp == null || temp.equals(""))
dest = null;
else
dest = new File(temp);
if(dest != null && (sources.length > 1 || !sources[0].isFile()) && dest.isFile())
{
GUIUtils.popupError("Destination must be a directory.");
return;
}
+ else if(dest != null && !dest.exists() && sources.length > 1)
+ {
+ dest.mkdirs();
+ }
temp = skip.getText();
int skipLines;
if(temp == null || temp.equals(""))
skipLines = 0;
else
{
Double doub = (Double)Utils.checkNum(temp, "skip lines field", null, false, null, new Double(0), true, null, false);
if(doub == null) return;
skipLines = doub.intValue();
}
Double val1 = new Double(0);
Double val2 = new Double(0);
Double val3 = new Double(0);
int sel;
String selStr;
if(cmgs.isSelected())
{
sel = SELECT_CMGS;
selStr = "Conversion from cm/s/s to g's";
}
else if(gscm.isSelected())
{
sel = SELECT_GSCM;
selStr = "Conversion from g's to cm/s/s";
}
else if(mult.isSelected())
{
val1 = (Double)Utils.checkNum(constant1f.getText(), "constant field", null, false, null, null, false, null, false);
if(val1 == null) return;
sel = SELECT_MULT;
selStr = "Multiplication by " + constant1f.getText();
}
else if(redigit.isSelected())
{
val1 = (Double)Utils.checkNum(constant1f.getText(), "digitization interval field", null, false, null, new Double(0), false, null, false);
if(val1 == null) return;
sel = SELECT_REDIGIT;
selStr = "Redigitization to digitization interval of " + constant1f.getText();
}
else if(bracket.isSelected())
{
val1 = (Double)Utils.checkNum(constant1f.getText(), "bracket value field", null, false, null, new Double(0), true, null, false);
if(val1 == null) return;
val2 = (Double)Utils.checkNum(constant2f.getText(), "bracket lead-in field", null, false, null, new Double(0), true, null, false);
if(val2 == null) return;
sel = SELECT_BRACKET;
selStr = "Bracket";
}
else if(trim.isSelected())
{
val1 = (Double)Utils.checkNum(constant1f.getText(), "first trim time field", null, false, null, null, false, null, false);
if(val1 == null) return;
val2 = (Double)Utils.checkNum(constant2f.getText(), "second trim time field", null, false, null, null, false, null, false);
if(val2 == null) return;
val3 = (Double)Utils.checkNum(constant3f.getText(), "digitization interval field", null, false, null, null, false, null, false);
if(val3 == null) return;
sel = SELECT_TRIM;
selStr = "Trim";
}
else
{
GUIUtils.popupError("No utilitiy selected.");
return;
}
int ret;
boolean ovw = overwrite.isSelected();
StringBuilder results = new StringBuilder();
int errors = 0;
global_overwrite = OVW_NONE;
Stack<File> stack = new Stack<File>();
Stack<File> source_stack = new Stack<File>();
TreeMap<File, File> map = new TreeMap<File, File>();
File parent;
for(int i = 0; i < sources.length; i++)
source_stack.push(sources[i]);
JFrame progFrame = new JFrame("Progress...");
JProgressBar prog = new JProgressBar();
prog.setStringPainted(true);
progFrame.getContentPane().add(prog);
progFrame.setSize(600, 75);
progFrame.setLocationRelativeTo(null);
progFrame.setVisible(true);
while(!source_stack.isEmpty())
{
source = source_stack.pop();
if(source.isFile())
stack.push(source);
else if(source.isDirectory())
{
parent = map.get(source.getParentFile());
if(parent != null)
map.put(source.getAbsoluteFile(), new File(parent, source.getName()));
else
map.put(source.getAbsoluteFile(), new File(source.getName()));
File list[] = source.listFiles();
if(dest != null)
{
d = new File(dest, map.get(source.getAbsoluteFile()).getPath());
d.mkdirs();
}
for(int i = 0; i < list.length; i++)
{
if(list[i].isFile())
stack.push(list[i]);
else if(list[i].isDirectory())
source_stack.push(list[i]);
}
}
}
prog.setMaximum(stack.size());
int processed = 0;
while(!stack.isEmpty())
{
source = stack.pop();
prog.setValue(processed++);
prog.setString(source.getAbsolutePath());
prog.paintImmediately(0, 0, prog.getWidth(), prog.getHeight());
if(dest == null)
d = source;
else if(!dest.exists() || dest.isFile())
d = dest;
else
{
d = map.get(source.getParentFile());
d = new File(d, source.getName());
d = new File(dest, d.getPath());
}
try
{
results.append("<br>" + runUtil(sel, source, d, skipLines, val1.doubleValue(), val2.doubleValue(), val3.doubleValue(), ovw));
}
catch (Exception ex)
{
results.insert(0, "<br>" + ex.getMessage());
errors++;
}
}
progFrame.dispose();
pane.setText(selStr + (errors == 0 ? " complete" : (" NOT complete: " + errors + " errors")) + "<hr>" + results);
}
}
catch (Exception ex)
{
Utils.catchException(ex);
}
}
private String runUtil(int sel, File s, File d, int skip, double var1, double var2, double var3, boolean ovw) throws Exception
{
File dest;
boolean overwrite = false;
if(!s.exists() || !s.canRead())
throw new Exception("Not readable: " + s.getAbsolutePath());
else if(!s.isFile())
throw new Exception("Invalid file: " + s.getAbsolutePath());
if(d == null)
dest = s;
else if(d.isDirectory())
dest = new File(d, s.getName());
else
dest = d;
String ret = dest.toString();
if(dest.exists())
{
if(ovw || global_overwrite == OVW_OVERWRITE)
overwrite = true;
else if(global_overwrite == OVW_SKIP)
return "Skip: " + ret;
else
{
Object[] options = { "Overwrite", "Overwrite All", "Skip", "Skip All" };
switch(JOptionPane.showOptionDialog(null, "File exists:\n" + dest.toString(), "Overwrite",
JOptionPane.DEFAULT_OPTION, JOptionPane.WARNING_MESSAGE,
null, options, options[0]))
{
case 0: // overwrite
overwrite = true;
break;
case 1: // overwrite all
overwrite = true;
global_overwrite = OVW_OVERWRITE;
break;
case 3: // skip all
global_overwrite = OVW_SKIP;
case 2: // skip
default:
return "Skip: " + ret;
}
}
}
DoubleList data = new DoubleList(s.getAbsolutePath(), skip, 1.0, true);
if(data.bad())
throw new Exception("Invalid data in " + ret + " at point " + data.badEntry());
try
{
FileWriter o = new FileWriter(dest);
switch(sel)
{
case SELECT_CMGS:
Utilities.CM_GS(data, o);
break;
case SELECT_GSCM:
Utilities.GS_CM(data, o);
break;
case SELECT_MULT:
Utilities.Mult(data, o, var1);
break;
case SELECT_REDIGIT:
Utilities.Redigitize(data, o, var1);
break;
case SELECT_BRACKET:
Utilities.Bracket(data, o, var1, (int)var2);
break;
case SELECT_TRIM:
Utilities.Trim(data, o, var1, var2, var3);
}
}
catch (Exception ex)
{
throw new Exception(ex.getMessage() + ": " + ret);
}
if(overwrite)
ret = "(overwritten) " + ret;
return "Success: " + ret;
}
}
| true | true | public void actionPerformed(java.awt.event.ActionEvent e)
{
try
{
String command = e.getActionCommand();
if(command.equals("dest"))
{
if(fcd.showSaveDialog(this) == JFileChooser.APPROVE_OPTION)
{
destf.setText(fcd.getSelectedFile().getAbsolutePath());
}
}
else if(command.equals("source"))
{
if(fcs.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
{
File files[] = fcs.getSelectedFiles();
String sf = "";
for(int i = 0; i < files.length; i++)
{
if(i > 0)
sf += ", ";
sf += files[i].getAbsolutePath();
}
sourcef.setText(sf);
}
}
else if(command.equals("change"))
{
constant1f.setText("");
constant1f.setEditable(false);
constant1.setText(" ");
constant1Pre.setText("");
constant1Post.setText("");
constant2f.setText("");
constant2f.setEditable(false);
constant2.setText(" ");
constant2Pre.setText("");
constant2Post.setText("");
constant3f.setText("");
constant3f.setEditable(false);
constant3.setText(" ");
constant3Pre.setText("");
constant3Post.setText("");
if(cmgs.isSelected() || gscm.isSelected())
{
if(cmgs.isSelected())
pane.setText("This program converts a file containing a sequence of accelerations in units of cm/s/s into a file containing a sequence of accelerations in units of g. The program simply divides each value of cm/s/s by 980.665 to obtain values in terms of g. Both the input and output file or directory must be specified or selected using the browser.");
else
pane.setText("This program converts a file containing a sequence of accelerations in units of g into a file containing a sequence of accelerations in units of cm/s/s. The program simply multiplies each value by 980.665 to obtain values in cm/s/s. Both the input and output file or directory must be specified or selected using the browser.");
}
else if(mult.isSelected())
{
constant1.setText("Constant");
constant1f.setEditable(true);
pane.setText("This program multiplies the values in a file by a user-specified constant. Both the input and output file or directory must be specified or selected using the browser. The constant is specified in the \"Constant\" field.");
}
else if(redigit.isSelected())
{
constant1.setText("Digitization interval (s)");
constant1f.setEditable(true);
pane.setText("This program converts a time file (a file containing paired time and acceleration values) into a file containing a sequence of acceleration values having a constant time spacing (digitization interval) using an interpolation algorithm. The input and output files or directories must be specified or selected using the browser. The digitization interval for the output file must be specified in the indicated field; any value can be selected by the user, but values of 0.01-0.05 generally are appropriate. The output file is in the format necessary to be imported into the program, but it must have units of g.");
}
else if(bracket.isSelected())
{
constant1Pre.setText("Bracket record between values of ");
constant1Post.setText(" (in units of source file)");
constant1f.setEditable(true);
constant2Pre.setText("Retain ");
constant2Post.setText(" points to each side for lead-in and -out time");
constant2f.setEditable(true);
constant2f.setText("0");
pane.setText("This program removes points from a record from the beginning and end of the file that have values less than that specified in the input box.");
}
else if(trim.isSelected())
{
constant1Pre.setText("Remove data before ");
constant1Post.setText(" seconds");
constant1f.setEditable(true);
constant2Pre.setText("Remove data after ");
constant2Post.setText(" seconds");
constant2f.setEditable(true);
constant3.setText("Digitization interval (s)");
constant3f.setEditable(true);
pane.setText("This program saves all data within (inclusive) the specified range. If the file is shorter than the specified range, the file will simply be copied to the destination.");
}
}
else if(command.equals("go"))
{
File sources[], source, dest, d;
String temp;
sources = fcs.getSelectedFiles();
if(sources == null || sources.length == 0)
{
GUIUtils.popupError("No sources specified.");
return;
}
temp = destf.getText();
if(temp == null || temp.equals(""))
dest = null;
else
dest = new File(temp);
if(dest != null && (sources.length > 1 || !sources[0].isFile()) && dest.isFile())
{
GUIUtils.popupError("Destination must be a directory.");
return;
}
temp = skip.getText();
int skipLines;
if(temp == null || temp.equals(""))
skipLines = 0;
else
{
Double doub = (Double)Utils.checkNum(temp, "skip lines field", null, false, null, new Double(0), true, null, false);
if(doub == null) return;
skipLines = doub.intValue();
}
Double val1 = new Double(0);
Double val2 = new Double(0);
Double val3 = new Double(0);
int sel;
String selStr;
if(cmgs.isSelected())
{
sel = SELECT_CMGS;
selStr = "Conversion from cm/s/s to g's";
}
else if(gscm.isSelected())
{
sel = SELECT_GSCM;
selStr = "Conversion from g's to cm/s/s";
}
else if(mult.isSelected())
{
val1 = (Double)Utils.checkNum(constant1f.getText(), "constant field", null, false, null, null, false, null, false);
if(val1 == null) return;
sel = SELECT_MULT;
selStr = "Multiplication by " + constant1f.getText();
}
else if(redigit.isSelected())
{
val1 = (Double)Utils.checkNum(constant1f.getText(), "digitization interval field", null, false, null, new Double(0), false, null, false);
if(val1 == null) return;
sel = SELECT_REDIGIT;
selStr = "Redigitization to digitization interval of " + constant1f.getText();
}
else if(bracket.isSelected())
{
val1 = (Double)Utils.checkNum(constant1f.getText(), "bracket value field", null, false, null, new Double(0), true, null, false);
if(val1 == null) return;
val2 = (Double)Utils.checkNum(constant2f.getText(), "bracket lead-in field", null, false, null, new Double(0), true, null, false);
if(val2 == null) return;
sel = SELECT_BRACKET;
selStr = "Bracket";
}
else if(trim.isSelected())
{
val1 = (Double)Utils.checkNum(constant1f.getText(), "first trim time field", null, false, null, null, false, null, false);
if(val1 == null) return;
val2 = (Double)Utils.checkNum(constant2f.getText(), "second trim time field", null, false, null, null, false, null, false);
if(val2 == null) return;
val3 = (Double)Utils.checkNum(constant3f.getText(), "digitization interval field", null, false, null, null, false, null, false);
if(val3 == null) return;
sel = SELECT_TRIM;
selStr = "Trim";
}
else
{
GUIUtils.popupError("No utilitiy selected.");
return;
}
int ret;
boolean ovw = overwrite.isSelected();
StringBuilder results = new StringBuilder();
int errors = 0;
global_overwrite = OVW_NONE;
Stack<File> stack = new Stack<File>();
Stack<File> source_stack = new Stack<File>();
TreeMap<File, File> map = new TreeMap<File, File>();
File parent;
for(int i = 0; i < sources.length; i++)
source_stack.push(sources[i]);
JFrame progFrame = new JFrame("Progress...");
JProgressBar prog = new JProgressBar();
prog.setStringPainted(true);
progFrame.getContentPane().add(prog);
progFrame.setSize(600, 75);
progFrame.setLocationRelativeTo(null);
progFrame.setVisible(true);
while(!source_stack.isEmpty())
{
source = source_stack.pop();
if(source.isFile())
stack.push(source);
else if(source.isDirectory())
{
parent = map.get(source.getParentFile());
if(parent != null)
map.put(source.getAbsoluteFile(), new File(parent, source.getName()));
else
map.put(source.getAbsoluteFile(), new File(source.getName()));
File list[] = source.listFiles();
if(dest != null)
{
d = new File(dest, map.get(source.getAbsoluteFile()).getPath());
d.mkdirs();
}
for(int i = 0; i < list.length; i++)
{
if(list[i].isFile())
stack.push(list[i]);
else if(list[i].isDirectory())
source_stack.push(list[i]);
}
}
}
prog.setMaximum(stack.size());
int processed = 0;
while(!stack.isEmpty())
{
source = stack.pop();
prog.setValue(processed++);
prog.setString(source.getAbsolutePath());
prog.paintImmediately(0, 0, prog.getWidth(), prog.getHeight());
if(dest == null)
d = source;
else if(!dest.exists() || dest.isFile())
d = dest;
else
{
d = map.get(source.getParentFile());
d = new File(d, source.getName());
d = new File(dest, d.getPath());
}
try
{
results.append("<br>" + runUtil(sel, source, d, skipLines, val1.doubleValue(), val2.doubleValue(), val3.doubleValue(), ovw));
}
catch (Exception ex)
{
results.insert(0, "<br>" + ex.getMessage());
errors++;
}
}
progFrame.dispose();
pane.setText(selStr + (errors == 0 ? " complete" : (" NOT complete: " + errors + " errors")) + "<hr>" + results);
}
}
catch (Exception ex)
{
Utils.catchException(ex);
}
}
| public void actionPerformed(java.awt.event.ActionEvent e)
{
try
{
String command = e.getActionCommand();
if(command.equals("dest"))
{
if(fcd.showSaveDialog(this) == JFileChooser.APPROVE_OPTION)
{
destf.setText(fcd.getSelectedFile().getAbsolutePath());
}
}
else if(command.equals("source"))
{
if(fcs.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
{
File files[] = fcs.getSelectedFiles();
String sf = "";
for(int i = 0; i < files.length; i++)
{
if(i > 0)
sf += ", ";
sf += files[i].getAbsolutePath();
}
sourcef.setText(sf);
}
}
else if(command.equals("change"))
{
constant1f.setText("");
constant1f.setEditable(false);
constant1.setText(" ");
constant1Pre.setText("");
constant1Post.setText("");
constant2f.setText("");
constant2f.setEditable(false);
constant2.setText(" ");
constant2Pre.setText("");
constant2Post.setText("");
constant3f.setText("");
constant3f.setEditable(false);
constant3.setText(" ");
constant3Pre.setText("");
constant3Post.setText("");
if(cmgs.isSelected() || gscm.isSelected())
{
if(cmgs.isSelected())
pane.setText("This program converts a file containing a sequence of accelerations in units of cm/s/s into a file containing a sequence of accelerations in units of g. The program simply divides each value of cm/s/s by 980.665 to obtain values in terms of g. Both the input and output file or directory must be specified or selected using the browser.");
else
pane.setText("This program converts a file containing a sequence of accelerations in units of g into a file containing a sequence of accelerations in units of cm/s/s. The program simply multiplies each value by 980.665 to obtain values in cm/s/s. Both the input and output file or directory must be specified or selected using the browser.");
}
else if(mult.isSelected())
{
constant1.setText("Constant");
constant1f.setEditable(true);
pane.setText("This program multiplies the values in a file by a user-specified constant. Both the input and output file or directory must be specified or selected using the browser. The constant is specified in the \"Constant\" field.");
}
else if(redigit.isSelected())
{
constant1.setText("Digitization interval (s)");
constant1f.setEditable(true);
pane.setText("This program converts a time file (a file containing paired time and acceleration values) into a file containing a sequence of acceleration values having a constant time spacing (digitization interval) using an interpolation algorithm. The input and output files or directories must be specified or selected using the browser. The digitization interval for the output file must be specified in the indicated field; any value can be selected by the user, but values of 0.01-0.05 generally are appropriate. The output file is in the format necessary to be imported into the program, but it must have units of g.");
}
else if(bracket.isSelected())
{
constant1Pre.setText("Bracket record between values of ");
constant1Post.setText(" (in units of source file)");
constant1f.setEditable(true);
constant2Pre.setText("Retain ");
constant2Post.setText(" points to each side for lead-in and -out time");
constant2f.setEditable(true);
constant2f.setText("0");
pane.setText("This program removes points from a record from the beginning and end of the file that have values less than that specified in the input box.");
}
else if(trim.isSelected())
{
constant1Pre.setText("Remove data before ");
constant1Post.setText(" seconds");
constant1f.setEditable(true);
constant2Pre.setText("Remove data after ");
constant2Post.setText(" seconds");
constant2f.setEditable(true);
constant3.setText("Digitization interval (s)");
constant3f.setEditable(true);
pane.setText("This program saves all data within (inclusive) the specified range. If the file is shorter than the specified range, the file will simply be copied to the destination.");
}
}
else if(command.equals("go"))
{
File sources[], source, dest, d;
String temp;
sources = fcs.getSelectedFiles();
if(sources == null || sources.length == 0)
{
GUIUtils.popupError("No sources specified.");
return;
}
temp = destf.getText();
if(temp == null || temp.equals(""))
dest = null;
else
dest = new File(temp);
if(dest != null && (sources.length > 1 || !sources[0].isFile()) && dest.isFile())
{
GUIUtils.popupError("Destination must be a directory.");
return;
}
else if(dest != null && !dest.exists() && sources.length > 1)
{
dest.mkdirs();
}
temp = skip.getText();
int skipLines;
if(temp == null || temp.equals(""))
skipLines = 0;
else
{
Double doub = (Double)Utils.checkNum(temp, "skip lines field", null, false, null, new Double(0), true, null, false);
if(doub == null) return;
skipLines = doub.intValue();
}
Double val1 = new Double(0);
Double val2 = new Double(0);
Double val3 = new Double(0);
int sel;
String selStr;
if(cmgs.isSelected())
{
sel = SELECT_CMGS;
selStr = "Conversion from cm/s/s to g's";
}
else if(gscm.isSelected())
{
sel = SELECT_GSCM;
selStr = "Conversion from g's to cm/s/s";
}
else if(mult.isSelected())
{
val1 = (Double)Utils.checkNum(constant1f.getText(), "constant field", null, false, null, null, false, null, false);
if(val1 == null) return;
sel = SELECT_MULT;
selStr = "Multiplication by " + constant1f.getText();
}
else if(redigit.isSelected())
{
val1 = (Double)Utils.checkNum(constant1f.getText(), "digitization interval field", null, false, null, new Double(0), false, null, false);
if(val1 == null) return;
sel = SELECT_REDIGIT;
selStr = "Redigitization to digitization interval of " + constant1f.getText();
}
else if(bracket.isSelected())
{
val1 = (Double)Utils.checkNum(constant1f.getText(), "bracket value field", null, false, null, new Double(0), true, null, false);
if(val1 == null) return;
val2 = (Double)Utils.checkNum(constant2f.getText(), "bracket lead-in field", null, false, null, new Double(0), true, null, false);
if(val2 == null) return;
sel = SELECT_BRACKET;
selStr = "Bracket";
}
else if(trim.isSelected())
{
val1 = (Double)Utils.checkNum(constant1f.getText(), "first trim time field", null, false, null, null, false, null, false);
if(val1 == null) return;
val2 = (Double)Utils.checkNum(constant2f.getText(), "second trim time field", null, false, null, null, false, null, false);
if(val2 == null) return;
val3 = (Double)Utils.checkNum(constant3f.getText(), "digitization interval field", null, false, null, null, false, null, false);
if(val3 == null) return;
sel = SELECT_TRIM;
selStr = "Trim";
}
else
{
GUIUtils.popupError("No utilitiy selected.");
return;
}
int ret;
boolean ovw = overwrite.isSelected();
StringBuilder results = new StringBuilder();
int errors = 0;
global_overwrite = OVW_NONE;
Stack<File> stack = new Stack<File>();
Stack<File> source_stack = new Stack<File>();
TreeMap<File, File> map = new TreeMap<File, File>();
File parent;
for(int i = 0; i < sources.length; i++)
source_stack.push(sources[i]);
JFrame progFrame = new JFrame("Progress...");
JProgressBar prog = new JProgressBar();
prog.setStringPainted(true);
progFrame.getContentPane().add(prog);
progFrame.setSize(600, 75);
progFrame.setLocationRelativeTo(null);
progFrame.setVisible(true);
while(!source_stack.isEmpty())
{
source = source_stack.pop();
if(source.isFile())
stack.push(source);
else if(source.isDirectory())
{
parent = map.get(source.getParentFile());
if(parent != null)
map.put(source.getAbsoluteFile(), new File(parent, source.getName()));
else
map.put(source.getAbsoluteFile(), new File(source.getName()));
File list[] = source.listFiles();
if(dest != null)
{
d = new File(dest, map.get(source.getAbsoluteFile()).getPath());
d.mkdirs();
}
for(int i = 0; i < list.length; i++)
{
if(list[i].isFile())
stack.push(list[i]);
else if(list[i].isDirectory())
source_stack.push(list[i]);
}
}
}
prog.setMaximum(stack.size());
int processed = 0;
while(!stack.isEmpty())
{
source = stack.pop();
prog.setValue(processed++);
prog.setString(source.getAbsolutePath());
prog.paintImmediately(0, 0, prog.getWidth(), prog.getHeight());
if(dest == null)
d = source;
else if(!dest.exists() || dest.isFile())
d = dest;
else
{
d = map.get(source.getParentFile());
d = new File(d, source.getName());
d = new File(dest, d.getPath());
}
try
{
results.append("<br>" + runUtil(sel, source, d, skipLines, val1.doubleValue(), val2.doubleValue(), val3.doubleValue(), ovw));
}
catch (Exception ex)
{
results.insert(0, "<br>" + ex.getMessage());
errors++;
}
}
progFrame.dispose();
pane.setText(selStr + (errors == 0 ? " complete" : (" NOT complete: " + errors + " errors")) + "<hr>" + results);
}
}
catch (Exception ex)
{
Utils.catchException(ex);
}
}
|
diff --git a/app/controllers/Application.java b/app/controllers/Application.java
index f355d00..af97190 100644
--- a/app/controllers/Application.java
+++ b/app/controllers/Application.java
@@ -1,13 +1,13 @@
package controllers;
import models.Hotel;
import play.data.Form;
import play.mvc.*;
public class Application extends Controller {
public static Result index() {
- return ok(views.html.index.render());
+ return redirect(routes.Hotels.all());
}
}
| true | true | public static Result index() {
return ok(views.html.index.render());
}
| public static Result index() {
return redirect(routes.Hotels.all());
}
|
diff --git a/net/sf/mpxj/mpp/MPP14Reader.java b/net/sf/mpxj/mpp/MPP14Reader.java
index fee7de4..d8c9c5c 100644
--- a/net/sf/mpxj/mpp/MPP14Reader.java
+++ b/net/sf/mpxj/mpp/MPP14Reader.java
@@ -1,2466 +1,2466 @@
/*
* file: MPP14Reader.java
* author: Jon Iles
* copyright: (c) Packwood Software 2002-2010
* date: 20/01/2010
*/
/*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by the
* Free Software Foundation; either version 2.1 of the License, or (at your
* option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this library; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*/
package net.sf.mpxj.mpp;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import net.sf.mpxj.DateRange;
import net.sf.mpxj.Day;
import net.sf.mpxj.DayType;
import net.sf.mpxj.Duration;
import net.sf.mpxj.MPPResourceField14;
import net.sf.mpxj.MPPTaskField14;
import net.sf.mpxj.MPXJException;
import net.sf.mpxj.ProjectCalendar;
import net.sf.mpxj.ProjectCalendarException;
import net.sf.mpxj.ProjectCalendarHours;
import net.sf.mpxj.ProjectFile;
import net.sf.mpxj.ProjectHeader;
import net.sf.mpxj.Relation;
import net.sf.mpxj.RelationType;
import net.sf.mpxj.Resource;
import net.sf.mpxj.ResourceField;
import net.sf.mpxj.ResourceType;
import net.sf.mpxj.SubProject;
import net.sf.mpxj.Table;
import net.sf.mpxj.Task;
import net.sf.mpxj.TaskField;
import net.sf.mpxj.TaskMode;
import net.sf.mpxj.TimeUnit;
import net.sf.mpxj.View;
import net.sf.mpxj.utility.DateUtility;
import net.sf.mpxj.utility.Pair;
import net.sf.mpxj.utility.RTFUtility;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.DocumentEntry;
import org.apache.poi.poifs.filesystem.DocumentInputStream;
/**
* This class is used to represent a Microsoft Project MPP14 file. This
* implementation allows the file to be read, and the data it contains
* exported as a set of MPX objects. These objects can be interrogated
* to retrieve any required data, or stored as an MPX file.
*/
final class MPP14Reader implements MPPVariantReader
{
/**
* This method is used to process an MPP14 file. This is the file format
* used by Project 14.
*
* @param reader parent file reader
* @param file parent MPP file
* @param root Root of the POI file system.
*/
public void process(MPPReader reader, ProjectFile file, DirectoryEntry root) throws MPXJException, IOException
{
try
{
//
// Retrieve the high level document properties
//
Props14 props14 = new Props14(new DocumentInputStream(((DocumentEntry) root.getEntry("Props14"))));
//System.out.println(props14);
file.setProjectFilePath(props14.getUnicodeString(Props.PROJECT_FILE_PATH));
file.setEncoded(props14.getByte(Props.PASSWORD_FLAG) != 0);
file.setEncryptionCode(props14.getByte(Props.ENCRYPTION_CODE));
//
// Test for password protection. In the single byte retrieved here:
//
// 0x00 = no password
// 0x01 = protection password has been supplied
// 0x02 = write reservation password has been supplied
// 0x03 = both passwords have been supplied
//
if ((props14.getByte(Props.PASSWORD_FLAG) & 0x01) != 0)
{
// Couldn't figure out how to get the password for MPP14 files so for now we just need to block the reading
// File is password protected for reading, let's read the password
// and see if the correct read password was given to us.
//byte[] data = props14.getByteArray(Props.READ_PASSWORD);
//MPPUtility.decodeBuffer(data, file.getEncryptionCode());
//System.out.println(MPPUtility.hexdump(data, true, 16, ""));
//System.out.println();
//data = props14.getByteArray(Props.WRITE_PASSWORD);
//MPPUtility.decodeBuffer(data, file.getEncryptionCode());
//System.out.println(MPPUtility.hexdump(data, true, 16, ""));
//String readPassword = MPPUtility.decodePassword(props14.getByteArray(Props.READ_PASSWORD), file.getEncryptionCode());
//System.out.println(readPassword);
//String writePassword = MPPUtility.decodePassword(props14.getByteArray(Props.WRITE_PASSWORD), file.getEncryptionCode());
//System.out.println(writePassword);
// See if the correct read password was given
//if (readPassword == null)
//{
// Couldn't read password, so no chance to ask the user
throw new MPXJException(MPXJException.PASSWORD_PROTECTED);
//}
//if (reader.getReadPassword() == null || reader.getReadPassword().matches(readPassword) == false)
//{
// Passwords don't match
// throw new MPXJException (MPXJException.PASSWORD_PROTECTED_ENTER_PASSWORD);
//}
// Passwords matched so let's allow the reading to continue.
}
m_reader = reader;
m_file = file;
m_root = root;
m_resourceMap = new HashMap<Integer, ProjectCalendar>();
m_projectDir = (DirectoryEntry) root.getEntry(" 114");
m_viewDir = (DirectoryEntry) root.getEntry(" 214");
DirectoryEntry outlineCodeDir = (DirectoryEntry) m_projectDir.getEntry("TBkndOutlCode");
m_outlineCodeVarMeta = new VarMeta12(new DocumentInputStream(((DocumentEntry) outlineCodeDir.getEntry("VarMeta"))));
m_outlineCodeVarData = new Var2Data(m_outlineCodeVarMeta, new DocumentInputStream(((DocumentEntry) outlineCodeDir.getEntry("Var2Data"))));
m_projectProps = new Props14(getEncryptableInputStream(m_projectDir, "Props"));
//MPPUtility.fileDump("c:\\temp\\props.txt", m_projectProps.toString().getBytes());
m_fontBases = new HashMap<Integer, FontBase>();
m_taskSubProjects = new HashMap<Integer, SubProject>();
m_parentTasks = new HashMap<Integer, Integer>();
m_taskOrder = new TreeMap<Long, Integer>();
m_nullTaskOrder = new TreeMap<Integer, Integer>();
m_file.setMppFileType(14);
m_file.setAutoFilter(props14.getBoolean(Props.AUTO_FILTER));
processCustomValueLists();
processPropertyData();
processCalendarData();
processResourceData();
processTaskData();
processConstraintData();
processAssignmentData();
//
// MPP14 files seem to exhibit some occasional weirdness
// with duplicate ID values which leads to the task structure
// being reported incorrectly. The following method
// attempts to correct this.
//
fixTaskOrder();
if (reader.getReadPresentationData())
{
processViewPropertyData();
processTableData();
processViewData();
processFilterData();
processGroupData();
processSavedViewState();
}
}
finally
{
m_reader = null;
m_file = null;
m_root = null;
m_resourceMap = null;
m_projectDir = null;
m_viewDir = null;
m_outlineCodeVarData = null;
m_outlineCodeVarMeta = null;
m_projectProps = null;
m_fontBases = null;
m_taskSubProjects = null;
m_parentTasks = null;
m_taskOrder = null;
m_nullTaskOrder = null;
}
}
/**
* This method extracts and collates the value list information
* for custom column value lists.
*/
private void processCustomValueLists()
{
Integer[] uniqueid = m_outlineCodeVarMeta.getUniqueIdentifierArray();
Integer id;
CustomFieldValueItem item;
for (int loop = 0; loop < uniqueid.length; loop++)
{
id = uniqueid[loop];
item = new CustomFieldValueItem(id);
item.setValue(m_outlineCodeVarData.getByteArray(id, VALUE_LIST_VALUE));
item.setDescription(m_outlineCodeVarData.getUnicodeString(id, VALUE_LIST_DESCRIPTION));
item.setUnknown(m_outlineCodeVarData.getByteArray(id, VALUE_LIST_UNKNOWN));
m_file.addCustomFieldValueItem(item);
}
}
/**
* This method extracts and collates global property data.
*
* @throws java.io.IOException
*/
private void processPropertyData() throws IOException, MPXJException
{
//
// Process the project header
//
ProjectHeaderReader projectHeaderReader = new ProjectHeaderReader();
projectHeaderReader.process(m_file, m_projectProps, m_root);
//
// Process subproject data
//
processSubProjectData();
//
// Process graphical indicators
//
GraphicalIndicatorReader reader = new GraphicalIndicatorReader();
reader.process(m_file, m_projectProps);
}
/**
* Read sub project data from the file, and add it to a hash map
* indexed by task ID.
*
* Project stores all subprojects that have ever been inserted into this project
* in sequence and that is what used to count unique id offsets for each of the
* subprojects.
*/
private void processSubProjectData()
{
byte[] subProjData = m_projectProps.getByteArray(Props.SUBPROJECT_DATA);
//System.out.println (MPPUtility.hexdump(subProjData, true, 16, ""));
//MPPUtility.fileHexDump("c:\\temp\\dump.txt", subProjData);
if (subProjData != null)
{
int index = 0;
int offset = 0;
int itemHeaderOffset;
int uniqueIDOffset;
int filePathOffset;
int fileNameOffset;
SubProject sp;
byte[] itemHeader = new byte[20];
/*int blockSize = MPPUtility.getInt(subProjData, offset);*/
offset += 4;
/*int unknown = MPPUtility.getInt(subProjData, offset);*/
offset += 4;
int itemCountOffset = MPPUtility.getInt(subProjData, offset);
offset += 4;
while (offset < itemCountOffset)
{
index++;
itemHeaderOffset = MPPUtility.getInt(subProjData, offset) & 0x1FFFF;
offset += 4;
MPPUtility.getByteArray(subProjData, itemHeaderOffset, itemHeader.length, itemHeader, 0);
byte subProjectType = itemHeader[16];
// System.out.println();
// System.out.println (MPPUtility.hexdump(itemHeader, false, 16, ""));
// System.out.println(MPPUtility.hexdump(subProjData, offset, 16, false));
// System.out.println("Offset1: " + (MPPUtility.getInt(subProjData, offset) & 0x1FFFF));
// System.out.println("Offset2: " + (MPPUtility.getInt(subProjData, offset+4) & 0x1FFFF));
// System.out.println("Offset3: " + (MPPUtility.getInt(subProjData, offset+8) & 0x1FFFF));
// System.out.println("Offset4: " + (MPPUtility.getInt(subProjData, offset+12) & 0x1FFFF));
// System.out.println ("Offset: " + offset);
// System.out.println ("Item Header Offset: " + itemHeaderOffset);
// System.out.println("SubProjectType: " + Integer.toHexString(subProjectType));
switch (subProjectType)
{
//
// Subproject that is no longer inserted. This is a placeholder in order to be
// able to always guarantee unique unique ids.
//
case 0x00 :
//
// deleted entry?
//
case 0x10 :
{
offset += 8;
break;
}
//
// task unique ID, 8 bytes, path, file name
//
case (byte) 0x99 :
case 0x09 :
case 0x0D :
{
uniqueIDOffset = MPPUtility.getInt(subProjData, offset) & 0x1FFFF;
offset += 4;
// sometimes offset of a task ID?
offset += 4;
filePathOffset = MPPUtility.getInt(subProjData, offset) & 0x1FFFF;
offset += 4;
fileNameOffset = MPPUtility.getInt(subProjData, offset) & 0x1FFFF;
offset += 4;
sp = readSubProject(subProjData, uniqueIDOffset, filePathOffset, fileNameOffset, index);
break;
}
//
// task unique ID, 8 bytes, path, file name
//
case 0x03 :
case 0x11 :
case (byte) 0x91 :
{
uniqueIDOffset = MPPUtility.getInt(subProjData, offset) & 0x1FFFF;
offset += 4;
filePathOffset = MPPUtility.getInt(subProjData, offset) & 0x1FFFF;
offset += 4;
fileNameOffset = MPPUtility.getInt(subProjData, offset) & 0x1FFFF;
offset += 4;
// Unknown offset
offset += 4;
sp = readSubProject(subProjData, uniqueIDOffset, filePathOffset, fileNameOffset, index);
break;
}
//
// task unique ID, path, unknown, file name
//
case (byte) 0x81 :
case (byte) 0x83 :
case 0x41 :
{
uniqueIDOffset = MPPUtility.getInt(subProjData, offset) & 0x1FFFF;
offset += 4;
filePathOffset = MPPUtility.getInt(subProjData, offset) & 0x1FFFF;
offset += 4;
// unknown offset to 2 bytes of data?
offset += 4;
fileNameOffset = MPPUtility.getInt(subProjData, offset) & 0x1FFFF;
offset += 4;
sp = readSubProject(subProjData, uniqueIDOffset, filePathOffset, fileNameOffset, index);
break;
}
//
// task unique ID, path, file name
//
case 0x01 :
case 0x08 :
{
uniqueIDOffset = MPPUtility.getInt(subProjData, offset) & 0x1FFFF;
offset += 4;
filePathOffset = MPPUtility.getInt(subProjData, offset) & 0x1FFFF;
offset += 4;
fileNameOffset = MPPUtility.getInt(subProjData, offset) & 0x1FFFF;
offset += 4;
sp = readSubProject(subProjData, uniqueIDOffset, filePathOffset, fileNameOffset, index);
break;
}
//
// task unique ID, path, file name
//
case (byte) 0xC0 :
{
uniqueIDOffset = itemHeaderOffset;
filePathOffset = MPPUtility.getInt(subProjData, offset) & 0x1FFFF;
offset += 4;
fileNameOffset = MPPUtility.getInt(subProjData, offset) & 0x1FFFF;
offset += 4;
// unknown offset
offset += 4;
sp = readSubProject(subProjData, uniqueIDOffset, filePathOffset, fileNameOffset, index);
break;
}
//
// resource, task unique ID, path, file name
//
case 0x05 :
{
uniqueIDOffset = MPPUtility.getInt(subProjData, offset) & 0x1FFFF;
offset += 4;
filePathOffset = MPPUtility.getInt(subProjData, offset) & 0x1FFFF;
offset += 4;
fileNameOffset = MPPUtility.getInt(subProjData, offset) & 0x1FFFF;
offset += 4;
sp = readSubProject(subProjData, uniqueIDOffset, filePathOffset, fileNameOffset, index);
m_file.setResourceSubProject(sp);
break;
}
case 0x45 :
{
uniqueIDOffset = MPPUtility.getInt(subProjData, offset) & 0x1FFFF;
offset += 4;
filePathOffset = MPPUtility.getInt(subProjData, offset) & 0x1FFFF;
offset += 4;
fileNameOffset = MPPUtility.getInt(subProjData, offset) & 0x1FFFF;
offset += 4;
offset += 4;
sp = readSubProject(subProjData, uniqueIDOffset, filePathOffset, fileNameOffset, index);
m_file.setResourceSubProject(sp);
break;
}
//
// path, file name
//
case 0x02 :
{
//filePathOffset = MPPUtility.getInt(subProjData, offset) & 0x1FFFF;
offset += 4;
//fileNameOffset = MPPUtility.getInt(subProjData, offset) & 0x1FFFF;
offset += 4;
//sp = readSubProject(subProjData, -1, filePathOffset, fileNameOffset, index);
// 0x02 looks to be the link FROM the resource pool to a project that is using it.
break;
}
case 0x04 :
{
filePathOffset = MPPUtility.getInt(subProjData, offset) & 0x1FFFF;
offset += 4;
fileNameOffset = MPPUtility.getInt(subProjData, offset) & 0x1FFFF;
offset += 4;
sp = readSubProject(subProjData, -1, filePathOffset, fileNameOffset, index);
m_file.setResourceSubProject(sp);
break;
}
//
// task unique ID, 4 bytes, path, 4 bytes, file name
//
case (byte) 0x8D :
{
uniqueIDOffset = MPPUtility.getShort(subProjData, offset);
offset += 8;
filePathOffset = MPPUtility.getShort(subProjData, offset);
offset += 8;
fileNameOffset = MPPUtility.getShort(subProjData, offset);
offset += 4;
sp = readSubProject(subProjData, uniqueIDOffset, filePathOffset, fileNameOffset, index);
break;
}
//
// task unique ID, path, file name
//
case 0x0A :
{
uniqueIDOffset = MPPUtility.getShort(subProjData, offset);
offset += 4;
filePathOffset = MPPUtility.getShort(subProjData, offset);
offset += 4;
fileNameOffset = MPPUtility.getShort(subProjData, offset);
offset += 4;
sp = readSubProject(subProjData, uniqueIDOffset, filePathOffset, fileNameOffset, index);
break;
}
// new resource pool entry
case (byte) 0x44 :
{
filePathOffset = MPPUtility.getInt(subProjData, offset) & 0x1FFFF;
offset += 4;
offset += 4;
fileNameOffset = MPPUtility.getInt(subProjData, offset) & 0x1FFFF;
offset += 4;
sp = readSubProject(subProjData, -1, filePathOffset, fileNameOffset, index);
break;
}
//
// Appears when a subproject is collapsed
//
case (byte) 0x80 :
{
offset += 12;
break;
}
//
// Any other value, assume 12 bytes to handle old/deleted data?
//
default :
{
offset += 12;
break;
}
}
}
}
}
/**
* Method used to read the sub project details from a byte array.
*
* @param data byte array
* @param uniqueIDOffset offset of unique ID
* @param filePathOffset offset of file path
* @param fileNameOffset offset of file name
* @param subprojectIndex index of the subproject, used to calculate unique id offset
* @return new SubProject instance
*/
private SubProject readSubProject(byte[] data, int uniqueIDOffset, int filePathOffset, int fileNameOffset, int subprojectIndex)
{
try
{
SubProject sp = new SubProject();
int type = SUBPROJECT_TASKUNIQUEID0;
if (uniqueIDOffset != -1)
{
int value = MPPUtility.getInt(data, uniqueIDOffset);
type = MPPUtility.getInt(data, uniqueIDOffset + 4);
switch (type)
{
case SUBPROJECT_TASKUNIQUEID0 :
case SUBPROJECT_TASKUNIQUEID1 :
case SUBPROJECT_TASKUNIQUEID2 :
case SUBPROJECT_TASKUNIQUEID3 :
case SUBPROJECT_TASKUNIQUEID4 :
case SUBPROJECT_TASKUNIQUEID5 :
case SUBPROJECT_TASKUNIQUEID6 :
case SUBPROJECT_TASKUNIQUEID7 :
{
sp.setTaskUniqueID(Integer.valueOf(value));
m_taskSubProjects.put(sp.getTaskUniqueID(), sp);
break;
}
default :
{
if (value != 0)
{
sp.addExternalTaskUniqueID(Integer.valueOf(value));
m_taskSubProjects.put(Integer.valueOf(value), sp);
}
break;
}
}
// Now get the unique id offset for this subproject
value = 0x00800000 + ((subprojectIndex - 1) * 0x00400000);
sp.setUniqueIDOffset(Integer.valueOf(value));
}
if (type == SUBPROJECT_TASKUNIQUEID4)
{
sp.setFullPath(MPPUtility.getUnicodeString(data, filePathOffset));
}
else
{
//
// First block header
//
filePathOffset += 18;
//
// String size as a 4 byte int
//
filePathOffset += 4;
//
// Full DOS path
//
sp.setDosFullPath(MPPUtility.getString(data, filePathOffset));
filePathOffset += (sp.getDosFullPath().length() + 1);
//
// 24 byte block
//
filePathOffset += 24;
//
// 4 byte block size
//
int size = MPPUtility.getInt(data, filePathOffset);
filePathOffset += 4;
if (size == 0)
{
sp.setFullPath(sp.getDosFullPath());
}
else
{
//
// 4 byte unicode string size in bytes
//
size = MPPUtility.getInt(data, filePathOffset);
filePathOffset += 4;
//
// 2 byte data
//
filePathOffset += 2;
//
// Unicode string
//
sp.setFullPath(MPPUtility.getUnicodeString(data, filePathOffset, size));
//filePathOffset += size;
}
//
// Second block header
//
fileNameOffset += 18;
//
// String size as a 4 byte int
//
fileNameOffset += 4;
//
// DOS file name
//
sp.setDosFileName(MPPUtility.getString(data, fileNameOffset));
fileNameOffset += (sp.getDosFileName().length() + 1);
//
// 24 byte block
//
fileNameOffset += 24;
//
// 4 byte block size
//
size = MPPUtility.getInt(data, fileNameOffset);
fileNameOffset += 4;
if (size == 0)
{
sp.setFileName(sp.getDosFileName());
}
else
{
//
// 4 byte unicode string size in bytes
//
size = MPPUtility.getInt(data, fileNameOffset);
fileNameOffset += 4;
//
// 2 byte data
//
fileNameOffset += 2;
//
// Unicode string
//
sp.setFileName(MPPUtility.getUnicodeString(data, fileNameOffset, size));
//fileNameOffset += size;
}
}
//System.out.println(sp.toString());
// Add to the list of subprojects
m_file.addSubProject(sp);
return (sp);
}
//
// Admit defeat at this point - we have probably stumbled
// upon a data format we don't understand, so we'll fail
// gracefully here. This will now be reported as a missing
// sub project error by end users of the library, rather
// than as an exception being thrown.
//
catch (ArrayIndexOutOfBoundsException ex)
{
return (null);
}
}
/**
* This method process the data held in the props file specific to the
* visual appearance of the project data.
*/
private void processViewPropertyData() throws IOException
{
Props14 props = new Props14(getEncryptableInputStream(m_viewDir, "Props"));
byte[] data = props.getByteArray(Props.FONT_BASES);
if (data != null)
{
processBaseFonts(data);
}
ProjectHeader header = m_file.getProjectHeader();
header.setShowProjectSummaryTask(props.getBoolean(Props.SHOW_PROJECT_SUMMARY_TASK));
}
/**
* Create an index of base font numbers and their associated base
* font instances.
* @param data property data
*/
private void processBaseFonts(byte[] data)
{
int offset = 0;
int blockCount = MPPUtility.getShort(data, 0);
offset += 2;
int size;
String name;
for (int loop = 0; loop < blockCount; loop++)
{
/*unknownAttribute = MPPUtility.getShort(data, offset);*/
offset += 2;
size = MPPUtility.getShort(data, offset);
offset += 2;
name = MPPUtility.getUnicodeString(data, offset);
offset += 64;
if (name.length() != 0)
{
FontBase fontBase = new FontBase(Integer.valueOf(loop), name, size);
m_fontBases.put(fontBase.getIndex(), fontBase);
}
}
}
/**
* Retrieve any task field aliases defined in the MPP file.
*
* @param data task field name alias data
*/
private void processTaskFieldNameAliases(byte[] data)
{
if (data != null)
{
int index = 0;
int offset = 0;
// First the length (repeated twice)
int length = MPPUtility.getInt(data, offset);
offset += 8;
// Then the number of custom columns
int numberOfAliases = MPPUtility.getInt(data, offset);
offset += 4;
// Then the aliases themselves
String alias = "";
int field = -1;
int aliasOffset = 0;
while (index < numberOfAliases && offset < length)
{
// Each item consists of the Field ID (2 bytes), 40 0B marker (2 bytes), and the
// offset to the string (4 bytes)
// Get the Field ID
field = MPPUtility.getShort(data, offset);
offset += 2;
// Go past 40 0B marker
offset += 2;
// Get the alias offset (offset + 4 for some reason).
aliasOffset = MPPUtility.getInt(data, offset) + 4;
offset += 4;
// Read the alias itself
if (aliasOffset < data.length)
{
alias = MPPUtility.getUnicodeString(data, aliasOffset);
m_file.setTaskFieldAlias(MPPTaskField14.getInstance(field), alias);
//System.out.println(field + ": " + alias);
}
index++;
}
}
//System.out.println(file.getTaskFieldAliasMap().toString());
}
/**
* Retrieve any resource field aliases defined in the MPP file.
*
* @param data resource field name alias data
*/
private void processResourceFieldNameAliases(byte[] data)
{
if (data != null)
{
int index = 0;
int offset = 0;
// First the length (repeated twice)
int length = MPPUtility.getInt(data, offset);
offset += 8;
// Then the number of custom columns
int numberOfAliases = MPPUtility.getInt(data, offset);
offset += 4;
// Then the aliases themselves
String alias = "";
int field = -1;
int aliasOffset = 0;
while (index < numberOfAliases && offset < length)
{
// Each item consists of the Field ID (2 bytes), 40 0B marker (2 bytes), and the
// offset to the string (4 bytes)
// Get the Field ID
field = MPPUtility.getShort(data, offset);
offset += 2;
// Go past 40 0B marker
offset += 2;
// Get the alias offset (offset + 4 for some reason).
aliasOffset = MPPUtility.getInt(data, offset) + 4;
offset += 4;
// Read the alias itself
if (aliasOffset < data.length)
{
alias = MPPUtility.getUnicodeString(data, aliasOffset);
m_file.setResourceFieldAlias(MPPResourceField14.getInstance(field), alias);
//System.out.println(field + ": " + alias);
}
index++;
}
}
//System.out.println(file.getResourceFieldAliasMap().toString());
}
/**
* This method maps the task unique identifiers to their index number
* within the FixedData block.
*
* @param fieldMap field map
* @param taskFixedMeta Fixed meta data for this task
* @param taskFixedData Fixed data for this task
* @return Mapping between task identifiers and block position
*/
private TreeMap<Integer, Integer> createTaskMap(FieldMap fieldMap, FixedMeta taskFixedMeta, FixedData taskFixedData)
{
TreeMap<Integer, Integer> taskMap = new TreeMap<Integer, Integer>();
int itemCount = taskFixedMeta.getItemCount();
byte[] data;
int uniqueID;
Integer key;
// First three items are not tasks, so let's skip them
for (int loop = 3; loop < itemCount; loop++)
{
data = taskFixedData.getByteArrayValue(loop);
if (data != null)
{
byte[] metaData = taskFixedMeta.getByteArrayValue(loop);
int metaDataItemSize = MPPUtility.getInt(metaData, 0);
if (metaDataItemSize < 16 && data.length != 16)
{
// Project stores the deleted tasks unique id's into the fixed data as well
// and at least in one case the deleted task was listed twice in the list
// the second time with data with it causing a phantom task to be shown.
// See CalendarErrorPhantomTasks.mpp
//
// So let's add the unique id for the deleted task into the map so we don't
// accidentally include the task later.
uniqueID = MPPUtility.getShort(data, 0); // Only a short stored for deleted tasks
key = Integer.valueOf(uniqueID);
if (taskMap.containsKey(key) == false)
{
taskMap.put(key, null); // use null so we can easily ignore this later
}
}
else
{
if (data.length == 16 || data.length >= fieldMap.getMaxFixedDataOffset(0))
{
uniqueID = MPPUtility.getInt(data, 0);
key = Integer.valueOf(uniqueID);
if (taskMap.containsKey(key) == false)
{
taskMap.put(key, Integer.valueOf(loop));
}
}
}
}
}
return (taskMap);
}
/**
* This method maps the resource unique identifiers to their index number
* within the FixedData block.
*
* @param fieldMap field map
* @param rscFixedMeta resource fixed meta data
* @param rscFixedData resource fixed data
* @return map of resource IDs to resource data
*/
private TreeMap<Integer, Integer> createResourceMap(FieldMap fieldMap, FixedMeta rscFixedMeta, FixedData rscFixedData)
{
TreeMap<Integer, Integer> resourceMap = new TreeMap<Integer, Integer>();
int itemCount = rscFixedMeta.getItemCount();
for (int loop = 0; loop < itemCount; loop++)
{
byte[] data = rscFixedData.getByteArrayValue(loop);
if (data == null || data.length <= fieldMap.getMaxFixedDataOffset(0))
{
continue;
}
Integer uniqueID = Integer.valueOf(MPPUtility.getShort(data, 0));
if (resourceMap.containsKey(uniqueID) == false)
{
resourceMap.put(uniqueID, Integer.valueOf(loop));
}
}
return (resourceMap);
}
/**
* The format of the calendar data is a 4 byte header followed
* by 7x 60 byte blocks, one for each day of the week. Optionally
* following this is a set of 64 byte blocks representing exceptions
* to the calendar.
*/
private void processCalendarData() throws IOException
{
DirectoryEntry calDir = (DirectoryEntry) m_projectDir.getEntry("TBkndCal");
//MPPUtility.fileHexDump("c:\\temp\\varmeta.txt", new DocumentInputStream (((DocumentEntry)calDir.getEntry("VarMeta"))));
VarMeta calVarMeta = new VarMeta12(new DocumentInputStream(((DocumentEntry) calDir.getEntry("VarMeta"))));
Var2Data calVarData = new Var2Data(calVarMeta, new DocumentInputStream((DocumentEntry) calDir.getEntry("Var2Data")));
//System.out.println(calVarMeta);
//System.out.println(calVarData);
FixedMeta calFixedMeta = new FixedMeta(new DocumentInputStream(((DocumentEntry) calDir.getEntry("FixedMeta"))), 10);
FixedData calFixedData = new FixedData(calFixedMeta, getEncryptableInputStream(calDir, "FixedData"), 12);
//System.out.println (calFixedMeta);
//System.out.println (calFixedData);
HashMap<Integer, ProjectCalendar> calendarMap = new HashMap<Integer, ProjectCalendar>();
int items = calFixedData.getItemCount();
List<Pair<ProjectCalendar, Integer>> baseCalendars = new LinkedList<Pair<ProjectCalendar, Integer>>();
byte[] defaultCalendarData = m_projectProps.getByteArray(Props.DEFAULT_CALENDAR_HOURS);
for (int loop = 0; loop < items; loop++)
{
byte[] fixedData = calFixedData.getByteArrayValue(loop);
if (fixedData != null && fixedData.length >= 8)
{
int offset = 0;
//
// Bug 890909, here we ensure that we have a complete 12 byte
// block before attempting to process the data.
//
while (offset + 12 <= fixedData.length)
{
Integer calendarID = Integer.valueOf(MPPUtility.getInt(fixedData, offset + 0));
int baseCalendarID = MPPUtility.getInt(fixedData, offset + 4);
if (calendarID.intValue() != -1 && calendarID.intValue() != 0 && baseCalendarID != 0 && calendarMap.containsKey(calendarID) == false)
{
byte[] varData = calVarData.getByteArray(calendarID, CALENDAR_DATA);
ProjectCalendar cal;
if (baseCalendarID == -1)
{
if (varData != null || defaultCalendarData != null)
{
cal = m_file.addBaseCalendar();
if (varData == null)
{
varData = defaultCalendarData;
}
}
else
{
cal = m_file.addDefaultBaseCalendar();
}
cal.setName(calVarData.getUnicodeString(calendarID, CALENDAR_NAME));
}
else
{
if (varData != null)
{
cal = m_file.addResourceCalendar();
}
else
{
cal = m_file.getDefaultResourceCalendar();
}
baseCalendars.add(new Pair<ProjectCalendar, Integer>(cal, Integer.valueOf(baseCalendarID)));
Integer resourceID = Integer.valueOf(MPPUtility.getInt(fixedData, offset + 8));
m_resourceMap.put(resourceID, cal);
}
cal.setUniqueID(calendarID);
if (varData != null)
{
processCalendarHours(varData, cal, baseCalendarID == -1);
processCalendarExceptions(varData, cal);
}
calendarMap.put(calendarID, cal);
m_file.fireCalendarReadEvent(cal);
}
offset += 12;
}
}
}
updateBaseCalendarNames(baseCalendars, calendarMap);
}
/**
* For a given set of calendar data, this method sets the working
* day status for each day, and if present, sets the hours for that
* day.
*
* NOTE: MPP14 defines the concept of working weeks. MPXJ does not
* currently support this, and thus we only read the working hours
* for the default working week.
*
* @param data calendar data block
* @param cal calendar instance
* @param isBaseCalendar true if this is a base calendar
*/
private void processCalendarHours(byte[] data, ProjectCalendar cal, boolean isBaseCalendar)
{
// Dump out the calendar related data and fields.
//MPPUtility.dataDump(data, true, false, false, false, true, false, true);
int offset;
ProjectCalendarHours hours;
int periodIndex;
int index;
int defaultFlag;
int periodCount;
Date start;
long duration;
Day day;
List<DateRange> dateRanges = new ArrayList<DateRange>(5);
for (index = 0; index < 7; index++)
{
offset = (60 * index);
defaultFlag = MPPUtility.getShort(data, offset);
periodCount = MPPUtility.getShort(data, offset + 2);
day = Day.getInstance(index + 1);
if (defaultFlag == 1)
{
if (isBaseCalendar == true)
{
cal.setWorkingDay(day, DEFAULT_WORKING_WEEK[index]);
if (cal.isWorkingDay(day) == true)
{
hours = cal.addCalendarHours(Day.getInstance(index + 1));
hours.addRange(new DateRange(ProjectCalendar.DEFAULT_START1, ProjectCalendar.DEFAULT_END1));
hours.addRange(new DateRange(ProjectCalendar.DEFAULT_START2, ProjectCalendar.DEFAULT_END2));
}
}
else
{
cal.setWorkingDay(day, DayType.DEFAULT);
}
}
else
{
dateRanges.clear();
periodIndex = 0;
while (periodIndex < periodCount)
{
int startOffset = offset + 8 + (periodIndex * 2);
start = MPPUtility.getTime(data, startOffset);
int durationOffset = offset + 20 + (periodIndex * 4);
duration = MPPUtility.getDuration(data, durationOffset);
Date end = new Date(start.getTime() + duration);
dateRanges.add(new DateRange(start, end));
++periodIndex;
}
if (dateRanges.isEmpty())
{
cal.setWorkingDay(day, false);
}
else
{
cal.setWorkingDay(day, true);
hours = cal.addCalendarHours(Day.getInstance(index + 1));
for (DateRange range : dateRanges)
{
hours.addRange(range);
}
}
}
}
}
/**
* This method extracts any exceptions associated with a calendar.
*
* @param data calendar data block
* @param cal calendar instance
*/
private void processCalendarExceptions(byte[] data, ProjectCalendar cal)
{
//
// Handle any exceptions
//
if (data.length > 420)
{
int offset = 420; // The first 420 is for the working hours data
int exceptionCount = MPPUtility.getShort(data, offset);
if (exceptionCount != 0)
{
int index;
ProjectCalendarException exception;
long duration;
int periodCount;
Date start;
//
// Move to the start of the first exception
//
offset += 4;
//
// Each exception is a 92 byte block, followed by a
// variable length text block
//
for (index = 0; index < exceptionCount; index++)
{
Date fromDate = MPPUtility.getDate(data, offset);
Date toDate = MPPUtility.getDate(data, offset + 2);
exception = cal.addCalendarException(fromDate, toDate);
periodCount = MPPUtility.getShort(data, offset + 14);
if (periodCount != 0)
{
for (int exceptionPeriodIndex = 0; exceptionPeriodIndex < periodCount; exceptionPeriodIndex++)
{
start = MPPUtility.getTime(data, offset + 20 + (exceptionPeriodIndex * 2));
duration = MPPUtility.getDuration(data, offset + 32 + (exceptionPeriodIndex * 4));
exception.addRange(new DateRange(start, new Date(start.getTime() + duration)));
}
}
//
// Extract the name length - ensure that it is aligned to a 4 byte boundary
//
int exceptionNameLength = MPPUtility.getInt(data, offset + 88);
if (exceptionNameLength % 4 != 0)
{
exceptionNameLength = ((exceptionNameLength / 4) + 1) * 4;
}
//String exceptionName = MPPUtility.getUnicodeString(data, offset+92);
offset += (92 + exceptionNameLength);
}
}
}
}
/**
* The way calendars are stored in an MPP14 file means that there
* can be forward references between the base calendar unique ID for a
* derived calendar, and the base calendar itself. To get around this,
* we initially populate the base calendar name attribute with the
* base calendar unique ID, and now in this method we can convert those
* ID values into the correct names.
*
* @param baseCalendars list of calendars and base calendar IDs
* @param map map of calendar ID values and calendar objects
*/
private void updateBaseCalendarNames(List<Pair<ProjectCalendar, Integer>> baseCalendars, HashMap<Integer, ProjectCalendar> map)
{
for (Pair<ProjectCalendar, Integer> pair : baseCalendars)
{
ProjectCalendar cal = pair.getFirst();
Integer baseCalendarID = pair.getSecond();
ProjectCalendar baseCal = map.get(baseCalendarID);
if (baseCal != null && baseCal.getName() != null)
{
cal.setBaseCalendar(baseCal);
}
else
{
// Remove invalid calendar to avoid serious problems later.
m_file.removeCalendar(cal);
}
}
}
/**
* This method extracts and collates task data. The code below
* goes through the modifier methods of the Task class in alphabetical
* order extracting the data from the MPP file. Where there is no
* mapping (e.g. the field is calculated on the fly, or we can't
* find it in the data) the line is commented out.
*
* The missing boolean attributes are probably represented in the Props
* section of the task data, which we have yet to decode.
*
* @throws java.io.IOException
*/
private void processTaskData() throws IOException
{
FieldMap fieldMap = new FieldMap14(m_file);
fieldMap.createTaskFieldMap(m_projectProps);
DirectoryEntry taskDir = (DirectoryEntry) m_projectDir.getEntry("TBkndTask");
VarMeta taskVarMeta = new VarMeta12(new DocumentInputStream(((DocumentEntry) taskDir.getEntry("VarMeta"))));
Var2Data taskVarData = new Var2Data(taskVarMeta, new DocumentInputStream(((DocumentEntry) taskDir.getEntry("Var2Data"))));
FixedMeta taskFixedMeta = new FixedMeta(new DocumentInputStream(((DocumentEntry) taskDir.getEntry("FixedMeta"))), 47);
FixedData taskFixedData = new FixedData(taskFixedMeta, new DocumentInputStream(((DocumentEntry) taskDir.getEntry("FixedData"))), fieldMap.getMaxFixedDataOffset(0));
FixedMeta taskFixed2Meta = new FixedMeta(new DocumentInputStream(((DocumentEntry) taskDir.getEntry("Fixed2Meta"))), 92);
FixedData taskFixed2Data = new FixedData(taskFixed2Meta, new DocumentInputStream(((DocumentEntry) taskDir.getEntry("Fixed2Data"))));
Props14 props = new Props14(getEncryptableInputStream(taskDir, "Props"));
//System.out.println(taskFixedMeta);
//System.out.println(taskFixedData);
//System.out.println(taskVarMeta);
//System.out.println(taskVarData);
//System.out.println(taskFixed2Meta);
//System.out.println(taskFixed2Data);
//System.out.println(m_outlineCodeVarData.getVarMeta());
//System.out.println(m_outlineCodeVarData);
//System.out.println(props);
// Process aliases
processTaskFieldNameAliases(props.getByteArray(TASK_FIELD_NAME_ALIASES));
TreeMap<Integer, Integer> taskMap = createTaskMap(fieldMap, taskFixedMeta, taskFixedData);
// The var data may not contain all the tasks as tasks with no var data assigned will
// not be saved in there. Most notably these are tasks with no name. So use the task map
// which contains all the tasks.
Object[] uniqueid = taskMap.keySet().toArray(); //taskVarMeta.getUniqueIdentifierArray();
Integer id;
Integer offset;
byte[] data;
byte[] metaData;
byte[] metaData2;
Task task;
boolean autoWBS = true;
LinkedList<Task> externalTasks = new LinkedList<Task>();
RecurringTaskReader recurringTaskReader = null;
RTFUtility rtf = new RTFUtility();
String notes;
for (int loop = 0; loop < uniqueid.length; loop++)
{
id = (Integer) uniqueid[loop];
offset = taskMap.get(id);
if (taskFixedData.isValidOffset(offset) == false)
{
continue;
}
data = taskFixedData.getByteArrayValue(offset.intValue());
if (data.length == 16)
{
task = m_file.addTask();
task.setNull(true);
task.setUniqueID(id);
task.setID(Integer.valueOf(MPPUtility.getInt(data, 4)));
m_nullTaskOrder.put(task.getID(), task.getUniqueID());
//System.out.println(task);
continue;
}
if (data.length < fieldMap.getMaxFixedDataOffset(0))
{
continue;
}
metaData = taskFixedMeta.getByteArrayValue(offset.intValue());
//System.out.println (MPPUtility.hexdump(data, false, 16, ""));
//System.out.println (MPPUtility.hexdump(data,false));
//System.out.println (MPPUtility.hexdump(metaData, false, 16, ""));
//MPPUtility.dataDump(m_file, data, false, false, false, true, false, false, false, false);
//MPPUtility.dataDump(metaData, true, true, true, true, true, true, true);
//MPPUtility.varDataDump(taskVarData, id, true, true, true, true, true, true);
metaData2 = taskFixed2Meta.getByteArrayValue(offset.intValue());
byte[] data2 = taskFixed2Data.getByteArrayValue(offset.intValue());
//System.out.println (MPPUtility.hexdump(metaData2, false, 16, ""));
//System.out.println(MPPUtility.hexdump(data2, false, 16, ""));
//System.out.println (MPPUtility.hexdump(metaData2,false));
byte[] recurringData = taskVarData.getByteArray(id, fieldMap.getVarDataKey(TaskField.RECURRING_DATA));
Task temp = m_file.getTaskByID(Integer.valueOf(MPPUtility.getInt(data, 4)));
if (temp != null)
{
// Task with this id already exists... determine if this is the 'real' task by seeing
// if this task has some var data. This is sort of hokey, but it's the best method i have
// been able to see.
if (!taskVarMeta.getUniqueIdentifierSet().contains(id))
{
// Sometimes Project contains phantom tasks that coexist on the same id as a valid
// task. In this case don't want to include the phantom task. Seems to be a very rare case.
continue;
}
else
if (temp.getName() == null)
{
// Ok, this looks valid. Remove the previous instance since it is most likely not a valid task.
// At worst case this removes a task with an empty name.
m_file.removeTask(temp);
}
}
task = m_file.addTask();
task.disableEvents();
fieldMap.populateContainer(task, id, new byte[][]
{
data,
data2
}, taskVarData);
task.enableEvents();
task.setActive((metaData2[8] & 0x04) != 0);
task.setEffortDriven((metaData[11] & 0x10) != 0);
task.setEstimated(getDurationEstimated(MPPUtility.getShort(data, fieldMap.getFixedDataOffset(TaskField.ACTUAL_DURATION_UNITS))));
task.setExpanded(((metaData[12] & 0x02) == 0));
Integer externalTaskID = task.getSubprojectTaskID();
if (externalTaskID != null && externalTaskID.intValue() != 0)
{
task.setExternalTask(true);
externalTasks.add(task);
}
task.setFlag1((metaData[35] & 0x40) != 0);
task.setFlag2((metaData[35] & 0x80) != 0);
task.setFlag3((metaData[36] & 0x01) != 0);
task.setFlag4((metaData[36] & 0x02) != 0);
task.setFlag5((metaData[36] & 0x04) != 0);
task.setFlag6((metaData[36] & 0x08) != 0);
task.setFlag7((metaData[36] & 0x10) != 0);
task.setFlag8((metaData[36] & 0x20) != 0);
task.setFlag9((metaData[36] & 0x40) != 0);
task.setFlag10((metaData[36] & 0x80) != 0);
task.setFlag11((metaData[37] & 0x01) != 0);
task.setFlag12((metaData[37] & 0x02) != 0);
task.setFlag13((metaData[37] & 0x04) != 0);
task.setFlag14((metaData[37] & 0x08) != 0);
task.setFlag15((metaData[37] & 0x10) != 0);
task.setFlag16((metaData[37] & 0x20) != 0);
task.setFlag17((metaData[37] & 0x40) != 0);
task.setFlag18((metaData[37] & 0x80) != 0);
task.setFlag19((metaData[38] & 0x01) != 0);
task.setFlag20((metaData[38] & 0x02) != 0);
task.setHideBar((metaData[10] & 0x80) != 0);
processHyperlinkData(task, taskVarData.getByteArray(id, fieldMap.getVarDataKey(TaskField.HYPERLINK_DATA)));
task.setID(Integer.valueOf(MPPUtility.getInt(data, 4)));
task.setIgnoreResourceCalendar((metaData[10] & 0x02) != 0);
task.setLevelAssignments((metaData[13] & 0x04) != 0);
task.setLevelingCanSplit((metaData[13] & 0x02) != 0);
task.setMarked((metaData[9] & 0x40) != 0);
task.setMilestone((metaData[8] & 0x20) != 0);
task.setOutlineCode1(getCustomFieldOutlineCodeValue(taskVarData, m_outlineCodeVarData, id, fieldMap.getVarDataKey(TaskField.OUTLINE_CODE1_INDEX)));
task.setOutlineCode2(getCustomFieldOutlineCodeValue(taskVarData, m_outlineCodeVarData, id, fieldMap.getVarDataKey(TaskField.OUTLINE_CODE2_INDEX)));
task.setOutlineCode3(getCustomFieldOutlineCodeValue(taskVarData, m_outlineCodeVarData, id, fieldMap.getVarDataKey(TaskField.OUTLINE_CODE3_INDEX)));
task.setOutlineCode4(getCustomFieldOutlineCodeValue(taskVarData, m_outlineCodeVarData, id, fieldMap.getVarDataKey(TaskField.OUTLINE_CODE4_INDEX)));
task.setOutlineCode5(getCustomFieldOutlineCodeValue(taskVarData, m_outlineCodeVarData, id, fieldMap.getVarDataKey(TaskField.OUTLINE_CODE5_INDEX)));
task.setOutlineCode6(getCustomFieldOutlineCodeValue(taskVarData, m_outlineCodeVarData, id, fieldMap.getVarDataKey(TaskField.OUTLINE_CODE6_INDEX)));
task.setOutlineCode7(getCustomFieldOutlineCodeValue(taskVarData, m_outlineCodeVarData, id, fieldMap.getVarDataKey(TaskField.OUTLINE_CODE7_INDEX)));
task.setOutlineCode8(getCustomFieldOutlineCodeValue(taskVarData, m_outlineCodeVarData, id, fieldMap.getVarDataKey(TaskField.OUTLINE_CODE8_INDEX)));
task.setOutlineCode9(getCustomFieldOutlineCodeValue(taskVarData, m_outlineCodeVarData, id, fieldMap.getVarDataKey(TaskField.OUTLINE_CODE9_INDEX)));
task.setOutlineCode10(getCustomFieldOutlineCodeValue(taskVarData, m_outlineCodeVarData, id, fieldMap.getVarDataKey(TaskField.OUTLINE_CODE10_INDEX)));
task.setRecurring(MPPUtility.getShort(data, 40) == 2);
task.setRollup((metaData[10] & 0x08) != 0);
task.setTaskMode((metaData2[8] & 0x08) == 0 ? TaskMode.AUTO_SCHEDULED : TaskMode.MANUALLY_SCHEDULED);
task.setUniqueID(id);
m_parentTasks.put(task.getUniqueID(), (Integer) task.getCachedValue(TaskField.PARENT_TASK_UNIQUE_ID));
- if (task.getStart() == null)
+ if (task.getStart() == null || (task.getCachedValue(TaskField.SCHEDULED_START) != null && task.getTaskMode() == TaskMode.AUTO_SCHEDULED))
{
task.setStart((Date) task.getCachedValue(TaskField.SCHEDULED_START));
}
- if (task.getFinish() == null)
+ if (task.getFinish() == null || (task.getCachedValue(TaskField.SCHEDULED_FINISH) != null && task.getTaskMode() == TaskMode.AUTO_SCHEDULED))
{
task.setFinish((Date) task.getCachedValue(TaskField.SCHEDULED_FINISH));
}
- if (task.getDuration() == null)
+ if (task.getDuration() == null || (task.getCachedValue(TaskField.SCHEDULED_DURATION) != null && task.getTaskMode() == TaskMode.AUTO_SCHEDULED))
{
task.setDuration((Duration) task.getCachedValue(TaskField.SCHEDULED_DURATION));
}
switch (task.getConstraintType())
{
//
// Adjust the start and finish dates if the task
// is constrained to start as late as possible.
//
case AS_LATE_AS_POSSIBLE :
{
if (DateUtility.compare(task.getStart(), task.getLateStart()) < 0)
{
task.setStart(task.getLateStart());
}
if (DateUtility.compare(task.getFinish(), task.getLateFinish()) < 0)
{
task.setFinish(task.getLateFinish());
}
break;
}
case START_NO_LATER_THAN :
case FINISH_NO_LATER_THAN :
{
if (DateUtility.compare(task.getFinish(), task.getStart()) < 0)
{
task.setFinish(task.getLateFinish());
}
break;
}
default :
{
break;
}
}
//
// Retrieve task recurring data
//
if (recurringData != null)
{
if (recurringTaskReader == null)
{
recurringTaskReader = new RecurringTaskReader(m_file);
}
recurringTaskReader.processRecurringTask(task, recurringData);
task.setRecurring(true);
}
//
// Retrieve the task notes.
//
notes = task.getNotes();
if (notes != null)
{
if (m_reader.getPreserveNoteFormatting() == false)
{
notes = rtf.strip(notes);
}
task.setNotes(notes);
}
//
// Set the calendar name
//
Integer calendarID = (Integer) task.getCachedValue(TaskField.CALENDAR_UNIQUE_ID);
if (calendarID != null && calendarID.intValue() != -1)
{
ProjectCalendar calendar = m_file.getBaseCalendarByUniqueID(calendarID);
if (calendar != null)
{
task.setCalendar(calendar);
}
}
//
// Set the sub project flag
//
SubProject sp = m_taskSubProjects.get(task.getUniqueID());
task.setSubProject(sp);
//
// Set the external flag
//
if (sp != null)
{
task.setExternalTask(sp.isExternalTask(task.getUniqueID()));
if (task.getExternalTask())
{
task.setExternalTaskProject(sp.getFullPath());
}
}
//
// If we have a WBS value from the MPP file, don't autogenerate
//
if (task.getWBS() != null)
{
autoWBS = false;
}
//
// If this is a split task, allocate space for the split durations
//
if ((metaData[9] & 0x80) == 0)
{
task.setSplits(new LinkedList<DateRange>());
}
//
// If this is a manually scheduled task, read the manual duration
//
if (task.getTaskMode() != TaskMode.MANUALLY_SCHEDULED)
{
task.setManualDuration(null);
}
//
// Process any enterprise columns
//
processTaskEnterpriseColumns(id, task, taskVarData, metaData2);
// Unfortunately it looks like 'null' tasks sometimes make it through. So let's check for to see if we
// need to mark this task as a null task after all.
if (task.getName() == null && ((task.getStart() == null || task.getStart().getTime() == MPPUtility.getEpochDate().getTime()) || (task.getFinish() == null || task.getFinish().getTime() == MPPUtility.getEpochDate().getTime()) || (task.getCreateDate() == null || task.getCreateDate().getTime() == MPPUtility.getEpochDate().getTime())))
{
// Remove this to avoid passing bad data to the client
m_file.removeTask(task);
task = m_file.addTask();
task.setNull(true);
task.setUniqueID(id);
task.setID(new Integer(MPPUtility.getInt(data, 4)));
m_nullTaskOrder.put(task.getID(), task.getUniqueID());
//System.out.println(task);
continue;
}
if (data2.length < 24)
{
m_nullTaskOrder.put(task.getID(), task.getUniqueID());
}
else
{
Long key = Long.valueOf(MPPUtility.getLong(data2, 16));
m_taskOrder.put(key, task.getUniqueID());
}
//System.out.println(task + " " + MPPUtility.getShort(data2, 22)); // JPI - looks like this value determines the ID order! Validate and check other versions!
m_file.fireTaskReadEvent(task);
//dumpUnknownData(task.getUniqueID().toString(), UNKNOWN_TASK_DATA, data);
//System.out.println(task);
}
//
// Enable auto WBS if necessary
//
m_file.setAutoWBS(autoWBS);
//
// We have now read all of the task, so we are in a position
// to perform post-processing to set up the relevant details
// for each external task.
//
if (!externalTasks.isEmpty())
{
processExternalTasks(externalTasks);
}
}
/**
* This method uses ordering data embedded in the file to reconstruct
* the correct ID order of the tasks.
*/
private void fixTaskOrder()
{
//
// Renumber ID values using a large increment to allow
// space for later inserts.
//
TreeMap<Integer, Integer> taskMap = new TreeMap<Integer, Integer>();
int nextIDIncrement = 1000;
int nextID = (m_file.getTaskByUniqueID(Integer.valueOf(0)) == null ? nextIDIncrement : 0);
for (Map.Entry<Long, Integer> entry : m_taskOrder.entrySet())
{
taskMap.put(Integer.valueOf(nextID), entry.getValue());
nextID += nextIDIncrement;
}
//
// Insert any null tasks into the correct location
//
int insertionCount = 0;
for (Map.Entry<Integer, Integer> entry : m_nullTaskOrder.entrySet())
{
int targetIDValue = entry.getKey().intValue();
targetIDValue = (targetIDValue - insertionCount) * nextIDIncrement;
++insertionCount;
while (taskMap.containsKey(Integer.valueOf(targetIDValue)))
{
--targetIDValue;
}
taskMap.put(Integer.valueOf(targetIDValue), entry.getValue());
}
//
// Finally, we can renumber the tasks
//
nextID = (m_file.getTaskByUniqueID(Integer.valueOf(0)) == null ? 1 : 0);
for (Map.Entry<Integer, Integer> entry : taskMap.entrySet())
{
Task task = m_file.getTaskByUniqueID(entry.getValue());
if (task != null)
{
task.setID(Integer.valueOf(nextID));
}
nextID++;
}
}
/**
* Extracts task enterprise column values.
*
* @param id task unique ID
* @param task task instance
* @param taskVarData task var data
* @param metaData2 task meta data
*/
private void processTaskEnterpriseColumns(Integer id, Task task, Var2Data taskVarData, byte[] metaData2)
{
if (metaData2 != null)
{
int bits = MPPUtility.getInt(metaData2, 29);
task.set(TaskField.ENTERPRISE_FLAG1, Boolean.valueOf((bits & 0x0000800) != 0));
task.set(TaskField.ENTERPRISE_FLAG2, Boolean.valueOf((bits & 0x0001000) != 0));
task.set(TaskField.ENTERPRISE_FLAG3, Boolean.valueOf((bits & 0x0002000) != 0));
task.set(TaskField.ENTERPRISE_FLAG4, Boolean.valueOf((bits & 0x0004000) != 0));
task.set(TaskField.ENTERPRISE_FLAG5, Boolean.valueOf((bits & 0x0008000) != 0));
task.set(TaskField.ENTERPRISE_FLAG6, Boolean.valueOf((bits & 0x0001000) != 0));
task.set(TaskField.ENTERPRISE_FLAG7, Boolean.valueOf((bits & 0x0002000) != 0));
task.set(TaskField.ENTERPRISE_FLAG8, Boolean.valueOf((bits & 0x0004000) != 0));
task.set(TaskField.ENTERPRISE_FLAG9, Boolean.valueOf((bits & 0x0008000) != 0));
task.set(TaskField.ENTERPRISE_FLAG10, Boolean.valueOf((bits & 0x0010000) != 0));
task.set(TaskField.ENTERPRISE_FLAG11, Boolean.valueOf((bits & 0x0020000) != 0));
task.set(TaskField.ENTERPRISE_FLAG12, Boolean.valueOf((bits & 0x0040000) != 0));
task.set(TaskField.ENTERPRISE_FLAG13, Boolean.valueOf((bits & 0x0080000) != 0));
task.set(TaskField.ENTERPRISE_FLAG14, Boolean.valueOf((bits & 0x0100000) != 0));
task.set(TaskField.ENTERPRISE_FLAG15, Boolean.valueOf((bits & 0x0200000) != 0));
task.set(TaskField.ENTERPRISE_FLAG16, Boolean.valueOf((bits & 0x0400000) != 0));
task.set(TaskField.ENTERPRISE_FLAG17, Boolean.valueOf((bits & 0x0800000) != 0));
task.set(TaskField.ENTERPRISE_FLAG18, Boolean.valueOf((bits & 0x1000000) != 0));
task.set(TaskField.ENTERPRISE_FLAG19, Boolean.valueOf((bits & 0x2000000) != 0));
task.set(TaskField.ENTERPRISE_FLAG20, Boolean.valueOf((bits & 0x4000000) != 0));
}
}
/**
* Extracts resource enterprise column data.
*
* @param id resource unique ID
* @param resource resource instance
* @param resourceVarData resource var data
* @param metaData2 resource meta data
*/
private void processResourceEnterpriseColumns(Integer id, Resource resource, Var2Data resourceVarData, byte[] metaData2)
{
if (metaData2 != null)
{
int bits = MPPUtility.getInt(metaData2, 16);
resource.set(ResourceField.ENTERPRISE_FLAG1, Boolean.valueOf((bits & 0x00010) != 0));
resource.set(ResourceField.ENTERPRISE_FLAG2, Boolean.valueOf((bits & 0x00020) != 0));
resource.set(ResourceField.ENTERPRISE_FLAG3, Boolean.valueOf((bits & 0x00040) != 0));
resource.set(ResourceField.ENTERPRISE_FLAG4, Boolean.valueOf((bits & 0x00080) != 0));
resource.set(ResourceField.ENTERPRISE_FLAG5, Boolean.valueOf((bits & 0x00100) != 0));
resource.set(ResourceField.ENTERPRISE_FLAG6, Boolean.valueOf((bits & 0x00200) != 0));
resource.set(ResourceField.ENTERPRISE_FLAG7, Boolean.valueOf((bits & 0x00400) != 0));
resource.set(ResourceField.ENTERPRISE_FLAG8, Boolean.valueOf((bits & 0x00800) != 0));
resource.set(ResourceField.ENTERPRISE_FLAG9, Boolean.valueOf((bits & 0x01000) != 0));
resource.set(ResourceField.ENTERPRISE_FLAG10, Boolean.valueOf((bits & 0x02000) != 0));
resource.set(ResourceField.ENTERPRISE_FLAG11, Boolean.valueOf((bits & 0x04000) != 0));
resource.set(ResourceField.ENTERPRISE_FLAG12, Boolean.valueOf((bits & 0x08000) != 0));
resource.set(ResourceField.ENTERPRISE_FLAG13, Boolean.valueOf((bits & 0x10000) != 0));
resource.set(ResourceField.ENTERPRISE_FLAG14, Boolean.valueOf((bits & 0x20000) != 0));
resource.set(ResourceField.ENTERPRISE_FLAG15, Boolean.valueOf((bits & 0x40000) != 0));
resource.set(ResourceField.ENTERPRISE_FLAG16, Boolean.valueOf((bits & 0x80000) != 0));
resource.set(ResourceField.ENTERPRISE_FLAG17, Boolean.valueOf((bits & 0x100000) != 0));
resource.set(ResourceField.ENTERPRISE_FLAG18, Boolean.valueOf((bits & 0x200000) != 0));
resource.set(ResourceField.ENTERPRISE_FLAG19, Boolean.valueOf((bits & 0x400000) != 0));
resource.set(ResourceField.ENTERPRISE_FLAG20, Boolean.valueOf((bits & 0x800000) != 0));
}
}
/**
* The project files to which external tasks relate appear not to be
* held against each task, instead there appears to be the concept
* of the "current" external task file, i.e. the last one used.
* This method iterates through the list of tasks marked as external
* and attempts to ensure that the correct external project data (in the
* form of a SubProject object) is linked to the task.
*
* @param externalTasks list of tasks marked as external
*/
private void processExternalTasks(List<Task> externalTasks)
{
//
// Sort the list of tasks into ID order
//
Collections.sort(externalTasks);
//
// Find any external tasks which don't have a sub project
// object, and set this attribute using the most recent
// value.
//
SubProject currentSubProject = null;
for (Task currentTask : externalTasks)
{
SubProject sp = currentTask.getSubProject();
if (sp == null)
{
currentTask.setSubProject(currentSubProject);
//we need to set the external task project path now that we have
//the subproject for this task (was skipped while processing the task earlier)
if (currentSubProject != null)
{
currentTask.setExternalTaskProject(currentSubProject.getFullPath());
}
}
else
{
currentSubProject = sp;
}
if (currentSubProject != null)
{
//System.out.println ("Task: " +currentTask.getUniqueID() + " " + currentTask.getName() + " File=" + currentSubProject.getFullPath() + " ID=" + currentTask.getExternalTaskID());
currentTask.setProject(currentSubProject.getFullPath());
}
}
}
/**
* This method is used to extract the task hyperlink attributes
* from a block of data and call the appropriate modifier methods
* to configure the specified task object.
*
* @param task task instance
* @param data hyperlink data block
*/
private void processHyperlinkData(Task task, byte[] data)
{
if (data != null)
{
int offset = 12;
String hyperlink;
String address;
String subaddress;
offset += 12;
hyperlink = MPPUtility.getUnicodeString(data, offset);
offset += ((hyperlink.length() + 1) * 2);
offset += 12;
address = MPPUtility.getUnicodeString(data, offset);
offset += ((address.length() + 1) * 2);
offset += 12;
subaddress = MPPUtility.getUnicodeString(data, offset);
task.setHyperlink(hyperlink);
task.setHyperlinkAddress(address);
task.setHyperlinkSubAddress(subaddress);
}
}
/**
* This method is used to extract the resource hyperlink attributes
* from a block of data and call the appropriate modifier methods
* to configure the specified task object.
*
* @param resource resource instance
* @param data hyperlink data block
*/
private void processHyperlinkData(Resource resource, byte[] data)
{
if (data != null)
{
int offset = 12;
String hyperlink;
String address;
String subaddress;
offset += 12;
hyperlink = MPPUtility.getUnicodeString(data, offset);
offset += ((hyperlink.length() + 1) * 2);
offset += 12;
address = MPPUtility.getUnicodeString(data, offset);
offset += ((address.length() + 1) * 2);
offset += 12;
subaddress = MPPUtility.getUnicodeString(data, offset);
resource.setHyperlink(hyperlink);
resource.setHyperlinkAddress(address);
resource.setHyperlinkSubAddress(subaddress);
}
}
/**
* This method extracts and collates constraint data.
*
* @throws java.io.IOException
*/
private void processConstraintData() throws IOException
{
DirectoryEntry consDir;
try
{
consDir = (DirectoryEntry) m_projectDir.getEntry("TBkndCons");
}
catch (FileNotFoundException ex)
{
consDir = null;
}
if (consDir != null)
{
FixedMeta consFixedMeta = new FixedMeta(new DocumentInputStream(((DocumentEntry) consDir.getEntry("FixedMeta"))), 10);
FixedData consFixedData = new FixedData(consFixedMeta, 20, getEncryptableInputStream(consDir, "FixedData"));
int count = consFixedMeta.getItemCount();
int lastConstraintID = -1;
for (int loop = 0; loop < count; loop++)
{
byte[] metaData = consFixedMeta.getByteArrayValue(loop);
//
// SourceForge bug 2209477: we were reading an int here, but
// it looks like the deleted flag is just a short.
//
if (MPPUtility.getShort(metaData, 0) == 0)
{
int index = consFixedData.getIndexFromOffset(MPPUtility.getInt(metaData, 4));
if (index != -1)
{
byte[] data = consFixedData.getByteArrayValue(index);
int constraintID = MPPUtility.getInt(data, 0);
if (constraintID > lastConstraintID)
{
lastConstraintID = constraintID;
int taskID1 = MPPUtility.getInt(data, 4);
int taskID2 = MPPUtility.getInt(data, 8);
if (taskID1 != taskID2)
{
Task task1 = m_file.getTaskByUniqueID(Integer.valueOf(taskID1));
Task task2 = m_file.getTaskByUniqueID(Integer.valueOf(taskID2));
if (task1 != null && task2 != null)
{
RelationType type = RelationType.getInstance(MPPUtility.getShort(data, 12));
TimeUnit durationUnits = MPPUtility.getDurationTimeUnits(MPPUtility.getShort(data, 14));
Duration lag = MPPUtility.getAdjustedDuration(m_file, MPPUtility.getInt(data, 16), durationUnits);
Relation relation = task2.addPredecessor(task1, type, lag);
m_file.fireRelationReadEvent(relation);
}
}
}
}
}
}
}
}
/**
* This method extracts and collates resource data.
*
* @throws java.io.IOException
*/
private void processResourceData() throws IOException
{
FieldMap fieldMap = new FieldMap14(m_file);
fieldMap.createResourceFieldMap(m_projectProps);
DirectoryEntry rscDir = (DirectoryEntry) m_projectDir.getEntry("TBkndRsc");
VarMeta rscVarMeta = new VarMeta12(new DocumentInputStream(((DocumentEntry) rscDir.getEntry("VarMeta"))));
Var2Data rscVarData = new Var2Data(rscVarMeta, new DocumentInputStream(((DocumentEntry) rscDir.getEntry("Var2Data"))));
FixedMeta rscFixedMeta = new FixedMeta(new DocumentInputStream(((DocumentEntry) rscDir.getEntry("FixedMeta"))), 37);
FixedData rscFixedData = new FixedData(rscFixedMeta, getEncryptableInputStream(rscDir, "FixedData"));
FixedMeta rscFixed2Meta = new FixedMeta(new DocumentInputStream(((DocumentEntry) rscDir.getEntry("Fixed2Meta"))), 50);
FixedData rscFixed2Data = new FixedData(rscFixed2Meta, getEncryptableInputStream(rscDir, "Fixed2Data"));
Props14 props = new Props14(getEncryptableInputStream(rscDir, "Props"));
//System.out.println(rscVarMeta);
//System.out.println(rscVarData);
//System.out.println(rscFixedMeta);
//System.out.println(rscFixedData);
//System.out.println(rscFixed2Meta);
//System.out.println(rscFixed2Data);
//System.out.println(props);
// Process aliases
processResourceFieldNameAliases(props.getByteArray(RESOURCE_FIELD_NAME_ALIASES));
TreeMap<Integer, Integer> resourceMap = createResourceMap(fieldMap, rscFixedMeta, rscFixedData);
Integer[] uniqueid = rscVarMeta.getUniqueIdentifierArray();
Integer id;
Integer offset;
byte[] data;
byte[] metaData;
Resource resource;
RTFUtility rtf = new RTFUtility();
String notes;
for (int loop = 0; loop < uniqueid.length; loop++)
{
id = uniqueid[loop];
offset = resourceMap.get(id);
if (offset == null)
{
continue;
}
data = rscFixedData.getByteArrayValue(offset.intValue());
byte[] metaData2 = rscFixed2Meta.getByteArrayValue(offset.intValue());
byte[] data2 = rscFixed2Data.getByteArrayValue(offset.intValue());
//metaData = rscFixedMeta.getByteArrayValue(offset.intValue());
//MPPUtility.dataDump(data, true, true, true, true, true, true, true);
//MPPUtility.dataDump(metaData, true, true, true, true, true, true, true);
//MPPUtility.varDataDump(rscVarData, id, true, true, true, true, true, true);
resource = m_file.addResource();
resource.disableEvents();
fieldMap.populateContainer(resource, id, new byte[][]
{
data,
data2
}, rscVarData);
resource.enableEvents();
resource.setBudget((metaData2[8] & 0x20) != 0);
processHyperlinkData(resource, rscVarData.getByteArray(id, fieldMap.getVarDataKey(ResourceField.HYPERLINK_DATA)));
resource.setID(Integer.valueOf(MPPUtility.getInt(data, 4)));
resource.setOutlineCode1(m_outlineCodeVarData.getUnicodeString(Integer.valueOf(rscVarData.getInt(id, 2, fieldMap.getVarDataKey(ResourceField.OUTLINE_CODE1_INDEX))), OUTLINECODE_DATA));
resource.setOutlineCode2(m_outlineCodeVarData.getUnicodeString(Integer.valueOf(rscVarData.getInt(id, 2, fieldMap.getVarDataKey(ResourceField.OUTLINE_CODE2_INDEX))), OUTLINECODE_DATA));
resource.setOutlineCode3(m_outlineCodeVarData.getUnicodeString(Integer.valueOf(rscVarData.getInt(id, 2, fieldMap.getVarDataKey(ResourceField.OUTLINE_CODE3_INDEX))), OUTLINECODE_DATA));
resource.setOutlineCode4(m_outlineCodeVarData.getUnicodeString(Integer.valueOf(rscVarData.getInt(id, 2, fieldMap.getVarDataKey(ResourceField.OUTLINE_CODE4_INDEX))), OUTLINECODE_DATA));
resource.setOutlineCode5(m_outlineCodeVarData.getUnicodeString(Integer.valueOf(rscVarData.getInt(id, 2, fieldMap.getVarDataKey(ResourceField.OUTLINE_CODE5_INDEX))), OUTLINECODE_DATA));
resource.setOutlineCode6(m_outlineCodeVarData.getUnicodeString(Integer.valueOf(rscVarData.getInt(id, 2, fieldMap.getVarDataKey(ResourceField.OUTLINE_CODE6_INDEX))), OUTLINECODE_DATA));
resource.setOutlineCode7(m_outlineCodeVarData.getUnicodeString(Integer.valueOf(rscVarData.getInt(id, 2, fieldMap.getVarDataKey(ResourceField.OUTLINE_CODE7_INDEX))), OUTLINECODE_DATA));
resource.setOutlineCode8(m_outlineCodeVarData.getUnicodeString(Integer.valueOf(rscVarData.getInt(id, 2, fieldMap.getVarDataKey(ResourceField.OUTLINE_CODE8_INDEX))), OUTLINECODE_DATA));
resource.setOutlineCode9(m_outlineCodeVarData.getUnicodeString(Integer.valueOf(rscVarData.getInt(id, 2, fieldMap.getVarDataKey(ResourceField.OUTLINE_CODE9_INDEX))), OUTLINECODE_DATA));
resource.setOutlineCode10(m_outlineCodeVarData.getUnicodeString(Integer.valueOf(rscVarData.getInt(id, 2, fieldMap.getVarDataKey(ResourceField.OUTLINE_CODE10_INDEX))), OUTLINECODE_DATA));
resource.setType((MPPUtility.getShort(data, 14) == 0 ? ResourceType.WORK : ((metaData2[8] & 0x10) == 0) ? ResourceType.MATERIAL : ResourceType.COST));
resource.setUniqueID(id);
metaData = rscFixedMeta.getByteArrayValue(offset.intValue());
resource.setFlag1((metaData[28] & 0x40) != 0);
resource.setFlag2((metaData[28] & 0x80) != 0);
resource.setFlag3((metaData[29] & 0x01) != 0);
resource.setFlag4((metaData[29] & 0x02) != 0);
resource.setFlag5((metaData[29] & 0x04) != 0);
resource.setFlag6((metaData[29] & 0x08) != 0);
resource.setFlag7((metaData[29] & 0x10) != 0);
resource.setFlag8((metaData[29] & 0x20) != 0);
resource.setFlag9((metaData[29] & 0x40) != 0);
resource.setFlag10((metaData[28] & 0x20) != 0);
resource.setFlag11((metaData[29] & 0x20) != 0);
resource.setFlag12((metaData[30] & 0x01) != 0);
resource.setFlag13((metaData[30] & 0x02) != 0);
resource.setFlag14((metaData[30] & 0x04) != 0);
resource.setFlag15((metaData[30] & 0x08) != 0);
resource.setFlag16((metaData[30] & 0x10) != 0);
resource.setFlag17((metaData[30] & 0x20) != 0);
resource.setFlag18((metaData[30] & 0x40) != 0);
resource.setFlag19((metaData[30] & 0x80) != 0);
resource.setFlag20((metaData[31] & 0x01) != 0);
notes = resource.getNotes();
if (notes != null)
{
if (m_reader.getPreserveNoteFormatting() == false)
{
notes = rtf.strip(notes);
}
resource.setNotes(notes);
}
//
// Configure the resource calendar
//
resource.setResourceCalendar(m_resourceMap.get(id));
//
// Process any enterprise columns
//
processResourceEnterpriseColumns(id, resource, rscVarData, metaData2);
//
// Process cost rate tables
//
CostRateTableFactory crt = new CostRateTableFactory();
resource.setCostRateTable(0, crt.process(rscVarData.getByteArray(id, fieldMap.getVarDataKey(ResourceField.COST_RATE_A))));
resource.setCostRateTable(1, crt.process(rscVarData.getByteArray(id, fieldMap.getVarDataKey(ResourceField.COST_RATE_B))));
resource.setCostRateTable(2, crt.process(rscVarData.getByteArray(id, fieldMap.getVarDataKey(ResourceField.COST_RATE_C))));
resource.setCostRateTable(3, crt.process(rscVarData.getByteArray(id, fieldMap.getVarDataKey(ResourceField.COST_RATE_D))));
resource.setCostRateTable(4, crt.process(rscVarData.getByteArray(id, fieldMap.getVarDataKey(ResourceField.COST_RATE_E))));
//
// Process availability table
//
AvailabilityFactory af = new AvailabilityFactory();
af.process(resource.getAvailability(), rscVarData.getByteArray(id, fieldMap.getVarDataKey(ResourceField.AVAILABILITY_DATA)));
m_file.fireResourceReadEvent(resource);
}
}
/**
* This method extracts and collates resource assignment data.
*
* @throws IOException
*/
private void processAssignmentData() throws IOException
{
FieldMap fieldMap = new FieldMap14(m_file);
fieldMap.createAssignmentFieldMap(m_projectProps);
DirectoryEntry assnDir = (DirectoryEntry) m_projectDir.getEntry("TBkndAssn");
VarMeta assnVarMeta = new VarMeta12(new DocumentInputStream(((DocumentEntry) assnDir.getEntry("VarMeta"))));
Var2Data assnVarData = new Var2Data(assnVarMeta, new DocumentInputStream(((DocumentEntry) assnDir.getEntry("Var2Data"))));
FixedMeta assnFixedMeta = new FixedMeta(new DocumentInputStream(((DocumentEntry) assnDir.getEntry("FixedMeta"))), 34);
FixedData assnFixedData = new FixedData(110, getEncryptableInputStream(assnDir, "FixedData"));
//FixedMeta assnFixedMeta2 = new FixedMeta(new DocumentInputStream(((DocumentEntry) assnDir.getEntry("Fixed2Meta"))), 53);
//Props props = new Props14(new DocumentInputStream(((DocumentEntry) assnDir.getEntry("Props"))));
ResourceAssignmentFactory factory = new ResourceAssignmentFactoryCommon();
factory.process(m_file, fieldMap, m_reader.getUseRawTimephasedData(), assnVarMeta, assnVarData, assnFixedMeta, assnFixedData);
}
/**
* This method is used to determine if a duration is estimated.
*
* @param type Duration units value
* @return boolean Estimated flag
*/
private boolean getDurationEstimated(int type)
{
return ((type & DURATION_CONFIRMED_MASK) != 0);
}
/**
* This method extracts view data from the MPP file.
*
* @throws java.io.IOException
*/
private void processViewData() throws IOException
{
DirectoryEntry dir = (DirectoryEntry) m_viewDir.getEntry("CV_iew");
VarMeta viewVarMeta = new VarMeta12(new DocumentInputStream(((DocumentEntry) dir.getEntry("VarMeta"))));
Var2Data viewVarData = new Var2Data(viewVarMeta, new DocumentInputStream(((DocumentEntry) dir.getEntry("Var2Data"))));
FixedMeta fixedMeta = new FixedMeta(new DocumentInputStream(((DocumentEntry) dir.getEntry("FixedMeta"))), 10);
FixedData fixedData = new FixedData(138, getEncryptableInputStream(dir, "FixedData"));
int items = fixedMeta.getItemCount();
View view;
ViewFactory factory = new ViewFactory14();
int lastOffset = -1;
for (int loop = 0; loop < items; loop++)
{
byte[] fm = fixedMeta.getByteArrayValue(loop);
int offset = MPPUtility.getShort(fm, 4);
if (offset > lastOffset)
{
byte[] fd = fixedData.getByteArrayValue(fixedData.getIndexFromOffset(offset));
if (fd != null)
{
view = factory.createView(m_file, fm, fd, viewVarData, m_fontBases);
m_file.addView(view);
}
lastOffset = offset;
}
}
}
/**
* This method extracts table data from the MPP file.
*
* @throws java.io.IOException
*/
private void processTableData() throws IOException
{
DirectoryEntry dir = (DirectoryEntry) m_viewDir.getEntry("CTable");
VarMeta varMeta = new VarMeta12(new DocumentInputStream(((DocumentEntry) dir.getEntry("VarMeta"))));
Var2Data varData = new Var2Data(varMeta, new DocumentInputStream(((DocumentEntry) dir.getEntry("Var2Data"))));
FixedData fixedData = new FixedData(230, new DocumentInputStream(((DocumentEntry) dir.getEntry("FixedData"))));
//System.out.println(varMeta);
//System.out.println(varData);
//System.out.println(fixedData);
TableFactory14 factory = new TableFactory14(TABLE_COLUMN_DATA_STANDARD, TABLE_COLUMN_DATA_ENTERPRISE, TABLE_COLUMN_DATA_BASELINE);
int items = fixedData.getItemCount();
for (int loop = 0; loop < items; loop++)
{
byte[] data = fixedData.getByteArrayValue(loop);
Table table = factory.createTable(m_file, data, varMeta, varData);
m_file.addTable(table);
//System.out.println(table);
}
}
/**
* Read filter definitions.
*
* @throws IOException
*/
private void processFilterData() throws IOException
{
DirectoryEntry dir = (DirectoryEntry) m_viewDir.getEntry("CFilter");
FixedMeta fixedMeta = new FixedMeta(new DocumentInputStream(((DocumentEntry) dir.getEntry("FixedMeta"))), 10);
FixedData fixedData = new FixedData(fixedMeta, getEncryptableInputStream(dir, "FixedData"));
VarMeta varMeta = new VarMeta12(new DocumentInputStream(((DocumentEntry) dir.getEntry("VarMeta"))));
Var2Data varData = new Var2Data(varMeta, new DocumentInputStream(((DocumentEntry) dir.getEntry("Var2Data"))));
//System.out.println(fixedMeta);
//System.out.println(fixedData);
//System.out.println(varMeta);
//System.out.println(varData);
FilterReader reader = new FilterReader14();
reader.process(m_file, fixedData, varData);
}
/**
* Read saved view state from an MPP file.
*
* @throws IOException
*/
private void processSavedViewState() throws IOException
{
DirectoryEntry dir = (DirectoryEntry) m_viewDir.getEntry("CEdl");
VarMeta varMeta = new VarMeta12(new DocumentInputStream(((DocumentEntry) dir.getEntry("VarMeta"))));
Var2Data varData = new Var2Data(varMeta, new DocumentInputStream(((DocumentEntry) dir.getEntry("Var2Data"))));
//System.out.println(varMeta);
//System.out.println(varData);
InputStream is = new DocumentInputStream(((DocumentEntry) dir.getEntry("FixedData")));
byte[] fixedData = new byte[is.available()];
is.read(fixedData);
is.close();
//System.out.println(MPPUtility.hexdump(fixedData, false, 16, ""));
ViewStateReader reader = new ViewStateReader12();
reader.process(m_file, varData, fixedData);
}
/**
* Read group definitions.
*
* @throws IOException
*/
private void processGroupData() throws IOException
{
DirectoryEntry dir = (DirectoryEntry) m_viewDir.getEntry("CGrouping");
FixedMeta fixedMeta = new FixedMeta(new DocumentInputStream(((DocumentEntry) dir.getEntry("FixedMeta"))), 10);
FixedData fixedData = new FixedData(fixedMeta, getEncryptableInputStream(dir, "FixedData"));
VarMeta varMeta = new VarMeta12(new DocumentInputStream(((DocumentEntry) dir.getEntry("VarMeta"))));
Var2Data varData = new Var2Data(varMeta, new DocumentInputStream(((DocumentEntry) dir.getEntry("Var2Data"))));
//System.out.println(fixedMeta);
//System.out.println(fixedData);
//System.out.println(varMeta);
//System.out.println(varData);
GroupReader14 reader = new GroupReader14();
reader.process(m_file, fixedData, varData, m_fontBases);
}
/**
* Retrieve custom field value.
*
* @param varData var data block
* @param outlineCodeVarData var data block
* @param id item ID
* @param type item type
* @return item value
*/
private String getCustomFieldOutlineCodeValue(Var2Data varData, Var2Data outlineCodeVarData, Integer id, Integer type)
{
String result = null;
int mask = varData.getShort(id, type);
if ((mask & 0xFF00) != VALUE_LIST_MASK)
{
result = outlineCodeVarData.getUnicodeString(Integer.valueOf(varData.getInt(id, 2, type)), OUTLINECODE_DATA);
}
else
{
int uniqueId = varData.getInt(id, 2, type);
CustomFieldValueItem item = m_file.getCustomFieldValueItem(Integer.valueOf(uniqueId));
if (item != null && item.getValue() != null)
{
result = MPPUtility.getUnicodeString(item.getValue());
}
}
return result;
}
/**
* Method used to instantiate the appropriate input stream reader,
* a standard one, or one which can deal with "encrypted" data.
*
* @param directory directory entry
* @param name file name
* @return new input stream
* @throws IOException
*/
private InputStream getEncryptableInputStream(DirectoryEntry directory, String name) throws IOException
{
DocumentEntry entry = (DocumentEntry) directory.getEntry(name);
InputStream stream;
if (m_file.getEncoded())
{
stream = new EncryptedDocumentInputStream(entry, m_file.getEncryptionCode());
}
else
{
stream = new DocumentInputStream(entry);
}
return (stream);
}
// private static void dumpUnknownData (String label, int[][] spec, byte[] data)
// {
// System.out.print (label);
// for (int loop=0; loop < spec.length; loop++)
// {
// int startByte = spec[loop][0];
// int length = spec[loop][1];
// if (length == -1)
// {
// length = data.length - startByte;
// }
// System.out.print ("["+spec[loop][0] + "]["+ MPPUtility.hexdump(data, startByte, length, false) + " ]");
// }
// System.out.println ();
// }
// private static final int[][] UNKNOWN_TASK_DATA = new int[][]
// {
// {42, 18},
// {116, 4},
// {134, 2},
// {144, 4},
// {144, 16},
// {248, 8},
// {256, -1}
// };
// private static final int[][] UNKNOWN_RESOURCE_DATA = new int[][]
// {
// {14, 6},
// {108, 16},
// };
private MPPReader m_reader;
private ProjectFile m_file;
private DirectoryEntry m_root;
private HashMap<Integer, ProjectCalendar> m_resourceMap;
private Var2Data m_outlineCodeVarData;
private VarMeta m_outlineCodeVarMeta;
private Props14 m_projectProps;
private Map<Integer, FontBase> m_fontBases;
private Map<Integer, SubProject> m_taskSubProjects;
private DirectoryEntry m_projectDir;
private DirectoryEntry m_viewDir;
private Map<Integer, Integer> m_parentTasks;
private Map<Long, Integer> m_taskOrder;
private Map<Integer, Integer> m_nullTaskOrder;
// private static final Comparator<Task> START_COMPARATOR = new Comparator<Task>()
// {
// public int compare(Task o1, Task o2)
// {
// int result = DateUtility.compare(o1.getStart(), o2.getStart());
// if (result == 0)
// {
// result = o1.getUniqueID().intValue() - o2.getUniqueID().intValue();
// //result = o1.getID().intValue() - o2.getID().intValue();
// }
// return (result);
// }
// };
// private static final Comparator<Task> FINISH_COMPARATOR = new Comparator<Task>()
// {
// public int compare(Task o1, Task o2)
// {
// int result = DateUtility.compare(o1.getFinish(), o2.getFinish());
// if (result == 0)
// {
// result = o1.getUniqueID().intValue() - o2.getUniqueID().intValue();
// }
// return (result);
// }
// };
// Signals the end of the list of subproject task unique ids
//private static final int SUBPROJECT_LISTEND = 0x00000303;
// Signals that the previous value was for the subproject task unique id
// TODO: figure out why the different value exist.
private static final int SUBPROJECT_TASKUNIQUEID0 = 0x00000000;
private static final int SUBPROJECT_TASKUNIQUEID1 = 0x0B340000;
private static final int SUBPROJECT_TASKUNIQUEID2 = 0x0ABB0000;
private static final int SUBPROJECT_TASKUNIQUEID3 = 0x05A10000;
private static final int SUBPROJECT_TASKUNIQUEID4 = 0x0BD50000;
private static final int SUBPROJECT_TASKUNIQUEID5 = 0x03D60000;
private static final int SUBPROJECT_TASKUNIQUEID6 = 0x067F0000;
private static final int SUBPROJECT_TASKUNIQUEID7 = 0x067D0000;
/**
* Calendar data types.
*/
private static final Integer CALENDAR_NAME = Integer.valueOf(1);
private static final Integer CALENDAR_DATA = Integer.valueOf(8);
/**
* Resource data types.
*/
private static final Integer TABLE_COLUMN_DATA_STANDARD = Integer.valueOf(6);
private static final Integer TABLE_COLUMN_DATA_ENTERPRISE = Integer.valueOf(7);
private static final Integer TABLE_COLUMN_DATA_BASELINE = Integer.valueOf(8);
private static final Integer OUTLINECODE_DATA = Integer.valueOf(22);
// Custom value list types
private static final Integer VALUE_LIST_VALUE = Integer.valueOf(22);
private static final Integer VALUE_LIST_DESCRIPTION = Integer.valueOf(8);
private static final Integer VALUE_LIST_UNKNOWN = Integer.valueOf(23);
private static final int VALUE_LIST_MASK = 0x0700;
/**
* Mask used to isolate confirmed flag from the duration units field.
*/
private static final int DURATION_CONFIRMED_MASK = 0x20;
private static final Integer RESOURCE_FIELD_NAME_ALIASES = Integer.valueOf(71303169);
private static final Integer TASK_FIELD_NAME_ALIASES = Integer.valueOf(71303169);
/**
* Default working week.
*/
private static final boolean[] DEFAULT_WORKING_WEEK =
{
false,
true,
true,
true,
true,
true,
false
};
}
| false | true | private void processTaskData() throws IOException
{
FieldMap fieldMap = new FieldMap14(m_file);
fieldMap.createTaskFieldMap(m_projectProps);
DirectoryEntry taskDir = (DirectoryEntry) m_projectDir.getEntry("TBkndTask");
VarMeta taskVarMeta = new VarMeta12(new DocumentInputStream(((DocumentEntry) taskDir.getEntry("VarMeta"))));
Var2Data taskVarData = new Var2Data(taskVarMeta, new DocumentInputStream(((DocumentEntry) taskDir.getEntry("Var2Data"))));
FixedMeta taskFixedMeta = new FixedMeta(new DocumentInputStream(((DocumentEntry) taskDir.getEntry("FixedMeta"))), 47);
FixedData taskFixedData = new FixedData(taskFixedMeta, new DocumentInputStream(((DocumentEntry) taskDir.getEntry("FixedData"))), fieldMap.getMaxFixedDataOffset(0));
FixedMeta taskFixed2Meta = new FixedMeta(new DocumentInputStream(((DocumentEntry) taskDir.getEntry("Fixed2Meta"))), 92);
FixedData taskFixed2Data = new FixedData(taskFixed2Meta, new DocumentInputStream(((DocumentEntry) taskDir.getEntry("Fixed2Data"))));
Props14 props = new Props14(getEncryptableInputStream(taskDir, "Props"));
//System.out.println(taskFixedMeta);
//System.out.println(taskFixedData);
//System.out.println(taskVarMeta);
//System.out.println(taskVarData);
//System.out.println(taskFixed2Meta);
//System.out.println(taskFixed2Data);
//System.out.println(m_outlineCodeVarData.getVarMeta());
//System.out.println(m_outlineCodeVarData);
//System.out.println(props);
// Process aliases
processTaskFieldNameAliases(props.getByteArray(TASK_FIELD_NAME_ALIASES));
TreeMap<Integer, Integer> taskMap = createTaskMap(fieldMap, taskFixedMeta, taskFixedData);
// The var data may not contain all the tasks as tasks with no var data assigned will
// not be saved in there. Most notably these are tasks with no name. So use the task map
// which contains all the tasks.
Object[] uniqueid = taskMap.keySet().toArray(); //taskVarMeta.getUniqueIdentifierArray();
Integer id;
Integer offset;
byte[] data;
byte[] metaData;
byte[] metaData2;
Task task;
boolean autoWBS = true;
LinkedList<Task> externalTasks = new LinkedList<Task>();
RecurringTaskReader recurringTaskReader = null;
RTFUtility rtf = new RTFUtility();
String notes;
for (int loop = 0; loop < uniqueid.length; loop++)
{
id = (Integer) uniqueid[loop];
offset = taskMap.get(id);
if (taskFixedData.isValidOffset(offset) == false)
{
continue;
}
data = taskFixedData.getByteArrayValue(offset.intValue());
if (data.length == 16)
{
task = m_file.addTask();
task.setNull(true);
task.setUniqueID(id);
task.setID(Integer.valueOf(MPPUtility.getInt(data, 4)));
m_nullTaskOrder.put(task.getID(), task.getUniqueID());
//System.out.println(task);
continue;
}
if (data.length < fieldMap.getMaxFixedDataOffset(0))
{
continue;
}
metaData = taskFixedMeta.getByteArrayValue(offset.intValue());
//System.out.println (MPPUtility.hexdump(data, false, 16, ""));
//System.out.println (MPPUtility.hexdump(data,false));
//System.out.println (MPPUtility.hexdump(metaData, false, 16, ""));
//MPPUtility.dataDump(m_file, data, false, false, false, true, false, false, false, false);
//MPPUtility.dataDump(metaData, true, true, true, true, true, true, true);
//MPPUtility.varDataDump(taskVarData, id, true, true, true, true, true, true);
metaData2 = taskFixed2Meta.getByteArrayValue(offset.intValue());
byte[] data2 = taskFixed2Data.getByteArrayValue(offset.intValue());
//System.out.println (MPPUtility.hexdump(metaData2, false, 16, ""));
//System.out.println(MPPUtility.hexdump(data2, false, 16, ""));
//System.out.println (MPPUtility.hexdump(metaData2,false));
byte[] recurringData = taskVarData.getByteArray(id, fieldMap.getVarDataKey(TaskField.RECURRING_DATA));
Task temp = m_file.getTaskByID(Integer.valueOf(MPPUtility.getInt(data, 4)));
if (temp != null)
{
// Task with this id already exists... determine if this is the 'real' task by seeing
// if this task has some var data. This is sort of hokey, but it's the best method i have
// been able to see.
if (!taskVarMeta.getUniqueIdentifierSet().contains(id))
{
// Sometimes Project contains phantom tasks that coexist on the same id as a valid
// task. In this case don't want to include the phantom task. Seems to be a very rare case.
continue;
}
else
if (temp.getName() == null)
{
// Ok, this looks valid. Remove the previous instance since it is most likely not a valid task.
// At worst case this removes a task with an empty name.
m_file.removeTask(temp);
}
}
task = m_file.addTask();
task.disableEvents();
fieldMap.populateContainer(task, id, new byte[][]
{
data,
data2
}, taskVarData);
task.enableEvents();
task.setActive((metaData2[8] & 0x04) != 0);
task.setEffortDriven((metaData[11] & 0x10) != 0);
task.setEstimated(getDurationEstimated(MPPUtility.getShort(data, fieldMap.getFixedDataOffset(TaskField.ACTUAL_DURATION_UNITS))));
task.setExpanded(((metaData[12] & 0x02) == 0));
Integer externalTaskID = task.getSubprojectTaskID();
if (externalTaskID != null && externalTaskID.intValue() != 0)
{
task.setExternalTask(true);
externalTasks.add(task);
}
task.setFlag1((metaData[35] & 0x40) != 0);
task.setFlag2((metaData[35] & 0x80) != 0);
task.setFlag3((metaData[36] & 0x01) != 0);
task.setFlag4((metaData[36] & 0x02) != 0);
task.setFlag5((metaData[36] & 0x04) != 0);
task.setFlag6((metaData[36] & 0x08) != 0);
task.setFlag7((metaData[36] & 0x10) != 0);
task.setFlag8((metaData[36] & 0x20) != 0);
task.setFlag9((metaData[36] & 0x40) != 0);
task.setFlag10((metaData[36] & 0x80) != 0);
task.setFlag11((metaData[37] & 0x01) != 0);
task.setFlag12((metaData[37] & 0x02) != 0);
task.setFlag13((metaData[37] & 0x04) != 0);
task.setFlag14((metaData[37] & 0x08) != 0);
task.setFlag15((metaData[37] & 0x10) != 0);
task.setFlag16((metaData[37] & 0x20) != 0);
task.setFlag17((metaData[37] & 0x40) != 0);
task.setFlag18((metaData[37] & 0x80) != 0);
task.setFlag19((metaData[38] & 0x01) != 0);
task.setFlag20((metaData[38] & 0x02) != 0);
task.setHideBar((metaData[10] & 0x80) != 0);
processHyperlinkData(task, taskVarData.getByteArray(id, fieldMap.getVarDataKey(TaskField.HYPERLINK_DATA)));
task.setID(Integer.valueOf(MPPUtility.getInt(data, 4)));
task.setIgnoreResourceCalendar((metaData[10] & 0x02) != 0);
task.setLevelAssignments((metaData[13] & 0x04) != 0);
task.setLevelingCanSplit((metaData[13] & 0x02) != 0);
task.setMarked((metaData[9] & 0x40) != 0);
task.setMilestone((metaData[8] & 0x20) != 0);
task.setOutlineCode1(getCustomFieldOutlineCodeValue(taskVarData, m_outlineCodeVarData, id, fieldMap.getVarDataKey(TaskField.OUTLINE_CODE1_INDEX)));
task.setOutlineCode2(getCustomFieldOutlineCodeValue(taskVarData, m_outlineCodeVarData, id, fieldMap.getVarDataKey(TaskField.OUTLINE_CODE2_INDEX)));
task.setOutlineCode3(getCustomFieldOutlineCodeValue(taskVarData, m_outlineCodeVarData, id, fieldMap.getVarDataKey(TaskField.OUTLINE_CODE3_INDEX)));
task.setOutlineCode4(getCustomFieldOutlineCodeValue(taskVarData, m_outlineCodeVarData, id, fieldMap.getVarDataKey(TaskField.OUTLINE_CODE4_INDEX)));
task.setOutlineCode5(getCustomFieldOutlineCodeValue(taskVarData, m_outlineCodeVarData, id, fieldMap.getVarDataKey(TaskField.OUTLINE_CODE5_INDEX)));
task.setOutlineCode6(getCustomFieldOutlineCodeValue(taskVarData, m_outlineCodeVarData, id, fieldMap.getVarDataKey(TaskField.OUTLINE_CODE6_INDEX)));
task.setOutlineCode7(getCustomFieldOutlineCodeValue(taskVarData, m_outlineCodeVarData, id, fieldMap.getVarDataKey(TaskField.OUTLINE_CODE7_INDEX)));
task.setOutlineCode8(getCustomFieldOutlineCodeValue(taskVarData, m_outlineCodeVarData, id, fieldMap.getVarDataKey(TaskField.OUTLINE_CODE8_INDEX)));
task.setOutlineCode9(getCustomFieldOutlineCodeValue(taskVarData, m_outlineCodeVarData, id, fieldMap.getVarDataKey(TaskField.OUTLINE_CODE9_INDEX)));
task.setOutlineCode10(getCustomFieldOutlineCodeValue(taskVarData, m_outlineCodeVarData, id, fieldMap.getVarDataKey(TaskField.OUTLINE_CODE10_INDEX)));
task.setRecurring(MPPUtility.getShort(data, 40) == 2);
task.setRollup((metaData[10] & 0x08) != 0);
task.setTaskMode((metaData2[8] & 0x08) == 0 ? TaskMode.AUTO_SCHEDULED : TaskMode.MANUALLY_SCHEDULED);
task.setUniqueID(id);
m_parentTasks.put(task.getUniqueID(), (Integer) task.getCachedValue(TaskField.PARENT_TASK_UNIQUE_ID));
if (task.getStart() == null)
{
task.setStart((Date) task.getCachedValue(TaskField.SCHEDULED_START));
}
if (task.getFinish() == null)
{
task.setFinish((Date) task.getCachedValue(TaskField.SCHEDULED_FINISH));
}
if (task.getDuration() == null)
{
task.setDuration((Duration) task.getCachedValue(TaskField.SCHEDULED_DURATION));
}
switch (task.getConstraintType())
{
//
// Adjust the start and finish dates if the task
// is constrained to start as late as possible.
//
case AS_LATE_AS_POSSIBLE :
{
if (DateUtility.compare(task.getStart(), task.getLateStart()) < 0)
{
task.setStart(task.getLateStart());
}
if (DateUtility.compare(task.getFinish(), task.getLateFinish()) < 0)
{
task.setFinish(task.getLateFinish());
}
break;
}
case START_NO_LATER_THAN :
case FINISH_NO_LATER_THAN :
{
if (DateUtility.compare(task.getFinish(), task.getStart()) < 0)
{
task.setFinish(task.getLateFinish());
}
break;
}
default :
{
break;
}
}
//
// Retrieve task recurring data
//
if (recurringData != null)
{
if (recurringTaskReader == null)
{
recurringTaskReader = new RecurringTaskReader(m_file);
}
recurringTaskReader.processRecurringTask(task, recurringData);
task.setRecurring(true);
}
//
// Retrieve the task notes.
//
notes = task.getNotes();
if (notes != null)
{
if (m_reader.getPreserveNoteFormatting() == false)
{
notes = rtf.strip(notes);
}
task.setNotes(notes);
}
//
// Set the calendar name
//
Integer calendarID = (Integer) task.getCachedValue(TaskField.CALENDAR_UNIQUE_ID);
if (calendarID != null && calendarID.intValue() != -1)
{
ProjectCalendar calendar = m_file.getBaseCalendarByUniqueID(calendarID);
if (calendar != null)
{
task.setCalendar(calendar);
}
}
//
// Set the sub project flag
//
SubProject sp = m_taskSubProjects.get(task.getUniqueID());
task.setSubProject(sp);
//
// Set the external flag
//
if (sp != null)
{
task.setExternalTask(sp.isExternalTask(task.getUniqueID()));
if (task.getExternalTask())
{
task.setExternalTaskProject(sp.getFullPath());
}
}
//
// If we have a WBS value from the MPP file, don't autogenerate
//
if (task.getWBS() != null)
{
autoWBS = false;
}
//
// If this is a split task, allocate space for the split durations
//
if ((metaData[9] & 0x80) == 0)
{
task.setSplits(new LinkedList<DateRange>());
}
//
// If this is a manually scheduled task, read the manual duration
//
if (task.getTaskMode() != TaskMode.MANUALLY_SCHEDULED)
{
task.setManualDuration(null);
}
//
// Process any enterprise columns
//
processTaskEnterpriseColumns(id, task, taskVarData, metaData2);
// Unfortunately it looks like 'null' tasks sometimes make it through. So let's check for to see if we
// need to mark this task as a null task after all.
if (task.getName() == null && ((task.getStart() == null || task.getStart().getTime() == MPPUtility.getEpochDate().getTime()) || (task.getFinish() == null || task.getFinish().getTime() == MPPUtility.getEpochDate().getTime()) || (task.getCreateDate() == null || task.getCreateDate().getTime() == MPPUtility.getEpochDate().getTime())))
{
// Remove this to avoid passing bad data to the client
m_file.removeTask(task);
task = m_file.addTask();
task.setNull(true);
task.setUniqueID(id);
task.setID(new Integer(MPPUtility.getInt(data, 4)));
m_nullTaskOrder.put(task.getID(), task.getUniqueID());
//System.out.println(task);
continue;
}
if (data2.length < 24)
{
m_nullTaskOrder.put(task.getID(), task.getUniqueID());
}
else
{
Long key = Long.valueOf(MPPUtility.getLong(data2, 16));
m_taskOrder.put(key, task.getUniqueID());
}
//System.out.println(task + " " + MPPUtility.getShort(data2, 22)); // JPI - looks like this value determines the ID order! Validate and check other versions!
m_file.fireTaskReadEvent(task);
//dumpUnknownData(task.getUniqueID().toString(), UNKNOWN_TASK_DATA, data);
//System.out.println(task);
}
//
// Enable auto WBS if necessary
//
m_file.setAutoWBS(autoWBS);
//
// We have now read all of the task, so we are in a position
// to perform post-processing to set up the relevant details
// for each external task.
//
if (!externalTasks.isEmpty())
{
processExternalTasks(externalTasks);
}
}
| private void processTaskData() throws IOException
{
FieldMap fieldMap = new FieldMap14(m_file);
fieldMap.createTaskFieldMap(m_projectProps);
DirectoryEntry taskDir = (DirectoryEntry) m_projectDir.getEntry("TBkndTask");
VarMeta taskVarMeta = new VarMeta12(new DocumentInputStream(((DocumentEntry) taskDir.getEntry("VarMeta"))));
Var2Data taskVarData = new Var2Data(taskVarMeta, new DocumentInputStream(((DocumentEntry) taskDir.getEntry("Var2Data"))));
FixedMeta taskFixedMeta = new FixedMeta(new DocumentInputStream(((DocumentEntry) taskDir.getEntry("FixedMeta"))), 47);
FixedData taskFixedData = new FixedData(taskFixedMeta, new DocumentInputStream(((DocumentEntry) taskDir.getEntry("FixedData"))), fieldMap.getMaxFixedDataOffset(0));
FixedMeta taskFixed2Meta = new FixedMeta(new DocumentInputStream(((DocumentEntry) taskDir.getEntry("Fixed2Meta"))), 92);
FixedData taskFixed2Data = new FixedData(taskFixed2Meta, new DocumentInputStream(((DocumentEntry) taskDir.getEntry("Fixed2Data"))));
Props14 props = new Props14(getEncryptableInputStream(taskDir, "Props"));
//System.out.println(taskFixedMeta);
//System.out.println(taskFixedData);
//System.out.println(taskVarMeta);
//System.out.println(taskVarData);
//System.out.println(taskFixed2Meta);
//System.out.println(taskFixed2Data);
//System.out.println(m_outlineCodeVarData.getVarMeta());
//System.out.println(m_outlineCodeVarData);
//System.out.println(props);
// Process aliases
processTaskFieldNameAliases(props.getByteArray(TASK_FIELD_NAME_ALIASES));
TreeMap<Integer, Integer> taskMap = createTaskMap(fieldMap, taskFixedMeta, taskFixedData);
// The var data may not contain all the tasks as tasks with no var data assigned will
// not be saved in there. Most notably these are tasks with no name. So use the task map
// which contains all the tasks.
Object[] uniqueid = taskMap.keySet().toArray(); //taskVarMeta.getUniqueIdentifierArray();
Integer id;
Integer offset;
byte[] data;
byte[] metaData;
byte[] metaData2;
Task task;
boolean autoWBS = true;
LinkedList<Task> externalTasks = new LinkedList<Task>();
RecurringTaskReader recurringTaskReader = null;
RTFUtility rtf = new RTFUtility();
String notes;
for (int loop = 0; loop < uniqueid.length; loop++)
{
id = (Integer) uniqueid[loop];
offset = taskMap.get(id);
if (taskFixedData.isValidOffset(offset) == false)
{
continue;
}
data = taskFixedData.getByteArrayValue(offset.intValue());
if (data.length == 16)
{
task = m_file.addTask();
task.setNull(true);
task.setUniqueID(id);
task.setID(Integer.valueOf(MPPUtility.getInt(data, 4)));
m_nullTaskOrder.put(task.getID(), task.getUniqueID());
//System.out.println(task);
continue;
}
if (data.length < fieldMap.getMaxFixedDataOffset(0))
{
continue;
}
metaData = taskFixedMeta.getByteArrayValue(offset.intValue());
//System.out.println (MPPUtility.hexdump(data, false, 16, ""));
//System.out.println (MPPUtility.hexdump(data,false));
//System.out.println (MPPUtility.hexdump(metaData, false, 16, ""));
//MPPUtility.dataDump(m_file, data, false, false, false, true, false, false, false, false);
//MPPUtility.dataDump(metaData, true, true, true, true, true, true, true);
//MPPUtility.varDataDump(taskVarData, id, true, true, true, true, true, true);
metaData2 = taskFixed2Meta.getByteArrayValue(offset.intValue());
byte[] data2 = taskFixed2Data.getByteArrayValue(offset.intValue());
//System.out.println (MPPUtility.hexdump(metaData2, false, 16, ""));
//System.out.println(MPPUtility.hexdump(data2, false, 16, ""));
//System.out.println (MPPUtility.hexdump(metaData2,false));
byte[] recurringData = taskVarData.getByteArray(id, fieldMap.getVarDataKey(TaskField.RECURRING_DATA));
Task temp = m_file.getTaskByID(Integer.valueOf(MPPUtility.getInt(data, 4)));
if (temp != null)
{
// Task with this id already exists... determine if this is the 'real' task by seeing
// if this task has some var data. This is sort of hokey, but it's the best method i have
// been able to see.
if (!taskVarMeta.getUniqueIdentifierSet().contains(id))
{
// Sometimes Project contains phantom tasks that coexist on the same id as a valid
// task. In this case don't want to include the phantom task. Seems to be a very rare case.
continue;
}
else
if (temp.getName() == null)
{
// Ok, this looks valid. Remove the previous instance since it is most likely not a valid task.
// At worst case this removes a task with an empty name.
m_file.removeTask(temp);
}
}
task = m_file.addTask();
task.disableEvents();
fieldMap.populateContainer(task, id, new byte[][]
{
data,
data2
}, taskVarData);
task.enableEvents();
task.setActive((metaData2[8] & 0x04) != 0);
task.setEffortDriven((metaData[11] & 0x10) != 0);
task.setEstimated(getDurationEstimated(MPPUtility.getShort(data, fieldMap.getFixedDataOffset(TaskField.ACTUAL_DURATION_UNITS))));
task.setExpanded(((metaData[12] & 0x02) == 0));
Integer externalTaskID = task.getSubprojectTaskID();
if (externalTaskID != null && externalTaskID.intValue() != 0)
{
task.setExternalTask(true);
externalTasks.add(task);
}
task.setFlag1((metaData[35] & 0x40) != 0);
task.setFlag2((metaData[35] & 0x80) != 0);
task.setFlag3((metaData[36] & 0x01) != 0);
task.setFlag4((metaData[36] & 0x02) != 0);
task.setFlag5((metaData[36] & 0x04) != 0);
task.setFlag6((metaData[36] & 0x08) != 0);
task.setFlag7((metaData[36] & 0x10) != 0);
task.setFlag8((metaData[36] & 0x20) != 0);
task.setFlag9((metaData[36] & 0x40) != 0);
task.setFlag10((metaData[36] & 0x80) != 0);
task.setFlag11((metaData[37] & 0x01) != 0);
task.setFlag12((metaData[37] & 0x02) != 0);
task.setFlag13((metaData[37] & 0x04) != 0);
task.setFlag14((metaData[37] & 0x08) != 0);
task.setFlag15((metaData[37] & 0x10) != 0);
task.setFlag16((metaData[37] & 0x20) != 0);
task.setFlag17((metaData[37] & 0x40) != 0);
task.setFlag18((metaData[37] & 0x80) != 0);
task.setFlag19((metaData[38] & 0x01) != 0);
task.setFlag20((metaData[38] & 0x02) != 0);
task.setHideBar((metaData[10] & 0x80) != 0);
processHyperlinkData(task, taskVarData.getByteArray(id, fieldMap.getVarDataKey(TaskField.HYPERLINK_DATA)));
task.setID(Integer.valueOf(MPPUtility.getInt(data, 4)));
task.setIgnoreResourceCalendar((metaData[10] & 0x02) != 0);
task.setLevelAssignments((metaData[13] & 0x04) != 0);
task.setLevelingCanSplit((metaData[13] & 0x02) != 0);
task.setMarked((metaData[9] & 0x40) != 0);
task.setMilestone((metaData[8] & 0x20) != 0);
task.setOutlineCode1(getCustomFieldOutlineCodeValue(taskVarData, m_outlineCodeVarData, id, fieldMap.getVarDataKey(TaskField.OUTLINE_CODE1_INDEX)));
task.setOutlineCode2(getCustomFieldOutlineCodeValue(taskVarData, m_outlineCodeVarData, id, fieldMap.getVarDataKey(TaskField.OUTLINE_CODE2_INDEX)));
task.setOutlineCode3(getCustomFieldOutlineCodeValue(taskVarData, m_outlineCodeVarData, id, fieldMap.getVarDataKey(TaskField.OUTLINE_CODE3_INDEX)));
task.setOutlineCode4(getCustomFieldOutlineCodeValue(taskVarData, m_outlineCodeVarData, id, fieldMap.getVarDataKey(TaskField.OUTLINE_CODE4_INDEX)));
task.setOutlineCode5(getCustomFieldOutlineCodeValue(taskVarData, m_outlineCodeVarData, id, fieldMap.getVarDataKey(TaskField.OUTLINE_CODE5_INDEX)));
task.setOutlineCode6(getCustomFieldOutlineCodeValue(taskVarData, m_outlineCodeVarData, id, fieldMap.getVarDataKey(TaskField.OUTLINE_CODE6_INDEX)));
task.setOutlineCode7(getCustomFieldOutlineCodeValue(taskVarData, m_outlineCodeVarData, id, fieldMap.getVarDataKey(TaskField.OUTLINE_CODE7_INDEX)));
task.setOutlineCode8(getCustomFieldOutlineCodeValue(taskVarData, m_outlineCodeVarData, id, fieldMap.getVarDataKey(TaskField.OUTLINE_CODE8_INDEX)));
task.setOutlineCode9(getCustomFieldOutlineCodeValue(taskVarData, m_outlineCodeVarData, id, fieldMap.getVarDataKey(TaskField.OUTLINE_CODE9_INDEX)));
task.setOutlineCode10(getCustomFieldOutlineCodeValue(taskVarData, m_outlineCodeVarData, id, fieldMap.getVarDataKey(TaskField.OUTLINE_CODE10_INDEX)));
task.setRecurring(MPPUtility.getShort(data, 40) == 2);
task.setRollup((metaData[10] & 0x08) != 0);
task.setTaskMode((metaData2[8] & 0x08) == 0 ? TaskMode.AUTO_SCHEDULED : TaskMode.MANUALLY_SCHEDULED);
task.setUniqueID(id);
m_parentTasks.put(task.getUniqueID(), (Integer) task.getCachedValue(TaskField.PARENT_TASK_UNIQUE_ID));
if (task.getStart() == null || (task.getCachedValue(TaskField.SCHEDULED_START) != null && task.getTaskMode() == TaskMode.AUTO_SCHEDULED))
{
task.setStart((Date) task.getCachedValue(TaskField.SCHEDULED_START));
}
if (task.getFinish() == null || (task.getCachedValue(TaskField.SCHEDULED_FINISH) != null && task.getTaskMode() == TaskMode.AUTO_SCHEDULED))
{
task.setFinish((Date) task.getCachedValue(TaskField.SCHEDULED_FINISH));
}
if (task.getDuration() == null || (task.getCachedValue(TaskField.SCHEDULED_DURATION) != null && task.getTaskMode() == TaskMode.AUTO_SCHEDULED))
{
task.setDuration((Duration) task.getCachedValue(TaskField.SCHEDULED_DURATION));
}
switch (task.getConstraintType())
{
//
// Adjust the start and finish dates if the task
// is constrained to start as late as possible.
//
case AS_LATE_AS_POSSIBLE :
{
if (DateUtility.compare(task.getStart(), task.getLateStart()) < 0)
{
task.setStart(task.getLateStart());
}
if (DateUtility.compare(task.getFinish(), task.getLateFinish()) < 0)
{
task.setFinish(task.getLateFinish());
}
break;
}
case START_NO_LATER_THAN :
case FINISH_NO_LATER_THAN :
{
if (DateUtility.compare(task.getFinish(), task.getStart()) < 0)
{
task.setFinish(task.getLateFinish());
}
break;
}
default :
{
break;
}
}
//
// Retrieve task recurring data
//
if (recurringData != null)
{
if (recurringTaskReader == null)
{
recurringTaskReader = new RecurringTaskReader(m_file);
}
recurringTaskReader.processRecurringTask(task, recurringData);
task.setRecurring(true);
}
//
// Retrieve the task notes.
//
notes = task.getNotes();
if (notes != null)
{
if (m_reader.getPreserveNoteFormatting() == false)
{
notes = rtf.strip(notes);
}
task.setNotes(notes);
}
//
// Set the calendar name
//
Integer calendarID = (Integer) task.getCachedValue(TaskField.CALENDAR_UNIQUE_ID);
if (calendarID != null && calendarID.intValue() != -1)
{
ProjectCalendar calendar = m_file.getBaseCalendarByUniqueID(calendarID);
if (calendar != null)
{
task.setCalendar(calendar);
}
}
//
// Set the sub project flag
//
SubProject sp = m_taskSubProjects.get(task.getUniqueID());
task.setSubProject(sp);
//
// Set the external flag
//
if (sp != null)
{
task.setExternalTask(sp.isExternalTask(task.getUniqueID()));
if (task.getExternalTask())
{
task.setExternalTaskProject(sp.getFullPath());
}
}
//
// If we have a WBS value from the MPP file, don't autogenerate
//
if (task.getWBS() != null)
{
autoWBS = false;
}
//
// If this is a split task, allocate space for the split durations
//
if ((metaData[9] & 0x80) == 0)
{
task.setSplits(new LinkedList<DateRange>());
}
//
// If this is a manually scheduled task, read the manual duration
//
if (task.getTaskMode() != TaskMode.MANUALLY_SCHEDULED)
{
task.setManualDuration(null);
}
//
// Process any enterprise columns
//
processTaskEnterpriseColumns(id, task, taskVarData, metaData2);
// Unfortunately it looks like 'null' tasks sometimes make it through. So let's check for to see if we
// need to mark this task as a null task after all.
if (task.getName() == null && ((task.getStart() == null || task.getStart().getTime() == MPPUtility.getEpochDate().getTime()) || (task.getFinish() == null || task.getFinish().getTime() == MPPUtility.getEpochDate().getTime()) || (task.getCreateDate() == null || task.getCreateDate().getTime() == MPPUtility.getEpochDate().getTime())))
{
// Remove this to avoid passing bad data to the client
m_file.removeTask(task);
task = m_file.addTask();
task.setNull(true);
task.setUniqueID(id);
task.setID(new Integer(MPPUtility.getInt(data, 4)));
m_nullTaskOrder.put(task.getID(), task.getUniqueID());
//System.out.println(task);
continue;
}
if (data2.length < 24)
{
m_nullTaskOrder.put(task.getID(), task.getUniqueID());
}
else
{
Long key = Long.valueOf(MPPUtility.getLong(data2, 16));
m_taskOrder.put(key, task.getUniqueID());
}
//System.out.println(task + " " + MPPUtility.getShort(data2, 22)); // JPI - looks like this value determines the ID order! Validate and check other versions!
m_file.fireTaskReadEvent(task);
//dumpUnknownData(task.getUniqueID().toString(), UNKNOWN_TASK_DATA, data);
//System.out.println(task);
}
//
// Enable auto WBS if necessary
//
m_file.setAutoWBS(autoWBS);
//
// We have now read all of the task, so we are in a position
// to perform post-processing to set up the relevant details
// for each external task.
//
if (!externalTasks.isEmpty())
{
processExternalTasks(externalTasks);
}
}
|
diff --git a/openFaces/source/org/openfaces/renderkit/filter/ComboBoxFilterRenderer.java b/openFaces/source/org/openfaces/renderkit/filter/ComboBoxFilterRenderer.java
index 19268bbeb..5ffdaf02a 100644
--- a/openFaces/source/org/openfaces/renderkit/filter/ComboBoxFilterRenderer.java
+++ b/openFaces/source/org/openfaces/renderkit/filter/ComboBoxFilterRenderer.java
@@ -1,192 +1,191 @@
/*
* OpenFaces - JSF Component Library 2.0
* Copyright (C) 2007-2011, TeamDev Ltd.
* [email protected]
* Unless agreed in writing the contents of this file are subject to
* the GNU Lesser General Public License Version 2.1 (the "LGPL" License).
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* Please visit http://openfaces.org/licensing/ for more details.
*/
package org.openfaces.renderkit.filter;
import org.openfaces.component.filter.ComboBoxFilter;
import org.openfaces.component.filter.ExpressionFilter;
import org.openfaces.component.filter.ExpressionFilterCriterion;
import org.openfaces.component.filter.FilterCondition;
import org.openfaces.renderkit.TableUtil;
import org.openfaces.renderkit.table.AbstractTableRenderer;
import org.openfaces.util.Rendering;
import org.openfaces.util.Resources;
import org.openfaces.util.ScriptBuilder;
import org.openfaces.util.Styles;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.context.ResponseWriter;
import javax.faces.convert.Converter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
/**
* @author Dmitry Pikhulya
*/
public class ComboBoxFilterRenderer extends ExpressionFilterRenderer {
private static final String USER_CRITERION_PREFIX = "u-";
private static final String PREDEFINED_CRITERION_PREFIX = "p-";
private static final String ALL = "ALL";
private static final String EMPTY = "EMPTY";
private static final String NON_EMPTY = "NON_EMPTY";
@Override
public boolean getRendersChildren() {
return true;
}
@Override
public void encodeChildren(FacesContext context, UIComponent component) throws IOException {
}
@Override
public void encodeBegin(FacesContext context, UIComponent component) throws IOException {
super.encodeBegin(context, component);
ComboBoxFilter filter = ((ComboBoxFilter) component);
ExpressionFilterCriterion currentCriterion = (ExpressionFilterCriterion) filter.getValue();
ResponseWriter writer = context.getResponseWriter();
writer.startElement("select", component);
String clientId = writeIdAttribute(context, component);
writeNameAttribute(context, component);
writer.writeAttribute("size", "1", null);
Rendering.writeStyleAndClassAttributes(writer, filter.getStyle(), filter.getStyleClass(), "o_fullWidth");
- String submitScript = getFilterSubmissionScript(filter);
- writer.writeAttribute("onchange", submitScript, null);
+ writer.writeAttribute("onchange", getFilterSubmissionScript(filter), null);
writer.writeAttribute("onclick", "event.cancelBubble = true;", null);
writer.writeAttribute("onkeydown", "O$.cancelBubble(event);", null);
writer.writeAttribute("dir", filter.getDir(), "dir");
writer.writeAttribute("lang", filter.getLang(), "lang");
boolean thereAreEmptyItems = false;
Collection<Object> criterionNamesCollection = filter.calculateAllCriterionNames(context);
for (Iterator<Object> criterionIterator = criterionNamesCollection.iterator(); criterionIterator.hasNext();) {
Object criterionObj = criterionIterator.next();
if (isEmptyItem(criterionObj)) {
thereAreEmptyItems = true;
criterionIterator.remove();
}
}
List<Object> criterionNames = new ArrayList<Object>(criterionNamesCollection);
String allRecordsCriterionName = filter.getAllRecordsText();
String predefinedCriterionsClass = getPredefinedCriterionClass(context, filter);
writeOption(writer, component, PREDEFINED_CRITERION_PREFIX + ALL, allRecordsCriterionName,
currentCriterion == null,
predefinedCriterionsClass);
FilterCondition condition = currentCriterion != null ? currentCriterion.getCondition() : null;
if (thereAreEmptyItems) {
String emptyRecordsCriterionName = filter.getEmptyRecordsText();
writeOption(writer, component, PREDEFINED_CRITERION_PREFIX + EMPTY, emptyRecordsCriterionName,
condition != null && condition.equals(FilterCondition.EMPTY) && !currentCriterion.isInverse(),
predefinedCriterionsClass);
String nonEmptyRecordsCriterionName = filter.getNonEmptyRecordsText();
writeOption(writer, component, PREDEFINED_CRITERION_PREFIX + NON_EMPTY,
nonEmptyRecordsCriterionName,
condition != null && condition.equals(FilterCondition.EMPTY) && currentCriterion.isInverse(),
predefinedCriterionsClass);
}
Converter converter = getConverter(filter);
Object currentCriterionArg = currentCriterion != null ? currentCriterion.getArg1() : null;
String currentCriterionStr = converter.getAsString(context, filter, currentCriterionArg);
boolean textCriterionSelected = false;
for (Object criterionObj : criterionNames) {
String criterionName = converter.getAsString(context, filter, criterionObj);
boolean selected = currentCriterion instanceof ExpressionFilterCriterion &&
currentCriterionStr.equals(criterionName);
writeOption(writer, component,
USER_CRITERION_PREFIX + criterionName,
criterionName,
selected, null);
if (selected)
textCriterionSelected = true;
}
boolean noRecordsWithSelectedCriterion = currentCriterion != null && condition != FilterCondition.EMPTY && !textCriterionSelected;
if (noRecordsWithSelectedCriterion) {
writeOption(writer, component,
USER_CRITERION_PREFIX + currentCriterionStr,
currentCriterionStr,
true, null);
}
UIComponent filteredComponent = (UIComponent) filter.getFilteredComponent();
Rendering.renderInitScript(context,
new ScriptBuilder().functionCall("O$.Filters._showFilter",
filteredComponent, clientId).semicolon(),
Resources.utilJsURL(context),
Resources.filtersJsURL(context),
TableUtil.getTableUtilJsURL(context),
AbstractTableRenderer.getTableJsURL(context));
Styles.renderStyleClasses(context, component);
writer.endElement("select");
}
private void writeOption(
ResponseWriter writer,
UIComponent component,
String value,
String text,
boolean selected,
String styleClass) throws IOException {
writer.startElement("option", component);
if (styleClass != null)
writer.writeAttribute("class", styleClass, null);
writer.writeAttribute("value", value, null);
if (selected)
writer.writeAttribute("selected", "true", null);
writer.writeText(text, null);
writer.endElement("option");
}
@Override
public void decode(FacesContext context, UIComponent component) {
super.decode(context, component);
Map<String, String> requestParameterMap = context.getExternalContext().getRequestParameterMap();
String selectedCriterion = requestParameterMap.get(component.getClientId(context));
if (selectedCriterion == null)
return;
ComboBoxFilter filter = ((ComboBoxFilter) component);
if (selectedCriterion.startsWith(USER_CRITERION_PREFIX)) {
String searchString = selectedCriterion.substring(USER_CRITERION_PREFIX.length());
setDecodedString(filter, searchString);
} else if (selectedCriterion.startsWith(PREDEFINED_CRITERION_PREFIX)) {
String criterion = selectedCriterion.substring(PREDEFINED_CRITERION_PREFIX.length());
ExpressionFilterCriterion newCriterion;
if (criterion.equals(ALL))
newCriterion = null;
else if (criterion.equals(EMPTY))
newCriterion = new ExpressionFilterCriterion(FilterCondition.EMPTY, false);
else if (criterion.equals(NON_EMPTY))
newCriterion = new ExpressionFilterCriterion(FilterCondition.EMPTY, true);
else
throw new IllegalStateException("Unknown predefined criterion came from client: " + criterion);
setDecodedCriterion(filter, newCriterion);
} else
throw new IllegalStateException("Improperly formatted criterion came from client: " + selectedCriterion);
}
@Override
protected FilterCondition getForceDefaultCondition(ExpressionFilter filter) {
return FilterCondition.EQUALS;
}
}
| true | true | public void encodeBegin(FacesContext context, UIComponent component) throws IOException {
super.encodeBegin(context, component);
ComboBoxFilter filter = ((ComboBoxFilter) component);
ExpressionFilterCriterion currentCriterion = (ExpressionFilterCriterion) filter.getValue();
ResponseWriter writer = context.getResponseWriter();
writer.startElement("select", component);
String clientId = writeIdAttribute(context, component);
writeNameAttribute(context, component);
writer.writeAttribute("size", "1", null);
Rendering.writeStyleAndClassAttributes(writer, filter.getStyle(), filter.getStyleClass(), "o_fullWidth");
String submitScript = getFilterSubmissionScript(filter);
writer.writeAttribute("onchange", submitScript, null);
writer.writeAttribute("onclick", "event.cancelBubble = true;", null);
writer.writeAttribute("onkeydown", "O$.cancelBubble(event);", null);
writer.writeAttribute("dir", filter.getDir(), "dir");
writer.writeAttribute("lang", filter.getLang(), "lang");
boolean thereAreEmptyItems = false;
Collection<Object> criterionNamesCollection = filter.calculateAllCriterionNames(context);
for (Iterator<Object> criterionIterator = criterionNamesCollection.iterator(); criterionIterator.hasNext();) {
Object criterionObj = criterionIterator.next();
if (isEmptyItem(criterionObj)) {
thereAreEmptyItems = true;
criterionIterator.remove();
}
}
List<Object> criterionNames = new ArrayList<Object>(criterionNamesCollection);
String allRecordsCriterionName = filter.getAllRecordsText();
String predefinedCriterionsClass = getPredefinedCriterionClass(context, filter);
writeOption(writer, component, PREDEFINED_CRITERION_PREFIX + ALL, allRecordsCriterionName,
currentCriterion == null,
predefinedCriterionsClass);
FilterCondition condition = currentCriterion != null ? currentCriterion.getCondition() : null;
if (thereAreEmptyItems) {
String emptyRecordsCriterionName = filter.getEmptyRecordsText();
writeOption(writer, component, PREDEFINED_CRITERION_PREFIX + EMPTY, emptyRecordsCriterionName,
condition != null && condition.equals(FilterCondition.EMPTY) && !currentCriterion.isInverse(),
predefinedCriterionsClass);
String nonEmptyRecordsCriterionName = filter.getNonEmptyRecordsText();
writeOption(writer, component, PREDEFINED_CRITERION_PREFIX + NON_EMPTY,
nonEmptyRecordsCriterionName,
condition != null && condition.equals(FilterCondition.EMPTY) && currentCriterion.isInverse(),
predefinedCriterionsClass);
}
Converter converter = getConverter(filter);
Object currentCriterionArg = currentCriterion != null ? currentCriterion.getArg1() : null;
String currentCriterionStr = converter.getAsString(context, filter, currentCriterionArg);
boolean textCriterionSelected = false;
for (Object criterionObj : criterionNames) {
String criterionName = converter.getAsString(context, filter, criterionObj);
boolean selected = currentCriterion instanceof ExpressionFilterCriterion &&
currentCriterionStr.equals(criterionName);
writeOption(writer, component,
USER_CRITERION_PREFIX + criterionName,
criterionName,
selected, null);
if (selected)
textCriterionSelected = true;
}
boolean noRecordsWithSelectedCriterion = currentCriterion != null && condition != FilterCondition.EMPTY && !textCriterionSelected;
if (noRecordsWithSelectedCriterion) {
writeOption(writer, component,
USER_CRITERION_PREFIX + currentCriterionStr,
currentCriterionStr,
true, null);
}
UIComponent filteredComponent = (UIComponent) filter.getFilteredComponent();
Rendering.renderInitScript(context,
new ScriptBuilder().functionCall("O$.Filters._showFilter",
filteredComponent, clientId).semicolon(),
Resources.utilJsURL(context),
Resources.filtersJsURL(context),
TableUtil.getTableUtilJsURL(context),
AbstractTableRenderer.getTableJsURL(context));
Styles.renderStyleClasses(context, component);
writer.endElement("select");
}
| public void encodeBegin(FacesContext context, UIComponent component) throws IOException {
super.encodeBegin(context, component);
ComboBoxFilter filter = ((ComboBoxFilter) component);
ExpressionFilterCriterion currentCriterion = (ExpressionFilterCriterion) filter.getValue();
ResponseWriter writer = context.getResponseWriter();
writer.startElement("select", component);
String clientId = writeIdAttribute(context, component);
writeNameAttribute(context, component);
writer.writeAttribute("size", "1", null);
Rendering.writeStyleAndClassAttributes(writer, filter.getStyle(), filter.getStyleClass(), "o_fullWidth");
writer.writeAttribute("onchange", getFilterSubmissionScript(filter), null);
writer.writeAttribute("onclick", "event.cancelBubble = true;", null);
writer.writeAttribute("onkeydown", "O$.cancelBubble(event);", null);
writer.writeAttribute("dir", filter.getDir(), "dir");
writer.writeAttribute("lang", filter.getLang(), "lang");
boolean thereAreEmptyItems = false;
Collection<Object> criterionNamesCollection = filter.calculateAllCriterionNames(context);
for (Iterator<Object> criterionIterator = criterionNamesCollection.iterator(); criterionIterator.hasNext();) {
Object criterionObj = criterionIterator.next();
if (isEmptyItem(criterionObj)) {
thereAreEmptyItems = true;
criterionIterator.remove();
}
}
List<Object> criterionNames = new ArrayList<Object>(criterionNamesCollection);
String allRecordsCriterionName = filter.getAllRecordsText();
String predefinedCriterionsClass = getPredefinedCriterionClass(context, filter);
writeOption(writer, component, PREDEFINED_CRITERION_PREFIX + ALL, allRecordsCriterionName,
currentCriterion == null,
predefinedCriterionsClass);
FilterCondition condition = currentCriterion != null ? currentCriterion.getCondition() : null;
if (thereAreEmptyItems) {
String emptyRecordsCriterionName = filter.getEmptyRecordsText();
writeOption(writer, component, PREDEFINED_CRITERION_PREFIX + EMPTY, emptyRecordsCriterionName,
condition != null && condition.equals(FilterCondition.EMPTY) && !currentCriterion.isInverse(),
predefinedCriterionsClass);
String nonEmptyRecordsCriterionName = filter.getNonEmptyRecordsText();
writeOption(writer, component, PREDEFINED_CRITERION_PREFIX + NON_EMPTY,
nonEmptyRecordsCriterionName,
condition != null && condition.equals(FilterCondition.EMPTY) && currentCriterion.isInverse(),
predefinedCriterionsClass);
}
Converter converter = getConverter(filter);
Object currentCriterionArg = currentCriterion != null ? currentCriterion.getArg1() : null;
String currentCriterionStr = converter.getAsString(context, filter, currentCriterionArg);
boolean textCriterionSelected = false;
for (Object criterionObj : criterionNames) {
String criterionName = converter.getAsString(context, filter, criterionObj);
boolean selected = currentCriterion instanceof ExpressionFilterCriterion &&
currentCriterionStr.equals(criterionName);
writeOption(writer, component,
USER_CRITERION_PREFIX + criterionName,
criterionName,
selected, null);
if (selected)
textCriterionSelected = true;
}
boolean noRecordsWithSelectedCriterion = currentCriterion != null && condition != FilterCondition.EMPTY && !textCriterionSelected;
if (noRecordsWithSelectedCriterion) {
writeOption(writer, component,
USER_CRITERION_PREFIX + currentCriterionStr,
currentCriterionStr,
true, null);
}
UIComponent filteredComponent = (UIComponent) filter.getFilteredComponent();
Rendering.renderInitScript(context,
new ScriptBuilder().functionCall("O$.Filters._showFilter",
filteredComponent, clientId).semicolon(),
Resources.utilJsURL(context),
Resources.filtersJsURL(context),
TableUtil.getTableUtilJsURL(context),
AbstractTableRenderer.getTableJsURL(context));
Styles.renderStyleClasses(context, component);
writer.endElement("select");
}
|
diff --git a/FiltersPlugin/src/org/gephi/filters/plugin/graph/EgoBuilder.java b/FiltersPlugin/src/org/gephi/filters/plugin/graph/EgoBuilder.java
index 87865743f..40ac4fa63 100644
--- a/FiltersPlugin/src/org/gephi/filters/plugin/graph/EgoBuilder.java
+++ b/FiltersPlugin/src/org/gephi/filters/plugin/graph/EgoBuilder.java
@@ -1,174 +1,174 @@
/*
Copyright 2008-2010 Gephi
Authors : Mathieu Bastian <[email protected]>
Website : http://www.gephi.org
This file is part of Gephi.
Gephi is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
Gephi 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 Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Gephi. If not, see <http://www.gnu.org/licenses/>.
*/
package org.gephi.filters.plugin.graph;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.swing.Icon;
import javax.swing.JPanel;
import org.gephi.filters.api.FilterLibrary;
import org.gephi.filters.spi.Category;
import org.gephi.filters.spi.ComplexFilter;
import org.gephi.filters.spi.Filter;
import org.gephi.filters.spi.FilterBuilder;
import org.gephi.filters.spi.FilterProperty;
import org.gephi.graph.api.Graph;
import org.gephi.graph.api.HierarchicalGraph;
import org.gephi.graph.api.Node;
import org.openide.util.Lookup;
import org.openide.util.NbBundle;
import org.openide.util.lookup.ServiceProvider;
/**
*
* @author Mathieu Bastian
*/
@ServiceProvider(service = FilterBuilder.class)
public class EgoBuilder implements FilterBuilder {
public Category getCategory() {
return FilterLibrary.TOPOLOGY;
}
public String getName() {
return NbBundle.getMessage(EgoBuilder.class, "EgoBuilder.name");
}
public Icon getIcon() {
return null;
}
public String getDescription() {
return NbBundle.getMessage(EgoBuilder.class, "EgoBuilder.description");
}
public Filter getFilter() {
return new EgoFilter();
}
public JPanel getPanel(Filter filter) {
EgoUI ui = Lookup.getDefault().lookup(EgoUI.class);
if (ui != null) {
return ui.getPanel((EgoFilter) filter);
}
return null;
}
public void destroy(Filter filter) {
}
public static class EgoFilter implements ComplexFilter {
private String pattern = "";
private boolean self = true;
private int depth = 1;
public Graph filter(Graph graph) {
HierarchicalGraph hgraph = (HierarchicalGraph) graph;
String str = pattern.toLowerCase();
List<Node> nodes = new ArrayList<Node>();
for (Node n : hgraph.getNodes()) {
- if (n.getNodeData().getId().toLowerCase().contains(str)) {
+ if (n.getNodeData().getId().toLowerCase().equals(str)) {
nodes.add(n);
- } else if ((n.getNodeData().getLabel() != null) && n.getNodeData().getLabel().toLowerCase().contains(str)) {
+ } else if ((n.getNodeData().getLabel() != null) && n.getNodeData().getLabel().toLowerCase().equals(str)) {
nodes.add(n);
}
}
Set<Node> result = new HashSet<Node>();
Set<Node> neighbours = new HashSet<Node>();
neighbours.addAll(nodes);
for (int i = 0; i < depth; i++) {
Node[] nei = neighbours.toArray(new Node[0]);
neighbours.clear();
for (Node n : nei) {
for (Node neighbor : hgraph.getNeighbors(n)) {
if (!result.contains(neighbor)) {
neighbours.add(neighbor);
result.add(neighbor);
}
}
}
if (neighbours.isEmpty()) {
break;
}
}
if (self) {
result.addAll(nodes);
}
for (Node node : hgraph.getNodes().toArray()) {
if (!result.contains(node)) {
hgraph.removeNode(node);
}
}
return hgraph;
}
public String getName() {
return NbBundle.getMessage(EgoBuilder.class, "EgoBuilder.name");
}
public FilterProperty[] getProperties() {
try {
return new FilterProperty[]{
FilterProperty.createProperty(this, String.class, "pattern"),
FilterProperty.createProperty(this, Integer.class, "depth"),
FilterProperty.createProperty(this, Boolean.class, "self")};
} catch (NoSuchMethodException ex) {
ex.printStackTrace();
}
return new FilterProperty[0];
}
public String getPattern() {
return pattern;
}
public void setPattern(String pattern) {
this.pattern = pattern;
}
public Integer getDepth() {
return depth;
}
public void setDepth(Integer depth) {
this.depth = depth;
}
public boolean isSelf() {
return self;
}
public void setSelf(boolean self) {
this.self = self;
}
}
}
| false | true | public Graph filter(Graph graph) {
HierarchicalGraph hgraph = (HierarchicalGraph) graph;
String str = pattern.toLowerCase();
List<Node> nodes = new ArrayList<Node>();
for (Node n : hgraph.getNodes()) {
if (n.getNodeData().getId().toLowerCase().contains(str)) {
nodes.add(n);
} else if ((n.getNodeData().getLabel() != null) && n.getNodeData().getLabel().toLowerCase().contains(str)) {
nodes.add(n);
}
}
Set<Node> result = new HashSet<Node>();
Set<Node> neighbours = new HashSet<Node>();
neighbours.addAll(nodes);
for (int i = 0; i < depth; i++) {
Node[] nei = neighbours.toArray(new Node[0]);
neighbours.clear();
for (Node n : nei) {
for (Node neighbor : hgraph.getNeighbors(n)) {
if (!result.contains(neighbor)) {
neighbours.add(neighbor);
result.add(neighbor);
}
}
}
if (neighbours.isEmpty()) {
break;
}
}
if (self) {
result.addAll(nodes);
}
for (Node node : hgraph.getNodes().toArray()) {
if (!result.contains(node)) {
hgraph.removeNode(node);
}
}
return hgraph;
}
| public Graph filter(Graph graph) {
HierarchicalGraph hgraph = (HierarchicalGraph) graph;
String str = pattern.toLowerCase();
List<Node> nodes = new ArrayList<Node>();
for (Node n : hgraph.getNodes()) {
if (n.getNodeData().getId().toLowerCase().equals(str)) {
nodes.add(n);
} else if ((n.getNodeData().getLabel() != null) && n.getNodeData().getLabel().toLowerCase().equals(str)) {
nodes.add(n);
}
}
Set<Node> result = new HashSet<Node>();
Set<Node> neighbours = new HashSet<Node>();
neighbours.addAll(nodes);
for (int i = 0; i < depth; i++) {
Node[] nei = neighbours.toArray(new Node[0]);
neighbours.clear();
for (Node n : nei) {
for (Node neighbor : hgraph.getNeighbors(n)) {
if (!result.contains(neighbor)) {
neighbours.add(neighbor);
result.add(neighbor);
}
}
}
if (neighbours.isEmpty()) {
break;
}
}
if (self) {
result.addAll(nodes);
}
for (Node node : hgraph.getNodes().toArray()) {
if (!result.contains(node)) {
hgraph.removeNode(node);
}
}
return hgraph;
}
|
diff --git a/src/main/java/plugins/WebOfTrust/FCPInterface.java b/src/main/java/plugins/WebOfTrust/FCPInterface.java
index 06deccc..c4a8096 100644
--- a/src/main/java/plugins/WebOfTrust/FCPInterface.java
+++ b/src/main/java/plugins/WebOfTrust/FCPInterface.java
@@ -1,54 +1,55 @@
package plugins.WebOfTrust;
import java.lang.reflect.Constructor;
import org.neo4j.graphdb.GraphDatabaseService;
import plugins.WebOfTrust.fcp.FCPBase;
import freenet.pluginmanager.PluginNotFoundException;
import freenet.pluginmanager.PluginReplySender;
import freenet.support.SimpleFieldSet;
import freenet.support.api.Bucket;
public class FCPInterface {
private GraphDatabaseService db;
public FCPInterface(GraphDatabaseService db)
{
this.db = db;
}
public void handle(PluginReplySender prs, SimpleFieldSet sfs, Bucket bucket, int accessType) throws PluginNotFoundException {
//System.out.println("Received the following message type: " + sfs.get("Message") + " with identifier: " + prs.getIdentifier());
try {
//find class with the name Message
@SuppressWarnings("unchecked")
Class<FCPBase> c = (Class<FCPBase>) Class.forName("plugins.WebOfTrust.fcp."+sfs.get("Message"));
Constructor<? extends FCPBase> ctor = c.getConstructor(GraphDatabaseService.class);
FCPBase handler = ctor.newInstance(db);
long start = System.currentTimeMillis();
//call its handle method with the input data
final SimpleFieldSet reply = handler.handle(sfs);
if (WebOfTrust.DEBUG) System.out.println(sfs.get("Message") + " took: " + (System.currentTimeMillis()-start) + "ms");
//send the reply
prs.send(reply);
}
catch(Exception e)
{
SimpleFieldSet reply = new SimpleFieldSet(true);
System.out.println("Failed to match message: " + sfs.get("Message") + " with reply");
e.printStackTrace();
reply.putSingle("Message", "Error");
- reply.putSingle("Description", "Could not match message with reply");
+ reply.putSingle("OriginalMessage", sfs.get("Message"));
+ reply.putSingle("Description", "Could not match message with reply because of an exception: " + e.getMessage());
prs.send(reply);
}
}
}
| true | true | public void handle(PluginReplySender prs, SimpleFieldSet sfs, Bucket bucket, int accessType) throws PluginNotFoundException {
//System.out.println("Received the following message type: " + sfs.get("Message") + " with identifier: " + prs.getIdentifier());
try {
//find class with the name Message
@SuppressWarnings("unchecked")
Class<FCPBase> c = (Class<FCPBase>) Class.forName("plugins.WebOfTrust.fcp."+sfs.get("Message"));
Constructor<? extends FCPBase> ctor = c.getConstructor(GraphDatabaseService.class);
FCPBase handler = ctor.newInstance(db);
long start = System.currentTimeMillis();
//call its handle method with the input data
final SimpleFieldSet reply = handler.handle(sfs);
if (WebOfTrust.DEBUG) System.out.println(sfs.get("Message") + " took: " + (System.currentTimeMillis()-start) + "ms");
//send the reply
prs.send(reply);
}
catch(Exception e)
{
SimpleFieldSet reply = new SimpleFieldSet(true);
System.out.println("Failed to match message: " + sfs.get("Message") + " with reply");
e.printStackTrace();
reply.putSingle("Message", "Error");
reply.putSingle("Description", "Could not match message with reply");
prs.send(reply);
}
}
| public void handle(PluginReplySender prs, SimpleFieldSet sfs, Bucket bucket, int accessType) throws PluginNotFoundException {
//System.out.println("Received the following message type: " + sfs.get("Message") + " with identifier: " + prs.getIdentifier());
try {
//find class with the name Message
@SuppressWarnings("unchecked")
Class<FCPBase> c = (Class<FCPBase>) Class.forName("plugins.WebOfTrust.fcp."+sfs.get("Message"));
Constructor<? extends FCPBase> ctor = c.getConstructor(GraphDatabaseService.class);
FCPBase handler = ctor.newInstance(db);
long start = System.currentTimeMillis();
//call its handle method with the input data
final SimpleFieldSet reply = handler.handle(sfs);
if (WebOfTrust.DEBUG) System.out.println(sfs.get("Message") + " took: " + (System.currentTimeMillis()-start) + "ms");
//send the reply
prs.send(reply);
}
catch(Exception e)
{
SimpleFieldSet reply = new SimpleFieldSet(true);
System.out.println("Failed to match message: " + sfs.get("Message") + " with reply");
e.printStackTrace();
reply.putSingle("Message", "Error");
reply.putSingle("OriginalMessage", sfs.get("Message"));
reply.putSingle("Description", "Could not match message with reply because of an exception: " + e.getMessage());
prs.send(reply);
}
}
|
diff --git a/src/friskstick/cops/plugin/FriskCommand.java b/src/friskstick/cops/plugin/FriskCommand.java
index f7cfc46..aa60ce4 100644
--- a/src/friskstick/cops/plugin/FriskCommand.java
+++ b/src/friskstick/cops/plugin/FriskCommand.java
@@ -1,148 +1,148 @@
package friskstick.cops.plugin;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
/*
*
* This is where the command for frisk will be implemented, making it easier to organize the program.
*
*/
public class FriskCommand implements CommandExecutor{
private FriskStick plugin;
JailPlayer jailed = new JailPlayer();
public FriskCommand(FriskStick plugin) {
this.plugin = plugin;
}
int index = 0;
@Override
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
Player player = (Player)sender;
if(player == null) {
sender.sendMessage("You cannot run this command in the console!");
} else {
if(commandLabel.equalsIgnoreCase("frisk")) { // If the player typed /frisk then do the following...
if(args.length == 0) {
player.sendMessage("Usage: /frisk <playername>");
} else if(args.length == 1) {
Player frisked = plugin.getServer().getPlayer(args[0]);
if(player.hasPermission("friskstick.chat")) {
PlayerInventory inventory = frisked.getInventory();
boolean found = false;
for(String drug: plugin.getConfig().getStringList("drug-ids")) {
if(drug.contains(":")) {
String firsthalf = drug.split(":")[0];
String lasthalf = drug.split(":")[1];
for(int i = 1; i <= plugin.getConfig().getInt("amount-to-search-for"); i++) {
ItemStack[] contents = inventory.getContents();
if(inventory.contains(new ItemStack(Integer.parseInt(firsthalf), i, Short.parseShort(lasthalf)))) {
player.getInventory().addItem(new ItemStack(contents[inventory.first(new ItemStack(Integer.parseInt(firsthalf), i, Short.parseShort(lasthalf)))]));
inventory.removeItem(new ItemStack(Integer.parseInt(firsthalf), 2305, Short.parseShort(lasthalf)));
- player.sendMessage(plugin.getConfig().getString("cop-found-msg").replaceAll("&", "�").replaceAll("%itemname%", plugin.getConfig().getStringList("drug-names").toArray()[index].toString()).replaceAll("%cop%", player.getName()).replaceAll("%player%", plugin.getServer().getPlayer(args[0]).getName()));
+ player.sendMessage(plugin.getConfig().getString("cop-found-msg").replaceAll("&", "�").replaceAll("%cop%", player.getName()).replaceAll("%itemname%", plugin.getConfig().getStringList("drug-names").toArray()[index].toString()).replaceAll("%player%", plugin.getServer().getPlayer(args[0]).getName()));
plugin.getServer().getPlayer(args[0]).sendMessage(plugin.getConfig().getString("player-found-msg").replaceAll("&", "�").replaceAll("%player%", player.getName()).replaceAll("%itemname%", plugin.getConfig().getStringList("drug-names").toArray()[index].toString()));
if(player.hasPermission("friskstick.jail")) {
jailed.jail(plugin.getServer().getPlayer(args[0]).getName());
}
found = true;
}
}
} else {
if(inventory.contains(Integer.parseInt(drug))) {
int drugid = Integer.parseInt(drug);
ItemStack[] contents = inventory.getContents();
player.getInventory().addItem(new ItemStack(contents[inventory.first(drugid)]));
inventory.removeItem(new ItemStack(drugid, 2305));
- player.sendMessage(plugin.getConfig().getString("cop-found-msg").replaceAll("&", "�").replaceAll("%itemname%", plugin.getConfig().getStringList("drug-names").toArray()[index].toString()).replaceAll("%cop%", player.getName()).replaceAll("%player%", plugin.getServer().getPlayer(args[0]).getName()));
+ player.sendMessage(plugin.getConfig().getString("cop-found-msg").replaceAll("&", "�").replaceAll("%cop%", player.getName()).replaceAll("%itemname%", plugin.getConfig().getStringList("drug-names").toArray()[index].toString()).replaceAll("%player%", plugin.getServer().getPlayer(args[0]).getName()));
plugin.getServer().getPlayer(args[0]).sendMessage(plugin.getConfig().getString("player-found-msg").replaceAll("&", "�").replaceAll("%player%", player.getName()).replaceAll("%itemname%", plugin.getConfig().getStringList("drug-names").toArray()[index].toString()));
if(player.hasPermission("friskstick.jail")) {
jailed.jail(plugin.getServer().getPlayer(args[0]).getName());
}
found = true;
}
}
index++;
}
index = 0;
if(!found) {
player.sendMessage(plugin.getConfig().getString("cop-not-found-msg").replaceAll("&", "�").replaceAll("%cop%", player.getName()).replaceAll("%player%", plugin.getServer().getPlayer(args[0]).getName()));
plugin.getServer().getPlayer(args[0]).sendMessage(plugin.getConfig().getString("player-not-found-msg").replaceAll("&", "�").replaceAll("%player%", player.getName()));
if(player.getHealth() >= 2) {
player.setHealth(player.getHealth() - 2);
} else {
player.setHealth(0);
}
}
}
}
return true;
}
}
return false;
}
}
| false | true | public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
Player player = (Player)sender;
if(player == null) {
sender.sendMessage("You cannot run this command in the console!");
} else {
if(commandLabel.equalsIgnoreCase("frisk")) { // If the player typed /frisk then do the following...
if(args.length == 0) {
player.sendMessage("Usage: /frisk <playername>");
} else if(args.length == 1) {
Player frisked = plugin.getServer().getPlayer(args[0]);
if(player.hasPermission("friskstick.chat")) {
PlayerInventory inventory = frisked.getInventory();
boolean found = false;
for(String drug: plugin.getConfig().getStringList("drug-ids")) {
if(drug.contains(":")) {
String firsthalf = drug.split(":")[0];
String lasthalf = drug.split(":")[1];
for(int i = 1; i <= plugin.getConfig().getInt("amount-to-search-for"); i++) {
ItemStack[] contents = inventory.getContents();
if(inventory.contains(new ItemStack(Integer.parseInt(firsthalf), i, Short.parseShort(lasthalf)))) {
player.getInventory().addItem(new ItemStack(contents[inventory.first(new ItemStack(Integer.parseInt(firsthalf), i, Short.parseShort(lasthalf)))]));
inventory.removeItem(new ItemStack(Integer.parseInt(firsthalf), 2305, Short.parseShort(lasthalf)));
player.sendMessage(plugin.getConfig().getString("cop-found-msg").replaceAll("&", "�").replaceAll("%itemname%", plugin.getConfig().getStringList("drug-names").toArray()[index].toString()).replaceAll("%cop%", player.getName()).replaceAll("%player%", plugin.getServer().getPlayer(args[0]).getName()));
plugin.getServer().getPlayer(args[0]).sendMessage(plugin.getConfig().getString("player-found-msg").replaceAll("&", "�").replaceAll("%player%", player.getName()).replaceAll("%itemname%", plugin.getConfig().getStringList("drug-names").toArray()[index].toString()));
if(player.hasPermission("friskstick.jail")) {
jailed.jail(plugin.getServer().getPlayer(args[0]).getName());
}
found = true;
}
}
} else {
if(inventory.contains(Integer.parseInt(drug))) {
int drugid = Integer.parseInt(drug);
ItemStack[] contents = inventory.getContents();
player.getInventory().addItem(new ItemStack(contents[inventory.first(drugid)]));
inventory.removeItem(new ItemStack(drugid, 2305));
player.sendMessage(plugin.getConfig().getString("cop-found-msg").replaceAll("&", "�").replaceAll("%itemname%", plugin.getConfig().getStringList("drug-names").toArray()[index].toString()).replaceAll("%cop%", player.getName()).replaceAll("%player%", plugin.getServer().getPlayer(args[0]).getName()));
plugin.getServer().getPlayer(args[0]).sendMessage(plugin.getConfig().getString("player-found-msg").replaceAll("&", "�").replaceAll("%player%", player.getName()).replaceAll("%itemname%", plugin.getConfig().getStringList("drug-names").toArray()[index].toString()));
if(player.hasPermission("friskstick.jail")) {
jailed.jail(plugin.getServer().getPlayer(args[0]).getName());
}
found = true;
}
}
index++;
}
index = 0;
if(!found) {
player.sendMessage(plugin.getConfig().getString("cop-not-found-msg").replaceAll("&", "�").replaceAll("%cop%", player.getName()).replaceAll("%player%", plugin.getServer().getPlayer(args[0]).getName()));
plugin.getServer().getPlayer(args[0]).sendMessage(plugin.getConfig().getString("player-not-found-msg").replaceAll("&", "�").replaceAll("%player%", player.getName()));
if(player.getHealth() >= 2) {
player.setHealth(player.getHealth() - 2);
} else {
player.setHealth(0);
}
}
}
}
return true;
}
}
return false;
}
| public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
Player player = (Player)sender;
if(player == null) {
sender.sendMessage("You cannot run this command in the console!");
} else {
if(commandLabel.equalsIgnoreCase("frisk")) { // If the player typed /frisk then do the following...
if(args.length == 0) {
player.sendMessage("Usage: /frisk <playername>");
} else if(args.length == 1) {
Player frisked = plugin.getServer().getPlayer(args[0]);
if(player.hasPermission("friskstick.chat")) {
PlayerInventory inventory = frisked.getInventory();
boolean found = false;
for(String drug: plugin.getConfig().getStringList("drug-ids")) {
if(drug.contains(":")) {
String firsthalf = drug.split(":")[0];
String lasthalf = drug.split(":")[1];
for(int i = 1; i <= plugin.getConfig().getInt("amount-to-search-for"); i++) {
ItemStack[] contents = inventory.getContents();
if(inventory.contains(new ItemStack(Integer.parseInt(firsthalf), i, Short.parseShort(lasthalf)))) {
player.getInventory().addItem(new ItemStack(contents[inventory.first(new ItemStack(Integer.parseInt(firsthalf), i, Short.parseShort(lasthalf)))]));
inventory.removeItem(new ItemStack(Integer.parseInt(firsthalf), 2305, Short.parseShort(lasthalf)));
player.sendMessage(plugin.getConfig().getString("cop-found-msg").replaceAll("&", "�").replaceAll("%cop%", player.getName()).replaceAll("%itemname%", plugin.getConfig().getStringList("drug-names").toArray()[index].toString()).replaceAll("%player%", plugin.getServer().getPlayer(args[0]).getName()));
plugin.getServer().getPlayer(args[0]).sendMessage(plugin.getConfig().getString("player-found-msg").replaceAll("&", "�").replaceAll("%player%", player.getName()).replaceAll("%itemname%", plugin.getConfig().getStringList("drug-names").toArray()[index].toString()));
if(player.hasPermission("friskstick.jail")) {
jailed.jail(plugin.getServer().getPlayer(args[0]).getName());
}
found = true;
}
}
} else {
if(inventory.contains(Integer.parseInt(drug))) {
int drugid = Integer.parseInt(drug);
ItemStack[] contents = inventory.getContents();
player.getInventory().addItem(new ItemStack(contents[inventory.first(drugid)]));
inventory.removeItem(new ItemStack(drugid, 2305));
player.sendMessage(plugin.getConfig().getString("cop-found-msg").replaceAll("&", "�").replaceAll("%cop%", player.getName()).replaceAll("%itemname%", plugin.getConfig().getStringList("drug-names").toArray()[index].toString()).replaceAll("%player%", plugin.getServer().getPlayer(args[0]).getName()));
plugin.getServer().getPlayer(args[0]).sendMessage(plugin.getConfig().getString("player-found-msg").replaceAll("&", "�").replaceAll("%player%", player.getName()).replaceAll("%itemname%", plugin.getConfig().getStringList("drug-names").toArray()[index].toString()));
if(player.hasPermission("friskstick.jail")) {
jailed.jail(plugin.getServer().getPlayer(args[0]).getName());
}
found = true;
}
}
index++;
}
index = 0;
if(!found) {
player.sendMessage(plugin.getConfig().getString("cop-not-found-msg").replaceAll("&", "�").replaceAll("%cop%", player.getName()).replaceAll("%player%", plugin.getServer().getPlayer(args[0]).getName()));
plugin.getServer().getPlayer(args[0]).sendMessage(plugin.getConfig().getString("player-not-found-msg").replaceAll("&", "�").replaceAll("%player%", player.getName()));
if(player.getHealth() >= 2) {
player.setHealth(player.getHealth() - 2);
} else {
player.setHealth(0);
}
}
}
}
return true;
}
}
return false;
}
|
diff --git a/src/java/com/idega/block/web2/presentation/Accordion.java b/src/java/com/idega/block/web2/presentation/Accordion.java
index 3610886..7804b38 100644
--- a/src/java/com/idega/block/web2/presentation/Accordion.java
+++ b/src/java/com/idega/block/web2/presentation/Accordion.java
@@ -1,247 +1,249 @@
package com.idega.block.web2.presentation;
import java.io.IOException;
import java.util.Collection;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import org.apache.myfaces.renderkit.html.util.AddResource;
import org.apache.myfaces.renderkit.html.util.AddResourceFactory;
import com.idega.block.web2.business.Web2Business;
import com.idega.business.IBOLookup;
import com.idega.presentation.Block;
import com.idega.presentation.IWContext;
import com.idega.presentation.Layer;
import com.idega.presentation.text.Text;
public class Accordion extends Block {
protected static final String PANELS_FACET_NAME = "PANELS";
private Collection panels = null;
private String accordionId = "";
private int panelCount = 0;
private boolean includeJavascript = true;
private String onActiveScriptString = null;
private String onBackgroundScriptString = null;
private String scriptString = null;
private boolean useSound = true;
public String getOnActiveScriptString() {
return onActiveScriptString;
}
public boolean isUseSound() {
return useSound;
}
public void setUseSound(boolean useSound) {
this.useSound = useSound;
}
public void setOnActiveScriptString(String onActiveScriptString) {
this.onActiveScriptString = onActiveScriptString;
}
public String getOnBackgroundScriptString() {
return onBackgroundScriptString;
}
public void setOnBackgroundScriptString(String onBackgroundScriptString) {
this.onBackgroundScriptString = onBackgroundScriptString;
}
public boolean isIncludeJavascript() {
return includeJavascript;
}
/**
* Sometimes needed if you want or need to manually add the script after or before a conflicting script
* @param includeJavascript
*/
public void setIncludeJavascript(boolean includeJavascript) {
this.includeJavascript = includeJavascript;
}
public Accordion() {
super();
}
public Accordion(String id) {
super();
this.accordionId = id;
}
public void main(IWContext iwc) {
//Page parentPage = PresentationObjectUtil.getParentPage(this);
//if (parentPage != null) {
try {
Web2Business business = (Web2Business) IBOLookup.getServiceInstance(iwc, Web2Business.class);
String styleURI = business.getBundleURIToMootoolsStyleFile();
AddResource resourceAdder = AddResourceFactory.getInstance(iwc.getRequest());
// add style
resourceAdder.addStyleSheet(iwc, AddResource.HEADER_BEGIN,styleURI);
if(includeJavascript == true) {
String mootoolsURI = business.getBundleURIToMootoolsLib();
//add a javascript to the header :)
resourceAdder.addJavaScriptAtPosition(iwc, AddResource.HEADER_BEGIN,mootoolsURI);
// parentPage.addScriptSource(mootoolsURI);
// parentPage.addStyleSheetURL(styleURI);
}
//add sounds :)
if(useSound){
Sound sound = new Sound();
this.getChildren().add(sound);
StringBuffer soundPlay = new StringBuffer();
soundPlay.append("\tif(canStartUsingSound){ \n")
.append("\t").append(sound.getPlayScriptlet("clicksound", sound.getTestSoundURI(),"volume:10,pan:-50"))
.append("\t} \n")
.append("\tcanStartUsingSound=true; \n");
setOnActiveScriptString(soundPlay.toString());
}
if (getScriptString()==null) {
StringBuffer scriptString = new StringBuffer();
scriptString.append("<script type=\"text/javascript\" > \n")
.append("var iwAccordion")
.append(accordionId)
.append(" = null; \n")
.append("var canStartUsingSound = false; \n")
- .append("window.onload = function() { \n")
+// .append("window.onload = function() { \n")
+ .append("function setAccordion"+accordionId+"() { \n")
//.append("function createAccordion").append(id).append("()").append("{ \n")
.append("\tvar stretchers = $$('div.acStretch").append(this.accordionId).append("'); \n")
.append("\tvar togglers = $$('div.acToggle").append(this.accordionId).append("'); \n")
.append("\tiwAccordion")
.append(accordionId)
.append(" = new Fx.Accordion(togglers, stretchers, { alwaysHide:false, opacity:false, transition: Fx.Transitions.quadOut, \n");
scriptString.append("\t\tonActive: function(toggler, i){ \n");
if (getOnActiveScriptString() != null) {
scriptString.append("\t\t").append(getOnActiveScriptString());
}
scriptString.append("\t\t}, \n").append("\t\tonBackground: function(toggler, i){ \n");
if (getOnBackgroundScriptString() != null) {
scriptString.append("\t\t").append(getOnBackgroundScriptString());
}
- scriptString.append("\t\t} \n").append("\t}); \n").append(
- "} \n");
+ scriptString.append("\t\t} \n").append("\t}); \n")
+ .append("} \n");
+ scriptString.append("registerEvent(window, 'load', setAccordion"+accordionId+");");
scriptString.append("</script> \n");
setScriptString(scriptString.toString());
}
this.getChildren().add(new Text(getScriptString()));
} catch (Exception e) {
e.printStackTrace();
}
}
public void addPanel(UIComponent header, UIComponent content) {
addPanel("panel"+(panelCount++), header, content);
}
public void addPanel(String panelID, UIComponent header, UIComponent content) {
//get outerlayer (facet)
Layer panels = (Layer)this.getFacet(PANELS_FACET_NAME);
if(panels==null){
panels = new Layer();
if("".equals(accordionId)){
accordionId = "accordionContainer";
}
panels.setId(accordionId);
panels.setStyleClass("accordionContainer");
this.getFacets().put(PANELS_FACET_NAME, panels);
}
//add panel to outerlayer
Layer l = new Layer();
l.setId(panelID);
Layer h = new Layer();
h.setId(panelID+"Header");
//for rapidweaver and typical mootools css
h.setStyleClass("acToggle acToggle"+accordionId);
h.getChildren().add(header);
Layer c = new Layer();
c.setId(panelID+"Content");
c.setStyleClass("acStretch acStretch"+accordionId);
c.getChildren().add(content);
l.add(h);
l.add(c);
panels.add(l);
}
public void encodeBegin(FacesContext fc)throws IOException{
super.encodeBegin(fc);
UIComponent panels = (UIComponent)this.getFacet(PANELS_FACET_NAME);
this.renderChild(fc,panels);
}
public Object clone(){
Accordion obj = (Accordion) super.clone();
obj.panels = this.panels;
obj.accordionId = this.accordionId;
obj.includeJavascript = this.includeJavascript;
obj.onActiveScriptString = this.onActiveScriptString;
obj.onBackgroundScriptString = this.onBackgroundScriptString;
obj.scriptString = this.scriptString;
return obj;
}
public Object saveState(FacesContext context) {
Object values[] = new Object[3];
values[0] = super.saveState(context);
values[1] = this.accordionId;
//todo add the other params?
return values;
}
public void restoreState(FacesContext context, Object state) {
Object values[] = (Object[])state;
super.restoreState(context, values[0]);
this.accordionId = (String) values[1];
}
public String getFamily() {
return null;
}
public String getScriptString() {
return scriptString;
}
public void setScriptString(String scriptString) {
this.scriptString = scriptString;
}
public String getAccordionId() {
return accordionId;
}
public void setAccordionId(String accordionId) {
this.accordionId = accordionId;
}
}
| false | true | public void main(IWContext iwc) {
//Page parentPage = PresentationObjectUtil.getParentPage(this);
//if (parentPage != null) {
try {
Web2Business business = (Web2Business) IBOLookup.getServiceInstance(iwc, Web2Business.class);
String styleURI = business.getBundleURIToMootoolsStyleFile();
AddResource resourceAdder = AddResourceFactory.getInstance(iwc.getRequest());
// add style
resourceAdder.addStyleSheet(iwc, AddResource.HEADER_BEGIN,styleURI);
if(includeJavascript == true) {
String mootoolsURI = business.getBundleURIToMootoolsLib();
//add a javascript to the header :)
resourceAdder.addJavaScriptAtPosition(iwc, AddResource.HEADER_BEGIN,mootoolsURI);
// parentPage.addScriptSource(mootoolsURI);
// parentPage.addStyleSheetURL(styleURI);
}
//add sounds :)
if(useSound){
Sound sound = new Sound();
this.getChildren().add(sound);
StringBuffer soundPlay = new StringBuffer();
soundPlay.append("\tif(canStartUsingSound){ \n")
.append("\t").append(sound.getPlayScriptlet("clicksound", sound.getTestSoundURI(),"volume:10,pan:-50"))
.append("\t} \n")
.append("\tcanStartUsingSound=true; \n");
setOnActiveScriptString(soundPlay.toString());
}
if (getScriptString()==null) {
StringBuffer scriptString = new StringBuffer();
scriptString.append("<script type=\"text/javascript\" > \n")
.append("var iwAccordion")
.append(accordionId)
.append(" = null; \n")
.append("var canStartUsingSound = false; \n")
.append("window.onload = function() { \n")
//.append("function createAccordion").append(id).append("()").append("{ \n")
.append("\tvar stretchers = $$('div.acStretch").append(this.accordionId).append("'); \n")
.append("\tvar togglers = $$('div.acToggle").append(this.accordionId).append("'); \n")
.append("\tiwAccordion")
.append(accordionId)
.append(" = new Fx.Accordion(togglers, stretchers, { alwaysHide:false, opacity:false, transition: Fx.Transitions.quadOut, \n");
scriptString.append("\t\tonActive: function(toggler, i){ \n");
if (getOnActiveScriptString() != null) {
scriptString.append("\t\t").append(getOnActiveScriptString());
}
scriptString.append("\t\t}, \n").append("\t\tonBackground: function(toggler, i){ \n");
if (getOnBackgroundScriptString() != null) {
scriptString.append("\t\t").append(getOnBackgroundScriptString());
}
scriptString.append("\t\t} \n").append("\t}); \n").append(
"} \n");
scriptString.append("</script> \n");
setScriptString(scriptString.toString());
}
this.getChildren().add(new Text(getScriptString()));
} catch (Exception e) {
e.printStackTrace();
}
}
| public void main(IWContext iwc) {
//Page parentPage = PresentationObjectUtil.getParentPage(this);
//if (parentPage != null) {
try {
Web2Business business = (Web2Business) IBOLookup.getServiceInstance(iwc, Web2Business.class);
String styleURI = business.getBundleURIToMootoolsStyleFile();
AddResource resourceAdder = AddResourceFactory.getInstance(iwc.getRequest());
// add style
resourceAdder.addStyleSheet(iwc, AddResource.HEADER_BEGIN,styleURI);
if(includeJavascript == true) {
String mootoolsURI = business.getBundleURIToMootoolsLib();
//add a javascript to the header :)
resourceAdder.addJavaScriptAtPosition(iwc, AddResource.HEADER_BEGIN,mootoolsURI);
// parentPage.addScriptSource(mootoolsURI);
// parentPage.addStyleSheetURL(styleURI);
}
//add sounds :)
if(useSound){
Sound sound = new Sound();
this.getChildren().add(sound);
StringBuffer soundPlay = new StringBuffer();
soundPlay.append("\tif(canStartUsingSound){ \n")
.append("\t").append(sound.getPlayScriptlet("clicksound", sound.getTestSoundURI(),"volume:10,pan:-50"))
.append("\t} \n")
.append("\tcanStartUsingSound=true; \n");
setOnActiveScriptString(soundPlay.toString());
}
if (getScriptString()==null) {
StringBuffer scriptString = new StringBuffer();
scriptString.append("<script type=\"text/javascript\" > \n")
.append("var iwAccordion")
.append(accordionId)
.append(" = null; \n")
.append("var canStartUsingSound = false; \n")
// .append("window.onload = function() { \n")
.append("function setAccordion"+accordionId+"() { \n")
//.append("function createAccordion").append(id).append("()").append("{ \n")
.append("\tvar stretchers = $$('div.acStretch").append(this.accordionId).append("'); \n")
.append("\tvar togglers = $$('div.acToggle").append(this.accordionId).append("'); \n")
.append("\tiwAccordion")
.append(accordionId)
.append(" = new Fx.Accordion(togglers, stretchers, { alwaysHide:false, opacity:false, transition: Fx.Transitions.quadOut, \n");
scriptString.append("\t\tonActive: function(toggler, i){ \n");
if (getOnActiveScriptString() != null) {
scriptString.append("\t\t").append(getOnActiveScriptString());
}
scriptString.append("\t\t}, \n").append("\t\tonBackground: function(toggler, i){ \n");
if (getOnBackgroundScriptString() != null) {
scriptString.append("\t\t").append(getOnBackgroundScriptString());
}
scriptString.append("\t\t} \n").append("\t}); \n")
.append("} \n");
scriptString.append("registerEvent(window, 'load', setAccordion"+accordionId+");");
scriptString.append("</script> \n");
setScriptString(scriptString.toString());
}
this.getChildren().add(new Text(getScriptString()));
} catch (Exception e) {
e.printStackTrace();
}
}
|
diff --git a/src/main/java/antidot/r2rml/main/R2RML.java b/src/main/java/antidot/r2rml/main/R2RML.java
index 1d50682..590a7db 100644
--- a/src/main/java/antidot/r2rml/main/R2RML.java
+++ b/src/main/java/antidot/r2rml/main/R2RML.java
@@ -1,276 +1,283 @@
/*
* Copyright 2011 Antidot [email protected]
* https://github.com/antidot/db2triples
*
* DB2Triples 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.
*
* DB2Triples 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/>.
*/
/**
*
* R2RML Main
*
* Interface between user and console.
*
* @author jhomo
*
*/
package antidot.r2rml.main;
import java.io.File;
import java.sql.Connection;
import java.sql.SQLException;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openrdf.rio.RDFFormat;
import antidot.r2rml.core.R2RMLMapper;
import antidot.rdf.impl.sesame.SesameDataSet;
import antidot.sql.core.SQLConnector;
@SuppressWarnings("static-access")
public class R2RML {
// Log
private static Log log = LogFactory.getLog(R2RML.class);
private static Option userNameOpt = OptionBuilder.withArgName("userName")
.hasArg().withDescription("Database user name").withLongOpt(
"userName").create("user");
private static Option passwordOpt = OptionBuilder.withArgName("password")
.hasArg().withDescription("Database password").withLongOpt(
"password").create("pass");
private static Option URLOpt = OptionBuilder.withArgName("URL").hasArg()
.withDescription(
"URL of database (default : jdbc:mysql://localhost/)")
.withLongOpt("URL").create("url");
private static Option driverOpt = OptionBuilder.withArgName("driver")
.hasArg().withDescription(
"Driver to use (default : com.mysql.jdbc.Driver)")
.withLongOpt("driver").create("driver");
private static Option dbOpt = OptionBuilder.withArgName("databaseName")
.hasArg().withDescription("database name").withLongOpt(
"databaseName").create("db");
private static Option forceOpt = new Option("f",
"Force loading of existing repository (without remove data)");
private static Option removeOpt = new Option("r",
"Force removing of old output file");
private static Option nativeOpt = new Option("n",
"Use native store (store in output directory path)");
private static Option nativeStoreNameOpt = OptionBuilder.withArgName(
"native_output").hasArg().withDescription(
"native store output directory").withLongOpt("nativeOutput")
.create("nativeout");
private static Option outputOpt = OptionBuilder.withArgName("output")
.hasArg().withDescription("output (default : output)").withLongOpt(
"output").create("out");
private static Option r2rmlFileOpt = OptionBuilder.withArgName("r2rml")
.hasArg().withDescription(
"r2ml instance").withLongOpt(
"r2rml").create("r2rml");
// Database settings
// private static String userName = "root";
// private static String password = "root";
// private static String url = "jdbc:mysql://localhost/";
// private static String driver = "com.mysql.jdbc.Driver";
public static void main(String[] args) {
// Get all options
Options options = new Options();
options.addOption(userNameOpt);
options.addOption(passwordOpt);
options.addOption(URLOpt);
options.addOption(driverOpt);
options.addOption(dbOpt);
options.addOption(forceOpt);
options.addOption(nativeOpt);
options.addOption(nativeStoreNameOpt);
options.addOption(outputOpt);
options.addOption(r2rmlFileOpt);
options.addOption(removeOpt);
// Init parameters
String userName = null;
String password = null;
String url = null;
String driver = null;
String dbName = null;
String r2rmlFile = null;
boolean useNativeStore = false;
boolean forceExistingRep = false;
boolean forceRemovingOld = false;
String nativeOutput = null;
String output = null;
// Option parsing
// Create the parser
CommandLineParser parser = new GnuParser();
try {
// parse the command line arguments
CommandLine line = parser.parse(options, args);
// Database settings
// user name
if (!line.hasOption("userName")) {
// automatically generate the help statement
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("R2RML", options);
System.exit(-1);
} else {
userName = line.getOptionValue("userName");
}
// password
if (!line.hasOption("password")) {
// automatically generate the help statement
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("R2RML", options);
System.exit(-1);
} else {
password = line.getOptionValue("password");
}
// Database URL
url = line.getOptionValue("URL", "jdbc:mysql://localhost/");
// driver
driver = line.getOptionValue("driver", "com.mysql.jdbc.Driver");
// Database name
if (!line.hasOption("databaseName")) {
// automatically generate the help statement
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("R2RML", options);
System.exit(-1);
} else {
dbName = line.getOptionValue("databaseName");
}
// r2rml instance
if (!line.hasOption("r2rml")) {
// automatically generate the help statement
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("R2RML", options);
System.exit(-1);
} else {
- File r2rmlFileTest = new File(r2rmlFile);
- if (!r2rmlFileTest.exists()){
- log.error("[R2RML:main] R2RML file does not exists.");
+ try
+ {
+ r2rmlFile = line.getOptionValue("r2rml");
+ File r2rmlFileTest = new File(r2rmlFile);
+ if (!r2rmlFileTest.exists()){
+ log.error("[R2RML:main] R2RML file does not exists.");
+ System.exit(-1);
+ }
+ }
+ catch(Exception e){
+ log.error(String.format("[R2RML:main] Error reading R2RML file '%0$s'.", r2rmlFile));
System.exit(-1);
}
- r2rmlFile = line.getOptionValue("r2rml");
}
// Use of native store ?
useNativeStore = line.hasOption("n");
// Name of native store
if (useNativeStore && !line.hasOption("nativeOutput")) {
// automatically generate the help statement
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("DirectMapping", options);
System.exit(-1);
} else {
nativeOutput = line.getOptionValue("nativeOutput");
}
// Force loading of repository
forceExistingRep = line.hasOption("f");
// Force removing of old output file
forceRemovingOld = line.hasOption("r");
// Output
output = line.getOptionValue("output", "output.n3");
} catch (ParseException exp) {
// oops, something went wrong
log.error("[DirectMapping:main] Parsing failed. Reason : "
+ exp.getMessage());
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("DirectMapping", options);
System.exit(-1);
}
// DB connection
Connection conn = null;
try {
conn = SQLConnector
.connect(userName, password, url, driver, dbName);
// Check nature of storage (memory by default)
if (useNativeStore) {
File pathToNativeOutputDir = new File(nativeOutput);
if (pathToNativeOutputDir.exists() && !forceExistingRep) {
if (log.isErrorEnabled())
log
.error("Directory "
+ pathToNativeOutputDir
+ " already exists. Use -f" +
" option to force loading of " +
"existing repository.");
}
R2RMLMapper.convertMySQLDatabase(conn,
r2rmlFile,
nativeOutput);
} else {
File outputFile = new File(output);
if (outputFile.exists() && !forceRemovingOld) {
if (log.isErrorEnabled())
log
.error("Output file "
+ outputFile.getAbsolutePath()
+ " already exists. Please remove it or " +
"modify ouput name option.");
System.exit(-1);
} else {
if (log.isInfoEnabled())
log
.info("Output file "
+ outputFile.getAbsolutePath()
+ " already exists. It will be removed" +
" during operation (option -r)..");
}
SesameDataSet sesameDataSet = R2RMLMapper.convertMySQLDatabase(
conn, r2rmlFile,
nativeOutput);
// Dump graph
sesameDataSet.dumpRDF(output, RDFFormat.N3);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// Close db connection
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
| false | true | public static void main(String[] args) {
// Get all options
Options options = new Options();
options.addOption(userNameOpt);
options.addOption(passwordOpt);
options.addOption(URLOpt);
options.addOption(driverOpt);
options.addOption(dbOpt);
options.addOption(forceOpt);
options.addOption(nativeOpt);
options.addOption(nativeStoreNameOpt);
options.addOption(outputOpt);
options.addOption(r2rmlFileOpt);
options.addOption(removeOpt);
// Init parameters
String userName = null;
String password = null;
String url = null;
String driver = null;
String dbName = null;
String r2rmlFile = null;
boolean useNativeStore = false;
boolean forceExistingRep = false;
boolean forceRemovingOld = false;
String nativeOutput = null;
String output = null;
// Option parsing
// Create the parser
CommandLineParser parser = new GnuParser();
try {
// parse the command line arguments
CommandLine line = parser.parse(options, args);
// Database settings
// user name
if (!line.hasOption("userName")) {
// automatically generate the help statement
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("R2RML", options);
System.exit(-1);
} else {
userName = line.getOptionValue("userName");
}
// password
if (!line.hasOption("password")) {
// automatically generate the help statement
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("R2RML", options);
System.exit(-1);
} else {
password = line.getOptionValue("password");
}
// Database URL
url = line.getOptionValue("URL", "jdbc:mysql://localhost/");
// driver
driver = line.getOptionValue("driver", "com.mysql.jdbc.Driver");
// Database name
if (!line.hasOption("databaseName")) {
// automatically generate the help statement
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("R2RML", options);
System.exit(-1);
} else {
dbName = line.getOptionValue("databaseName");
}
// r2rml instance
if (!line.hasOption("r2rml")) {
// automatically generate the help statement
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("R2RML", options);
System.exit(-1);
} else {
File r2rmlFileTest = new File(r2rmlFile);
if (!r2rmlFileTest.exists()){
log.error("[R2RML:main] R2RML file does not exists.");
System.exit(-1);
}
r2rmlFile = line.getOptionValue("r2rml");
}
// Use of native store ?
useNativeStore = line.hasOption("n");
// Name of native store
if (useNativeStore && !line.hasOption("nativeOutput")) {
// automatically generate the help statement
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("DirectMapping", options);
System.exit(-1);
} else {
nativeOutput = line.getOptionValue("nativeOutput");
}
// Force loading of repository
forceExistingRep = line.hasOption("f");
// Force removing of old output file
forceRemovingOld = line.hasOption("r");
// Output
output = line.getOptionValue("output", "output.n3");
} catch (ParseException exp) {
// oops, something went wrong
log.error("[DirectMapping:main] Parsing failed. Reason : "
+ exp.getMessage());
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("DirectMapping", options);
System.exit(-1);
}
// DB connection
Connection conn = null;
try {
conn = SQLConnector
.connect(userName, password, url, driver, dbName);
// Check nature of storage (memory by default)
if (useNativeStore) {
File pathToNativeOutputDir = new File(nativeOutput);
if (pathToNativeOutputDir.exists() && !forceExistingRep) {
if (log.isErrorEnabled())
log
.error("Directory "
+ pathToNativeOutputDir
+ " already exists. Use -f" +
" option to force loading of " +
"existing repository.");
}
R2RMLMapper.convertMySQLDatabase(conn,
r2rmlFile,
nativeOutput);
} else {
File outputFile = new File(output);
if (outputFile.exists() && !forceRemovingOld) {
if (log.isErrorEnabled())
log
.error("Output file "
+ outputFile.getAbsolutePath()
+ " already exists. Please remove it or " +
"modify ouput name option.");
System.exit(-1);
} else {
if (log.isInfoEnabled())
log
.info("Output file "
+ outputFile.getAbsolutePath()
+ " already exists. It will be removed" +
" during operation (option -r)..");
}
SesameDataSet sesameDataSet = R2RMLMapper.convertMySQLDatabase(
conn, r2rmlFile,
nativeOutput);
// Dump graph
sesameDataSet.dumpRDF(output, RDFFormat.N3);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// Close db connection
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
| public static void main(String[] args) {
// Get all options
Options options = new Options();
options.addOption(userNameOpt);
options.addOption(passwordOpt);
options.addOption(URLOpt);
options.addOption(driverOpt);
options.addOption(dbOpt);
options.addOption(forceOpt);
options.addOption(nativeOpt);
options.addOption(nativeStoreNameOpt);
options.addOption(outputOpt);
options.addOption(r2rmlFileOpt);
options.addOption(removeOpt);
// Init parameters
String userName = null;
String password = null;
String url = null;
String driver = null;
String dbName = null;
String r2rmlFile = null;
boolean useNativeStore = false;
boolean forceExistingRep = false;
boolean forceRemovingOld = false;
String nativeOutput = null;
String output = null;
// Option parsing
// Create the parser
CommandLineParser parser = new GnuParser();
try {
// parse the command line arguments
CommandLine line = parser.parse(options, args);
// Database settings
// user name
if (!line.hasOption("userName")) {
// automatically generate the help statement
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("R2RML", options);
System.exit(-1);
} else {
userName = line.getOptionValue("userName");
}
// password
if (!line.hasOption("password")) {
// automatically generate the help statement
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("R2RML", options);
System.exit(-1);
} else {
password = line.getOptionValue("password");
}
// Database URL
url = line.getOptionValue("URL", "jdbc:mysql://localhost/");
// driver
driver = line.getOptionValue("driver", "com.mysql.jdbc.Driver");
// Database name
if (!line.hasOption("databaseName")) {
// automatically generate the help statement
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("R2RML", options);
System.exit(-1);
} else {
dbName = line.getOptionValue("databaseName");
}
// r2rml instance
if (!line.hasOption("r2rml")) {
// automatically generate the help statement
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("R2RML", options);
System.exit(-1);
} else {
try
{
r2rmlFile = line.getOptionValue("r2rml");
File r2rmlFileTest = new File(r2rmlFile);
if (!r2rmlFileTest.exists()){
log.error("[R2RML:main] R2RML file does not exists.");
System.exit(-1);
}
}
catch(Exception e){
log.error(String.format("[R2RML:main] Error reading R2RML file '%0$s'.", r2rmlFile));
System.exit(-1);
}
}
// Use of native store ?
useNativeStore = line.hasOption("n");
// Name of native store
if (useNativeStore && !line.hasOption("nativeOutput")) {
// automatically generate the help statement
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("DirectMapping", options);
System.exit(-1);
} else {
nativeOutput = line.getOptionValue("nativeOutput");
}
// Force loading of repository
forceExistingRep = line.hasOption("f");
// Force removing of old output file
forceRemovingOld = line.hasOption("r");
// Output
output = line.getOptionValue("output", "output.n3");
} catch (ParseException exp) {
// oops, something went wrong
log.error("[DirectMapping:main] Parsing failed. Reason : "
+ exp.getMessage());
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("DirectMapping", options);
System.exit(-1);
}
// DB connection
Connection conn = null;
try {
conn = SQLConnector
.connect(userName, password, url, driver, dbName);
// Check nature of storage (memory by default)
if (useNativeStore) {
File pathToNativeOutputDir = new File(nativeOutput);
if (pathToNativeOutputDir.exists() && !forceExistingRep) {
if (log.isErrorEnabled())
log
.error("Directory "
+ pathToNativeOutputDir
+ " already exists. Use -f" +
" option to force loading of " +
"existing repository.");
}
R2RMLMapper.convertMySQLDatabase(conn,
r2rmlFile,
nativeOutput);
} else {
File outputFile = new File(output);
if (outputFile.exists() && !forceRemovingOld) {
if (log.isErrorEnabled())
log
.error("Output file "
+ outputFile.getAbsolutePath()
+ " already exists. Please remove it or " +
"modify ouput name option.");
System.exit(-1);
} else {
if (log.isInfoEnabled())
log
.info("Output file "
+ outputFile.getAbsolutePath()
+ " already exists. It will be removed" +
" during operation (option -r)..");
}
SesameDataSet sesameDataSet = R2RMLMapper.convertMySQLDatabase(
conn, r2rmlFile,
nativeOutput);
// Dump graph
sesameDataSet.dumpRDF(output, RDFFormat.N3);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
// Close db connection
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
|
diff --git a/kernel-impl/src/main/java/org/sakaiproject/util/impl/FormattedTextImpl.java b/kernel-impl/src/main/java/org/sakaiproject/util/impl/FormattedTextImpl.java
index 8fa6ee56..e1e327d0 100644
--- a/kernel-impl/src/main/java/org/sakaiproject/util/impl/FormattedTextImpl.java
+++ b/kernel-impl/src/main/java/org/sakaiproject/util/impl/FormattedTextImpl.java
@@ -1,1278 +1,1279 @@
/**********************************************************************************
* $URL$
* $Id$
***********************************************************************************
*
* Copyright (c) 2003, 2004, 2005, 2006, 2007, 2008 Sakai Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ECL-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.sakaiproject.util.impl;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URI;
import java.util.Stack;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.validator.routines.UrlValidator;
import org.w3c.dom.Element;
import org.owasp.validator.html.AntiSamy;
import org.owasp.validator.html.CleanResults;
import org.owasp.validator.html.Policy;
import org.owasp.validator.html.PolicyException;
import org.owasp.validator.html.ScanException;
import org.sakaiproject.component.api.ServerConfigurationService;
import org.sakaiproject.tool.api.Session;
import org.sakaiproject.tool.api.SessionManager;
import org.sakaiproject.util.Resource;
import org.sakaiproject.util.ResourceLoader;
import org.sakaiproject.util.Xml;
import org.sakaiproject.util.api.FormattedText;
/**
* FormattedText provides support for user entry of formatted text; the formatted text is HTML. This includes text formatting in user input such as bold, underline, and fonts.
*/
public class FormattedTextImpl implements FormattedText
{
/** Our log (commons). */
private static final Log M_log = LogFactory.getLog(FormattedTextImpl.class);
private ServerConfigurationService serverConfigurationService = null;
public void setServerConfigurationService(ServerConfigurationService serverConfigurationService) {
this.serverConfigurationService = serverConfigurationService;
}
private SessionManager sessionManager = null;
public void setSessionManager(SessionManager sessionManager) {
this.sessionManager = sessionManager;
}
/**
* This is the high level html cleaner object
*/
private AntiSamy antiSamyHigh = null;
/**
* This is the low level html cleaner object
*/
private AntiSamy antiSamyLow = null;
/* KNL-1075 - content.cleaner.errors.handling = none|logged|return|notify|display
* - none - errors are completely ignored and not even stored at all
* - logged - errors are output in the logs only
* - return - errors are returned to the tool (legacy behavior)
* - notify - user notified about errors using a non-blocking JS popup
* - display - errors are displayed to the user using the new and fancy JS popup
*/
private String errorsHandling = "notify"; // set this to the default
private boolean showErrorToUser = false;
private boolean showDetailedErrorToUser = false;
private boolean returnErrorToTool = false;
private boolean logErrors = false;
private final String DEFAULT_RESOURCECLASS = "org.sakaiproject.localization.util.ContentProperties";
protected final String DEFAULT_RESOURCEBUNDLE = "org.sakaiproject.localization.bundle.content.content";
private final String RESOURCECLASS = "resource.class.content";
protected final String RESOURCEBUNDLE = "resource.bundle.content";
public void init() {
boolean useLegacy = false;
if (serverConfigurationService != null) { // this keeps the tests from dying
useLegacy = serverConfigurationService.getBoolean("content.cleaner.use.legacy.html", useLegacy);
/* KNL-1075 - content.cleaner.errors.handling = none|logged|return|notify|display
* - none - errors are completely ignored and not even stored at all
* - logged - errors are output in the logs only
* - return - errors are returned to the tool (legacy behavior)
* - notify - user notified about errors using a non-blocking JS popup
* - display - errors are displayed to the user using the new and fancy JS popup
*/
errorsHandling = serverConfigurationService.getString("content.cleaner.errors.handling", errorsHandling);
// NONE is the case when the string is not matched as well
if ("logged".equalsIgnoreCase(errorsHandling)) {
logErrors = true;
} else if ("return".equalsIgnoreCase(errorsHandling)) {
returnErrorToTool = true;
} else if ("notify".equalsIgnoreCase(errorsHandling)) {
showErrorToUser = true;
} else if ("display".equalsIgnoreCase(errorsHandling)) {
showDetailedErrorToUser = true;
} else {
// probably the none case, but maybe also a case of invalid config....
if (!"none".equalsIgnoreCase(errorsHandling)) {
M_log.warn("FormattedText error handling option invalid: "+errorsHandling+", defaulting to 'none'");
}
}
// allow one extra option to control logging if desired
logErrors = serverConfigurationService.getBoolean("content.cleaner.errors.logged", logErrors);
M_log.info("FormattedText error handling: "+errorsHandling+
"; log errors=" + logErrors +
"; return to tool=" + returnErrorToTool +
"; notify user=" + showErrorToUser +
"; details to user=" + showDetailedErrorToUser);
}
if (useLegacy) {
M_log.error(
"**************************************************\n"
+"* -----------<<< WARNING >>>---------------- *\n"
+"* The LEGACY Sakai content scanner is no longer *\n"
+"* available. It has been deprecated and removed. *\n"
+"* Content scanning uses AntiSamy scanner now. *\n"
+"* https://jira.sakaiproject.org/browse/KNL-1127 *\n"
+"**************************************************\n"
);
}
/* INIT Antisamy
* added in support for antisamy html cleaner - KNL-1015
* https://www.owasp.org/index.php/Category:OWASP_AntiSamy_Project
*/
try {
ClassLoader current = FormattedTextImpl.class.getClassLoader();
URL lowPolicyURL = current.getResource("antisamy/low-security-policy.xml");
URL highPolicyURL = current.getResource("antisamy/high-security-policy.xml");
// Allow lookup of the policy files in sakai home - KNL-1047
String sakaiHomePath = getSakaiHomeDir();
File lowFile = new File(sakaiHomePath, "antisamy"+File.separator+"low-security-policy.xml");
if (lowFile.canRead()) {
lowPolicyURL = lowFile.toURI().toURL();
M_log.info("AntiSamy found override for low policy file at: "+lowPolicyURL);
}
File highFile = new File(sakaiHomePath, "antisamy"+File.separator+"high-security-policy.xml");
if (highFile.canRead()) {
highPolicyURL = highFile.toURI().toURL();
M_log.info("AntiSamy found override for high policy file at: "+highPolicyURL);
}
Policy policyHigh = Policy.getInstance(highPolicyURL);
antiSamyHigh = new AntiSamy(policyHigh);
Policy policyLow = Policy.getInstance(lowPolicyURL);
antiSamyLow = new AntiSamy(policyLow);
// TODO should we attempt to fallback to internal files if the parsing/init fails of external ones?
M_log.info("AntiSamy INIT default security level ("+(defaultLowSecurity()?"LOW":"high")+"), policy files: high="+highPolicyURL+", low="+lowPolicyURL);
} catch (Exception e) {
throw new IllegalStateException("Unable to startup the antisamy html code cleanup handler (cannot complete startup): " + e, e);
}
}
boolean defaultAddBlankTargetToLinks = true;
/**
* For TESTING
* Sets the default - if not set, this will be "true"
* @param addBlankTargetToLinks if we should add ' target="_blank" ' to all A tags which contain no target, false if they should not be touched
*/
void setDefaultAddBlankTargetToLinks(boolean addBlankTargetToLinks) {
this.defaultAddBlankTargetToLinks = addBlankTargetToLinks;
}
/**
* Asks SCS for the value of the "content.cleaner.add.blank.target", DEFAULT is true (match legacy)
* @return true if we should add ' target="_blank" ' to all A tags which contain no target, false if they should not be touched
*/
private boolean addBlankTargetToLinks() {
boolean add = defaultAddBlankTargetToLinks;
if (serverConfigurationService != null) { // this keeps the tests from dying
add = serverConfigurationService.getBoolean("content.cleaner.add.blank.target", defaultAddBlankTargetToLinks);
}
return add;
}
/**
* Asks SCS for the value of the "content.cleaner.default.low.security", DEFAULT is false
* @return true if low security is on be default for the scanner OR false to use high security scan (no unsafe embeds or objects)
*/
private boolean defaultLowSecurity() {
boolean defaultLowSecurity = false;
if (serverConfigurationService != null) { // this keeps the tests from dying
defaultLowSecurity = serverConfigurationService.getBoolean("content.cleaner.default.low.security", defaultLowSecurity);
}
return defaultLowSecurity;
}
public ResourceLoader getResourceLoader() {
String resourceClass = serverConfigurationService.getString(RESOURCECLASS, DEFAULT_RESOURCECLASS);
String resourceBundle = serverConfigurationService.getString(RESOURCEBUNDLE, DEFAULT_RESOURCEBUNDLE);
ResourceLoader loader = new Resource().getLoader(resourceClass, resourceBundle);
return loader;
}
/**
* @return the path to the sakai home directory on the server
*/
private String getSakaiHomeDir() {
String sakaiHome = ""; // current dir (should be tomcat home) - this failsafe should not be used
if (serverConfigurationService != null) { // this keeps the tests from dying
String sh = serverConfigurationService.getSakaiHomePath();
if (sh != null) {
sakaiHome = sh;
}
}
sakaiHome = new File(sakaiHome).getAbsolutePath(); // standardize
return sakaiHome;
}
/** Matches HTML-style line breaks like <br> */
private Pattern M_patternTagBr = Pattern.compile("<\\s*br\\s+?[^<>]*?>", Pattern.CASE_INSENSITIVE);
/** Matches any HTML-style tag, like <anything> */
private Pattern M_patternTag = Pattern.compile("<.*?>", Pattern.DOTALL);
/** Matches newlines */
private Pattern M_patternNewline = Pattern.compile("\\n");
/** Matches all anchor tags that have a target attribute. */
public final Pattern M_patternAnchorTagWithTarget = Pattern.compile("([<]a\\s[^<>]*?)target=[^<>\\s]*([^<>]*?)[>]",
Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
/** Matches all anchor tags that do not have a target attribute. */
public final Pattern M_patternAnchorTagWithOutTarget =
Pattern.compile("([<]a\\s)(?![^>]*target=)([^>]*?)[>]",
Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
/** Matches href attribute */
private Pattern M_patternHref = Pattern.compile("\\shref\\s*=\\s*(\".*?\"|'.*?')",
Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
private Pattern M_patternHrefTarget = Pattern.compile("\\starget\\s*=\\s*(\".*?\"|'.*?')",
Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
private Pattern M_patternHrefTitle = Pattern.compile("\\stitle\\s*=\\s*(\".*?\"|'.*?')",
Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
/* (non-Javadoc)
* @see org.sakaiproject.utils.impl.FormattedText#processFormattedText(java.lang.String, java.lang.StringBuffer)
*/
public String processFormattedText(final String strFromBrowser, StringBuffer errorMessages) {
StringBuilder sb = new StringBuilder(errorMessages.toString());
String fixed = processFormattedText(strFromBrowser, sb);
errorMessages.setLength(0);
errorMessages.append(sb.toString());
return fixed;
}
/* (non-Javadoc)
* @see org.sakaiproject.utils.impl.FormattedText#processFormattedText(java.lang.String, java.lang.StringBuilder)
*/
public String processFormattedText(final String strFromBrowser, StringBuilder errorMessages)
{
boolean checkForEvilTags = true;
boolean replaceWhitespaceTags = true;
return processFormattedText(strFromBrowser, errorMessages, null, checkForEvilTags, replaceWhitespaceTags, false);
}
/* (non-Javadoc)
* @see org.sakaiproject.util.api.FormattedText#processFormattedText(java.lang.String, java.lang.StringBuilder, org.sakaiproject.util.api.FormattedText.Level)
*/
public String processFormattedText(String strFromBrowser, StringBuilder errorMessages, Level level) {
boolean checkForEvilTags = true;
boolean replaceWhitespaceTags = true;
return processFormattedText(strFromBrowser, errorMessages, level, checkForEvilTags, replaceWhitespaceTags, false);
}
/* (non-Javadoc)
* @see org.sakaiproject.utils.impl.FormattedText#processFormattedText(java.lang.String, java.lang.StringBuilder, boolean)
*/
public String processFormattedText(final String strFromBrowser,
StringBuilder errorMessages, boolean useLegacySakaiCleaner) {
boolean checkForEvilTags = true;
boolean replaceWhitespaceTags = true;
return processFormattedText(strFromBrowser, errorMessages, null, checkForEvilTags,
replaceWhitespaceTags, useLegacySakaiCleaner);
}
/* (non-Javadoc)
* @see org.sakaiproject.utils.impl.FormattedText#processHtmlDocument(java.lang.String, java.lang.StringBuilder)
*/
public String processHtmlDocument(final String strFromBrowser, StringBuilder errorMessages)
{
return strFromBrowser;
}
/* (non-Javadoc)
* @see org.sakaiproject.utils.impl.FormattedText#processFormattedText(java.lang.String, java.lang.StringBuilder, boolean, boolean)
*/
public String processFormattedText(final String strFromBrowser, StringBuilder errorMessages, boolean checkForEvilTags,
boolean replaceWhitespaceTags)
{
return processFormattedText(strFromBrowser, errorMessages, null, checkForEvilTags, replaceWhitespaceTags, false);
}
/* (non-Javadoc)
* @see org.sakaiproject.util.api.FormattedText#processFormattedText(java.lang.String, java.lang.StringBuilder, org.sakaiproject.util.api.FormattedText.Level, boolean, boolean, boolean)
*/
public String processFormattedText(final String strFromBrowser, StringBuilder errorMessages, Level level,
boolean checkForEvilTags, boolean replaceWhitespaceTags, boolean doNotUseLegacySakaiCleaner) {
// KNL-1075: bypass the old error system and present our formatted text errors using growl notification
StringBuilder formattedTextErrors = new StringBuilder();
if (level == null || Level.DEFAULT.equals(level)) {
// Select the default policy as high or low - KNL-1015
level = defaultLowSecurity() ? Level.LOW : Level.HIGH; // default to system setting
} else if (Level.NONE.equals(level)) {
checkForEvilTags = false; // disable scan
}
String val = strFromBrowser;
if (val == null || val.length() == 0) {
return val;
}
try {
if (replaceWhitespaceTags) {
// normalize all variants of the "<br>" HTML tag to be "<br />\n"
val = M_patternTagBr.matcher(val).replaceAll("<br />");
// replace "<p>" with nothing. Replace "</p>" and "<p />" HTML tags with "<br />"
// val = val.replaceAll("<p>", "");
// val = val.replaceAll("</p>", "<br />\n");
// val = val.replaceAll("<p />", "<br />\n");
}
if (checkForEvilTags) {
// use the owasp antisamy processor
AntiSamy as = antiSamyHigh;
if (Level.LOW.equals(level)) {
as = antiSamyLow;
}
try {
CleanResults cr = as.scan(strFromBrowser);
if (cr.getNumberOfErrors() > 0) {
// TODO currently no way to get internationalized versions of error messages
- for (Object errorMsg : cr.getErrorMessages()) {
- formattedTextErrors.append(errorMsg.toString() + "<br/>");
+ for (String errorMsg : cr.getErrorMessages()) {
+ String i18nErrorMsg = new String(errorMsg.getBytes("ISO-8859-1"),"UTF8");
+ formattedTextErrors.append(i18nErrorMsg + "<br/>");
}
}
val = cr.getCleanHTML();
// now replace all the A tags WITHOUT a target with _blank (to match the old functionality)
if (addBlankTargetToLinks() && StringUtils.isNotBlank(val)) {
Matcher m = M_patternAnchorTagWithOutTarget.matcher(val);
if (m.find()) {
val = m.replaceAll("$1$2 target=\"_blank\">"); // adds a target to A tags without one
}
}
} catch (ScanException e) {
// this will match the legacy behavior
val = "";
M_log.warn("processFormattedText: Failure during scan of input html: " + e, e);
} catch (PolicyException e) {
// this is an unrecoverable failure
throw new RuntimeException("Unable to access the antiSamy policy file: "+e, e);
}
}
// deal with hardcoded empty space character from Firefox 1.5
if (val.equalsIgnoreCase(" ")) {
val = "";
}
} catch (Exception e) {
// We catch all exceptions here because doing so will usually give the user the
// opportunity to work around the issue, rather than causing a tool stack trace
M_log.warn("Unexpected error processing text", e);
formattedTextErrors.append(getResourceLoader().getString("unknown_error_markup") + "\n");
val = null;
}
// KNL-1075: re-do the way error messages are handled
if (formattedTextErrors.length() > 0) {
// allow one extra option to control logging in real time if desired
logErrors = serverConfigurationService.getBoolean("content.cleaner.errors.logged", logErrors);
if (showErrorToUser || showDetailedErrorToUser) {
Session session = sessionManager.getCurrentSession();
if (showDetailedErrorToUser) {
session.setAttribute("userWarning", formattedTextErrors.toString());
} else {
session.setAttribute("userWarning", getResourceLoader().getString("content_has_been_cleaned"));
}
} else if (logErrors && M_log.isInfoEnabled()) {
// KNL-1075 - Log errors if desired so they can be easily found
String user = "UNKNOWN";
try {
user = sessionManager.getCurrentSession().getUserEid();
} catch (Exception e) {
try {
user = "id="+sessionManager.getCurrentSessionUserId();
} catch (Exception e1) {
// nothing to do in this case
}
}
M_log.info("FormattedText Error: user=" + user + " : " + formattedTextErrors.toString()
+"\n -- processing input:\n"+strFromBrowser
+"\n -- resulting output:\n"+val
);
}
// KNL-1075 - Allows passing kernel tests and preserving legacy behavior
if (returnErrorToTool) {
errorMessages.append(formattedTextErrors);
}
}
return val;
}
/* (non-Javadoc)
* @see org.sakaiproject.utils.impl.FormattedText#escapeHtmlFormattedText(java.lang.String)
*/
public String escapeHtmlFormattedText(String value)
{
boolean supressNewlines = false;
return escapeHtmlFormattedText(value, supressNewlines);
}
/* (non-Javadoc)
* @see org.sakaiproject.utils.impl.FormattedText#escapeHtmlFormattedTextSupressNewlines(java.lang.String)
*/
public String escapeHtmlFormattedTextSupressNewlines(String value)
{
boolean supressNewlines = true;
return escapeHtmlFormattedText(value, supressNewlines);
}
/**
* Prepares the given HTML formatted text for output as part of an HTML document. Makes sure that links open up in a new window by setting 'target="_blank"' on anchor tags.
*
* @param value
* The formatted text to escape
* @param supressNewlines
* If true, remove newlines ("<br />") when escaping.
* @return The string to include in an HTML document.
*/
private String escapeHtmlFormattedText(String value, boolean supressNewlines)
{
if (value == null) return "";
if (value.length() == 0) return "";
if (supressNewlines)
{
// zap HTML line breaks ("<br />") into plain-old whitespace
value = M_patternTagBr.matcher(value).replaceAll(" ");
}
// make sure that links open up in a new window. This
// makes sure every anchor tag has a blank target.
// for example:
// <a href="http://www.microsoft.com">Microsoft</a>
// becomes:
// <a href="http://www.microsoft.com" target="_blank">Microsoft</a>
// removed for KNL-526
//value = M_patternAnchorTagWithTarget.matcher(value).replaceAll("$1$2>"); // strips out targets
//value = M_patternAnchorTag.matcher(value).replaceAll("$1$2$3 target=\"_blank\">"); // adds in blank targets
// added for KNL-526
if (addBlankTargetToLinks()) {
Matcher m = M_patternAnchorTagWithOutTarget.matcher(value);
if (m.find()) {
value = m.replaceAll("$1$2 target=\"_blank\">"); // adds a target to A tags without one
}
}
return value;
}
/* (non-Javadoc)
* @see org.sakaiproject.utils.impl.FormattedText#escapeHtmlFormattedTextarea(java.lang.String)
*/
public String escapeHtmlFormattedTextarea(String value)
{
return escapeHtml(value, false);
}
/* (non-Javadoc)
* @see org.sakaiproject.utils.impl.FormattedText#convertPlaintextToFormattedText(java.lang.String)
*/
public String convertPlaintextToFormattedText(String value)
{
return escapeHtml(value, true);
}
private final boolean LAZY_CONSTRUCTION = true;
/* (non-Javadoc)
* @see org.sakaiproject.util.api.FormattedText#escapeHtml(java.lang.String)
*/
public String escapeHtml(String value) {
return escapeHtml(value, true);
}
/* (non-Javadoc)
* @see org.sakaiproject.utils.impl.FormattedText#escapeHtml(java.lang.String, boolean)
*/
public String escapeHtml(String value, boolean escapeNewlines) {
/*
* Velocity tools depend on this returning empty string (and never null),
* they also depend on this handling a null input and converting it to null
*/
String val = "";
if (value != null && !"".equals(value)) {
val = StringEscapeUtils.escapeHtml(value);
if (escapeNewlines && val != null) {
val = val.replace("\n", "<br/>\n");
}
}
return val;
} // escapeHtml
/* (non-Javadoc)
* @see org.sakaiproject.utils.impl.FormattedText#encodeFormattedTextAttribute(org.w3c.dom.Element, java.lang.String, java.lang.String)
*/
public void encodeFormattedTextAttribute(Element element, String baseAttributeName, String value)
{
// store the formatted text in an attribute called baseAttributeName-html
Xml.encodeAttribute(element, baseAttributeName + "-html", value);
// Store the non-formatted (plaintext) version as well
Xml.encodeAttribute(element, baseAttributeName, convertFormattedTextToPlaintext(value));
}
/* (non-Javadoc)
* @see org.sakaiproject.utils.impl.FormattedText#encodeUnicode(java.lang.String)
*/
public String encodeUnicode(String value)
{
// TODO call method in each process routine
if (value == null) return "";
try
{
// lazily allocate the StringBuilder
// only if changes are actually made; otherwise
// just return the given string without changing it.
StringBuilder buf = (LAZY_CONSTRUCTION) ? null : new StringBuilder();
final int len = value.length();
for (int i = 0; i < len; i++)
{
char c = value.charAt(i);
if (c < 128)
{
if (buf != null) buf.append(c);
}
else
{
// escape higher Unicode characters using an
// HTML numeric character entity reference like "㴸"
if (buf == null) buf = new StringBuilder(value.substring(0, i));
buf.append("&#");
buf.append(Integer.toString((int) c));
buf.append(";");
}
} // for
return (buf == null) ? value : buf.toString();
}
catch (Exception e)
{
M_log.warn("Validator.escapeHtml: ", e);
return "";
}
}
/* (non-Javadoc)
* @see org.sakaiproject.utils.impl.FormattedText#unEscapeHtml(java.lang.String)
*/
public String unEscapeHtml(String value)
{
if (value == null || value.equals("")) return "";
value = value.replaceAll("<", "<");
value = value.replaceAll(">", ">");
value = value.replaceAll("&", "&");
value = value.replaceAll(""", "\"");
return value;
}
/* (non-Javadoc)
* @see org.sakaiproject.utils.impl.FormattedText#processAnchor(java.lang.String)
*/
public String processAnchor(String anchor) {
String newAnchor = "";
String href = null;
String hrefTarget = null;
String hrefTitle = null;
try {
// get HREF value
Matcher matcher = M_patternHref.matcher(anchor);
if (matcher.find()) {
href = matcher.group();
}
// get target value
matcher = M_patternHrefTarget.matcher(anchor);
if (matcher.find()) {
hrefTarget = matcher.group();
}
// get title value
matcher = M_patternHrefTitle.matcher(anchor);
if (matcher.find()) {
hrefTitle = matcher.group();
}
} catch (Exception e) {
M_log.warn("FormattedText.processAnchor ", e);
}
if (hrefTarget != null) {
// use the existing one
hrefTarget = hrefTarget.trim();
hrefTarget = hrefTarget.replaceAll("\"", ""); // slightly paranoid
hrefTarget = hrefTarget.replaceAll(">", ""); // slightly paranoid
hrefTarget = hrefTarget.replaceFirst("target=", ""); // slightly paranoid
hrefTarget = " target=\"" + hrefTarget + "\"";
} else {
// default to _blank if not set and configured to force
if (addBlankTargetToLinks()) {
hrefTarget = " target=\"_blank\"";
}
}
if (hrefTitle != null) {
// use the existing one
hrefTitle = hrefTitle.trim();
hrefTitle = hrefTitle.replaceAll("\"", ""); // slightly paranoid
hrefTitle = hrefTitle.replaceAll(">", ""); // slightly paranoid
hrefTitle = hrefTitle.replaceFirst("title=", ""); // slightly paranoid
hrefTitle = " title=\"" + hrefTitle + "\"";
}
// open in a new window
if (href != null) {
href = href.replaceAll("\"", "");
href = href.replaceAll(">", "");
href = href.replaceFirst("href=", "href=\"");
newAnchor = "<a " + href + "\"" + hrefTarget;
if (hrefTitle != null)
{
newAnchor += hrefTitle;
}
newAnchor += ">";
} else {
M_log.debug("FormattedText.processAnchor href == null");
newAnchor = anchor; // default to the original one so we don't lose the anchor
}
return newAnchor;
}
/* (non-Javadoc)
* @see org.sakaiproject.util.api.FormattedText#processEscapedHtml(java.lang.String)
*/
public String processEscapedHtml(final String source) {
if (source == null)
return "";
if (source.equals(""))
return "";
String html = null;
try {
// TODO call encodeUnicode in other process routine
html = encodeUnicode(source);
} catch (Exception e) {
M_log.warn("FormattedText.processEscapedHtml encodeUnicode(source):"+e, e);
}
try {
// to use the FormattedText functions
html = unEscapeHtml(html);
} catch (Exception e) {
M_log.warn("FormattedText.processEscapedHtml unEscapeHtml(Html):"+e, e);
}
return processFormattedText(html, new StringBuilder());
}
/* (non-Javadoc)
* @see org.sakaiproject.utils.impl.FormattedText#decodeFormattedTextAttribute(org.w3c.dom.Element, java.lang.String)
*/
public String decodeFormattedTextAttribute(Element element, String baseAttributeName)
{
String ret;
// first check if an HTML-encoded attribute exists, for example "foo-html", and use it if available
ret = StringUtils.trimToNull(Xml.decodeAttribute(element, baseAttributeName + "-html"));
if (ret != null) return ret;
// next try the older kind of formatted text like "foo-formatted", and convert it if found
ret = StringUtils.trimToNull(Xml.decodeAttribute(element, baseAttributeName + "-formatted"));
ret = convertOldFormattedText(ret);
if (ret != null) return ret;
// next try just a plaintext attribute and convert the plaintext to formatted text if found
// convert from old plaintext instructions to new formatted text instruction
ret = Xml.decodeAttribute(element, baseAttributeName);
ret = convertPlaintextToFormattedText(ret);
return ret;
}
/* (non-Javadoc)
* @see org.sakaiproject.utils.impl.FormattedText#convertFormattedTextToPlaintext(java.lang.String)
*/
public String convertFormattedTextToPlaintext(String value)
{
if (value == null) return null;
if (value.length() == 0) return "";
// strip out newlines
value = M_patternNewline.matcher(value).replaceAll("");
// convert "<br />" to newline
value = M_patternTagBr.matcher(value).replaceAll("\n");
// strip out all the HTML-style tags so that:
// <font face="verdana">Something</font> <b>Something else</b>
// becomes:
// Something Something else
value = M_patternTag.matcher(value).replaceAll("");
// Replace HTML character entity references (like >)
// with the plain Unicode characters to which they refer.
String ref;
char val;
for (int i = 0; i < M_htmlCharacterEntityReferences.length; i++)
{
ref = M_htmlCharacterEntityReferences[i];
if (value.indexOf(ref) >= 0)
{
val = M_htmlCharacterEntityReferencesUnicode[i];
// System.out.println("REPLACING "+ref+" WITH UNICODE CHARACTER #"+val+" WHICH IN JAVA IS "+Character.toString(val));
value = value.replaceAll(ref, Character.toString(val));
}
}
// Replace HTML numeric character entity references (like &#nnnn; or &#xnnnn;)
// with the plain Unicode characters to which they refer.
value = decodeNumericCharacterReferences(value);
return value;
}
/* (non-Javadoc)
* @see org.sakaiproject.utils.impl.FormattedText#convertOldFormattedText(java.lang.String)
*/
public String convertOldFormattedText(String value)
{
// previously, formatted text used "\n" to indicate a line break.
// now we use "<br />\n" as a line break. This code converts old
// formatted text to new formatted text.
if (value == null) return null;
if (value.length() == 0) return "";
value = M_patternNewline.matcher(value).replaceAll("<br />\n");
return value;
}
/* (non-Javadoc)
* @see org.sakaiproject.utils.impl.FormattedText#trimFormattedText(java.lang.String, int, java.lang.StringBuilder)
*/
public boolean trimFormattedText(String formattedText, final int maxNumOfChars, StringBuilder strTrimmed)
{
// This should return a formatted text substring which contains formatting, but which
// isn't broken in the middle of formatting, eg, "<strong>Hi there</stro" It also shouldn't
// break HTML character entities such as ">".
String str = formattedText;
strTrimmed.setLength(0);
strTrimmed.append(str);
if (str == null) return false;
int count = 0; // number of displayed characters seen so far
int pos = 0; // raw position within the formatted text string
int len = str.length();
Stack<String> tags = new Stack<String>(); // currently open tags (may need to be closed at the end)
while (pos < len && count < maxNumOfChars)
{
while (pos < len && str.charAt(pos) == '<')
{
// currently parsing a tag
pos++;
if (pos < len && str.charAt(pos) == '!')
{
// parsing an HTML comment
if (pos + 2 < len)
{
if (str.charAt(pos + 1) == '-' && str.charAt(pos + 2) == '-')
{
// skip past the close of the comment tag
int close = str.indexOf("-->", pos);
if (close != -1)
{
pos = close + 3;
continue;
}
}
}
}
if (pos < len && str.charAt(pos) == '/')
{
// currently parsing an closing tag
if (!tags.isEmpty()) tags.pop();
while (pos < len && str.charAt(pos) != '>')
pos++;
pos++;
continue;
}
// capture the name of the opening tag and put it on the stack of open tags
int taglen = 0;
String tag;
while (pos < len && str.charAt(pos) != '>' && !Character.isWhitespace(str.charAt(pos)))
{
pos++;
taglen++;
}
tag = str.substring(pos - taglen, pos);
tags.push(tag);
while (pos < len && str.charAt(pos) != '>')
pos++;
if (tag.length() == 0)
{
if (!tags.isEmpty()) tags.pop();
continue;
}
if (str.charAt(pos - 1) == '/') if (!tags.isEmpty()) tags.pop(); // singleton tag like "<br />" has no closing tag
if (tag.charAt(0) == '!') if (!tags.isEmpty()) tags.pop(); // comment tag like "<!-- comment -->", so just ignore it
if ("br".equalsIgnoreCase(tag)) if (!tags.isEmpty()) tags.pop();
if ("hr".equalsIgnoreCase(tag)) if (!tags.isEmpty()) tags.pop();
if ("meta".equalsIgnoreCase(tag)) if (!tags.isEmpty()) tags.pop();
if ("link".equalsIgnoreCase(tag)) if (!tags.isEmpty()) tags.pop();
pos++;
}
if (pos < len && str.charAt(pos) == '&')
{
// HTML character entity references, like ">"
// count this as one single character
while (pos < len && str.charAt(pos) != ';')
pos++;
}
if (pos < len)
{
count++;
pos++;
}
}
// close any unclosed tags
strTrimmed.setLength(0);
strTrimmed.append(str.substring(0, pos));
while (tags.size() > 0)
{
strTrimmed.append("</");
strTrimmed.append(tags.pop());
strTrimmed.append(">");
}
boolean didTrim = (count == maxNumOfChars);
return didTrim;
} // trimFormattedText()
/* (non-Javadoc)
* @see org.sakaiproject.utils.impl.FormattedText#decodeNumericCharacterReferences(java.lang.String)
*/
public String decodeNumericCharacterReferences(String value)
{
// lazily allocate StringBuilder only if needed
// buf is not null ONLY when a numeric character reference
// is found - otherwise, buf is not used at all
StringBuilder buf = null;
final int valuelength = value.length();
for (int i = 0; i < valuelength; i++)
{
if ((value.charAt(i) == '&' || value.charAt(i) == '^') && (i + 2 < valuelength)
&& (value.charAt(i + 1) == '#' || value.charAt(i + 1) == '^'))
{
int pos = i + 2;
boolean hex = false;
if ((value.charAt(pos) == 'x') || (value.charAt(pos) == 'X'))
{
pos++;
hex = true;
}
StringBuilder num = new StringBuilder(6);
while (pos < valuelength && value.charAt(pos) != ';' && value.charAt(pos) != '^')
{
num.append(value.charAt(pos));
pos++;
}
if (pos < valuelength)
{
try
{
int val = Integer.parseInt(num.toString(), (hex ? 16 : 10));
// Found an HTML numeric character reference!
if (buf == null)
{
buf = new StringBuilder();
buf.append(value.substring(0, i));
}
buf.append((char) val);
i = pos;
}
catch (Exception ignore)
{
if (buf != null) buf.append(value.charAt(i));
}
}
else
{
if (buf != null) buf.append(value.charAt(i));
}
}
else
{
if (buf != null) buf.append(value.charAt(i));
}
}
if (buf != null) value = buf.toString();
return value;
}
/* (non-Javadoc)
* @see org.sakaiproject.util.api.FormattedText#encodeUrlsAsHtml(java.lang.String)
*/
public String encodeUrlsAsHtml(String text) {
// MOVED FROM Web
Pattern p = Pattern.compile("(?<!href=['\"]{1})(((https?|s?ftp|ftps|file|smb|afp|nfs|(x-)?man|gopher|txmt)://|mailto:)[-:;@a-zA-Z0-9_.,~%+/?=&#]+(?<![.,?:]))");
Matcher m = p.matcher(text);
StringBuffer buf = new StringBuffer();
while(m.find()) {
String matchedUrl = m.group();
m.appendReplacement(buf, "<a href=\"" + unEscapeHtml(matchedUrl) + "\">$1</a>");
}
m.appendTail(buf);
return buf.toString();
}
public String escapeJavascript(String value) {
if (value == null || "".equals(value)) return "";
try
{
StringBuilder buf = new StringBuilder();
// prepend 'i' if first character is not a letter
if (!java.lang.Character.isLetter(value.charAt(0)))
{
buf.append("i");
}
// change non-alphanumeric characters to 'x'
for (int i = 0; i < value.length(); i++)
{
char c = value.charAt(i);
if (!java.lang.Character.isLetterOrDigit(c))
{
buf.append("x");
}
else
{
buf.append(c);
}
}
String rv = buf.toString();
return rv;
}
catch (Exception e)
{
M_log.warn("escapeJavascript: ", e);
return value;
}
}
/* (non-Javadoc)
* @see org.sakaiproject.util.api.FormattedText#escapeJsQuoted(java.lang.String)
*/
public String escapeJsQuoted(String value) {
return StringEscapeUtils.escapeJavaScript(value);
}
/** These characters are escaped when making a URL */
// protected static final String ESCAPE_URL = "#%?&='\"+ ";
// not '/' as that is assumed to be part of the path
protected static final String ESCAPE_URL = "$&+,:;=?@ '\"<>#%{}|\\^~[]`";
/**
* These can't be encoded in URLs safely even using %nn notation, so encode them using our own custom URL encoding
*/
protected static final String ESCAPE_URL_SPECIAL = "^?;";
public String escapeUrl(String id) {
if (id == null) return "";
id = id.trim();
try
{
// convert the string to bytes in UTF-8
byte[] bytes = id.getBytes("UTF-8");
StringBuilder buf = new StringBuilder();
for (int i = 0; i < bytes.length; i++)
{
byte b = bytes[i];
// escape ascii control characters, ascii high bits, specials
if (ESCAPE_URL_SPECIAL.indexOf((char) b) != -1)
{
buf.append("^^x"); // special funky way to encode bad URL characters
buf.append(toHex(b));
buf.append('^');
}
// 0x1F is the last control character
// 0x7F is DEL chatecter
// 0x80 is the start of the top of the 256bit set.
else if ((ESCAPE_URL.indexOf((char) b) != -1) || (b <= 0x1F) || (b == 0x7F) || (b >= 0x80))
{
buf.append("%");
buf.append(toHex(b));
}
else
{
buf.append((char) b);
}
}
String rv = buf.toString();
return rv;
}
catch (UnsupportedEncodingException e)
{
M_log.warn("Validator.escapeUrl: ", e);
return "";
}
}
/* (non-Javadoc)
* @see org.sakaiproject.util.api.FormattedText#validateURL(java.lang.String)
*/
private static final String PROTOCOL_PREFIX = "http:";
private static final String HOST_PREFIX = "http://127.0.0.1";
private static final String ABOUT_BLANK = "about:blank";
public boolean validateURL(String urlToValidate) {
if (StringUtils.isBlank(urlToValidate)) return false;
if ( ABOUT_BLANK.equals(urlToValidate) ) return true;
// Check if the url is "Escapable" - run through the URL-URI-URL gauntlet
String escapedURL = sanitizeHrefURL(urlToValidate);
if ( escapedURL == null ) return false;
// For a protocol-relative URL, we validate with protocol attached
// RFC 1808 Section 4
if ((urlToValidate.startsWith("//")) && (urlToValidate.indexOf("://") == -1))
{
urlToValidate = PROTOCOL_PREFIX + urlToValidate;
}
// For a site-relative URL, we validate with host name and protocol attached
// SAK-13787 SAK-23752
if ((urlToValidate.startsWith("/")) && (urlToValidate.indexOf("://") == -1))
{
urlToValidate = HOST_PREFIX + urlToValidate;
}
// Validate the url
UrlValidator urlValidator = new UrlValidator(UrlValidator.ALLOW_LOCAL_URLS);
return urlValidator.isValid(urlToValidate);
}
/* (non-Javadoc)
* @see org.sakaiproject.util.api.FormattedText#sanitizeHrefURL(java.lang.String)
*/
public String sanitizeHrefURL(String urlToSanitize) {
if ( urlToSanitize == null ) return null;
if (StringUtils.isBlank(urlToSanitize)) return null;
if ( ABOUT_BLANK.equals(urlToSanitize) ) return ABOUT_BLANK;
boolean trimProtocol = false;
boolean trimHost = false;
// For a protocol-relative URL, we validate with protocol attached
// RFC 1808 Section 4
if ((urlToSanitize.startsWith("//")) && (urlToSanitize.indexOf("://") == -1))
{
urlToSanitize = PROTOCOL_PREFIX + urlToSanitize;
trimProtocol = true;
}
// For a site-relative URL, we validate with host name and protocol attached
// SAK-13787 SAK-23752
if ((urlToSanitize.startsWith("/")) && (urlToSanitize.indexOf("://") == -1))
{
urlToSanitize = HOST_PREFIX + urlToSanitize;
trimHost = true;
}
// KNL-1105
try {
URL rawUrl = new URL(urlToSanitize);
URI uri = new URI(rawUrl.getProtocol(), rawUrl.getUserInfo(), rawUrl.getHost(),
rawUrl.getPort(), rawUrl.getPath(), rawUrl.getQuery(), rawUrl.getRef());
URL encoded = uri.toURL();
String retval = encoded.toString();
// Un-trim the added bits
if ( trimHost && retval.startsWith(HOST_PREFIX) )
{
retval = retval.substring(HOST_PREFIX.length());
}
if ( trimProtocol && retval.startsWith(PROTOCOL_PREFIX) )
{
retval = retval.substring(PROTOCOL_PREFIX.length());
}
// http://stackoverflow.com/questions/7731919/why-doesnt-uri-escape-escape-single-quotes
// We want these to be usable in JavaScript string values so we map single quotes
retval = retval.replace("'", "%27");
// We want anchors to work
retval = retval.replace("%23", "#");
// Sorry - these just need to come out - they cause to much trouble
// Note that ampersand is not encoded as it is used for parameters.
retval = retval.replace("&#", "");
retval = retval.replace("%25","%");
return retval;
} catch ( java.net.URISyntaxException e ) {
M_log.info("Failure during encode of href url: " + e);
return null;
} catch ( java.net.MalformedURLException e ) {
M_log.info("Failure during encode of href url: " + e);
return null;
}
}
// PRIVATE STUFF
/**
* Returns a hex representation of a byte.
*
* @param b
* The byte to convert to hex.
* @return The 2-digit hex value of the supplied byte.
*/
protected static final String toHex(byte b) {
char ret[] = new char[2];
ret[0] = hexDigit((b >>> 4) & (byte) 0x0F);
ret[1] = hexDigit((b >>> 0) & (byte) 0x0F);
return new String(ret);
}
/**
* Returns the hex digit corresponding to a number between 0 and 15.
*
* @param i
* The number to get the hex digit for.
* @return The hex digit corresponding to that number.
* @exception java.lang.IllegalArgumentException
* If supplied digit is not between 0 and 15 inclusive.
*/
protected static final char hexDigit(int i)
{
switch (i)
{
case 0:
return '0';
case 1:
return '1';
case 2:
return '2';
case 3:
return '3';
case 4:
return '4';
case 5:
return '5';
case 6:
return '6';
case 7:
return '7';
case 8:
return '8';
case 9:
return '9';
case 10:
return 'A';
case 11:
return 'B';
case 12:
return 'C';
case 13:
return 'D';
case 14:
return 'E';
case 15:
return 'F';
}
throw new IllegalArgumentException("Invalid digit:" + i);
}
/**
* HTML character entity references. These abbreviations are used in HTML to escape certain Unicode characters, including characters used in HTML markup. These character entity references were taken directly from the HTML 4.0 specification at:
*
* http://www.w3.org/TR/REC-html40/sgml/entities.html
*/
private final String[] M_htmlCharacterEntityReferences = { " ", "¡", "¢", "£", "¤",
"¥", "¦", "§", "¨", "©", "ª", "«", "¬", "­", "®", "¯", "°",
"±", "²", "³", "´", "µ", "¶", "·", "¸", "¹", "º", "»",
"¼", "½", "¾", "¿", "À", "Á", "Â", "Ã", "Ä", "Å",
"Æ", "Ç", "È", "É", "Ê", "Ë", "Ì", "Í", "Î", "Ï",
"Ð", "Ñ", "Ò", "Ó", "Ô", "Õ", "Ö", "×", "Ø", "Ù",
"Ú", "Û", "Ü", "Ý", "Þ", "ß", "à", "á", "â", "ã",
"ä", "å", "æ", "ç", "è", "é", "ê", "ë", "ì", "í",
"î", "ï", "ð", "ñ", "ò", "ó", "ô", "õ", "ö", "÷",
"ø", "ù", "ú", "û", "ü", "ý", "þ", "ÿ", "ƒ", "Α",
"Β", "Γ", "Δ", "&Epsilo;", "Ζ", "Η", "Θ", "Ι", "Κ", "Λ", "Μ",
"Ν", "Ξ", "&Omicro;", "Π", "Ρ", "Σ", "Τ", "&Upsilo;", "Φ", "Χ", "Ψ", "Ω",
"α", "β", "γ", "δ", "&epsilo;", "ζ", "η", "θ", "ι", "κ", "λ",
"μ", "ν", "ξ", "&omicro;", "π", "ρ", "ς", "σ", "τ", "&upsilo;", "φ", "χ",
"ψ", "ω", "&thetas;", "ϒ", "ϖ", "•", "…", "′", "″", "‾", "⁄",
"℘", "ℑ", "ℜ", "™", "&alefsy;", "←", "↑", "→", "↓", "↔", "↵",
"⇐", "⇑", "⇒", "⇓", "⇔", "∀", "∂", "∃", "∅", "∇", "∈",
"∉", "∋", "∏", "∑", "−", "∗", "√", "∝", "∞", "∠", "∧", "∨",
"∩", "∪", "∫", "∴", "∼", "≅", "≈", "≠", "≡", "≤", "≥", "⊂",
"⊃", "⊄", "⊆", "⊇", "⊕", "⊗", "⊥", "⋅", "⌈", "⌉", "⌊",
"⌋", "⟨", "⟩", "◊", "♠", "♣", "♥", "♦", """, "&", "<",
">", "Œ", "œ", "Š", "š", "Ÿ", "ˆ", "˜", " ", " ", " ",
"‌", "‍", "‎", "‏", "–", "—", "‘", "’", "‚", "“", "”",
"„", "†", "‡", "‰", "‹", "›", "€" };
/**
* These character entity references were taken directly from the HTML 4.0 specification at:
*
* http://www.w3.org/TR/REC-html40/sgml/entities.html
*/
private final char[] M_htmlCharacterEntityReferencesUnicode = { 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170,
171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194,
195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218,
219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242,
243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 402, 913, 914, 915, 916, 917, 918, 919, 920, 921, 922,
923, 924, 925, 926, 927, 928, 929, 931, 932, 933, 934, 935, 936, 937, 945, 946, 947, 948, 949, 950, 951, 952, 953, 954,
955, 956, 957, 958, 959, 960, 961, 962, 963, 964, 965, 966, 967, 968, 969, 977, 978, 982, 8226, 8230, 8242, 8243, 8254,
8260, 8472, 8465, 8476, 8482, 8501, 8592, 8593, 8594, 8595, 8596, 8629, 8656, 8657, 8658, 8659, 8660, 8704, 8706, 8707,
8709, 8711, 8712, 8713, 8715, 8719, 8721, 8722, 8727, 8730, 8733, 8734, 8736, 8743, 8744, 8745, 8746, 8747, 8756, 8764,
8773, 8776, 8800, 8801, 8804, 8805, 8834, 8835, 8836, 8838, 8839, 8853, 8855, 8869, 8901, 8968, 8969, 8970, 8971, 9001,
9002, 9674, 9824, 9827, 9829, 9830, 34, 38, 60, 62, 338, 339, 352, 353, 376, 710, 732, 8194, 8195, 8201, 8204, 8205,
8206, 8207, 8211, 8212, 8216, 8217, 8218, 8220, 8221, 8222, 8224, 8225, 8240, 8249, 8250, 8364 };
}
| true | true | public String processFormattedText(final String strFromBrowser, StringBuilder errorMessages, Level level,
boolean checkForEvilTags, boolean replaceWhitespaceTags, boolean doNotUseLegacySakaiCleaner) {
// KNL-1075: bypass the old error system and present our formatted text errors using growl notification
StringBuilder formattedTextErrors = new StringBuilder();
if (level == null || Level.DEFAULT.equals(level)) {
// Select the default policy as high or low - KNL-1015
level = defaultLowSecurity() ? Level.LOW : Level.HIGH; // default to system setting
} else if (Level.NONE.equals(level)) {
checkForEvilTags = false; // disable scan
}
String val = strFromBrowser;
if (val == null || val.length() == 0) {
return val;
}
try {
if (replaceWhitespaceTags) {
// normalize all variants of the "<br>" HTML tag to be "<br />\n"
val = M_patternTagBr.matcher(val).replaceAll("<br />");
// replace "<p>" with nothing. Replace "</p>" and "<p />" HTML tags with "<br />"
// val = val.replaceAll("<p>", "");
// val = val.replaceAll("</p>", "<br />\n");
// val = val.replaceAll("<p />", "<br />\n");
}
if (checkForEvilTags) {
// use the owasp antisamy processor
AntiSamy as = antiSamyHigh;
if (Level.LOW.equals(level)) {
as = antiSamyLow;
}
try {
CleanResults cr = as.scan(strFromBrowser);
if (cr.getNumberOfErrors() > 0) {
// TODO currently no way to get internationalized versions of error messages
for (Object errorMsg : cr.getErrorMessages()) {
formattedTextErrors.append(errorMsg.toString() + "<br/>");
}
}
val = cr.getCleanHTML();
// now replace all the A tags WITHOUT a target with _blank (to match the old functionality)
if (addBlankTargetToLinks() && StringUtils.isNotBlank(val)) {
Matcher m = M_patternAnchorTagWithOutTarget.matcher(val);
if (m.find()) {
val = m.replaceAll("$1$2 target=\"_blank\">"); // adds a target to A tags without one
}
}
} catch (ScanException e) {
// this will match the legacy behavior
val = "";
M_log.warn("processFormattedText: Failure during scan of input html: " + e, e);
} catch (PolicyException e) {
// this is an unrecoverable failure
throw new RuntimeException("Unable to access the antiSamy policy file: "+e, e);
}
}
// deal with hardcoded empty space character from Firefox 1.5
if (val.equalsIgnoreCase(" ")) {
val = "";
}
} catch (Exception e) {
// We catch all exceptions here because doing so will usually give the user the
// opportunity to work around the issue, rather than causing a tool stack trace
M_log.warn("Unexpected error processing text", e);
formattedTextErrors.append(getResourceLoader().getString("unknown_error_markup") + "\n");
val = null;
}
// KNL-1075: re-do the way error messages are handled
if (formattedTextErrors.length() > 0) {
// allow one extra option to control logging in real time if desired
logErrors = serverConfigurationService.getBoolean("content.cleaner.errors.logged", logErrors);
if (showErrorToUser || showDetailedErrorToUser) {
Session session = sessionManager.getCurrentSession();
if (showDetailedErrorToUser) {
session.setAttribute("userWarning", formattedTextErrors.toString());
} else {
session.setAttribute("userWarning", getResourceLoader().getString("content_has_been_cleaned"));
}
} else if (logErrors && M_log.isInfoEnabled()) {
// KNL-1075 - Log errors if desired so they can be easily found
String user = "UNKNOWN";
try {
user = sessionManager.getCurrentSession().getUserEid();
} catch (Exception e) {
try {
user = "id="+sessionManager.getCurrentSessionUserId();
} catch (Exception e1) {
// nothing to do in this case
}
}
M_log.info("FormattedText Error: user=" + user + " : " + formattedTextErrors.toString()
+"\n -- processing input:\n"+strFromBrowser
+"\n -- resulting output:\n"+val
);
}
// KNL-1075 - Allows passing kernel tests and preserving legacy behavior
if (returnErrorToTool) {
errorMessages.append(formattedTextErrors);
}
}
return val;
}
| public String processFormattedText(final String strFromBrowser, StringBuilder errorMessages, Level level,
boolean checkForEvilTags, boolean replaceWhitespaceTags, boolean doNotUseLegacySakaiCleaner) {
// KNL-1075: bypass the old error system and present our formatted text errors using growl notification
StringBuilder formattedTextErrors = new StringBuilder();
if (level == null || Level.DEFAULT.equals(level)) {
// Select the default policy as high or low - KNL-1015
level = defaultLowSecurity() ? Level.LOW : Level.HIGH; // default to system setting
} else if (Level.NONE.equals(level)) {
checkForEvilTags = false; // disable scan
}
String val = strFromBrowser;
if (val == null || val.length() == 0) {
return val;
}
try {
if (replaceWhitespaceTags) {
// normalize all variants of the "<br>" HTML tag to be "<br />\n"
val = M_patternTagBr.matcher(val).replaceAll("<br />");
// replace "<p>" with nothing. Replace "</p>" and "<p />" HTML tags with "<br />"
// val = val.replaceAll("<p>", "");
// val = val.replaceAll("</p>", "<br />\n");
// val = val.replaceAll("<p />", "<br />\n");
}
if (checkForEvilTags) {
// use the owasp antisamy processor
AntiSamy as = antiSamyHigh;
if (Level.LOW.equals(level)) {
as = antiSamyLow;
}
try {
CleanResults cr = as.scan(strFromBrowser);
if (cr.getNumberOfErrors() > 0) {
// TODO currently no way to get internationalized versions of error messages
for (String errorMsg : cr.getErrorMessages()) {
String i18nErrorMsg = new String(errorMsg.getBytes("ISO-8859-1"),"UTF8");
formattedTextErrors.append(i18nErrorMsg + "<br/>");
}
}
val = cr.getCleanHTML();
// now replace all the A tags WITHOUT a target with _blank (to match the old functionality)
if (addBlankTargetToLinks() && StringUtils.isNotBlank(val)) {
Matcher m = M_patternAnchorTagWithOutTarget.matcher(val);
if (m.find()) {
val = m.replaceAll("$1$2 target=\"_blank\">"); // adds a target to A tags without one
}
}
} catch (ScanException e) {
// this will match the legacy behavior
val = "";
M_log.warn("processFormattedText: Failure during scan of input html: " + e, e);
} catch (PolicyException e) {
// this is an unrecoverable failure
throw new RuntimeException("Unable to access the antiSamy policy file: "+e, e);
}
}
// deal with hardcoded empty space character from Firefox 1.5
if (val.equalsIgnoreCase(" ")) {
val = "";
}
} catch (Exception e) {
// We catch all exceptions here because doing so will usually give the user the
// opportunity to work around the issue, rather than causing a tool stack trace
M_log.warn("Unexpected error processing text", e);
formattedTextErrors.append(getResourceLoader().getString("unknown_error_markup") + "\n");
val = null;
}
// KNL-1075: re-do the way error messages are handled
if (formattedTextErrors.length() > 0) {
// allow one extra option to control logging in real time if desired
logErrors = serverConfigurationService.getBoolean("content.cleaner.errors.logged", logErrors);
if (showErrorToUser || showDetailedErrorToUser) {
Session session = sessionManager.getCurrentSession();
if (showDetailedErrorToUser) {
session.setAttribute("userWarning", formattedTextErrors.toString());
} else {
session.setAttribute("userWarning", getResourceLoader().getString("content_has_been_cleaned"));
}
} else if (logErrors && M_log.isInfoEnabled()) {
// KNL-1075 - Log errors if desired so they can be easily found
String user = "UNKNOWN";
try {
user = sessionManager.getCurrentSession().getUserEid();
} catch (Exception e) {
try {
user = "id="+sessionManager.getCurrentSessionUserId();
} catch (Exception e1) {
// nothing to do in this case
}
}
M_log.info("FormattedText Error: user=" + user + " : " + formattedTextErrors.toString()
+"\n -- processing input:\n"+strFromBrowser
+"\n -- resulting output:\n"+val
);
}
// KNL-1075 - Allows passing kernel tests and preserving legacy behavior
if (returnErrorToTool) {
errorMessages.append(formattedTextErrors);
}
}
return val;
}
|
diff --git a/src/openblocks/common/tileentity/TileEntityElevator.java b/src/openblocks/common/tileentity/TileEntityElevator.java
index c5d5355d..026b9ded 100644
--- a/src/openblocks/common/tileentity/TileEntityElevator.java
+++ b/src/openblocks/common/tileentity/TileEntityElevator.java
@@ -1,169 +1,169 @@
package openblocks.common.tileentity;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import net.minecraft.block.Block;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemDye;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.AxisAlignedBB;
import net.minecraftforge.common.ForgeDirection;
import openblocks.OpenBlocks;
import openblocks.OpenBlocks.Config;
import com.google.common.base.Preconditions;
public class TileEntityElevator extends OpenTileEntity {
/**
* How far a player must be looking in a direction to be teleported
*/
private static final float DIRECTION_MAGNITUDE = 0.95f;
private HashMap<String, Integer> cooldown = new HashMap<String, Integer>();
@Override
public void updateEntity() {
super.updateEntity();
if (!worldObj.isRemote) {
Iterator<Entry<String, Integer>> cooldownIter = cooldown.entrySet().iterator();
while (cooldownIter.hasNext()) {
Entry<String, Integer> entry = cooldownIter.next();
int less = entry.getValue() - 1;
entry.setValue(less);
if (less == 0) {
cooldownIter.remove();
}
}
@SuppressWarnings("unchecked")
List<EntityPlayer> playersInRange = worldObj.getEntitiesWithinAABB(EntityPlayer.class, AxisAlignedBB.getAABBPool().getAABB(xCoord, yCoord, zCoord, xCoord + 1, yCoord + 3, zCoord + 1));
if (playersInRange.size() > 0) {
ForgeDirection teleportDirection = ForgeDirection.UNKNOWN;
for (EntityPlayer player : playersInRange) {
if (cooldown.containsKey(player.username)) {
continue;
}
/*
* Don't activate when a player is flying around in
* creative, it's annoying
*/
if (player.capabilities.isCreativeMode
&& player.capabilities.isFlying) continue;
if (player.isSneaking()
&& player.ridingEntity == null
&& (!Config.elevatorBlockMustFaceDirection || player.getLookVec().yCoord < -DIRECTION_MAGNITUDE)) {
teleportDirection = ForgeDirection.DOWN;
/* player.isJumping doesn't seem to work server side ? */
} else if (player.posY > yCoord + 1.2
&& player.ridingEntity == null
&& (!Config.elevatorBlockMustFaceDirection || player.getLookVec().yCoord > DIRECTION_MAGNITUDE)) {
teleportDirection = ForgeDirection.UP;
}
if (teleportDirection != ForgeDirection.UNKNOWN) {
int level = findLevel(teleportDirection);
if (level != 0) {
- player.setPositionAndUpdate(player.posX, level + 1.1, player.posZ);
+ player.setPositionAndUpdate(xCoord + 0.5F, level + 1.1, zCoord + 0.5F);
worldObj.playSoundAtEntity(player, "openblocks:teleport", 1F, 1F);
addPlayerCooldownToTargetAndNeighbours(player, xCoord, level, zCoord);
}
}
}
}
}
}
private void addPlayerCooldownToTargetAndNeighbours(EntityPlayer player, int xCoord, int level, int zCoord) {
for (int x = xCoord - 1; x <= xCoord + 1; x++) {
for (int z = zCoord - 1; z <= zCoord + 1; z++) {
TileEntity targetTile = worldObj.getBlockTileEntity(x, level, z);
if (targetTile instanceof TileEntityElevator) {
((TileEntityElevator)targetTile).addPlayerCooldown(player);
}
}
}
}
private void addPlayerCooldown(EntityPlayer player) {
cooldown.put(player.username, 6);
}
private boolean isPassable(int x, int y, int z, boolean canStandHere) {
int blockId = worldObj.getBlockId(x, y, z);
if (canStandHere) {
return worldObj.isAirBlock(x, y, z)
|| Block.blocksList[blockId] == null
|| (OpenBlocks.Config.irregularBlocksArePassable && Block.blocksList[blockId].getCollisionBoundingBoxFromPool(worldObj, x, y, z) == null);
} else {
/* Ugly logic makes NC sad :( */
return !(blockId == 0
|| OpenBlocks.Config.elevatorMaxBlockPassCount == -1 || OpenBlocks.Config.elevatorIgnoreHalfBlocks
&& !Block.isNormalCube(blockId));
}
}
private int findLevel(ForgeDirection direction){
Preconditions.checkArgument(direction == ForgeDirection.UP || direction == ForgeDirection.DOWN,
"Must be either up or down... for now");
int blocksInTheWay = 0;
for (int y = 2; y <= Config.elevatorTravelDistance; y++) {
int yPos = yCoord + (y * direction.offsetY);
if (worldObj.blockExists(xCoord, yPos, zCoord)) {
int blockId = worldObj.getBlockId(xCoord, yPos, zCoord);
if (blockId == OpenBlocks.Config.blockElevatorId) {
TileEntity otherBlock = worldObj.getBlockTileEntity(xCoord, yPos, zCoord);
// Check that it is a drop block and that it has the same
// color index.
if (!(otherBlock instanceof TileEntityElevator)) continue;
if (((TileEntityElevator)otherBlock).getBlockMetadata() != this.getBlockMetadata()) continue;
if (isPassable(xCoord, yPos + 1, zCoord, true)
&& isPassable(xCoord, yPos + 2, zCoord, true)) { return yPos; }
return 0;
} else if (isPassable(xCoord, yPos, zCoord, false)
&& ++blocksInTheWay > OpenBlocks.Config.elevatorMaxBlockPassCount) { return 0; }
} else {
return 0;
}
}
return 0;
}
public boolean onActivated(EntityPlayer player) {
ItemStack stack = player.getHeldItem();
if (stack != null) {
Item item = stack.getItem();
if (item instanceof ItemDye) {
int dmg = stack.getItemDamage();
// temp hack, dont tell anyone.
if (dmg == 15) {
dmg = 0;
} else if (dmg == 0) {
dmg = 15;
}
worldObj.setBlockMetadataWithNotify(xCoord, yCoord, zCoord, dmg, 3);
worldObj.markBlockForRenderUpdate(xCoord, yCoord, zCoord);
return true;
}
}
return false; // Don't update the block and don't block placement if
// it's not dye we're using
}
@Override
protected void initialize() {}
}
| true | true | public void updateEntity() {
super.updateEntity();
if (!worldObj.isRemote) {
Iterator<Entry<String, Integer>> cooldownIter = cooldown.entrySet().iterator();
while (cooldownIter.hasNext()) {
Entry<String, Integer> entry = cooldownIter.next();
int less = entry.getValue() - 1;
entry.setValue(less);
if (less == 0) {
cooldownIter.remove();
}
}
@SuppressWarnings("unchecked")
List<EntityPlayer> playersInRange = worldObj.getEntitiesWithinAABB(EntityPlayer.class, AxisAlignedBB.getAABBPool().getAABB(xCoord, yCoord, zCoord, xCoord + 1, yCoord + 3, zCoord + 1));
if (playersInRange.size() > 0) {
ForgeDirection teleportDirection = ForgeDirection.UNKNOWN;
for (EntityPlayer player : playersInRange) {
if (cooldown.containsKey(player.username)) {
continue;
}
/*
* Don't activate when a player is flying around in
* creative, it's annoying
*/
if (player.capabilities.isCreativeMode
&& player.capabilities.isFlying) continue;
if (player.isSneaking()
&& player.ridingEntity == null
&& (!Config.elevatorBlockMustFaceDirection || player.getLookVec().yCoord < -DIRECTION_MAGNITUDE)) {
teleportDirection = ForgeDirection.DOWN;
/* player.isJumping doesn't seem to work server side ? */
} else if (player.posY > yCoord + 1.2
&& player.ridingEntity == null
&& (!Config.elevatorBlockMustFaceDirection || player.getLookVec().yCoord > DIRECTION_MAGNITUDE)) {
teleportDirection = ForgeDirection.UP;
}
if (teleportDirection != ForgeDirection.UNKNOWN) {
int level = findLevel(teleportDirection);
if (level != 0) {
player.setPositionAndUpdate(player.posX, level + 1.1, player.posZ);
worldObj.playSoundAtEntity(player, "openblocks:teleport", 1F, 1F);
addPlayerCooldownToTargetAndNeighbours(player, xCoord, level, zCoord);
}
}
}
}
}
}
| public void updateEntity() {
super.updateEntity();
if (!worldObj.isRemote) {
Iterator<Entry<String, Integer>> cooldownIter = cooldown.entrySet().iterator();
while (cooldownIter.hasNext()) {
Entry<String, Integer> entry = cooldownIter.next();
int less = entry.getValue() - 1;
entry.setValue(less);
if (less == 0) {
cooldownIter.remove();
}
}
@SuppressWarnings("unchecked")
List<EntityPlayer> playersInRange = worldObj.getEntitiesWithinAABB(EntityPlayer.class, AxisAlignedBB.getAABBPool().getAABB(xCoord, yCoord, zCoord, xCoord + 1, yCoord + 3, zCoord + 1));
if (playersInRange.size() > 0) {
ForgeDirection teleportDirection = ForgeDirection.UNKNOWN;
for (EntityPlayer player : playersInRange) {
if (cooldown.containsKey(player.username)) {
continue;
}
/*
* Don't activate when a player is flying around in
* creative, it's annoying
*/
if (player.capabilities.isCreativeMode
&& player.capabilities.isFlying) continue;
if (player.isSneaking()
&& player.ridingEntity == null
&& (!Config.elevatorBlockMustFaceDirection || player.getLookVec().yCoord < -DIRECTION_MAGNITUDE)) {
teleportDirection = ForgeDirection.DOWN;
/* player.isJumping doesn't seem to work server side ? */
} else if (player.posY > yCoord + 1.2
&& player.ridingEntity == null
&& (!Config.elevatorBlockMustFaceDirection || player.getLookVec().yCoord > DIRECTION_MAGNITUDE)) {
teleportDirection = ForgeDirection.UP;
}
if (teleportDirection != ForgeDirection.UNKNOWN) {
int level = findLevel(teleportDirection);
if (level != 0) {
player.setPositionAndUpdate(xCoord + 0.5F, level + 1.1, zCoord + 0.5F);
worldObj.playSoundAtEntity(player, "openblocks:teleport", 1F, 1F);
addPlayerCooldownToTargetAndNeighbours(player, xCoord, level, zCoord);
}
}
}
}
}
}
|
diff --git a/src/org/GreenTeaScript/GtTypeEnv.java b/src/org/GreenTeaScript/GtTypeEnv.java
index 2f02295..bdf3f47 100644
--- a/src/org/GreenTeaScript/GtTypeEnv.java
+++ b/src/org/GreenTeaScript/GtTypeEnv.java
@@ -1,244 +1,244 @@
// ***************************************************************************
// Copyright (c) 2013, JST/CREST DEOS project authors. 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.
//
// 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 HOLDER 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.
// **************************************************************************
//ifdef JAVA
package org.GreenTeaScript;
import java.util.ArrayList;
//endif VAJA
public final class GtTypeEnv extends GreenTeaUtils {
/*field*/public final GtParserContext Context;
/*field*/public final GtGenerator Generator;
/*field*/public GtNameSpace NameSpace;
/*field*/public ArrayList<GtVariableInfo> LocalStackList;
/*field*/public int StackTopIndex;
/*field*/public GtFunc Func;
/*field*/boolean FoundUncommonFunc;
/* for convinient short cut */
/*field*/public final GtType VoidType;
/*field*/public final GtType BooleanType;
/*field*/public final GtType IntType;
/*field*/public final GtType StringType;
/*field*/public final GtType VarType;
/*field*/public final GtType AnyType;
/*field*/public final GtType ArrayType;
/*field*/public final GtType FuncType;
GtTypeEnv/*constructor*/(GtNameSpace NameSpace) {
this.NameSpace = NameSpace;
this.Context = NameSpace.Context;
this.Generator = NameSpace.Context.Generator;
this.Func = null;
this.FoundUncommonFunc = false;
this.LocalStackList = new ArrayList<GtVariableInfo>();
this.StackTopIndex = 0;
this.VoidType = NameSpace.Context.VoidType;
this.BooleanType = NameSpace.Context.BooleanType;
this.IntType = NameSpace.Context.IntType;
this.StringType = NameSpace.Context.StringType;
this.VarType = NameSpace.Context.VarType;
this.AnyType = NameSpace.Context.AnyType;
this.ArrayType = NameSpace.Context.ArrayType;
this.FuncType = NameSpace.Context.FuncType;
}
public final boolean IsStrictMode() {
return this.Generator.IsStrictMode();
}
public final boolean IsTopLevel() {
return (this.Func == null);
}
public void AppendRecv(GtType RecvType) {
/*local*/String ThisName = this.Generator.GetRecvName();
this.AppendDeclaredVariable(0, RecvType, ThisName, null, null);
this.LocalStackList.get(this.StackTopIndex-1).NativeName = ThisName;
}
public GtVariableInfo AppendDeclaredVariable(int VarFlag, GtType Type, String Name, GtToken NameToken, Object InitValue) {
/*local*/GtVariableInfo VarInfo = new GtVariableInfo(VarFlag, Type, Name, this.StackTopIndex, NameToken, InitValue);
if(this.StackTopIndex < this.LocalStackList.size()) {
this.LocalStackList.set(this.StackTopIndex, VarInfo);
}
else {
this.LocalStackList.add(VarInfo);
}
this.StackTopIndex += 1;
return VarInfo;
}
public GtVariableInfo LookupDeclaredVariable(String Symbol) {
/*local*/int i = this.StackTopIndex - 1;
while(i >= 0) {
/*local*/GtVariableInfo VarInfo = this.LocalStackList.get(i);
if(VarInfo.Name.equals(Symbol)) {
return VarInfo;
}
i = i - 1;
}
return null;
}
public void PushBackStackIndex(int PushBackIndex) {
/*local*/int i = this.StackTopIndex - 1;
while(i >= PushBackIndex) {
/*local*/GtVariableInfo VarInfo = this.LocalStackList.get(i);
VarInfo.Check();
i = i - 1;
}
this.StackTopIndex = PushBackIndex;
}
public void CheckFunc(String FuncType, GtFunc Func, GtToken SourceToken) {
if(!this.FoundUncommonFunc && (!Func.Is(CommonFunc))) {
this.FoundUncommonFunc = true;
if(this.Func != null && this.Func.Is(CommonFunc)) {
this.NameSpace.Context.ReportError(WarningLevel, SourceToken, "using uncommon " + FuncType + ": " + Func.FuncName);
}
}
}
public final GtNode ReportTypeResult(GtSyntaxTree ParsedTree, GtNode Node, int Level, String Message) {
if(Level == ErrorLevel || (this.IsStrictMode() && Level == TypeErrorLevel)) {
LibGreenTea.Assert(Node.Token == ParsedTree.KeyToken);
this.NameSpace.Context.ReportError(ErrorLevel, Node.Token, Message);
return this.Generator.CreateErrorNode(this.VoidType, ParsedTree);
}
else {
this.NameSpace.Context.ReportError(Level, Node.Token, Message);
}
return Node;
}
public final void ReportTypeInference(GtToken SourceToken, String Name, GtType InfferedType) {
this.Context.ReportError(InfoLevel, SourceToken, Name + " has type " + InfferedType);
}
public final GtNode CreateSyntaxErrorNode(GtSyntaxTree ParsedTree, String Message) {
this.NameSpace.Context.ReportError(ErrorLevel, ParsedTree.KeyToken, Message);
return this.Generator.CreateErrorNode(this.VoidType, ParsedTree);
}
public final GtNode UnsupportedTopLevelError(GtSyntaxTree ParsedTree) {
return this.CreateSyntaxErrorNode(ParsedTree, "unsupported " + ParsedTree.Pattern.PatternName + " at the top level");
}
public final GtNode CreateLocalNode(GtSyntaxTree ParsedTree, String Name) {
/*local*/GtVariableInfo VariableInfo = this.LookupDeclaredVariable(Name);
if(VariableInfo != null) {
return this.Generator.CreateLocalNode(VariableInfo.Type, ParsedTree, VariableInfo.NativeName);
}
return this.CreateSyntaxErrorNode(ParsedTree, "unresolved name: " + Name + "; not your fault");
}
public final GtNode CreateDefaultValue(GtSyntaxTree ParsedTree, GtType Type) {
return this.Generator.CreateConstNode(Type, ParsedTree, Type.DefaultNullValue);
}
public final GtNode TypeCheckSingleNode(GtSyntaxTree ParsedTree, GtNode Node, GtType Type, int TypeCheckPolicy) {
LibGreenTea.Assert(Node != null);
if(Node.IsErrorNode() || IsFlag(TypeCheckPolicy, NoCheckPolicy)) {
return Node;
}
if(Node.Type.IsUnrevealedType()) {
/*local*/GtFunc Func = ParsedTree.NameSpace.GetConverterFunc(Node.Type, Node.Type.BaseType, true);
//System.err.println("found weaktype = " + Node.Type);
Node = this.Generator.CreateCoercionNode(Func.GetReturnType(), Func, Node);
}
//System.err.println("**** " + Node.getClass());
/*local*/Object ConstValue = Node.ToConstValue(IsFlag(TypeCheckPolicy, OnlyConstPolicy));
if(ConstValue != null && !(Node instanceof GtConstNode)) { // recreated
Node = this.Generator.CreateConstNode(Node.Type, ParsedTree, ConstValue);
}
if(IsFlag(TypeCheckPolicy, OnlyConstPolicy) && ConstValue == null) {
if(IsFlag(TypeCheckPolicy, NullablePolicy) && Node.IsNullNode()) { // OK
}
else {
return this.CreateSyntaxErrorNode(ParsedTree, "value must be const");
}
}
if(IsFlag(TypeCheckPolicy, AllowVoidPolicy) || Type == this.VoidType) {
return Node;
}
if(Node.Type == this.VarType) {
return this.ReportTypeResult(ParsedTree, Node, TypeErrorLevel, "unspecified type: " + Node.Token.ParsedText);
}
if(Node.Type == Type || Type == this.VarType || Node.Type.Accept(Type)) {
return Node;
}
/*local*/GtFunc Func = ParsedTree.NameSpace.GetConverterFunc(Node.Type, Type, true);
if(Func != null && (Func.Is(CoercionFunc) || IsFlag(TypeCheckPolicy, CastPolicy))) {
return this.Generator.CreateCoercionNode(Type, Func, Node);
}
- System.err.println("node="+Node.getClass()+ "type error: requested = " + Type + ", given = " + Node.Type);
+ System.err.println("node="+ LibGreenTea.GetClassName(Node) + "type error: requested = " + Type + ", given = " + Node.Type);
return this.ReportTypeResult(ParsedTree, Node, TypeErrorLevel, "type error: requested = " + Type + ", given = " + Node.Type);
}
}
class GtVariableInfo extends GreenTeaUtils {
/*field*/public int VariableFlag;
/*field*/public GtType Type;
/*field*/public String Name;
/*field*/public String NativeName;
/*field*/public GtToken NameToken;
/*field*/public Object InitValue;
/*field*/public int DefCount;
/*field*/public int UsedCount;
GtVariableInfo/*constructor*/(int VarFlag, GtType Type, String Name, int Index, GtToken NameToken, Object InitValue) {
this.VariableFlag = VarFlag;
this.Type = Type;
this.NameToken = NameToken;
this.Name = Name;
this.NativeName = (NameToken == null) ? Name : GreenTeaUtils.NativeVariableName(Name, Index);
this.InitValue = null;
this.UsedCount = 0;
this.DefCount = 1;
}
public final void Defined() {
this.DefCount += 1;
this.InitValue = null;
}
public final void Used() {
this.UsedCount += 1;
}
public void Check() {
if(this.UsedCount == 0 && this.NameToken != null) {
this.Type.Context.ReportError(WarningLevel, this.NameToken, "unused variable: " + this.Name);
}
}
// for debug
@Override public String toString() {
return "(" + this.Type + " " + this.Name + ", " + this.NativeName + ")";
}
}
| true | true | public final GtNode TypeCheckSingleNode(GtSyntaxTree ParsedTree, GtNode Node, GtType Type, int TypeCheckPolicy) {
LibGreenTea.Assert(Node != null);
if(Node.IsErrorNode() || IsFlag(TypeCheckPolicy, NoCheckPolicy)) {
return Node;
}
if(Node.Type.IsUnrevealedType()) {
/*local*/GtFunc Func = ParsedTree.NameSpace.GetConverterFunc(Node.Type, Node.Type.BaseType, true);
//System.err.println("found weaktype = " + Node.Type);
Node = this.Generator.CreateCoercionNode(Func.GetReturnType(), Func, Node);
}
//System.err.println("**** " + Node.getClass());
/*local*/Object ConstValue = Node.ToConstValue(IsFlag(TypeCheckPolicy, OnlyConstPolicy));
if(ConstValue != null && !(Node instanceof GtConstNode)) { // recreated
Node = this.Generator.CreateConstNode(Node.Type, ParsedTree, ConstValue);
}
if(IsFlag(TypeCheckPolicy, OnlyConstPolicy) && ConstValue == null) {
if(IsFlag(TypeCheckPolicy, NullablePolicy) && Node.IsNullNode()) { // OK
}
else {
return this.CreateSyntaxErrorNode(ParsedTree, "value must be const");
}
}
if(IsFlag(TypeCheckPolicy, AllowVoidPolicy) || Type == this.VoidType) {
return Node;
}
if(Node.Type == this.VarType) {
return this.ReportTypeResult(ParsedTree, Node, TypeErrorLevel, "unspecified type: " + Node.Token.ParsedText);
}
if(Node.Type == Type || Type == this.VarType || Node.Type.Accept(Type)) {
return Node;
}
/*local*/GtFunc Func = ParsedTree.NameSpace.GetConverterFunc(Node.Type, Type, true);
if(Func != null && (Func.Is(CoercionFunc) || IsFlag(TypeCheckPolicy, CastPolicy))) {
return this.Generator.CreateCoercionNode(Type, Func, Node);
}
System.err.println("node="+Node.getClass()+ "type error: requested = " + Type + ", given = " + Node.Type);
return this.ReportTypeResult(ParsedTree, Node, TypeErrorLevel, "type error: requested = " + Type + ", given = " + Node.Type);
}
| public final GtNode TypeCheckSingleNode(GtSyntaxTree ParsedTree, GtNode Node, GtType Type, int TypeCheckPolicy) {
LibGreenTea.Assert(Node != null);
if(Node.IsErrorNode() || IsFlag(TypeCheckPolicy, NoCheckPolicy)) {
return Node;
}
if(Node.Type.IsUnrevealedType()) {
/*local*/GtFunc Func = ParsedTree.NameSpace.GetConverterFunc(Node.Type, Node.Type.BaseType, true);
//System.err.println("found weaktype = " + Node.Type);
Node = this.Generator.CreateCoercionNode(Func.GetReturnType(), Func, Node);
}
//System.err.println("**** " + Node.getClass());
/*local*/Object ConstValue = Node.ToConstValue(IsFlag(TypeCheckPolicy, OnlyConstPolicy));
if(ConstValue != null && !(Node instanceof GtConstNode)) { // recreated
Node = this.Generator.CreateConstNode(Node.Type, ParsedTree, ConstValue);
}
if(IsFlag(TypeCheckPolicy, OnlyConstPolicy) && ConstValue == null) {
if(IsFlag(TypeCheckPolicy, NullablePolicy) && Node.IsNullNode()) { // OK
}
else {
return this.CreateSyntaxErrorNode(ParsedTree, "value must be const");
}
}
if(IsFlag(TypeCheckPolicy, AllowVoidPolicy) || Type == this.VoidType) {
return Node;
}
if(Node.Type == this.VarType) {
return this.ReportTypeResult(ParsedTree, Node, TypeErrorLevel, "unspecified type: " + Node.Token.ParsedText);
}
if(Node.Type == Type || Type == this.VarType || Node.Type.Accept(Type)) {
return Node;
}
/*local*/GtFunc Func = ParsedTree.NameSpace.GetConverterFunc(Node.Type, Type, true);
if(Func != null && (Func.Is(CoercionFunc) || IsFlag(TypeCheckPolicy, CastPolicy))) {
return this.Generator.CreateCoercionNode(Type, Func, Node);
}
System.err.println("node="+ LibGreenTea.GetClassName(Node) + "type error: requested = " + Type + ", given = " + Node.Type);
return this.ReportTypeResult(ParsedTree, Node, TypeErrorLevel, "type error: requested = " + Type + ", given = " + Node.Type);
}
|
diff --git a/src/ilmarse/mobile/activities/OrderDetailActivity.java b/src/ilmarse/mobile/activities/OrderDetailActivity.java
index b6e6238..2692c66 100644
--- a/src/ilmarse/mobile/activities/OrderDetailActivity.java
+++ b/src/ilmarse/mobile/activities/OrderDetailActivity.java
@@ -1,93 +1,94 @@
package ilmarse.mobile.activities;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
public class OrderDetailActivity extends Activity {
private String TAG = getClass().getSimpleName();
Bitmap bmImg;
ImageView imView;
// String orderid = ((OrderImpl)o).getId()+"";
// String username = ((OrderImpl)o).getUsername();
// String token = ((OrderImpl)o).getToken();
// String location = ((OrderImpl)o).getLocation();
// String created_date = ((OrderImpl)o).getCreated_date();
@Override
public void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.order_detail);
Log.d(TAG, "inside onCreate");
- String orderid = this.getIntent().getExtras().getString("catid");
+ String orderid = this.getIntent().getExtras().getString("order_id");
String username = this.getIntent().getExtras().getString("username");
String token = this.getIntent().getExtras().getString("token");
String location = this.getIntent().getExtras().getString("location");
String created_date = this.getIntent().getExtras()
.getString("created_date");
String status = this.getIntent().getExtras().getString("status");
System.out.println(" " + orderid + " " + status + " " + created_date
+ " " + location);
TextView orderidView;
TextView statusView;
TextView created_dateView;
String phoneLanguage = getResources().getConfiguration().locale
.getLanguage();
if (phoneLanguage.equals("en"))
setTitle("Order " + orderid);
else
setTitle("Orden " + orderid);
+ Log.d("asd1", String.valueOf(orderid));
orderidView = (TextView) findViewById(R.id.detail_orderid);
statusView = (TextView) findViewById(R.id.detail_orderstatus);
created_dateView = (TextView) findViewById(R.id.detail_created_date);
imView = (ImageView) findViewById(R.id.ordermap);
orderidView.setText(orderid);
statusView.setText(status);
created_dateView.setText(created_date);
downloadFile(location);
}
void downloadFile(String fileUrl) {
URL myFileUrl = null;
Log.d(TAG, fileUrl);
try {
myFileUrl = new URL(fileUrl);
Log.d(TAG, fileUrl);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
HttpURLConnection conn = (HttpURLConnection) myFileUrl
.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
imView.setImageBitmap(bmImg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| false | true | public void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.order_detail);
Log.d(TAG, "inside onCreate");
String orderid = this.getIntent().getExtras().getString("catid");
String username = this.getIntent().getExtras().getString("username");
String token = this.getIntent().getExtras().getString("token");
String location = this.getIntent().getExtras().getString("location");
String created_date = this.getIntent().getExtras()
.getString("created_date");
String status = this.getIntent().getExtras().getString("status");
System.out.println(" " + orderid + " " + status + " " + created_date
+ " " + location);
TextView orderidView;
TextView statusView;
TextView created_dateView;
String phoneLanguage = getResources().getConfiguration().locale
.getLanguage();
if (phoneLanguage.equals("en"))
setTitle("Order " + orderid);
else
setTitle("Orden " + orderid);
orderidView = (TextView) findViewById(R.id.detail_orderid);
statusView = (TextView) findViewById(R.id.detail_orderstatus);
created_dateView = (TextView) findViewById(R.id.detail_created_date);
imView = (ImageView) findViewById(R.id.ordermap);
orderidView.setText(orderid);
statusView.setText(status);
created_dateView.setText(created_date);
downloadFile(location);
}
| public void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.order_detail);
Log.d(TAG, "inside onCreate");
String orderid = this.getIntent().getExtras().getString("order_id");
String username = this.getIntent().getExtras().getString("username");
String token = this.getIntent().getExtras().getString("token");
String location = this.getIntent().getExtras().getString("location");
String created_date = this.getIntent().getExtras()
.getString("created_date");
String status = this.getIntent().getExtras().getString("status");
System.out.println(" " + orderid + " " + status + " " + created_date
+ " " + location);
TextView orderidView;
TextView statusView;
TextView created_dateView;
String phoneLanguage = getResources().getConfiguration().locale
.getLanguage();
if (phoneLanguage.equals("en"))
setTitle("Order " + orderid);
else
setTitle("Orden " + orderid);
Log.d("asd1", String.valueOf(orderid));
orderidView = (TextView) findViewById(R.id.detail_orderid);
statusView = (TextView) findViewById(R.id.detail_orderstatus);
created_dateView = (TextView) findViewById(R.id.detail_created_date);
imView = (ImageView) findViewById(R.id.ordermap);
orderidView.setText(orderid);
statusView.setText(status);
created_dateView.setText(created_date);
downloadFile(location);
}
|
diff --git a/FlexUnit4AntTasks/src/org/flexunit/ant/launcher/commands/player/CustomPlayerCommand.java b/FlexUnit4AntTasks/src/org/flexunit/ant/launcher/commands/player/CustomPlayerCommand.java
index 986df43..f3363b5 100644
--- a/FlexUnit4AntTasks/src/org/flexunit/ant/launcher/commands/player/CustomPlayerCommand.java
+++ b/FlexUnit4AntTasks/src/org/flexunit/ant/launcher/commands/player/CustomPlayerCommand.java
@@ -1,95 +1,96 @@
package org.flexunit.ant.launcher.commands.player;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Vector;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Execute;
import org.flexunit.ant.LoggingUtil;
public class CustomPlayerCommand implements PlayerCommand
{
private DefaultPlayerCommand proxiedCommand;
private File executable;
public PlayerCommand getProxiedCommand()
{
return proxiedCommand;
}
public void setProxiedCommand(DefaultPlayerCommand playerCommand)
{
this.proxiedCommand = playerCommand;
}
public File getExecutable()
{
return executable;
}
public void setExecutable(File executable)
{
this.executable = executable;
}
public void setProject(Project project)
{
proxiedCommand.setProject(project);
}
public void setSwf(File swf)
{
proxiedCommand.setSwf(swf);
}
public File getFileToExecute()
{
return proxiedCommand.getFileToExecute();
}
public void prepare()
{
proxiedCommand.prepare();
proxiedCommand.getCommandLine().setExecutable(executable.getAbsolutePath());
proxiedCommand.getCommandLine().clearArgs();
proxiedCommand.getCommandLine().addArguments(new String[]{getFileToExecute().getAbsolutePath()});
}
public Process launch() throws IOException
{
prepare();
LoggingUtil.log(proxiedCommand.getCommandLine().describeCommand());
- //execute the command directly using Runtime
- return Runtime.getRuntime().exec(
- proxiedCommand.getCommandLine().getCommandline(),
- getProcessEnvironment(),
- proxiedCommand.getProject().getBaseDir());
+ //execute the command directly
+ return Execute.launch(proxiedCommand.getProject(), proxiedCommand.getCommandLine().getCommandline(), getProcessEnvironment(), proxiedCommand.getProject().getBaseDir(), false);
+// return Runtime.getRuntime().exec(
+// proxiedCommand.getCommandLine().getCommandline(),
+// getProcessEnvironment(),
+// proxiedCommand.getProject().getBaseDir());
}
public void setEnvironment(String[] variables)
{
proxiedCommand.setEnvironment(variables);
}
/**
* Combine process environment variables and command's environment to emulate the default
* behavior of the Execute task. Needed especially when using Xvnc with a custom command.
*/
@SuppressWarnings("unchecked")
private String[] getProcessEnvironment()
{
Vector procEnvironment = Execute.getProcEnvironment();
String[] environment = new String[procEnvironment.size() + proxiedCommand.getEnvironment().length];
System.arraycopy(procEnvironment.toArray(), 0, environment, 0, procEnvironment.size());
System.arraycopy(proxiedCommand.getEnvironment(), 0, environment, procEnvironment.size(), proxiedCommand.getEnvironment().length);
LoggingUtil.log("Environment variables: " + Arrays.toString(environment));
return environment;
}
}
| true | true | public Process launch() throws IOException
{
prepare();
LoggingUtil.log(proxiedCommand.getCommandLine().describeCommand());
//execute the command directly using Runtime
return Runtime.getRuntime().exec(
proxiedCommand.getCommandLine().getCommandline(),
getProcessEnvironment(),
proxiedCommand.getProject().getBaseDir());
}
| public Process launch() throws IOException
{
prepare();
LoggingUtil.log(proxiedCommand.getCommandLine().describeCommand());
//execute the command directly
return Execute.launch(proxiedCommand.getProject(), proxiedCommand.getCommandLine().getCommandline(), getProcessEnvironment(), proxiedCommand.getProject().getBaseDir(), false);
// return Runtime.getRuntime().exec(
// proxiedCommand.getCommandLine().getCommandline(),
// getProcessEnvironment(),
// proxiedCommand.getProject().getBaseDir());
}
|
diff --git a/CubicTestPlugin/src/main/java/org/cubictest/ui/gef/dnd/DataEditDropTargetListner.java b/CubicTestPlugin/src/main/java/org/cubictest/ui/gef/dnd/DataEditDropTargetListner.java
index 8e62608b..66a9513d 100644
--- a/CubicTestPlugin/src/main/java/org/cubictest/ui/gef/dnd/DataEditDropTargetListner.java
+++ b/CubicTestPlugin/src/main/java/org/cubictest/ui/gef/dnd/DataEditDropTargetListner.java
@@ -1,46 +1,49 @@
/*
* Created on 28.may.2005
*
* This software is licensed under the terms of the GNU GENERAL PUBLIC LICENSE
* Version 2, which can be found at http://www.gnu.org/copyleft/gpl.html
*
*/
package org.cubictest.ui.gef.dnd;
import org.cubictest.ui.gef.factory.DataCreationFactory;
import org.eclipse.core.resources.IProject;
import org.eclipse.gef.EditPartViewer;
import org.eclipse.gef.dnd.TemplateTransferDropTargetListener;
import org.eclipse.gef.requests.CreationFactory;
/**
* @author SK Skytteren
*
* Enables drag and drop in the figure.
*/
public class DataEditDropTargetListner extends TemplateTransferDropTargetListener{
/**
* The constructor for the <code>DataEditDropTargetListner</code>.
* Uses only the <code>TemplateTransferDropTargetListener</code>'s constructor.
* @param project
* @param viewer
*/
public DataEditDropTargetListner(IProject project, EditPartViewer viewer) {
super(viewer);
}
/* (non-Javadoc)
* @see org.eclipse.gef.dnd.TemplateTransferDropTargetListener#getFactory(java.lang.Object)
*/
protected CreationFactory getFactory(Object template) {
// if(template instanceof CustomPageElement) {
// return new CustomPageElementCreationFactory(project, ((
// CustomPageElement)template).getName());
// } else {
+ if (template instanceof DataCreationFactory) {
+ return (DataCreationFactory) template;
+ }
return new DataCreationFactory(template);
// }
}
}
| true | true | protected CreationFactory getFactory(Object template) {
// if(template instanceof CustomPageElement) {
// return new CustomPageElementCreationFactory(project, ((
// CustomPageElement)template).getName());
// } else {
return new DataCreationFactory(template);
// }
}
| protected CreationFactory getFactory(Object template) {
// if(template instanceof CustomPageElement) {
// return new CustomPageElementCreationFactory(project, ((
// CustomPageElement)template).getName());
// } else {
if (template instanceof DataCreationFactory) {
return (DataCreationFactory) template;
}
return new DataCreationFactory(template);
// }
}
|
diff --git a/working-capital/src/module/workingCapital/domain/EmailDigesterUtil.java b/working-capital/src/module/workingCapital/domain/EmailDigesterUtil.java
index 2f0e4164..972739cd 100644
--- a/working-capital/src/module/workingCapital/domain/EmailDigesterUtil.java
+++ b/working-capital/src/module/workingCapital/domain/EmailDigesterUtil.java
@@ -1,142 +1,142 @@
package module.workingCapital.domain;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import myorg.applicationTier.Authenticate;
import myorg.applicationTier.Authenticate.UserView;
import myorg.domain.User;
import org.joda.time.LocalDate;
import pt.ist.emailNotifier.domain.Email;
import pt.ist.expenditureTrackingSystem.domain.ExpenditureTrackingSystem;
import pt.ist.expenditureTrackingSystem.domain.Role;
import pt.ist.expenditureTrackingSystem.domain.RoleType;
import pt.ist.expenditureTrackingSystem.domain.authorizations.Authorization;
import pt.ist.expenditureTrackingSystem.domain.organization.AccountingUnit;
import pt.ist.expenditureTrackingSystem.domain.organization.Person;
import pt.ist.fenixframework.plugins.remote.domain.exception.RemoteException;
import pt.utl.ist.fenix.tools.util.i18n.Language;
public class EmailDigesterUtil {
public static void executeTask() {
Language.setLocale(Language.getDefaultLocale());
for (Person person : getPeopleToProcess()) {
final User user = person.getUser();
if (user.hasPerson() && user.hasExpenditurePerson()) {
final UserView userView = Authenticate.authenticate(user);
pt.ist.fenixWebFramework.security.UserView.setUser(userView);
try {
final WorkingCapitalYear workingCapitalYear = WorkingCapitalYear.getCurrentYear();
final int takenByUser = workingCapitalYear.getTaken().size();
final int pendingApprovalCount = workingCapitalYear.getPendingAproval().size();
final int pendingVerificationnCount = workingCapitalYear.getPendingVerification().size();
final int pendingAuthorizationCount = workingCapitalYear.getPendingAuthorization().size();
final int pendingPaymentCount = workingCapitalYear.getPendingPayment().size();
final int totalPending = takenByUser + pendingApprovalCount + pendingVerificationnCount + pendingAuthorizationCount + pendingPaymentCount;
if (totalPending > 0) {
try {
final String email = person.getEmail();
if (email != null) {
final StringBuilder body = new StringBuilder("Caro utilizador, possui processos de fundos de maneio pendentes nas aplicações centrais do IST, em http://dot.ist.utl.pt/.\n");
if (takenByUser > 0) {
body.append("\n\tPendentes de Libertação\t");
body.append(takenByUser);
}
if (pendingApprovalCount > 0) {
body.append("\n\tPendentes de Aprovação\t");
body.append(pendingApprovalCount);
}
if (pendingVerificationnCount > 0) {
body.append("\n\tPendentes de Verificação\t");
body.append(pendingVerificationnCount);
}
if (pendingAuthorizationCount > 0) {
body.append("\n\tPendentes de Autorização\t");
body.append(pendingAuthorizationCount);
}
if (pendingPaymentCount > 0) {
body.append("\n\tPendentes de Pagamento\t");
body.append(pendingPaymentCount);
}
- body.append("\n\n\tTotal de Processos de Missão Pendentes\t");
+ body.append("\n\n\tTotal de Processos de Fundos de Maneio Pendentes\t");
body.append(totalPending);
body.append("\n\n---\n");
body.append("Esta mensagem foi enviada por meio das Aplicações Centrais do IST.\n");
final Collection<String> toAddress = Collections.singleton(email);
new Email("Aplicações Centrais do IST", "[email protected]", new String[] {}, toAddress, Collections.EMPTY_LIST,
Collections.EMPTY_LIST, "Processos Pendentes - Fundos de Maneio", body.toString());
}
} catch (final RemoteException ex) {
System.out.println("Unable to lookup email address for: " + person.getUsername());
// skip this person... keep going to next.
}
}
} finally {
pt.ist.fenixWebFramework.security.UserView.setUser(null);
}
}
}
}
private static Collection<Person> getPeopleToProcess() {
final Set<Person> people = new HashSet<Person>();
final LocalDate today = new LocalDate();
final ExpenditureTrackingSystem instance = ExpenditureTrackingSystem.getInstance();
for (final Authorization authorization : instance.getAuthorizationsSet()) {
if (authorization.isValidFor(today)) {
final Person person = authorization.getPerson();
if (person.getOptions().getReceiveNotificationsByEmail()) {
people.add(person);
}
}
}
for (final RoleType roleType : RoleType.values()) {
addPeopleWithRole(people, roleType);
}
for (final AccountingUnit accountingUnit : instance.getAccountingUnitsSet()) {
addPeople(people, accountingUnit.getPeopleSet());
addPeople(people, accountingUnit.getProjectAccountantsSet());
addPeople(people, accountingUnit.getResponsiblePeopleSet());
addPeople(people, accountingUnit.getResponsibleProjectAccountantsSet());
addPeople(people, accountingUnit.getTreasuryMembersSet());
}
final WorkingCapitalYear workingCapitalYear = WorkingCapitalYear.getCurrentYear();
for (final WorkingCapital workingCapital : workingCapitalYear.getWorkingCapitalsSet()) {
final module.organization.domain.Person movementResponsible = workingCapital.getMovementResponsible();
if (movementResponsible.hasUser()) {
final User user = movementResponsible.getUser();
if (user.hasExpenditurePerson()) {
final Person person = user.getExpenditurePerson();
if (person.getOptions().getReceiveNotificationsByEmail()) {
people.add(person);
}
}
}
}
return people;
}
private static void addPeopleWithRole(final Set<Person> people, final RoleType roleType) {
final Role role = Role.getRole(roleType);
addPeople(people, role.getPersonSet());
}
private static void addPeople(final Set<Person> people, Collection<Person> unverified) {
for (final Person person : unverified) {
if (person.getOptions().getReceiveNotificationsByEmail()) {
people.add(person);
}
}
}
}
| true | true | public static void executeTask() {
Language.setLocale(Language.getDefaultLocale());
for (Person person : getPeopleToProcess()) {
final User user = person.getUser();
if (user.hasPerson() && user.hasExpenditurePerson()) {
final UserView userView = Authenticate.authenticate(user);
pt.ist.fenixWebFramework.security.UserView.setUser(userView);
try {
final WorkingCapitalYear workingCapitalYear = WorkingCapitalYear.getCurrentYear();
final int takenByUser = workingCapitalYear.getTaken().size();
final int pendingApprovalCount = workingCapitalYear.getPendingAproval().size();
final int pendingVerificationnCount = workingCapitalYear.getPendingVerification().size();
final int pendingAuthorizationCount = workingCapitalYear.getPendingAuthorization().size();
final int pendingPaymentCount = workingCapitalYear.getPendingPayment().size();
final int totalPending = takenByUser + pendingApprovalCount + pendingVerificationnCount + pendingAuthorizationCount + pendingPaymentCount;
if (totalPending > 0) {
try {
final String email = person.getEmail();
if (email != null) {
final StringBuilder body = new StringBuilder("Caro utilizador, possui processos de fundos de maneio pendentes nas aplicações centrais do IST, em http://dot.ist.utl.pt/.\n");
if (takenByUser > 0) {
body.append("\n\tPendentes de Libertação\t");
body.append(takenByUser);
}
if (pendingApprovalCount > 0) {
body.append("\n\tPendentes de Aprovação\t");
body.append(pendingApprovalCount);
}
if (pendingVerificationnCount > 0) {
body.append("\n\tPendentes de Verificação\t");
body.append(pendingVerificationnCount);
}
if (pendingAuthorizationCount > 0) {
body.append("\n\tPendentes de Autorização\t");
body.append(pendingAuthorizationCount);
}
if (pendingPaymentCount > 0) {
body.append("\n\tPendentes de Pagamento\t");
body.append(pendingPaymentCount);
}
body.append("\n\n\tTotal de Processos de Missão Pendentes\t");
body.append(totalPending);
body.append("\n\n---\n");
body.append("Esta mensagem foi enviada por meio das Aplicações Centrais do IST.\n");
final Collection<String> toAddress = Collections.singleton(email);
new Email("Aplicações Centrais do IST", "[email protected]", new String[] {}, toAddress, Collections.EMPTY_LIST,
Collections.EMPTY_LIST, "Processos Pendentes - Fundos de Maneio", body.toString());
}
} catch (final RemoteException ex) {
System.out.println("Unable to lookup email address for: " + person.getUsername());
// skip this person... keep going to next.
}
}
} finally {
pt.ist.fenixWebFramework.security.UserView.setUser(null);
}
}
}
}
| public static void executeTask() {
Language.setLocale(Language.getDefaultLocale());
for (Person person : getPeopleToProcess()) {
final User user = person.getUser();
if (user.hasPerson() && user.hasExpenditurePerson()) {
final UserView userView = Authenticate.authenticate(user);
pt.ist.fenixWebFramework.security.UserView.setUser(userView);
try {
final WorkingCapitalYear workingCapitalYear = WorkingCapitalYear.getCurrentYear();
final int takenByUser = workingCapitalYear.getTaken().size();
final int pendingApprovalCount = workingCapitalYear.getPendingAproval().size();
final int pendingVerificationnCount = workingCapitalYear.getPendingVerification().size();
final int pendingAuthorizationCount = workingCapitalYear.getPendingAuthorization().size();
final int pendingPaymentCount = workingCapitalYear.getPendingPayment().size();
final int totalPending = takenByUser + pendingApprovalCount + pendingVerificationnCount + pendingAuthorizationCount + pendingPaymentCount;
if (totalPending > 0) {
try {
final String email = person.getEmail();
if (email != null) {
final StringBuilder body = new StringBuilder("Caro utilizador, possui processos de fundos de maneio pendentes nas aplicações centrais do IST, em http://dot.ist.utl.pt/.\n");
if (takenByUser > 0) {
body.append("\n\tPendentes de Libertação\t");
body.append(takenByUser);
}
if (pendingApprovalCount > 0) {
body.append("\n\tPendentes de Aprovação\t");
body.append(pendingApprovalCount);
}
if (pendingVerificationnCount > 0) {
body.append("\n\tPendentes de Verificação\t");
body.append(pendingVerificationnCount);
}
if (pendingAuthorizationCount > 0) {
body.append("\n\tPendentes de Autorização\t");
body.append(pendingAuthorizationCount);
}
if (pendingPaymentCount > 0) {
body.append("\n\tPendentes de Pagamento\t");
body.append(pendingPaymentCount);
}
body.append("\n\n\tTotal de Processos de Fundos de Maneio Pendentes\t");
body.append(totalPending);
body.append("\n\n---\n");
body.append("Esta mensagem foi enviada por meio das Aplicações Centrais do IST.\n");
final Collection<String> toAddress = Collections.singleton(email);
new Email("Aplicações Centrais do IST", "[email protected]", new String[] {}, toAddress, Collections.EMPTY_LIST,
Collections.EMPTY_LIST, "Processos Pendentes - Fundos de Maneio", body.toString());
}
} catch (final RemoteException ex) {
System.out.println("Unable to lookup email address for: " + person.getUsername());
// skip this person... keep going to next.
}
}
} finally {
pt.ist.fenixWebFramework.security.UserView.setUser(null);
}
}
}
}
|
diff --git a/tests/org.jboss.tools.ui.bot.ext/src/org/jboss/tools/ui/bot/ext/helper/ContentAssistHelper.java b/tests/org.jboss.tools.ui.bot.ext/src/org/jboss/tools/ui/bot/ext/helper/ContentAssistHelper.java
index 40e82e32..c7de6f9a 100644
--- a/tests/org.jboss.tools.ui.bot.ext/src/org/jboss/tools/ui/bot/ext/helper/ContentAssistHelper.java
+++ b/tests/org.jboss.tools.ui.bot.ext/src/org/jboss/tools/ui/bot/ext/helper/ContentAssistHelper.java
@@ -1,170 +1,171 @@
/*******************************************************************************
* Copyright (c) 2007-2012 Red Hat, Inc.
* Distributed under license by Red Hat, Inc. All rights reserved.
* This program is 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
*
* Contributor:
* Red Hat, Inc. - initial API and implementation
******************************************************************************/
package org.jboss.tools.ui.bot.ext.helper;
import static org.junit.Assert.assertTrue;
import java.util.List;
import org.apache.log4j.Logger;
import org.eclipse.swtbot.eclipse.finder.widgets.SWTBotEditor;
import org.jboss.tools.ui.bot.ext.FormatUtils;
import org.jboss.tools.ui.bot.ext.SWTBotExt;
import org.jboss.tools.ui.bot.ext.SWTJBTExt;
import org.jboss.tools.ui.bot.ext.SWTTestExt;
import org.jboss.tools.ui.bot.ext.Timing;
import org.jboss.tools.ui.bot.ext.parts.ContentAssistBot;
import org.jboss.tools.ui.bot.ext.parts.SWTBotEditorExt;
/**
* Helper for Content Assist functionality testing
* @author Vladimir Pakan
*
*/
public class ContentAssistHelper {
protected static final Logger log = Logger.getLogger(ContentAssistHelper.class);
/**
* Checks Content Assist content on specified position within editor with editorTitle
* and checks if expectedProposalList is equal to current Proposal List
* @param editorTitle
* @param textToSelect
* @param selectionOffset
* @param selectionLength
* @param textToSelectIndex
* @param expectedProposalList
*/
public static SWTBotEditor checkContentAssistContent(SWTBotExt bot,
String editorTitle, String textToSelect, int selectionOffset,
int selectionLength, int textToSelectIndex, List<String> expectedProposalList) {
return checkContentAssistContent(bot, editorTitle, textToSelect, selectionOffset,
selectionLength, textToSelectIndex, expectedProposalList, true);
}
/**
* Checks Content Assist content on specified position within editor with editorTitle
* and checks if expectedProposalList is equal to current Proposal List
* @param editorTitle
* @param textToSelect
* @param selectionOffset
* @param selectionLength
* @param textToSelectIndex
* @param expectedProposalList
* @param mustEquals
*/
public static SWTBotEditor checkContentAssistContent(SWTBotExt bot,
String editorTitle, String textToSelect, int selectionOffset,
int selectionLength, int textToSelectIndex, List<String> expectedProposalList,
boolean mustEquals) {
SWTJBTExt.selectTextInSourcePane(bot,
editorTitle, textToSelect, selectionOffset, selectionLength,
textToSelectIndex);
bot.sleep(Timing.time1S());
SWTBotEditorExt editor = SWTTestExt.bot.swtBotEditorExtByTitle(editorTitle);
ContentAssistBot contentAssist = editor.contentAssist();
List<String> currentProposalList = contentAssist.getProposalList();
assertTrue("Code Assist menu has incorrect menu items.\n" +
"Expected Proposal Menu Labels vs. Current Proposal Menu Labels :\n" +
FormatUtils.getListsDiffFormatted(expectedProposalList,currentProposalList),
mustEquals?expectedProposalList.equals(currentProposalList):
currentProposalList.containsAll(expectedProposalList));
return editor;
}
/**
* Checks Content Assist content on specified position within editor with editorTitle
* and checks if expectedProposalList is equal to current Proposal List
* @param editorTitle
* @param textToSelect
* @param selectionOffset
* @param selectionLength
* @param textToSelectIndex
* @param expectedProposalList
*/
public static SWTBotEditor checkContentAssistContent(SWTBotExt bot,
String editorTitle, String textToSelect, int selectionOffset,
int selectionLength, List<String> expectedProposalList) {
return checkContentAssistContent(bot, editorTitle, textToSelect,
selectionOffset, selectionLength, expectedProposalList, true);
}
/**
* Checks Content Assist content on specified position within editor with editorTitle
* and checks if expectedProposalList is equal to current Proposal List
* @param editorTitle
* @param textToSelect
* @param selectionOffset
* @param selectionLength
* @param textToSelectIndex
* @param expectedProposalList
* @param mustEquals
*/
public static SWTBotEditor checkContentAssistContent(SWTBotExt bot,
String editorTitle, String textToSelect, int selectionOffset,
int selectionLength, List<String> expectedProposalList, boolean mustEquals) {
return ContentAssistHelper.checkContentAssistContent(bot,
editorTitle,
textToSelect,
selectionOffset,
selectionLength,
0,
expectedProposalList,
mustEquals);
}
/**
* Checks Content Assist auto proposal. It's case when there is only one
* content assist item and that item is automatically inserted into editor
* and checks if expectedProposalList is equal to current Proposal List
* @param editorTitle
* @param textToSelect
* @param selectionOffset
* @param selectionLength
* @param textToSelectIndex
* @param expectedInsertedText
*/
public static SWTBotEditor checkContentAssistAutoProposal(SWTBotExt bot,
String editorTitle, String textToSelect, int selectionOffset,
int selectionLength, int textToSelectIndex, String expectedInsertedText) {
SWTJBTExt.selectTextInSourcePane(bot,
editorTitle, textToSelect, selectionOffset, selectionLength,
textToSelectIndex);
bot.sleep(Timing.time1S());
SWTBotEditorExt editor = SWTTestExt.bot.swtBotEditorExtByTitle(editorTitle);
String editorLineBeforeInsert = editor.getTextOnCurrentLine();
int xPos = editor.cursorPosition().column;
String expectedEditorLineAfterInsert = editorLineBeforeInsert.substring(0,xPos) +
expectedInsertedText +
editorLineBeforeInsert.substring(xPos);
ContentAssistBot contentAssist = editor.contentAssist();
contentAssist.invokeContentAssist();
String editorLineAfterInsert = editor.getTextOnCurrentLine();
- assertTrue("Text on current line should be:\n" +
- "but is :\n" + editorLineAfterInsert
+ assertTrue("Text on current line should be:\n" +
+ expectedEditorLineAfterInsert +
+ "\nbut is:\n" + editorLineAfterInsert
, editorLineAfterInsert.equals(expectedEditorLineAfterInsert));
return editor;
}
}
| true | true | public static SWTBotEditor checkContentAssistAutoProposal(SWTBotExt bot,
String editorTitle, String textToSelect, int selectionOffset,
int selectionLength, int textToSelectIndex, String expectedInsertedText) {
SWTJBTExt.selectTextInSourcePane(bot,
editorTitle, textToSelect, selectionOffset, selectionLength,
textToSelectIndex);
bot.sleep(Timing.time1S());
SWTBotEditorExt editor = SWTTestExt.bot.swtBotEditorExtByTitle(editorTitle);
String editorLineBeforeInsert = editor.getTextOnCurrentLine();
int xPos = editor.cursorPosition().column;
String expectedEditorLineAfterInsert = editorLineBeforeInsert.substring(0,xPos) +
expectedInsertedText +
editorLineBeforeInsert.substring(xPos);
ContentAssistBot contentAssist = editor.contentAssist();
contentAssist.invokeContentAssist();
String editorLineAfterInsert = editor.getTextOnCurrentLine();
assertTrue("Text on current line should be:\n" +
"but is :\n" + editorLineAfterInsert
, editorLineAfterInsert.equals(expectedEditorLineAfterInsert));
return editor;
}
| public static SWTBotEditor checkContentAssistAutoProposal(SWTBotExt bot,
String editorTitle, String textToSelect, int selectionOffset,
int selectionLength, int textToSelectIndex, String expectedInsertedText) {
SWTJBTExt.selectTextInSourcePane(bot,
editorTitle, textToSelect, selectionOffset, selectionLength,
textToSelectIndex);
bot.sleep(Timing.time1S());
SWTBotEditorExt editor = SWTTestExt.bot.swtBotEditorExtByTitle(editorTitle);
String editorLineBeforeInsert = editor.getTextOnCurrentLine();
int xPos = editor.cursorPosition().column;
String expectedEditorLineAfterInsert = editorLineBeforeInsert.substring(0,xPos) +
expectedInsertedText +
editorLineBeforeInsert.substring(xPos);
ContentAssistBot contentAssist = editor.contentAssist();
contentAssist.invokeContentAssist();
String editorLineAfterInsert = editor.getTextOnCurrentLine();
assertTrue("Text on current line should be:\n" +
expectedEditorLineAfterInsert +
"\nbut is:\n" + editorLineAfterInsert
, editorLineAfterInsert.equals(expectedEditorLineAfterInsert));
return editor;
}
|
diff --git a/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb.edit/src/org/wso2/developerstudio/eclipse/gmf/esb/provider/EndPointItemProvider.java b/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb.edit/src/org/wso2/developerstudio/eclipse/gmf/esb/provider/EndPointItemProvider.java
index 935bac037..c52d95b42 100755
--- a/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb.edit/src/org/wso2/developerstudio/eclipse/gmf/esb/provider/EndPointItemProvider.java
+++ b/ide/eclipse/esb/org.wso2.developerstudio.eclipse.gmf.esb.edit/src/org/wso2/developerstudio/eclipse/gmf/esb/provider/EndPointItemProvider.java
@@ -1,241 +1,240 @@
/**
* <copyright>
* </copyright>
*
* $Id$
*/
package org.wso2.developerstudio.eclipse.gmf.esb.provider;
import java.util.Collection;
import java.util.List;
import org.eclipse.emf.common.notify.AdapterFactory;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.edit.provider.ComposeableAdapterFactory;
import org.eclipse.emf.edit.provider.IEditingDomainItemProvider;
import org.eclipse.emf.edit.provider.IItemLabelProvider;
import org.eclipse.emf.edit.provider.IItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.IItemPropertySource;
import org.eclipse.emf.edit.provider.IStructuredItemContentProvider;
import org.eclipse.emf.edit.provider.ITreeItemContentProvider;
import org.eclipse.emf.edit.provider.ItemPropertyDescriptor;
import org.eclipse.emf.edit.provider.ViewerNotification;
import org.wso2.developerstudio.eclipse.gmf.esb.ArtifactType;
import org.wso2.developerstudio.eclipse.gmf.esb.EndPoint;
import org.wso2.developerstudio.eclipse.gmf.esb.EsbDiagram;
import org.wso2.developerstudio.eclipse.gmf.esb.EsbPackage;
/**
* This is the item provider adapter for a {@link org.wso2.developerstudio.eclipse.gmf.esb.EndPoint} object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public class EndPointItemProvider
extends EsbElementItemProvider
implements
IEditingDomainItemProvider,
IStructuredItemContentProvider,
ITreeItemContentProvider,
IItemLabelProvider,
IItemPropertySource {
/**
* This constructs an instance from a factory and a notifier.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EndPointItemProvider(AdapterFactory adapterFactory) {
super(adapterFactory);
}
/**
* This returns the property descriptors for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated NOT
*/
@Override
public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) {
if (itemPropertyDescriptors != null) {
itemPropertyDescriptors.clear();
}
EndPoint endPoint = (EndPoint) object;
super.getPropertyDescriptors(object);
//addEndPointNamePropertyDescriptor(object);
//addAnonymousPropertyDescriptor(object);
- /* 'InLine' property only applicable for Proxies and APIs */
+ /* 'InLine' property only applicable for Proxies */
EObject rootContainer = EcoreUtil.getRootContainer(endPoint);
if(rootContainer instanceof EsbDiagram){
EsbDiagram esbDiagram = (EsbDiagram) rootContainer;
ArtifactType type = esbDiagram.getServer().getType();
switch (type) {
case PROXY:
- case API:
addInLinePropertyDescriptor(object);
break;
}
}
return itemPropertyDescriptors;
}
/**
* This adds a property descriptor for the End Point Name feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated NOT
*/
protected void addEndPointNamePropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_EndPoint_endPointName_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_EndPoint_endPointName_feature", "_UI_EndPoint_type"),
EsbPackage.Literals.END_POINT__END_POINT_NAME,
true,
false,
false,
ItemPropertyDescriptor.GENERIC_VALUE_IMAGE,
"Basic",
null));
}
/**
* This adds a property descriptor for the Anonymous feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addAnonymousPropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_EndPoint_anonymous_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_EndPoint_anonymous_feature", "_UI_EndPoint_type"),
EsbPackage.Literals.END_POINT__ANONYMOUS,
true,
false,
false,
ItemPropertyDescriptor.BOOLEAN_VALUE_IMAGE,
null,
null));
}
/**
* This adds a property descriptor for the In Line feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated NOT
*/
protected void addInLinePropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_EndPoint_InLine_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_EndPoint_InLine_feature", "_UI_EndPoint_type"),
EsbPackage.Literals.END_POINT__IN_LINE,
true,
false,
false,
ItemPropertyDescriptor.BOOLEAN_VALUE_IMAGE,
"Basic",
null));
}
/**
* This adds a property descriptor for the Duplicate feature.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected void addDuplicatePropertyDescriptor(Object object) {
itemPropertyDescriptors.add
(createItemPropertyDescriptor
(((ComposeableAdapterFactory)adapterFactory).getRootAdapterFactory(),
getResourceLocator(),
getString("_UI_EndPoint_duplicate_feature"),
getString("_UI_PropertyDescriptor_description", "_UI_EndPoint_duplicate_feature", "_UI_EndPoint_type"),
EsbPackage.Literals.END_POINT__DUPLICATE,
true,
false,
false,
ItemPropertyDescriptor.BOOLEAN_VALUE_IMAGE,
null,
null));
}
/**
* This returns EndPoint.gif.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object getImage(Object object) {
return overlayImage(object, getResourceLocator().getImage("full/obj16/EndPoint"));
}
/**
* This returns the label text for the adapted class.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String getText(Object object) {
String label = ((EndPoint)object).getEndPointName();
return label == null || label.length() == 0 ?
getString("_UI_EndPoint_type") :
getString("_UI_EndPoint_type") + " " + label;
}
/**
* This handles model notifications by calling {@link #updateChildren} to update any cached
* children and by creating a viewer notification, which it passes to {@link #fireNotifyChanged}.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void notifyChanged(Notification notification) {
updateChildren(notification);
switch (notification.getFeatureID(EndPoint.class)) {
case EsbPackage.END_POINT__END_POINT_NAME:
case EsbPackage.END_POINT__ANONYMOUS:
case EsbPackage.END_POINT__IN_LINE:
case EsbPackage.END_POINT__DUPLICATE:
fireNotifyChanged(new ViewerNotification(notification, notification.getNotifier(), false, true));
return;
}
super.notifyChanged(notification);
}
/**
* This adds {@link org.eclipse.emf.edit.command.CommandParameter}s describing the children
* that can be created under this object.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected void collectNewChildDescriptors(Collection<Object> newChildDescriptors, Object object) {
super.collectNewChildDescriptors(newChildDescriptors, object);
}
}
| false | true | public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) {
if (itemPropertyDescriptors != null) {
itemPropertyDescriptors.clear();
}
EndPoint endPoint = (EndPoint) object;
super.getPropertyDescriptors(object);
//addEndPointNamePropertyDescriptor(object);
//addAnonymousPropertyDescriptor(object);
/* 'InLine' property only applicable for Proxies and APIs */
EObject rootContainer = EcoreUtil.getRootContainer(endPoint);
if(rootContainer instanceof EsbDiagram){
EsbDiagram esbDiagram = (EsbDiagram) rootContainer;
ArtifactType type = esbDiagram.getServer().getType();
switch (type) {
case PROXY:
case API:
addInLinePropertyDescriptor(object);
break;
}
}
return itemPropertyDescriptors;
}
| public List<IItemPropertyDescriptor> getPropertyDescriptors(Object object) {
if (itemPropertyDescriptors != null) {
itemPropertyDescriptors.clear();
}
EndPoint endPoint = (EndPoint) object;
super.getPropertyDescriptors(object);
//addEndPointNamePropertyDescriptor(object);
//addAnonymousPropertyDescriptor(object);
/* 'InLine' property only applicable for Proxies */
EObject rootContainer = EcoreUtil.getRootContainer(endPoint);
if(rootContainer instanceof EsbDiagram){
EsbDiagram esbDiagram = (EsbDiagram) rootContainer;
ArtifactType type = esbDiagram.getServer().getType();
switch (type) {
case PROXY:
addInLinePropertyDescriptor(object);
break;
}
}
return itemPropertyDescriptors;
}
|
diff --git a/src/main/java/me/eccentric_nz/TARDIS/commands/admin/TARDISEnterCommand.java b/src/main/java/me/eccentric_nz/TARDIS/commands/admin/TARDISEnterCommand.java
index e93b1d8b8..1d158e113 100644
--- a/src/main/java/me/eccentric_nz/TARDIS/commands/admin/TARDISEnterCommand.java
+++ b/src/main/java/me/eccentric_nz/TARDIS/commands/admin/TARDISEnterCommand.java
@@ -1,148 +1,149 @@
/*
* Copyright (C) 2013 eccentric_nz
*
* 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 me.eccentric_nz.TARDIS.commands.admin;
import java.util.HashMap;
import me.eccentric_nz.TARDIS.TARDIS;
import me.eccentric_nz.TARDIS.TARDISConstants;
import me.eccentric_nz.TARDIS.database.QueryFactory;
import me.eccentric_nz.TARDIS.database.ResultSetDoors;
import me.eccentric_nz.TARDIS.database.ResultSetTardis;
import org.bukkit.Effect;
import org.bukkit.Location;
import org.bukkit.Sound;
import org.bukkit.World;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
/**
*
* @author eccentric_nz
*/
public class TARDISEnterCommand {
private final TARDIS plugin;
public TARDISEnterCommand(TARDIS plugin) {
this.plugin = plugin;
}
public boolean enterTARDIS(CommandSender sender, String[] args) {
Player player = null;
if (sender instanceof Player) {
player = (Player) sender;
}
if (player == null) {
sender.sendMessage(plugin.pluginName + "Only a player can run this command!");
return true;
}
if (!player.hasPermission("tardis.skeletonkey")) {
sender.sendMessage(plugin.pluginName + "You do not have permission to run this command!");
return true;
}
HashMap<String, Object> where = new HashMap<String, Object>();
where.put("owner", args[1]);
ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false);
if (rs.resultSet()) {
int id = rs.getTardis_id();
HashMap<String, Object> wherei = new HashMap<String, Object>();
wherei.put("door_type", 1);
wherei.put("tardis_id", id);
ResultSetDoors rsi = new ResultSetDoors(plugin, wherei, false);
if (rsi.resultSet()) {
TARDISConstants.COMPASS innerD = rsi.getDoor_direction();
String doorLocStr = rsi.getDoor_location();
String[] split = doorLocStr.split(":");
World cw = plugin.getServer().getWorld(split[0]);
int cx = 0, cy = 0, cz = 0;
try {
cx = Integer.parseInt(split[1]);
cy = Integer.parseInt(split[2]);
cz = Integer.parseInt(split[3]);
} catch (NumberFormatException nfe) {
plugin.debug("Could not convert to number!");
}
Location tmp_loc = cw.getBlockAt(cx, cy, cz).getLocation();
int getx = tmp_loc.getBlockX();
int getz = tmp_loc.getBlockZ();
switch (innerD) {
case NORTH:
// z -ve
tmp_loc.setX(getx + 0.5);
tmp_loc.setZ(getz - 0.5);
break;
case EAST:
// x +ve
tmp_loc.setX(getx + 1.5);
tmp_loc.setZ(getz + 0.5);
break;
case SOUTH:
// z +ve
tmp_loc.setX(getx + 0.5);
tmp_loc.setZ(getz + 1.5);
break;
case WEST:
// x -ve
tmp_loc.setX(getx - 0.5);
tmp_loc.setZ(getz + 0.5);
break;
}
// enter TARDIS!
try {
Class.forName("org.bukkit.Sound");
player.playSound(player.getLocation(), Sound.ENDERMAN_TELEPORT, 1, 1);
} catch (ClassNotFoundException e) {
player.getLocation().getWorld().playEffect(player.getLocation(), Effect.GHAST_SHRIEK, 0);
}
cw.getChunkAt(tmp_loc).load();
float yaw = player.getLocation().getYaw();
float pitch = player.getLocation().getPitch();
tmp_loc.setPitch(pitch);
// get players direction so we can adjust yaw if necessary
TARDISConstants.COMPASS d = TARDISConstants.COMPASS.valueOf(plugin.utils.getPlayersDirection(player, false));
if (!innerD.equals(d)) {
switch (d) {
case NORTH:
yaw += plugin.doorListener.adjustYaw[0][innerD.ordinal()];
break;
case WEST:
yaw += plugin.doorListener.adjustYaw[1][innerD.ordinal()];
break;
case SOUTH:
yaw += plugin.doorListener.adjustYaw[2][innerD.ordinal()];
break;
case EAST:
yaw += plugin.doorListener.adjustYaw[3][innerD.ordinal()];
break;
}
}
tmp_loc.setYaw(yaw);
final Location tardis_loc = tmp_loc;
World playerWorld = player.getLocation().getWorld();
plugin.doorListener.movePlayer(player, tardis_loc, false, playerWorld, false);
// put player into travellers table
QueryFactory qf = new QueryFactory(plugin);
HashMap<String, Object> set = new HashMap<String, Object>();
set.put("tardis_id", id);
set.put("player", player.getName());
qf.doInsert("travellers", set);
return true;
}
}
- return false;
+ sender.sendMessage(plugin.pluginName + args[1] + " has not created a TARDIS yet!");
+ return true;
}
}
| true | true | public boolean enterTARDIS(CommandSender sender, String[] args) {
Player player = null;
if (sender instanceof Player) {
player = (Player) sender;
}
if (player == null) {
sender.sendMessage(plugin.pluginName + "Only a player can run this command!");
return true;
}
if (!player.hasPermission("tardis.skeletonkey")) {
sender.sendMessage(plugin.pluginName + "You do not have permission to run this command!");
return true;
}
HashMap<String, Object> where = new HashMap<String, Object>();
where.put("owner", args[1]);
ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false);
if (rs.resultSet()) {
int id = rs.getTardis_id();
HashMap<String, Object> wherei = new HashMap<String, Object>();
wherei.put("door_type", 1);
wherei.put("tardis_id", id);
ResultSetDoors rsi = new ResultSetDoors(plugin, wherei, false);
if (rsi.resultSet()) {
TARDISConstants.COMPASS innerD = rsi.getDoor_direction();
String doorLocStr = rsi.getDoor_location();
String[] split = doorLocStr.split(":");
World cw = plugin.getServer().getWorld(split[0]);
int cx = 0, cy = 0, cz = 0;
try {
cx = Integer.parseInt(split[1]);
cy = Integer.parseInt(split[2]);
cz = Integer.parseInt(split[3]);
} catch (NumberFormatException nfe) {
plugin.debug("Could not convert to number!");
}
Location tmp_loc = cw.getBlockAt(cx, cy, cz).getLocation();
int getx = tmp_loc.getBlockX();
int getz = tmp_loc.getBlockZ();
switch (innerD) {
case NORTH:
// z -ve
tmp_loc.setX(getx + 0.5);
tmp_loc.setZ(getz - 0.5);
break;
case EAST:
// x +ve
tmp_loc.setX(getx + 1.5);
tmp_loc.setZ(getz + 0.5);
break;
case SOUTH:
// z +ve
tmp_loc.setX(getx + 0.5);
tmp_loc.setZ(getz + 1.5);
break;
case WEST:
// x -ve
tmp_loc.setX(getx - 0.5);
tmp_loc.setZ(getz + 0.5);
break;
}
// enter TARDIS!
try {
Class.forName("org.bukkit.Sound");
player.playSound(player.getLocation(), Sound.ENDERMAN_TELEPORT, 1, 1);
} catch (ClassNotFoundException e) {
player.getLocation().getWorld().playEffect(player.getLocation(), Effect.GHAST_SHRIEK, 0);
}
cw.getChunkAt(tmp_loc).load();
float yaw = player.getLocation().getYaw();
float pitch = player.getLocation().getPitch();
tmp_loc.setPitch(pitch);
// get players direction so we can adjust yaw if necessary
TARDISConstants.COMPASS d = TARDISConstants.COMPASS.valueOf(plugin.utils.getPlayersDirection(player, false));
if (!innerD.equals(d)) {
switch (d) {
case NORTH:
yaw += plugin.doorListener.adjustYaw[0][innerD.ordinal()];
break;
case WEST:
yaw += plugin.doorListener.adjustYaw[1][innerD.ordinal()];
break;
case SOUTH:
yaw += plugin.doorListener.adjustYaw[2][innerD.ordinal()];
break;
case EAST:
yaw += plugin.doorListener.adjustYaw[3][innerD.ordinal()];
break;
}
}
tmp_loc.setYaw(yaw);
final Location tardis_loc = tmp_loc;
World playerWorld = player.getLocation().getWorld();
plugin.doorListener.movePlayer(player, tardis_loc, false, playerWorld, false);
// put player into travellers table
QueryFactory qf = new QueryFactory(plugin);
HashMap<String, Object> set = new HashMap<String, Object>();
set.put("tardis_id", id);
set.put("player", player.getName());
qf.doInsert("travellers", set);
return true;
}
}
return false;
}
| public boolean enterTARDIS(CommandSender sender, String[] args) {
Player player = null;
if (sender instanceof Player) {
player = (Player) sender;
}
if (player == null) {
sender.sendMessage(plugin.pluginName + "Only a player can run this command!");
return true;
}
if (!player.hasPermission("tardis.skeletonkey")) {
sender.sendMessage(plugin.pluginName + "You do not have permission to run this command!");
return true;
}
HashMap<String, Object> where = new HashMap<String, Object>();
where.put("owner", args[1]);
ResultSetTardis rs = new ResultSetTardis(plugin, where, "", false);
if (rs.resultSet()) {
int id = rs.getTardis_id();
HashMap<String, Object> wherei = new HashMap<String, Object>();
wherei.put("door_type", 1);
wherei.put("tardis_id", id);
ResultSetDoors rsi = new ResultSetDoors(plugin, wherei, false);
if (rsi.resultSet()) {
TARDISConstants.COMPASS innerD = rsi.getDoor_direction();
String doorLocStr = rsi.getDoor_location();
String[] split = doorLocStr.split(":");
World cw = plugin.getServer().getWorld(split[0]);
int cx = 0, cy = 0, cz = 0;
try {
cx = Integer.parseInt(split[1]);
cy = Integer.parseInt(split[2]);
cz = Integer.parseInt(split[3]);
} catch (NumberFormatException nfe) {
plugin.debug("Could not convert to number!");
}
Location tmp_loc = cw.getBlockAt(cx, cy, cz).getLocation();
int getx = tmp_loc.getBlockX();
int getz = tmp_loc.getBlockZ();
switch (innerD) {
case NORTH:
// z -ve
tmp_loc.setX(getx + 0.5);
tmp_loc.setZ(getz - 0.5);
break;
case EAST:
// x +ve
tmp_loc.setX(getx + 1.5);
tmp_loc.setZ(getz + 0.5);
break;
case SOUTH:
// z +ve
tmp_loc.setX(getx + 0.5);
tmp_loc.setZ(getz + 1.5);
break;
case WEST:
// x -ve
tmp_loc.setX(getx - 0.5);
tmp_loc.setZ(getz + 0.5);
break;
}
// enter TARDIS!
try {
Class.forName("org.bukkit.Sound");
player.playSound(player.getLocation(), Sound.ENDERMAN_TELEPORT, 1, 1);
} catch (ClassNotFoundException e) {
player.getLocation().getWorld().playEffect(player.getLocation(), Effect.GHAST_SHRIEK, 0);
}
cw.getChunkAt(tmp_loc).load();
float yaw = player.getLocation().getYaw();
float pitch = player.getLocation().getPitch();
tmp_loc.setPitch(pitch);
// get players direction so we can adjust yaw if necessary
TARDISConstants.COMPASS d = TARDISConstants.COMPASS.valueOf(plugin.utils.getPlayersDirection(player, false));
if (!innerD.equals(d)) {
switch (d) {
case NORTH:
yaw += plugin.doorListener.adjustYaw[0][innerD.ordinal()];
break;
case WEST:
yaw += plugin.doorListener.adjustYaw[1][innerD.ordinal()];
break;
case SOUTH:
yaw += plugin.doorListener.adjustYaw[2][innerD.ordinal()];
break;
case EAST:
yaw += plugin.doorListener.adjustYaw[3][innerD.ordinal()];
break;
}
}
tmp_loc.setYaw(yaw);
final Location tardis_loc = tmp_loc;
World playerWorld = player.getLocation().getWorld();
plugin.doorListener.movePlayer(player, tardis_loc, false, playerWorld, false);
// put player into travellers table
QueryFactory qf = new QueryFactory(plugin);
HashMap<String, Object> set = new HashMap<String, Object>();
set.put("tardis_id", id);
set.put("player", player.getName());
qf.doInsert("travellers", set);
return true;
}
}
sender.sendMessage(plugin.pluginName + args[1] + " has not created a TARDIS yet!");
return true;
}
|
diff --git a/src/org/liberty/android/fantastischmemo/DatabaseHelper.java b/src/org/liberty/android/fantastischmemo/DatabaseHelper.java
index c9ed4b94..f8181e86 100644
--- a/src/org/liberty/android/fantastischmemo/DatabaseHelper.java
+++ b/src/org/liberty/android/fantastischmemo/DatabaseHelper.java
@@ -1,571 +1,571 @@
package org.liberty.android.fantastischmemo;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Set;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class DatabaseHelper extends SQLiteOpenHelper {
private final String DB_PATH;
private final String DB_NAME;
private SQLiteDatabase myDatabase;
private final Context myContext;
private static final String TAG = "org.liberty.android.fantastischmemo.DatabaseHelper";
public DatabaseHelper(Context context, String dbPath, String dbName){
super(context, dbName, null, 1);
DB_PATH = dbPath;
DB_NAME = dbName;
this.myContext = context;
this.openDatabase();
}
public DatabaseHelper(Context context, String dbPath, String dbName, int noOpen){
super(context, dbName, null, 1);
DB_PATH = dbPath;
DB_NAME = dbName;
this.myContext = context;
if(noOpen == 0){
this.openDatabase();
}
}
public void createDatabase() throws IOException{
boolean dbExist = checkDatabase();
if(dbExist){
}
else{
this.getReadableDatabase();
try{
copyDatabase();
}
catch(IOException e){
throw new Error("Error copying database");
}
}
}
public void createEmptyDatabase() throws IOException{
boolean dbExist = checkDatabase();
if(dbExist){
throw new IOException("DB already exist");
}
try{
myDatabase = SQLiteDatabase.openDatabase(DB_PATH + "/" + DB_NAME, null, SQLiteDatabase.OPEN_READWRITE | SQLiteDatabase.CREATE_IF_NECESSARY);
}
catch(Exception e){
Log.e("DB open error here", e.toString());
}
myDatabase.execSQL("CREATE TABLE dict_tbl(_id INTEGER PRIMARY KEY ASC AUTOINCREMENT, question TEXT, answer TEXT, note TEXT, category TEXT)");
myDatabase.execSQL("CREATE TABLE learn_tbl(_id INTEGER PRIMARY KEY ASC AUTOINCREMENT, date_learn, interval, grade INTEGER, easiness REAL, acq_reps INTEGER, ret_reps INTEGER, lapses INTEGER, acq_reps_since_lapse INTEGER, ret_reps_since_lapse INTEGER)");
myDatabase.execSQL("CREATE TABLE control_tbl(ctrl_key TEXT, value TEXT)");
myDatabase.beginTransaction();
try{
this.myDatabase.execSQL("DELETE FROM learn_tbl");
this.myDatabase.execSQL("INSERT INTO learn_tbl(_id) SELECT _id FROM dict_tbl");
this.myDatabase.execSQL("UPDATE learn_tbl SET date_learn = '2010-01-01', interval = 0, grade = 0, easiness = 2.5, acq_reps = 0, ret_reps = 0, lapses = 0, acq_reps_since_lapse = 0, ret_reps_since_lapse = 0");
this.myDatabase.execSQL("INSERT INTO control_tbl(ctrl_key, value) VALUES('question_locale', 'US')");
this.myDatabase.execSQL("INSERT INTO control_tbl(ctrl_key, value) VALUES('answer_locale', 'US')");
this.myDatabase.execSQL("INSERT INTO control_tbl(ctrl_key, value) VALUES('question_align', 'center')");
this.myDatabase.execSQL("INSERT INTO control_tbl(ctrl_key, value) VALUES('answer_align', 'center')");
this.myDatabase.execSQL("INSERT INTO control_tbl(ctrl_key, value) VALUES('question_font_size', '24')");
this.myDatabase.execSQL("INSERT INTO control_tbl(ctrl_key, value) VALUES('answer_font_size', '24')");
myDatabase.setTransactionSuccessful();
}
finally{
myDatabase.endTransaction();
}
}
public void createDatabaseFromList(List<String> questionList, List<String> answerList, List<String> categoryList, List<String> datelearnList, List<Integer> intervalList, List<Double> easinessList, List<Integer> gradeList, List<Integer> lapsesList, List<Integer> acrpList, List<Integer> rtrpList, List<Integer> arslList, List<Integer> rrslList) throws IOException{
boolean dbExist = checkDatabase();
if(dbExist){
throw new IOException("DB already exist");
}
try{
myDatabase = SQLiteDatabase.openDatabase(DB_PATH + "/" + DB_NAME, null, SQLiteDatabase.OPEN_READWRITE | SQLiteDatabase.CREATE_IF_NECESSARY);
}
catch(Exception e){
Log.e("DB open error here", e.toString());
}
myDatabase.execSQL("CREATE TABLE dict_tbl(_id INTEGER PRIMARY KEY ASC AUTOINCREMENT, question TEXT, answer TEXT, note TEXT, category TEXT)");
myDatabase.execSQL("CREATE TABLE learn_tbl(_id INTEGER PRIMARY KEY ASC AUTOINCREMENT, date_learn, interval, grade INTEGER, easiness REAL, acq_reps INTEGER, ret_reps INTEGER, lapses INTEGER, acq_reps_since_lapse INTEGER, ret_reps_since_lapse INTEGER)");
myDatabase.execSQL("CREATE TABLE control_tbl(ctrl_key TEXT, value TEXT)");
ListIterator<String> liq = questionList.listIterator();
ListIterator<String> lia = answerList.listIterator();
ListIterator<String> lic = categoryList.listIterator();
ListIterator<String> liDatelearn = datelearnList.listIterator();
ListIterator<Integer> liInterval = intervalList.listIterator();
ListIterator<Double> liEasiness = easinessList.listIterator();
ListIterator<Integer> liGrade = gradeList.listIterator();
ListIterator<Integer> liLapses = lapsesList.listIterator();
ListIterator<Integer> liAcrp = acrpList.listIterator();
ListIterator<Integer> liRtrp = rtrpList.listIterator();
ListIterator<Integer> liArsl = arslList.listIterator();
ListIterator<Integer> liRrsl = rrslList.listIterator();
String date_learn, interval, grade, easiness, acq_reps, ret_reps, lapses, acq_reps_since_lapse, ret_reps_since_lapse;
myDatabase.beginTransaction();
try{
while(liq.hasNext() && lia.hasNext()){
String category;
if(lic.hasNext()){
category = lic.next();
}
else{
category = "";
}
if(questionList.size() == arslList.size()){
date_learn = liDatelearn.next();
Log.v(TAG, date_learn);
interval = liInterval.next().toString();
grade = liGrade.next().toString();
easiness = liEasiness.next().toString();
acq_reps = liAcrp.next().toString();
ret_reps = liRtrp.next().toString();
lapses = liLapses.next().toString();
acq_reps_since_lapse = liArsl.next().toString();
ret_reps_since_lapse = liRrsl.next().toString();
}
else{
date_learn = "2010-01-01";
interval = "0";
grade = "0";
easiness = "2.5";
acq_reps = "0";
ret_reps = "0";
lapses = "0";
acq_reps_since_lapse = "0";
ret_reps_since_lapse = "0";
}
myDatabase.execSQL("INSERT INTO dict_tbl(question,answer,category) VALUES(?, ?, ?)", new String[]{liq.next(), lia.next(), category});
myDatabase.execSQL("INSERT INTO learn_tbl(date_learn, interval, grade, easiness, acq_reps, ret_reps, lapses, acq_reps_since_lapse, ret_reps_since_lapse) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)", new String[]{date_learn, interval, grade, easiness, acq_reps, ret_reps, lapses, acq_reps_since_lapse, ret_reps_since_lapse});
}
//myDatabase.execSQL("DELETE FROM learn_tbl");
//myDatabase.execSQL("INSERT INTO learn_tbl(_id) SELECT _id FROM dict_tbl");
myDatabase.execSQL("INSERT INTO control_tbl(ctrl_key, value) VALUES('question_locale', 'US')");
myDatabase.execSQL("INSERT INTO control_tbl(ctrl_key, value) VALUES('answer_locale', 'US')");
myDatabase.execSQL("INSERT INTO control_tbl(ctrl_key, value) VALUES('question_align', 'center')");
myDatabase.execSQL("INSERT INTO control_tbl(ctrl_key, value) VALUES('answer_align', 'center')");
myDatabase.execSQL("INSERT INTO control_tbl(ctrl_key, value) VALUES('question_font_size', '24')");
myDatabase.execSQL("INSERT INTO control_tbl(ctrl_key, value) VALUES('answer_font_size', '24')");
myDatabase.setTransactionSuccessful();
}
finally{
myDatabase.endTransaction();
}
}
public boolean checkDatabase(){
SQLiteDatabase checkDB = null;
try{
String myPath = DB_PATH + "/" + DB_NAME;
checkDB = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READONLY);
}
catch(SQLiteException e){
checkDB = null;
}
if(checkDB != null){
checkDB.close();
}
return checkDB != null ? true : false;
}
private void copyDatabase() throws IOException{
InputStream myInput = myContext.getAssets().open(DB_NAME);
String outFilename = DB_PATH + "/" + DB_NAME;
OutputStream myOutput = new FileOutputStream(outFilename);
byte[] buffer = new byte[1024];
int length;
while((length = myInput.read(buffer)) > 0){
myOutput.write(buffer, 0, length);
}
myOutput.flush();
myOutput.close();
myInput.close();
}
public void openDatabase() throws SQLException{
String myPath = DB_PATH + "/" + DB_NAME;
Cursor result;
int count_dict = 0, count_learn = 0;
try{
myDatabase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE | SQLiteDatabase.CREATE_IF_NECESSARY);
}
catch(Exception e){
Log.e("First", "Database error first here!: " + e.toString());
throw new SQLException();
}
try{
result = myDatabase.rawQuery("SELECT _id FROM dict_tbl", null);
count_dict = result.getCount();
result.close();
}
catch(Exception e){
//new AlertDialog.Builder(this).setMessage(e.toString()).show();
Log.e("Second", "Database error here!: " + e.toString());
}
if(count_dict == 0){
return;
}
result = myDatabase.rawQuery("SELECT _id FROM learn_tbl", null);
count_learn = result.getCount();
result.close();
if(count_learn != count_dict){
this.myDatabase.execSQL("DELETE FROM learn_tbl");
this.myDatabase.execSQL("INSERT INTO learn_tbl(_id) SELECT _id FROM dict_tbl");
this.myDatabase.execSQL("UPDATE learn_tbl SET date_learn = '2010-01-01', interval = 0, grade = 0, easiness = 2.5, acq_reps = 0, ret_reps = 0, lapses = 0, acq_reps_since_lapse = 0, ret_reps_since_lapse = 0");
}
}
//@Override
public synchronized void close(){
if(myDatabase != null){
myDatabase.close();
}
super.close();
}
//@Override
public void onCreate(SQLiteDatabase db){
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){
}
public boolean getListItems(int id, int windowSize, List<Item> list){
// These function are related to read db operation
// flag = 0 means no condition
// flag = 1 means new items, the items user have never seen
// flag = 2 means item due, they need to be reviewed.
// windowSize = -1 means all items from id and on
HashMap<String, String> hm = new HashMap<String, String>();
String acqQuery;
String retQuery;
// ArrayList<String> list = new ArrayList<String>();
String query = "SELECT learn_tbl._id, date_learn, interval, grade, easiness, acq_reps, ret_reps, lapses, acq_reps_since_lapse, ret_reps_since_lapse, question, answer, note FROM dict_tbl INNER JOIN learn_tbl ON dict_tbl._id=learn_tbl._id WHERE dict_tbl._id >= "
+ id + " ";
Cursor acqResult;
Cursor retResult;
// result = myDatabase.query(true, "dict_tbl", null, querySelection,
// null, null, null, "_id", null);
// result = myDatabase.query("dict_tbl", null, querySelection, null,
// null, null, "_id");
// result = myDatabase.query(true, "dict_tbl", null, querySelection,
// null, null, null, null, "1");
if(windowSize >= 0){
retQuery = query
+ "AND round((julianday(date('now', 'localtime')) - julianday(date_learn))) - interval >= 0 AND acq_reps > 0 LIMIT "
+ windowSize;
}
else{
retQuery = query;
}
try {
retResult = myDatabase.rawQuery(retQuery, null);
} catch (Exception e) {
Log.e("Query item error", e.toString());
return false;
}
if (retResult.getCount() > 0) {
Cursor result = retResult;
retResult.moveToFirst();
do {
hm.put("_id", Integer.toString(result.getInt(result
.getColumnIndex("_id"))));
hm.put("question", result.getString(result
.getColumnIndex("question")));
hm.put("answer", result.getString(result
.getColumnIndex("answer")));
hm.put("note", result.getString(result.getColumnIndex("note")));
hm.put("date_learn", result.getString(result
.getColumnIndex("date_learn")));
hm.put("interval", Integer.toString(result.getInt(result
.getColumnIndex("interval"))));
hm.put("grade", Integer.toString(result.getInt(result
.getColumnIndex("grade"))));
hm.put("easiness", Double.toString(result.getDouble(result
- .getColumnIndex("grade"))));
+ .getColumnIndex("easiness"))));
hm.put("acq_reps", Integer.toString(result.getInt(result
.getColumnIndex("acq_reps"))));
hm.put("ret_reps", Integer.toString(result.getInt(result
.getColumnIndex("ret_reps"))));
hm.put("lapses", Integer.toString(result.getInt(result
.getColumnIndex("lapses"))));
hm.put("acq_reps_since_lapse",Integer.toString(result.getInt(result
.getColumnIndex("acq_reps_since_lapse"))));
hm.put("ret_reps_since_lapse", Integer.toString(result.getInt(result
.getColumnIndex("ret_reps_since_lapse"))));
Item resultItem = new Item();
resultItem.setData(hm);
list.add(resultItem);
} while (result.moveToNext());
}
retResult.close();
int remainingSize = windowSize - list.size();
if (remainingSize > 0) {
acqQuery = query + "AND acq_reps = 0 LIMIT " + remainingSize;
try {
acqResult = myDatabase.rawQuery(acqQuery, null);
} catch (Exception e) {
Log.e("Query item error", e.toString());
return false;
}
// System.out.println("The result is: " + result.getString(0));
// return result.getString(1);
if (acqResult.getCount() > 0) {
Cursor result = acqResult;
acqResult.moveToFirst();
do {
hm.put("_id", Integer.toString(result.getInt(result
.getColumnIndex("_id"))));
hm.put("question", result.getString(result
.getColumnIndex("question")));
hm.put("answer", result.getString(result
.getColumnIndex("answer")));
hm.put("note", result.getString(result
.getColumnIndex("note")));
hm.put("date_learn", result.getString(result
.getColumnIndex("date_learn")));
hm.put("interval", Integer.toString(result.getInt(result
.getColumnIndex("interval"))));
hm.put("grade", Integer.toString(result.getInt(result
.getColumnIndex("grade"))));
hm.put("easiness", Double.toString(result.getDouble(result
- .getColumnIndex("grade"))));
+ .getColumnIndex("easiness"))));
hm.put("acq_reps", Integer.toString(result.getInt(result
.getColumnIndex("acq_reps"))));
hm.put("ret_reps", Integer.toString(result.getInt(result
.getColumnIndex("ret_reps"))));
hm.put("lapses", Integer.toString(result.getInt(result
.getColumnIndex("lapses"))));
hm.put("acq_reps_since_lapse", Integer.toString(result
.getInt(result
.getColumnIndex("acq_reps_since_lapse"))));
hm.put("ret_reps_since_lapse", Integer.toString(result
.getInt(result
.getColumnIndex("ret_reps_since_lapse"))));
Item resultItem = new Item();
resultItem.setData(hm);
list.add(resultItem);
} while (result.moveToNext());
}
acqResult.close();
}
if (list.size() <= 0) {
return false;
} else {
return true;
}
}
public Item getItemById(int id, int flag){
// These function are related to read db operation
// flag = 0 means no condition
// flag = 1 means new items, the items user have never seen
// flag = 2 means item due, they need to be reviewed.
HashMap<String, String> hm = new HashMap<String, String>();
//ArrayList<String> list = new ArrayList<String>();
String query = "SELECT learn_tbl._id, date_learn, interval, grade, easiness, acq_reps, ret_reps, lapses, acq_reps_since_lapse, ret_reps_since_lapse, question, answer, note FROM dict_tbl INNER JOIN learn_tbl ON dict_tbl._id=learn_tbl._id WHERE dict_tbl._id >= " + id + " ";
if(flag == 1){
query += "AND acq_reps = 0 LIMIT 1";
}
else if(flag == 2){
query += "AND round((julianday(date('now', 'localtime')) - julianday(date_learn))) - interval >= 0 AND acq_reps > 0 LIMIT 1";
}
else{
query += "LIMIT 1";
}
Cursor result;
//result = myDatabase.query(true, "dict_tbl", null, querySelection, null, null, null, "_id", null);
//result = myDatabase.query("dict_tbl", null, querySelection, null, null, null, "_id");
//result = myDatabase.query(true, "dict_tbl", null, querySelection, null, null, null, null, "1");
try{
result = myDatabase.rawQuery(query, null);
}
catch(Exception e){
Log.e("Query item error", e.toString());
return null;
}
//System.out.println("The result is: " + result.getString(0));
//return result.getString(1);
if(result.getCount() == 0){
result.close();
return null;
}
result.moveToFirst();
//int resultId = result.getInt(result.getColumnIndex("_id"));
hm.put("_id", Integer.toString(result.getInt(result.getColumnIndex("_id"))));
hm.put("question", result.getString(result.getColumnIndex("question")));
hm.put("answer", result.getString(result.getColumnIndex("answer")));
hm.put("note", result.getString(result.getColumnIndex("note")));
//querySelection = " _id = " + resultId;
//result = myDatabase.query(true, "learn_tbl", null, querySelection, null, null, null, null, "1");
//if(result.getCount() == 0){
// return null;
//}
//result.moveToFirst();
hm.put("date_learn", result.getString(result.getColumnIndex("date_learn")));
hm.put("interval", Integer.toString(result.getInt(result.getColumnIndex("interval"))));
hm.put("grade", Integer.toString(result.getInt(result.getColumnIndex("grade"))));
hm.put("easiness", Double.toString(result.getDouble(result.getColumnIndex("easiness"))));
hm.put("acq_reps", Integer.toString(result.getInt(result.getColumnIndex("acq_reps"))));
hm.put("ret_reps", Integer.toString(result.getInt(result.getColumnIndex("ret_reps"))));
hm.put("lapses", Integer.toString(result.getInt(result.getColumnIndex("lapses"))));
hm.put("acq_reps_since_lapse", Integer.toString(result.getInt(result.getColumnIndex("acq_reps_since_lapse"))));
hm.put("ret_reps_since_lapse", Integer.toString(result.getInt(result.getColumnIndex("ret_reps_since_lapse"))));
result.close();
Item resultItem = new Item();
resultItem.setData(hm);
return resultItem;
}
public void updateItem(Item item){
// Only update the learn_tbl
try{
myDatabase.execSQL("UPDATE learn_tbl SET date_learn = ?, interval = ?, grade = ?, easiness = ?, acq_reps = ?, ret_reps = ?, lapses = ?, acq_reps_since_lapse = ?, ret_reps_since_lapse = ? WHERE _id = ?", item.getLearningData());
}
catch(Exception e){
Log.e("Query error in updateItem!", e.toString());
}
}
public void updateQA(Item item){
myDatabase.execSQL("UPDATE dict_tbl SET question = ?, answer = ?, note = ? WHERE _id = ?", new String[]{item.getQuestion(), item.getAnswer(), item.getNote(), Integer.toString(item.getId())});
}
public int getScheduledCount(){
Cursor result = myDatabase.rawQuery("SELECT count(_id) FROM learn_tbl WHERE round((julianday(date('now', 'localtime')) - julianday(date_learn))) - interval >= 0 AND acq_reps > 0", null);
result.moveToFirst();
int res = result.getInt(0);
result.close();
return res;
}
public int getNewCount(){
Cursor result = myDatabase.rawQuery("SELECT count(_id) FROM learn_tbl WHERE acq_reps = 0", null);
result.moveToFirst();
int res = result.getInt(0);
result.close();
return res;
}
public int getTotalCount(){
Cursor result = myDatabase.rawQuery("SELECT count(_id) FROM learn_tbl", null);
result.moveToFirst();
int res = result.getInt(0);
result.close();
return res;
}
public HashMap<String, String> getSettings(){
// Dump all the key/value pairs from the learn_tbl
String key;
String value;
HashMap<String, String> hm = new HashMap<String, String>();
Cursor result = myDatabase.rawQuery("SELECT * FROM control_tbl", null);
int count = result.getCount();
for(int i = 0; i < count; i++){
if(i == 0){
result.moveToFirst();
}
else{
result.moveToNext();
}
key = result.getString(result.getColumnIndex("ctrl_key"));
value = result.getString(result.getColumnIndex("value"));
hm.put(key, value);
}
result.close();
return hm;
}
public void deleteItem(Item item){
myDatabase.execSQL("DELETE FROM learn_tbl where _id = ?", new String[]{"" + item.getId()});
myDatabase.execSQL("DELETE FROM dict_tbl where _id = ?", new String[]{"" + item.getId()});
}
public void setSettings(HashMap<String, String> hm){
// Update the control_tbl in database using the hm
Set<Map.Entry<String, String>> set = hm.entrySet();
Iterator<Map.Entry<String, String> > i = set.iterator();
while(i.hasNext()){
Map.Entry<String, String> me = i.next();
myDatabase.execSQL("REPLACE INTO control_tbl values(?, ?)", new String[]{me.getKey().toString(), me.getValue().toString()});
}
}
public void wipeLearnData(){
this.myDatabase.execSQL("UPDATE learn_tbl SET date_learn = '2010-01-01', interval = 0, grade = 0, easiness = 2.5, acq_reps = 0, ret_reps = 0, lapses = 0, acq_reps_since_lapse = 0, ret_reps_since_lapse = 0");
}
public int getNewId(){
Cursor result = this.myDatabase.rawQuery("SELECT _id FROM dict_tbl ORDER BY _id DESC LIMIT 1", null);
if(result.getCount() != 1){
result.close();
return 1;
}
result.moveToFirst();
int res = result.getInt(result.getColumnIndex("_id"));
res += 1;
result.close();
return res;
}
public void addOrReplaceItem(Item item){
this.myDatabase.execSQL("REPLACE INTO dict_tbl(_id, question, answer) VALUES(?, ?, ?)", new String[]{"" + item.getId(), item.getQuestion(), item.getAnswer()});
this.myDatabase.execSQL("REPLACE INTO learn_tbl(_id, date_learn, interval, grade, easiness, acq_reps, ret_reps, lapses, acq_reps_since_lapse, ret_reps_since_lapse) VALUES (?, '2010-01-01', 0, 0, 2.5, 0, 0, 0, 0, 0)", new String[]{"" + item.getId()});
}
}
| false | true | public boolean getListItems(int id, int windowSize, List<Item> list){
// These function are related to read db operation
// flag = 0 means no condition
// flag = 1 means new items, the items user have never seen
// flag = 2 means item due, they need to be reviewed.
// windowSize = -1 means all items from id and on
HashMap<String, String> hm = new HashMap<String, String>();
String acqQuery;
String retQuery;
// ArrayList<String> list = new ArrayList<String>();
String query = "SELECT learn_tbl._id, date_learn, interval, grade, easiness, acq_reps, ret_reps, lapses, acq_reps_since_lapse, ret_reps_since_lapse, question, answer, note FROM dict_tbl INNER JOIN learn_tbl ON dict_tbl._id=learn_tbl._id WHERE dict_tbl._id >= "
+ id + " ";
Cursor acqResult;
Cursor retResult;
// result = myDatabase.query(true, "dict_tbl", null, querySelection,
// null, null, null, "_id", null);
// result = myDatabase.query("dict_tbl", null, querySelection, null,
// null, null, "_id");
// result = myDatabase.query(true, "dict_tbl", null, querySelection,
// null, null, null, null, "1");
if(windowSize >= 0){
retQuery = query
+ "AND round((julianday(date('now', 'localtime')) - julianday(date_learn))) - interval >= 0 AND acq_reps > 0 LIMIT "
+ windowSize;
}
else{
retQuery = query;
}
try {
retResult = myDatabase.rawQuery(retQuery, null);
} catch (Exception e) {
Log.e("Query item error", e.toString());
return false;
}
if (retResult.getCount() > 0) {
Cursor result = retResult;
retResult.moveToFirst();
do {
hm.put("_id", Integer.toString(result.getInt(result
.getColumnIndex("_id"))));
hm.put("question", result.getString(result
.getColumnIndex("question")));
hm.put("answer", result.getString(result
.getColumnIndex("answer")));
hm.put("note", result.getString(result.getColumnIndex("note")));
hm.put("date_learn", result.getString(result
.getColumnIndex("date_learn")));
hm.put("interval", Integer.toString(result.getInt(result
.getColumnIndex("interval"))));
hm.put("grade", Integer.toString(result.getInt(result
.getColumnIndex("grade"))));
hm.put("easiness", Double.toString(result.getDouble(result
.getColumnIndex("grade"))));
hm.put("acq_reps", Integer.toString(result.getInt(result
.getColumnIndex("acq_reps"))));
hm.put("ret_reps", Integer.toString(result.getInt(result
.getColumnIndex("ret_reps"))));
hm.put("lapses", Integer.toString(result.getInt(result
.getColumnIndex("lapses"))));
hm.put("acq_reps_since_lapse",Integer.toString(result.getInt(result
.getColumnIndex("acq_reps_since_lapse"))));
hm.put("ret_reps_since_lapse", Integer.toString(result.getInt(result
.getColumnIndex("ret_reps_since_lapse"))));
Item resultItem = new Item();
resultItem.setData(hm);
list.add(resultItem);
} while (result.moveToNext());
}
retResult.close();
int remainingSize = windowSize - list.size();
if (remainingSize > 0) {
acqQuery = query + "AND acq_reps = 0 LIMIT " + remainingSize;
try {
acqResult = myDatabase.rawQuery(acqQuery, null);
} catch (Exception e) {
Log.e("Query item error", e.toString());
return false;
}
// System.out.println("The result is: " + result.getString(0));
// return result.getString(1);
if (acqResult.getCount() > 0) {
Cursor result = acqResult;
acqResult.moveToFirst();
do {
hm.put("_id", Integer.toString(result.getInt(result
.getColumnIndex("_id"))));
hm.put("question", result.getString(result
.getColumnIndex("question")));
hm.put("answer", result.getString(result
.getColumnIndex("answer")));
hm.put("note", result.getString(result
.getColumnIndex("note")));
hm.put("date_learn", result.getString(result
.getColumnIndex("date_learn")));
hm.put("interval", Integer.toString(result.getInt(result
.getColumnIndex("interval"))));
hm.put("grade", Integer.toString(result.getInt(result
.getColumnIndex("grade"))));
hm.put("easiness", Double.toString(result.getDouble(result
.getColumnIndex("grade"))));
hm.put("acq_reps", Integer.toString(result.getInt(result
.getColumnIndex("acq_reps"))));
hm.put("ret_reps", Integer.toString(result.getInt(result
.getColumnIndex("ret_reps"))));
hm.put("lapses", Integer.toString(result.getInt(result
.getColumnIndex("lapses"))));
hm.put("acq_reps_since_lapse", Integer.toString(result
.getInt(result
.getColumnIndex("acq_reps_since_lapse"))));
hm.put("ret_reps_since_lapse", Integer.toString(result
.getInt(result
.getColumnIndex("ret_reps_since_lapse"))));
Item resultItem = new Item();
resultItem.setData(hm);
list.add(resultItem);
} while (result.moveToNext());
}
acqResult.close();
}
if (list.size() <= 0) {
return false;
} else {
return true;
}
}
| public boolean getListItems(int id, int windowSize, List<Item> list){
// These function are related to read db operation
// flag = 0 means no condition
// flag = 1 means new items, the items user have never seen
// flag = 2 means item due, they need to be reviewed.
// windowSize = -1 means all items from id and on
HashMap<String, String> hm = new HashMap<String, String>();
String acqQuery;
String retQuery;
// ArrayList<String> list = new ArrayList<String>();
String query = "SELECT learn_tbl._id, date_learn, interval, grade, easiness, acq_reps, ret_reps, lapses, acq_reps_since_lapse, ret_reps_since_lapse, question, answer, note FROM dict_tbl INNER JOIN learn_tbl ON dict_tbl._id=learn_tbl._id WHERE dict_tbl._id >= "
+ id + " ";
Cursor acqResult;
Cursor retResult;
// result = myDatabase.query(true, "dict_tbl", null, querySelection,
// null, null, null, "_id", null);
// result = myDatabase.query("dict_tbl", null, querySelection, null,
// null, null, "_id");
// result = myDatabase.query(true, "dict_tbl", null, querySelection,
// null, null, null, null, "1");
if(windowSize >= 0){
retQuery = query
+ "AND round((julianday(date('now', 'localtime')) - julianday(date_learn))) - interval >= 0 AND acq_reps > 0 LIMIT "
+ windowSize;
}
else{
retQuery = query;
}
try {
retResult = myDatabase.rawQuery(retQuery, null);
} catch (Exception e) {
Log.e("Query item error", e.toString());
return false;
}
if (retResult.getCount() > 0) {
Cursor result = retResult;
retResult.moveToFirst();
do {
hm.put("_id", Integer.toString(result.getInt(result
.getColumnIndex("_id"))));
hm.put("question", result.getString(result
.getColumnIndex("question")));
hm.put("answer", result.getString(result
.getColumnIndex("answer")));
hm.put("note", result.getString(result.getColumnIndex("note")));
hm.put("date_learn", result.getString(result
.getColumnIndex("date_learn")));
hm.put("interval", Integer.toString(result.getInt(result
.getColumnIndex("interval"))));
hm.put("grade", Integer.toString(result.getInt(result
.getColumnIndex("grade"))));
hm.put("easiness", Double.toString(result.getDouble(result
.getColumnIndex("easiness"))));
hm.put("acq_reps", Integer.toString(result.getInt(result
.getColumnIndex("acq_reps"))));
hm.put("ret_reps", Integer.toString(result.getInt(result
.getColumnIndex("ret_reps"))));
hm.put("lapses", Integer.toString(result.getInt(result
.getColumnIndex("lapses"))));
hm.put("acq_reps_since_lapse",Integer.toString(result.getInt(result
.getColumnIndex("acq_reps_since_lapse"))));
hm.put("ret_reps_since_lapse", Integer.toString(result.getInt(result
.getColumnIndex("ret_reps_since_lapse"))));
Item resultItem = new Item();
resultItem.setData(hm);
list.add(resultItem);
} while (result.moveToNext());
}
retResult.close();
int remainingSize = windowSize - list.size();
if (remainingSize > 0) {
acqQuery = query + "AND acq_reps = 0 LIMIT " + remainingSize;
try {
acqResult = myDatabase.rawQuery(acqQuery, null);
} catch (Exception e) {
Log.e("Query item error", e.toString());
return false;
}
// System.out.println("The result is: " + result.getString(0));
// return result.getString(1);
if (acqResult.getCount() > 0) {
Cursor result = acqResult;
acqResult.moveToFirst();
do {
hm.put("_id", Integer.toString(result.getInt(result
.getColumnIndex("_id"))));
hm.put("question", result.getString(result
.getColumnIndex("question")));
hm.put("answer", result.getString(result
.getColumnIndex("answer")));
hm.put("note", result.getString(result
.getColumnIndex("note")));
hm.put("date_learn", result.getString(result
.getColumnIndex("date_learn")));
hm.put("interval", Integer.toString(result.getInt(result
.getColumnIndex("interval"))));
hm.put("grade", Integer.toString(result.getInt(result
.getColumnIndex("grade"))));
hm.put("easiness", Double.toString(result.getDouble(result
.getColumnIndex("easiness"))));
hm.put("acq_reps", Integer.toString(result.getInt(result
.getColumnIndex("acq_reps"))));
hm.put("ret_reps", Integer.toString(result.getInt(result
.getColumnIndex("ret_reps"))));
hm.put("lapses", Integer.toString(result.getInt(result
.getColumnIndex("lapses"))));
hm.put("acq_reps_since_lapse", Integer.toString(result
.getInt(result
.getColumnIndex("acq_reps_since_lapse"))));
hm.put("ret_reps_since_lapse", Integer.toString(result
.getInt(result
.getColumnIndex("ret_reps_since_lapse"))));
Item resultItem = new Item();
resultItem.setData(hm);
list.add(resultItem);
} while (result.moveToNext());
}
acqResult.close();
}
if (list.size() <= 0) {
return false;
} else {
return true;
}
}
|
diff --git a/moria/src/no/feide/moria/service/AuthenticationImpl.java b/moria/src/no/feide/moria/service/AuthenticationImpl.java
index 0f0862e3..f13116c4 100644
--- a/moria/src/no/feide/moria/service/AuthenticationImpl.java
+++ b/moria/src/no/feide/moria/service/AuthenticationImpl.java
@@ -1,302 +1,302 @@
/**
* Copyright (C) 2003 FEIDE
* 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.
*/
package no.feide.moria.service;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.security.Principal;
import java.rmi.RemoteException;
import java.net.MalformedURLException;
import java.util.Date;
import java.util.Timer;
import java.util.HashMap;
import java.util.logging.Logger;
import javax.xml.rpc.ServiceException;
import javax.xml.rpc.server.ServiceLifecycle;
import javax.xml.rpc.server.ServletEndpointContext;
import no.feide.moria.Configuration;
import no.feide.moria.ConfigurationException;
import no.feide.moria.Session;
import no.feide.moria.SessionStore;
import no.feide.moria.SessionException;
import no.feide.moria.BackendException;
import no.feide.moria.Credentials;
import no.feide.moria.authorization.WebService;
import no.feide.moria.authorization.AuthorizationData;
import no.feide.moria.authorization.AuthorizationTask;
public class AuthenticationImpl
implements AuthenticationIF, ServiceLifecycle {
/** Used for logging. */
private static Logger log = Logger.getLogger(AuthenticationImpl.class.toString());
/** Used to retrieve the client identity. */
private ServletEndpointContext ctx;
/** Session store. */
private SessionStore sessionStore;
/** Timer for updating the web service authorization module. */
private Timer authTimer = new Timer(true);
/**
* Service endpoint destructor. Some basic housekeeping.
*/
public void destroy() {
log.finer("destroy()");
authTimer.cancel();
log = null;
ctx = null;
}
/**
* Service endpoint initialization. Will read the <code>Properties</code>
* file found in the location given by the system property
* <code>no.feide.moria.config.file</code>. If the property is not
* set, the default filename is <code>/moria.properties</code>.
* @param context The servlet context, used to find the user (client service)
* identity in later methods.
* @throws ServiceException If a FileNotFoundException or IOException id
* caught when reading the properties file. Also
* thrown if the system property
* <code>no.feide.moria.AuthorizationTimerDelay</code>
* is not set, or if there is a problem getting
* the session store instance.
*/
public void init(Object context)
throws ServiceException {
log.finer("init(Object)");
ctx = (ServletEndpointContext)context;
try {
sessionStore = SessionStore.getInstance();
int authDelay = new Integer(Configuration.getProperty("no.feide.moria.AuthorizationTimerDelay")).intValue()*1000; // Seconds to milliseconds
log.config("Starting authorization update service with delay= "+authDelay+"ms");
authTimer.scheduleAtFixedRate(new AuthorizationTask(), new Date(), authDelay);
/* Sleep a short while. If not the authorization data will not
be updated in time to authorize the first authentication request. */
try {
int initialSleep = new Integer(Configuration.getProperty("no.feide.moria.AuthorizationTimerInitThreadSleep")).intValue();
log.config("Sleep "+initialSleep+" seconds while reading auth. config.");
Thread.sleep(initialSleep*1000);
}
catch (InterruptedException e) {
/* We didn't get any sleep. Don't care. If this is the
* case, the first web service authorization request will
* end in an exception. After that everything will be all
* right.
*/
}
} catch (ConfigurationException e) {
log.severe("ConfigurationException caught and re-thrown as ServiceException");
throw new ServiceException("ConfigurationException caught", e);
} catch (SessionException e) {
log.severe("SessionException caught and re-thrown as ServiceException");
throw new ServiceException("SessionException caught", e);
}
}
/**
* A simple wrapper for
* <code>requestSession(String[], String, String, true)</code>. That is,
* the web service configuration is used to determine if SSO should be
* used or not.
* @param attributes The requested user attributes, to be returned from
* <code>verifySession()</code> once authentication is
* complete. <code>null</code> value allowed.
* @param prefix The prefix, used to build the <code>verifySession</code>
* return value. May be <code>null</code>.
* @param postfix The postfix, used to build the
* <code>verifySession</code> return value. May be
* <code>null</code>.
* @return An URL to the authentication service.
* @throws RemoteException If a SessionException or a
* BackendException is caught. Also thrown if the
* prefix/postfix doesn't combine into a valid
* URL, or if the
*/
public String requestSession(String[] attributes, String prefix, String postfix)
throws RemoteException {
log.finer("requestSession(String[], String, String)");
return requestSession(attributes, prefix, postfix, false);
}
/**
* Request a new Moria session, with the option to turn off SSO even though
* the web service authorization config would allow it.
* @param attributes The requested user attributes, to be returned from
* <code>verifySession()</code> once authentication is
* complete. <code>null</code> value allowed.
* @param prefix The prefix, used to build the <code>verifySession</code>
* return value. May be <code>null</code>.
* @param postfix The postfix, used to build the
* <code>verifySession</code> return value. May be
* <code>null</code>.
* @param denySSO If <code>true</code> SSO is disabled even though the
* web service config may allow SSO. If <code>false</code>,
* the config is used to determine if the web service can
* use SSO.
* @return An URL to the authentication service.
* @throws RemoteException If a SessionException or a
* BackendException is caught. Also thrown if the
* prefix/postfix doesn't combine into a valid
* URL, or if a <code>ConfigurationException<code>
* is caught.
*/
public String requestSession(String[] attributes, String prefix, String postfix, boolean denySso)
throws RemoteException {
log.finer("requestSession(String[], String, String, boolean)");
/* Check if prefix and postfix, together with a possible
* session ID, is a valid URL. */
String simulatedURL = prefix+"MORIAID"+postfix;
try {
new URL(simulatedURL);
} catch (MalformedURLException e) {
log.severe("Malformed URL: "+simulatedURL);
throw new RemoteException("Malformed URL: "+simulatedURL);
}
/* Look up service authorization data. */
Principal p = ctx.getUserPrincipal();
String serviceName = null;
if (p != null)
serviceName = p.getName();
log.fine("Client service requesting session: "+serviceName);
WebService ws = AuthorizationData.getInstance().getWebService(serviceName);
if (ws == null) {
log.warning("Unauthorized service access: "+serviceName);
throw new RemoteException("Web Service not authorized for use with Moria");
} else if (!ws.allowAccessToAttributes(attributes)) {
log.warning("Attribute request from service "+serviceName+" refused");
throw new RemoteException("Access to one or more attributes prohibited");
}
try {
Session session = sessionStore.createSession(attributes, prefix, postfix, p, ws);
/* Turn of SSO if required by web service. */
- if (!denySso)
+ if (denySso)
session.denySso();
return session.getRedirectURL();
} catch (SessionException e) {
log.severe("SessionException caught and re-thrown as RemoteException");
throw new RemoteException("SessionException caught", e);
} catch (ConfigurationException e) {
log.severe("ConfigurationException caught and re-thrown as RemoteException");
throw new RemoteException("ConfigurationException caught", e);
}
}
/* Return the previously requested user attributes.
* @param The session ID.
* @return The previously requested user attributes.
* @throws RemoteException If a SessionException or a
* BackendException is caught. Also thrown if
* the current client's identity (as found in
* the context) is different from the identity
* of the client service originally requesting
* the session.
*/
public HashMap getAttributes(String id)
throws RemoteException {
log.finer("getAttributes(String)");
try {
/* Look up session and check the client identity. */
Session session = sessionStore.getSession(id);
String serviceName = null;
if (ctx.getUserPrincipal() != null)
serviceName = ctx.getUserPrincipal().getName();
if (!session.getWebService().getId().equals(serviceName)) {
log.severe("WebService ("+serviceName+") tried to get unauthorized access to auth session.");
throw new RemoteException("Access denied");
}
if (session.isLocked()) {
log.warning("Service ("+serviceName+") tried to access locked session: "+session.getID());
throw new RemoteException("No such session.");
}
assertPrincipals(ctx.getUserPrincipal(), session.getClientPrincipal());
/* Return attributes. */
HashMap result = session.getAttributes();
return result;
} catch (SessionException e) {
log.severe("SessionException caught, and re-thrown as RemoteException");
throw new RemoteException("SessionException caught", e);
}
}
/**
* Utility method, used to check if a given client service principal
* matches the principal stored in the session. <code>null</code> values
* are allowed.
* @param pCurrent The current client principal.
* @param pStored The principal stored in the session.
* @throws SessionException If there's a problem getting the session from
* the session sessionStore.
* @throws RemoteException If the client principals didn't match.
*/
private static void assertPrincipals(Principal pCurrent, Principal pStored)
throws SessionException, RemoteException {
log.finer("assertPrincipals(Principal, String)");
if (pCurrent == null) {
if (pStored == null)
return;
}
else if (pCurrent.toString().equals(pStored.toString()))
return;
log.severe("Client service identity mismatch; "+pCurrent+" != "+pStored);
throw new RemoteException("Client service identity mismatch");
}
}
| true | true | public String requestSession(String[] attributes, String prefix, String postfix, boolean denySso)
throws RemoteException {
log.finer("requestSession(String[], String, String, boolean)");
/* Check if prefix and postfix, together with a possible
* session ID, is a valid URL. */
String simulatedURL = prefix+"MORIAID"+postfix;
try {
new URL(simulatedURL);
} catch (MalformedURLException e) {
log.severe("Malformed URL: "+simulatedURL);
throw new RemoteException("Malformed URL: "+simulatedURL);
}
/* Look up service authorization data. */
Principal p = ctx.getUserPrincipal();
String serviceName = null;
if (p != null)
serviceName = p.getName();
log.fine("Client service requesting session: "+serviceName);
WebService ws = AuthorizationData.getInstance().getWebService(serviceName);
if (ws == null) {
log.warning("Unauthorized service access: "+serviceName);
throw new RemoteException("Web Service not authorized for use with Moria");
} else if (!ws.allowAccessToAttributes(attributes)) {
log.warning("Attribute request from service "+serviceName+" refused");
throw new RemoteException("Access to one or more attributes prohibited");
}
try {
Session session = sessionStore.createSession(attributes, prefix, postfix, p, ws);
/* Turn of SSO if required by web service. */
if (!denySso)
session.denySso();
return session.getRedirectURL();
} catch (SessionException e) {
log.severe("SessionException caught and re-thrown as RemoteException");
throw new RemoteException("SessionException caught", e);
} catch (ConfigurationException e) {
log.severe("ConfigurationException caught and re-thrown as RemoteException");
throw new RemoteException("ConfigurationException caught", e);
}
}
| public String requestSession(String[] attributes, String prefix, String postfix, boolean denySso)
throws RemoteException {
log.finer("requestSession(String[], String, String, boolean)");
/* Check if prefix and postfix, together with a possible
* session ID, is a valid URL. */
String simulatedURL = prefix+"MORIAID"+postfix;
try {
new URL(simulatedURL);
} catch (MalformedURLException e) {
log.severe("Malformed URL: "+simulatedURL);
throw new RemoteException("Malformed URL: "+simulatedURL);
}
/* Look up service authorization data. */
Principal p = ctx.getUserPrincipal();
String serviceName = null;
if (p != null)
serviceName = p.getName();
log.fine("Client service requesting session: "+serviceName);
WebService ws = AuthorizationData.getInstance().getWebService(serviceName);
if (ws == null) {
log.warning("Unauthorized service access: "+serviceName);
throw new RemoteException("Web Service not authorized for use with Moria");
} else if (!ws.allowAccessToAttributes(attributes)) {
log.warning("Attribute request from service "+serviceName+" refused");
throw new RemoteException("Access to one or more attributes prohibited");
}
try {
Session session = sessionStore.createSession(attributes, prefix, postfix, p, ws);
/* Turn of SSO if required by web service. */
if (denySso)
session.denySso();
return session.getRedirectURL();
} catch (SessionException e) {
log.severe("SessionException caught and re-thrown as RemoteException");
throw new RemoteException("SessionException caught", e);
} catch (ConfigurationException e) {
log.severe("ConfigurationException caught and re-thrown as RemoteException");
throw new RemoteException("ConfigurationException caught", e);
}
}
|
diff --git a/src/com/soartech/bolt/testing/Script.java b/src/com/soartech/bolt/testing/Script.java
index 34fe775..2e85cb2 100644
--- a/src/com/soartech/bolt/testing/Script.java
+++ b/src/com/soartech/bolt/testing/Script.java
@@ -1,46 +1,48 @@
package com.soartech.bolt.testing;
import java.util.LinkedList;
public class Script {
private LinkedList<Action> actions;
public Script() {
actions = new LinkedList<Action>();
}
public void insertFirstAction(Action a) {
actions.addFirst(a);
}
public void addAction(Action a) {
actions.add(a);
}
public Action getNextAction() {
return actions.pop();
}
public ActionType peekType() {
if(actions.peek() != null)
return actions.peek().getType();
else
return null;
}
public boolean hasNextAction() {
return !(actions.peek() == null);
}
public boolean nextActionRequiresMentorAttention() {
+ if(actions.peek() == null)
+ return false;
ActionType type = actions.peek().getType();
if(type == null)
return false;
switch(type) {
case Mentor: return false;
case MentorAction: return true;
case AgentAction: return true;
default: return false;
}
}
}
| true | true | public boolean nextActionRequiresMentorAttention() {
ActionType type = actions.peek().getType();
if(type == null)
return false;
switch(type) {
case Mentor: return false;
case MentorAction: return true;
case AgentAction: return true;
default: return false;
}
}
| public boolean nextActionRequiresMentorAttention() {
if(actions.peek() == null)
return false;
ActionType type = actions.peek().getType();
if(type == null)
return false;
switch(type) {
case Mentor: return false;
case MentorAction: return true;
case AgentAction: return true;
default: return false;
}
}
|
diff --git a/src/main/java/org/lastbamboo/common/turn/server/allocated/TcpAllocatedTurnServer.java b/src/main/java/org/lastbamboo/common/turn/server/allocated/TcpAllocatedTurnServer.java
index 11c682d..789fa8a 100644
--- a/src/main/java/org/lastbamboo/common/turn/server/allocated/TcpAllocatedTurnServer.java
+++ b/src/main/java/org/lastbamboo/common/turn/server/allocated/TcpAllocatedTurnServer.java
@@ -1,151 +1,151 @@
package org.lastbamboo.common.turn.server.allocated;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import org.apache.mina.common.ByteBuffer;
import org.apache.mina.common.ExecutorThreadModel;
import org.apache.mina.common.IoFilter;
import org.apache.mina.common.IoHandler;
import org.apache.mina.common.IoService;
import org.apache.mina.common.IoServiceConfig;
import org.apache.mina.common.IoServiceListener;
import org.apache.mina.common.IoSession;
import org.apache.mina.common.SimpleByteBufferAllocator;
import org.apache.mina.common.ThreadModel;
import org.apache.mina.transport.socket.nio.SocketAcceptor;
import org.apache.mina.transport.socket.nio.SocketAcceptorConfig;
import org.lastbamboo.common.turn.server.TurnClient;
import org.lastbamboo.common.util.NetworkUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Implementation of a TCP allocated TURN server.
*/
public class TcpAllocatedTurnServer implements AllocatedTurnServer,
IoServiceListener
{
private final Logger LOG =
LoggerFactory.getLogger(TcpAllocatedTurnServer.class);
private final TurnClient m_turnClient;
private final SocketAcceptor m_acceptor;
private final InetAddress m_publicAddress;
private InetSocketAddress m_serviceAddress;
/**
* Creates a new TURN server allocated on behalf of a TURN client. This
* server will accept connections with permission to connect to the TURN
* client and will relay data on the TURN client's behalf.
*
* @param turnClient The TURN client.
* @param publicAddress The address to bind to.
*/
public TcpAllocatedTurnServer(final TurnClient turnClient,
final InetAddress publicAddress)
{
m_turnClient = turnClient;
this.m_publicAddress = publicAddress;
ByteBuffer.setUseDirectBuffers(false);
ByteBuffer.setAllocator(new SimpleByteBufferAllocator());
final Executor executor = Executors.newCachedThreadPool();
this.m_acceptor = new SocketAcceptor(
Runtime.getRuntime().availableProcessors() + 1, executor);
m_acceptor.addListener(this);
}
public void start()
{
// Note there's no encoder here because we just write raw bytes to
// remote hosts. The TURN server is responsible for unwrapping the
// raw bytes from the TURN Send Indication messages.
// We're receiving raw data on these sockets and packaging it for
// our TURN client. This filter just reads the raw data and
// encapsulates it in TURN Data Indication messages.
final IoFilter rawDataFilter = new TurnRawDataFilter();
m_acceptor.getFilterChain().addLast("to-stun", rawDataFilter);
final SocketAcceptorConfig config = new SocketAcceptorConfig();
final ThreadModel threadModel =
ExecutorThreadModel.getInstance("TCP-TURN-Allocated-Server");
config.setThreadModel(threadModel);
m_acceptor.setDefaultConfig(config);
// The IO handler just processes the Data Indication messages.
final IoHandler handler =
new AllocatedTurnServerIoHandler(this.m_turnClient);
try
{
final InetSocketAddress bindAddress =
new InetSocketAddress(NetworkUtils.getLocalHost(), 0);
m_acceptor.bind(bindAddress, handler);
- LOG.debug("Started TCP allocated TURN server, binding to: "+
- this.m_publicAddress);
+ LOG.debug("Started TCP allocated TURN server, bound to: "+
+ bindAddress);
}
catch (final IOException e)
{
LOG.error("Could not bind server", e);
}
}
public void stop()
{
this.m_acceptor.unbindAll();
}
public void serviceActivated(final IoService service,
final SocketAddress serviceAddress, final IoHandler handler,
final IoServiceConfig config)
{
final InetSocketAddress isa = (InetSocketAddress) serviceAddress;
this.m_serviceAddress =
new InetSocketAddress(this.m_publicAddress, isa.getPort());
LOG.debug("Allocated server started on: {}", serviceAddress);
LOG.debug("Using public address: {}", this.m_serviceAddress);
}
public void serviceDeactivated(final IoService service,
final SocketAddress serviceAddress, final IoHandler handler,
final IoServiceConfig config)
{
// TODO Auto-generated method stub
}
public void sessionCreated(final IoSession session)
{
this.m_turnClient.addConnection(session);
/*
if (this.m_turnClient.hasIncomingPermission(session))
{
this.m_turnClient.addConnection(session);
}
else
{
session.close();
}
*/
}
public void sessionDestroyed(final IoSession session)
{
LOG.debug("Lost connection to: {}", session);
this.m_turnClient.removeConnection(session);
}
public InetSocketAddress getSocketAddress()
{
return this.m_serviceAddress;
}
}
| true | true | public void start()
{
// Note there's no encoder here because we just write raw bytes to
// remote hosts. The TURN server is responsible for unwrapping the
// raw bytes from the TURN Send Indication messages.
// We're receiving raw data on these sockets and packaging it for
// our TURN client. This filter just reads the raw data and
// encapsulates it in TURN Data Indication messages.
final IoFilter rawDataFilter = new TurnRawDataFilter();
m_acceptor.getFilterChain().addLast("to-stun", rawDataFilter);
final SocketAcceptorConfig config = new SocketAcceptorConfig();
final ThreadModel threadModel =
ExecutorThreadModel.getInstance("TCP-TURN-Allocated-Server");
config.setThreadModel(threadModel);
m_acceptor.setDefaultConfig(config);
// The IO handler just processes the Data Indication messages.
final IoHandler handler =
new AllocatedTurnServerIoHandler(this.m_turnClient);
try
{
final InetSocketAddress bindAddress =
new InetSocketAddress(NetworkUtils.getLocalHost(), 0);
m_acceptor.bind(bindAddress, handler);
LOG.debug("Started TCP allocated TURN server, binding to: "+
this.m_publicAddress);
}
catch (final IOException e)
{
LOG.error("Could not bind server", e);
}
}
| public void start()
{
// Note there's no encoder here because we just write raw bytes to
// remote hosts. The TURN server is responsible for unwrapping the
// raw bytes from the TURN Send Indication messages.
// We're receiving raw data on these sockets and packaging it for
// our TURN client. This filter just reads the raw data and
// encapsulates it in TURN Data Indication messages.
final IoFilter rawDataFilter = new TurnRawDataFilter();
m_acceptor.getFilterChain().addLast("to-stun", rawDataFilter);
final SocketAcceptorConfig config = new SocketAcceptorConfig();
final ThreadModel threadModel =
ExecutorThreadModel.getInstance("TCP-TURN-Allocated-Server");
config.setThreadModel(threadModel);
m_acceptor.setDefaultConfig(config);
// The IO handler just processes the Data Indication messages.
final IoHandler handler =
new AllocatedTurnServerIoHandler(this.m_turnClient);
try
{
final InetSocketAddress bindAddress =
new InetSocketAddress(NetworkUtils.getLocalHost(), 0);
m_acceptor.bind(bindAddress, handler);
LOG.debug("Started TCP allocated TURN server, bound to: "+
bindAddress);
}
catch (final IOException e)
{
LOG.error("Could not bind server", e);
}
}
|
diff --git a/xcmis-sp-jcr-exo/src/main/java/org/xcmis/sp/jcr/exo/JcrTypeHelper.java b/xcmis-sp-jcr-exo/src/main/java/org/xcmis/sp/jcr/exo/JcrTypeHelper.java
index 588116ba..542d0f7c 100644
--- a/xcmis-sp-jcr-exo/src/main/java/org/xcmis/sp/jcr/exo/JcrTypeHelper.java
+++ b/xcmis-sp-jcr-exo/src/main/java/org/xcmis/sp/jcr/exo/JcrTypeHelper.java
@@ -1,439 +1,439 @@
/**
* Copyright (C) 2010 eXo Platform SAS.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.xcmis.sp.jcr.exo;
import org.xcmis.spi.BaseType;
import org.xcmis.spi.CMIS;
import org.xcmis.spi.ContentStreamAllowed;
import org.xcmis.spi.DateResolution;
import org.xcmis.spi.Precision;
import org.xcmis.spi.PropertyDefinition;
import org.xcmis.spi.PropertyType;
import org.xcmis.spi.TypeDefinition;
import org.xcmis.spi.Updatability;
import org.xcmis.spi.impl.PropertyDefinitionImpl;
import org.xcmis.spi.impl.TypeDefinitionImpl;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import javax.jcr.nodetype.NodeType;
/**
* @author <a href="mailto:[email protected]">Andrey Parfonov</a>
* @version $Id$
*/
class JcrTypeHelper
{
/**
* Get object type definition.
*
* @param nt JCR back-end node
* @param includePropertyDefinition true if need include property definition
* false otherwise
* @return object definition or <code>null</code> if specified JCR node-type
* has not corresponded CMIS type
* @throws NotSupportedNodeTypeException if specified node-type is
* unsupported by xCMIS
*/
public static TypeDefinition getTypeDefinition(NodeType nt, boolean includePropertyDefinition)
throws NotSupportedNodeTypeException
{
if (nt.isNodeType(JcrCMIS.NT_FILE))
{
return getDocumentDefinition(nt, includePropertyDefinition);
}
else if (nt.isNodeType(JcrCMIS.NT_FOLDER) || nt.isNodeType(JcrCMIS.NT_UNSTRUCTURED))
{
return getFolderDefinition(nt, includePropertyDefinition);
}
else if (nt.isNodeType(JcrCMIS.CMIS_NT_RELATIONSHIP))
{
return getRelationshipDefinition(nt, includePropertyDefinition);
}
else if (nt.isNodeType(JcrCMIS.CMIS_NT_POLICY))
{
return getPolicyDefinition(nt, includePropertyDefinition);
}
else
{
throw new NotSupportedNodeTypeException("Type " + nt.getName() + " is unsupported for xCMIS.");
}
}
/**
* Get CMIS object type id by the JCR node type name.
*
* @param ntName the JCR node type name
* @return CMIS object type id
*/
public static String getCmisTypeId(String ntName)
{
if (ntName.equals(JcrCMIS.NT_FILE))
{
return BaseType.DOCUMENT.value();
}
if (ntName.equals(JcrCMIS.NT_FOLDER) || ntName.equals(JcrCMIS.NT_UNSTRUCTURED))
{
return BaseType.FOLDER.value();
}
return ntName;
}
/**
* Get JCR node type name by the CMIS object type id.
*
* @param typeId the CMIS base object type id
* @return JCR string node type
*/
public static String getNodeTypeName(String typeId)
{
if (typeId.equals(BaseType.DOCUMENT.value()))
{
return JcrCMIS.NT_FILE;
}
if (typeId.equals(BaseType.FOLDER.value()))
{
return JcrCMIS.NT_FOLDER;
}
return typeId;
}
/**
* Document type definition.
*
* @param nt node type
* @param includePropertyDefinition true if need include property definition
* false otherwise
* @return document type definition
*/
protected static TypeDefinition getDocumentDefinition(NodeType nt, boolean includePropertyDefinition)
{
TypeDefinitionImpl def = new TypeDefinitionImpl();
String localTypeName = nt.getName();
String typeId = getCmisTypeId(localTypeName);
def.setBaseId(BaseType.DOCUMENT);
def.setContentStreamAllowed(ContentStreamAllowed.ALLOWED);
def.setControllableACL(true);
def.setControllablePolicy(true);
def.setCreatable(true);
def.setDescription("Cmis Document Type");
def.setDisplayName(typeId);
def.setFileable(true);
def.setFulltextIndexed(true);
def.setId(typeId);
def.setIncludedInSupertypeQuery(true);
def.setLocalName(localTypeName);
def.setLocalNamespace(JcrCMIS.EXO_CMIS_NS_URI);
if (typeId.equals(BaseType.DOCUMENT.value()))
{
def.setParentId(null); // no parents for root type
}
else
{
// Try determine parent type.
NodeType[] superTypes = nt.getDeclaredSupertypes();
for (NodeType superType : superTypes)
{
if (superType.isNodeType(JcrCMIS.NT_FILE))
{
// Take first type that is super for cmis:document or is cmis:document.
def.setParentId(getCmisTypeId(superType.getName()));
break;
}
}
}
def.setQueryable(true);
def.setQueryName(typeId);
def.setVersionable(true);
if (includePropertyDefinition)
{
addPropertyDefinitions(def, nt);
}
return def;
}
/**
* Folder type definition.
*
* @param nt node type
* @param includePropertyDefinition true if need include property definition
* false otherwise
* @return folder type definition
*/
protected static TypeDefinition getFolderDefinition(NodeType nt, boolean includePropertyDefinition)
{
TypeDefinitionImpl def = new TypeDefinitionImpl();
String localTypeName = nt.getName();
String typeId = getCmisTypeId(localTypeName);
def.setBaseId(BaseType.FOLDER);
def.setControllableACL(true);
def.setControllablePolicy(true);
def.setCreatable(true);
def.setDescription("Cmis Folder Type");
def.setDisplayName(typeId);
def.setFileable(true);
def.setFulltextIndexed(false);
def.setId(typeId);
def.setIncludedInSupertypeQuery(true);
def.setLocalName(localTypeName);
def.setLocalNamespace(JcrCMIS.EXO_CMIS_NS_URI);
if (typeId.equals(BaseType.FOLDER.value()))
{
def.setParentId(null); // no parents for root type
}
else
{
// Try determine parent type.
NodeType[] superTypes = nt.getDeclaredSupertypes();
for (NodeType superType : superTypes)
{
if (superType.isNodeType(JcrCMIS.NT_FOLDER))
{
// Take first type that is super for cmis:folder or is cmis:folder.
def.setParentId(getCmisTypeId(superType.getName()));
break;
}
}
}
def.setQueryable(true);
def.setQueryName(typeId);
if (includePropertyDefinition)
{
addPropertyDefinitions(def, nt);
}
return def;
}
/**
* Get policy type definition.
*
* @param nt node type
* @param includePropertyDefinition true if need include property definition
* false otherwise
* @return type policy definition
*/
protected static TypeDefinition getPolicyDefinition(NodeType nt, boolean includePropertyDefinition)
{
TypeDefinitionImpl def = new TypeDefinitionImpl();
String localTypeName = nt.getName();
String typeId = getCmisTypeId(localTypeName);
def.setBaseId(BaseType.POLICY);
def.setControllableACL(true);
def.setControllablePolicy(true);
def.setCreatable(true);
def.setDescription("Cmis Policy Type");
def.setDisplayName(typeId);
def.setFileable(false);
def.setFulltextIndexed(false);
def.setId(typeId);
def.setIncludedInSupertypeQuery(true);
def.setLocalName(localTypeName);
def.setLocalNamespace(JcrCMIS.EXO_CMIS_NS_URI);
if (typeId.equals(BaseType.POLICY.value()))
{
def.setParentId(null); // no parents for root type
}
else
{
// Try determine parent type.
NodeType[] superTypes = nt.getDeclaredSupertypes();
for (NodeType superType : superTypes)
{
if (superType.isNodeType(JcrCMIS.CMIS_NT_POLICY))
{
// Take first type that is super for cmis:policy or is cmis:policy.
def.setParentId(getCmisTypeId(superType.getName()));
break;
}
}
}
def.setQueryable(false);
def.setQueryName(typeId);
if (includePropertyDefinition)
{
addPropertyDefinitions(def, nt);
}
return def;
}
/**
* Get relationship type definition.
*
* @param nt node type
* @param includePropertyDefinition true if need include property definition
* false otherwise
* @return type relationship definition
*/
protected static TypeDefinition getRelationshipDefinition(NodeType nt, boolean includePropertyDefinition)
{
TypeDefinitionImpl def = new TypeDefinitionImpl();
String localTypeName = nt.getName();
String typeId = getCmisTypeId(localTypeName);
def.setBaseId(BaseType.RELATIONSHIP);
def.setControllableACL(false);
def.setControllablePolicy(false);
def.setCreatable(true);
def.setDescription("Cmis Relationship Type");
def.setDisplayName(typeId);
def.setFileable(false);
def.setFulltextIndexed(false);
def.setId(typeId);
def.setIncludedInSupertypeQuery(false);
def.setLocalName(localTypeName);
def.setLocalNamespace(JcrCMIS.EXO_CMIS_NS_URI);
if (typeId.equals(BaseType.RELATIONSHIP.value()))
{
def.setParentId(null); // no parents for root type
}
else
{
// Try determine parent type.
NodeType[] superTypes = nt.getDeclaredSupertypes();
for (NodeType superType : superTypes)
{
if (superType.isNodeType(JcrCMIS.CMIS_NT_RELATIONSHIP))
{
// Take first type that is super for cmis:relationship or is cmis:relationship.
def.setParentId(getCmisTypeId(superType.getName()));
break;
}
}
}
def.setQueryable(false);
def.setQueryName(typeId);
if (includePropertyDefinition)
{
addPropertyDefinitions(def, nt);
}
return def;
}
/**
* Add property definitions.
*
* @param typeDefinition the object type definition
* @param nt the JCR node type.
*/
private static void addPropertyDefinitions(TypeDefinition typeDefinition, NodeType nt)
{
// Known described in spec. property definitions
// for (PropertyDefinition<?> propDef : PropertyDefinitionsMap.getAll(typeDefinition.getBaseId().value()))
// typeDefinition.getPropertyDefinitions().add(propDef);
Map<String, PropertyDefinition<?>> pd =
new HashMap<String, PropertyDefinition<?>>(PropertyDefinitions.getAll(typeDefinition.getBaseId().value()));
Set<String> knownIds = PropertyDefinitions.getPropertyIds(typeDefinition.getBaseId().value());
for (javax.jcr.nodetype.PropertyDefinition jcrPropertyDef : nt.getPropertyDefinitions())
{
String pdName = jcrPropertyDef.getName();
// TODO : Do not use any constraint about prefixes, need discovery
// hierarchy of JCR types or so on.
if (pdName.startsWith("cmis:"))
{
// Do not process known properties
if (!knownIds.contains(pdName))
{
PropertyDefinition<?> cmisPropDef = null;
// TODO : default values.
switch (jcrPropertyDef.getRequiredType())
{
case javax.jcr.PropertyType.BOOLEAN :
PropertyDefinitionImpl<Boolean> boolDef =
new PropertyDefinitionImpl<Boolean>(pdName, pdName, pdName, null, pdName, null,
PropertyType.BOOLEAN, jcrPropertyDef.isProtected() ? Updatability.READONLY
: Updatability.READWRITE, false, jcrPropertyDef.isMandatory(), true, true, null,
jcrPropertyDef.isMultiple(), null, null);
cmisPropDef = boolDef;
break;
case javax.jcr.PropertyType.DATE :
PropertyDefinitionImpl<Calendar> dateDef =
new PropertyDefinitionImpl<Calendar>(pdName, pdName, pdName, null, pdName, null,
PropertyType.DATETIME, jcrPropertyDef.isProtected() ? Updatability.READONLY
: Updatability.READWRITE, false, jcrPropertyDef.isMandatory(), true, true, null,
jcrPropertyDef.isMultiple(), null, null);
dateDef.setDateResolution(DateResolution.TIME);
cmisPropDef = dateDef;
break;
case javax.jcr.PropertyType.DOUBLE :
PropertyDefinitionImpl<BigDecimal> decimalDef =
new PropertyDefinitionImpl<BigDecimal>(pdName, pdName, pdName, null, pdName, null,
PropertyType.DECIMAL, jcrPropertyDef.isProtected() ? Updatability.READONLY
: Updatability.READWRITE, false, jcrPropertyDef.isMandatory(), true, true, null,
jcrPropertyDef.isMultiple(), null, null);
- decimalDef.setPrecision(Precision.Bit32);
+ decimalDef.setDecimalPrecision(Precision.Bit32);
decimalDef.setMaxDecimal(CMIS.MAX_DECIMAL_VALUE);
decimalDef.setMinDecimal(CMIS.MIN_DECIMAL_VALUE);
cmisPropDef = decimalDef;
break;
case javax.jcr.PropertyType.LONG :
PropertyDefinitionImpl<BigInteger> integerDef =
new PropertyDefinitionImpl<BigInteger>(pdName, pdName, pdName, null, pdName, null,
PropertyType.INTEGER, jcrPropertyDef.isProtected() ? Updatability.READONLY
: Updatability.READWRITE, false, jcrPropertyDef.isMandatory(), true, true, null,
jcrPropertyDef.isMultiple(), null, null);
integerDef.setMaxInteger(CMIS.MAX_INTEGER_VALUE);
integerDef.setMinInteger(CMIS.MIN_INTEGER_VALUE);
cmisPropDef = integerDef;
break;
case javax.jcr.PropertyType.NAME : // TODO
// CmisPropertyIdDefinitionType idDef = new CmisPropertyIdDefinitionType();
// idDef.setPropertyType(EnumPropertyType.ID);
// cmisPropDef = idDef;
// break;
case javax.jcr.PropertyType.REFERENCE :
case javax.jcr.PropertyType.STRING :
case javax.jcr.PropertyType.PATH :
case javax.jcr.PropertyType.BINARY :
case javax.jcr.PropertyType.UNDEFINED :
PropertyDefinitionImpl<String> stringDef =
new PropertyDefinitionImpl<String>(pdName, pdName, pdName, null, pdName, null,
PropertyType.STRING, jcrPropertyDef.isProtected() ? Updatability.READONLY
: Updatability.READWRITE, false, jcrPropertyDef.isMandatory(), true, true, null,
jcrPropertyDef.isMultiple(), null, null);
stringDef.setMaxLength(CMIS.MAX_STRING_LENGTH);
cmisPropDef = stringDef;
break;
}
pd.put(cmisPropDef.getId(), cmisPropDef);
}
}
}
((TypeDefinitionImpl)typeDefinition).setPropertyDefinitions(pd);
}
}
| true | true | private static void addPropertyDefinitions(TypeDefinition typeDefinition, NodeType nt)
{
// Known described in spec. property definitions
// for (PropertyDefinition<?> propDef : PropertyDefinitionsMap.getAll(typeDefinition.getBaseId().value()))
// typeDefinition.getPropertyDefinitions().add(propDef);
Map<String, PropertyDefinition<?>> pd =
new HashMap<String, PropertyDefinition<?>>(PropertyDefinitions.getAll(typeDefinition.getBaseId().value()));
Set<String> knownIds = PropertyDefinitions.getPropertyIds(typeDefinition.getBaseId().value());
for (javax.jcr.nodetype.PropertyDefinition jcrPropertyDef : nt.getPropertyDefinitions())
{
String pdName = jcrPropertyDef.getName();
// TODO : Do not use any constraint about prefixes, need discovery
// hierarchy of JCR types or so on.
if (pdName.startsWith("cmis:"))
{
// Do not process known properties
if (!knownIds.contains(pdName))
{
PropertyDefinition<?> cmisPropDef = null;
// TODO : default values.
switch (jcrPropertyDef.getRequiredType())
{
case javax.jcr.PropertyType.BOOLEAN :
PropertyDefinitionImpl<Boolean> boolDef =
new PropertyDefinitionImpl<Boolean>(pdName, pdName, pdName, null, pdName, null,
PropertyType.BOOLEAN, jcrPropertyDef.isProtected() ? Updatability.READONLY
: Updatability.READWRITE, false, jcrPropertyDef.isMandatory(), true, true, null,
jcrPropertyDef.isMultiple(), null, null);
cmisPropDef = boolDef;
break;
case javax.jcr.PropertyType.DATE :
PropertyDefinitionImpl<Calendar> dateDef =
new PropertyDefinitionImpl<Calendar>(pdName, pdName, pdName, null, pdName, null,
PropertyType.DATETIME, jcrPropertyDef.isProtected() ? Updatability.READONLY
: Updatability.READWRITE, false, jcrPropertyDef.isMandatory(), true, true, null,
jcrPropertyDef.isMultiple(), null, null);
dateDef.setDateResolution(DateResolution.TIME);
cmisPropDef = dateDef;
break;
case javax.jcr.PropertyType.DOUBLE :
PropertyDefinitionImpl<BigDecimal> decimalDef =
new PropertyDefinitionImpl<BigDecimal>(pdName, pdName, pdName, null, pdName, null,
PropertyType.DECIMAL, jcrPropertyDef.isProtected() ? Updatability.READONLY
: Updatability.READWRITE, false, jcrPropertyDef.isMandatory(), true, true, null,
jcrPropertyDef.isMultiple(), null, null);
decimalDef.setPrecision(Precision.Bit32);
decimalDef.setMaxDecimal(CMIS.MAX_DECIMAL_VALUE);
decimalDef.setMinDecimal(CMIS.MIN_DECIMAL_VALUE);
cmisPropDef = decimalDef;
break;
case javax.jcr.PropertyType.LONG :
PropertyDefinitionImpl<BigInteger> integerDef =
new PropertyDefinitionImpl<BigInteger>(pdName, pdName, pdName, null, pdName, null,
PropertyType.INTEGER, jcrPropertyDef.isProtected() ? Updatability.READONLY
: Updatability.READWRITE, false, jcrPropertyDef.isMandatory(), true, true, null,
jcrPropertyDef.isMultiple(), null, null);
integerDef.setMaxInteger(CMIS.MAX_INTEGER_VALUE);
integerDef.setMinInteger(CMIS.MIN_INTEGER_VALUE);
cmisPropDef = integerDef;
break;
case javax.jcr.PropertyType.NAME : // TODO
// CmisPropertyIdDefinitionType idDef = new CmisPropertyIdDefinitionType();
// idDef.setPropertyType(EnumPropertyType.ID);
// cmisPropDef = idDef;
// break;
case javax.jcr.PropertyType.REFERENCE :
case javax.jcr.PropertyType.STRING :
case javax.jcr.PropertyType.PATH :
case javax.jcr.PropertyType.BINARY :
case javax.jcr.PropertyType.UNDEFINED :
PropertyDefinitionImpl<String> stringDef =
new PropertyDefinitionImpl<String>(pdName, pdName, pdName, null, pdName, null,
PropertyType.STRING, jcrPropertyDef.isProtected() ? Updatability.READONLY
: Updatability.READWRITE, false, jcrPropertyDef.isMandatory(), true, true, null,
jcrPropertyDef.isMultiple(), null, null);
stringDef.setMaxLength(CMIS.MAX_STRING_LENGTH);
cmisPropDef = stringDef;
break;
}
pd.put(cmisPropDef.getId(), cmisPropDef);
}
}
}
((TypeDefinitionImpl)typeDefinition).setPropertyDefinitions(pd);
}
| private static void addPropertyDefinitions(TypeDefinition typeDefinition, NodeType nt)
{
// Known described in spec. property definitions
// for (PropertyDefinition<?> propDef : PropertyDefinitionsMap.getAll(typeDefinition.getBaseId().value()))
// typeDefinition.getPropertyDefinitions().add(propDef);
Map<String, PropertyDefinition<?>> pd =
new HashMap<String, PropertyDefinition<?>>(PropertyDefinitions.getAll(typeDefinition.getBaseId().value()));
Set<String> knownIds = PropertyDefinitions.getPropertyIds(typeDefinition.getBaseId().value());
for (javax.jcr.nodetype.PropertyDefinition jcrPropertyDef : nt.getPropertyDefinitions())
{
String pdName = jcrPropertyDef.getName();
// TODO : Do not use any constraint about prefixes, need discovery
// hierarchy of JCR types or so on.
if (pdName.startsWith("cmis:"))
{
// Do not process known properties
if (!knownIds.contains(pdName))
{
PropertyDefinition<?> cmisPropDef = null;
// TODO : default values.
switch (jcrPropertyDef.getRequiredType())
{
case javax.jcr.PropertyType.BOOLEAN :
PropertyDefinitionImpl<Boolean> boolDef =
new PropertyDefinitionImpl<Boolean>(pdName, pdName, pdName, null, pdName, null,
PropertyType.BOOLEAN, jcrPropertyDef.isProtected() ? Updatability.READONLY
: Updatability.READWRITE, false, jcrPropertyDef.isMandatory(), true, true, null,
jcrPropertyDef.isMultiple(), null, null);
cmisPropDef = boolDef;
break;
case javax.jcr.PropertyType.DATE :
PropertyDefinitionImpl<Calendar> dateDef =
new PropertyDefinitionImpl<Calendar>(pdName, pdName, pdName, null, pdName, null,
PropertyType.DATETIME, jcrPropertyDef.isProtected() ? Updatability.READONLY
: Updatability.READWRITE, false, jcrPropertyDef.isMandatory(), true, true, null,
jcrPropertyDef.isMultiple(), null, null);
dateDef.setDateResolution(DateResolution.TIME);
cmisPropDef = dateDef;
break;
case javax.jcr.PropertyType.DOUBLE :
PropertyDefinitionImpl<BigDecimal> decimalDef =
new PropertyDefinitionImpl<BigDecimal>(pdName, pdName, pdName, null, pdName, null,
PropertyType.DECIMAL, jcrPropertyDef.isProtected() ? Updatability.READONLY
: Updatability.READWRITE, false, jcrPropertyDef.isMandatory(), true, true, null,
jcrPropertyDef.isMultiple(), null, null);
decimalDef.setDecimalPrecision(Precision.Bit32);
decimalDef.setMaxDecimal(CMIS.MAX_DECIMAL_VALUE);
decimalDef.setMinDecimal(CMIS.MIN_DECIMAL_VALUE);
cmisPropDef = decimalDef;
break;
case javax.jcr.PropertyType.LONG :
PropertyDefinitionImpl<BigInteger> integerDef =
new PropertyDefinitionImpl<BigInteger>(pdName, pdName, pdName, null, pdName, null,
PropertyType.INTEGER, jcrPropertyDef.isProtected() ? Updatability.READONLY
: Updatability.READWRITE, false, jcrPropertyDef.isMandatory(), true, true, null,
jcrPropertyDef.isMultiple(), null, null);
integerDef.setMaxInteger(CMIS.MAX_INTEGER_VALUE);
integerDef.setMinInteger(CMIS.MIN_INTEGER_VALUE);
cmisPropDef = integerDef;
break;
case javax.jcr.PropertyType.NAME : // TODO
// CmisPropertyIdDefinitionType idDef = new CmisPropertyIdDefinitionType();
// idDef.setPropertyType(EnumPropertyType.ID);
// cmisPropDef = idDef;
// break;
case javax.jcr.PropertyType.REFERENCE :
case javax.jcr.PropertyType.STRING :
case javax.jcr.PropertyType.PATH :
case javax.jcr.PropertyType.BINARY :
case javax.jcr.PropertyType.UNDEFINED :
PropertyDefinitionImpl<String> stringDef =
new PropertyDefinitionImpl<String>(pdName, pdName, pdName, null, pdName, null,
PropertyType.STRING, jcrPropertyDef.isProtected() ? Updatability.READONLY
: Updatability.READWRITE, false, jcrPropertyDef.isMandatory(), true, true, null,
jcrPropertyDef.isMultiple(), null, null);
stringDef.setMaxLength(CMIS.MAX_STRING_LENGTH);
cmisPropDef = stringDef;
break;
}
pd.put(cmisPropDef.getId(), cmisPropDef);
}
}
}
((TypeDefinitionImpl)typeDefinition).setPropertyDefinitions(pd);
}
|
diff --git a/deskshare/applet/src/main/java/org/bigbluebutton/deskshare/client/MouseLocationTaker.java b/deskshare/applet/src/main/java/org/bigbluebutton/deskshare/client/MouseLocationTaker.java
index dcd1cdcf71..a7fa99c5cf 100755
--- a/deskshare/applet/src/main/java/org/bigbluebutton/deskshare/client/MouseLocationTaker.java
+++ b/deskshare/applet/src/main/java/org/bigbluebutton/deskshare/client/MouseLocationTaker.java
@@ -1,212 +1,211 @@
/**
* ===License Header===
*
* BigBlueButton open source conferencing system - http://www.bigbluebutton.org/
*
* Copyright (c) 2010 BigBlueButton Inc. and by respective authors (see below).
*
* 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.
*
* BigBlueButton 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 BigBlueButton; if not, see <http://www.gnu.org/licenses/>.
*
* ===License Header===
*/
package org.bigbluebutton.deskshare.client;
import java.awt.HeadlessException;
import java.awt.Image;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.PointerInfo;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import org.bigbluebutton.deskshare.client.MouseLocationListener;
public class MouseLocationTaker {
private MouseLocationListener listeners;
private volatile boolean trackMouseLocation = false;
private final Executor mouseLocTakerExec = Executors.newSingleThreadExecutor();
private Runnable mouseLocRunner;
private int captureWidth;
private int captureHeight;
private int scaleWidth;
private int scaleHeight;
private int captureX;
private int captureY;
private Point oldMouseLocation = new Point(Integer.MIN_VALUE, Integer.MIN_VALUE);
public MouseLocationTaker(int captureWidth, int captureHeight, int scaleWidth, int scaleHeight, int captureX, int captureY) {
this.captureWidth = captureWidth;
this.captureHeight = captureHeight;
this.scaleWidth = scaleWidth;
this.scaleHeight = scaleHeight;
this.captureX = captureX;
this.captureY = captureY;
}
private Point getMouseLocation() {
PointerInfo pInfo;
Point pointerLocation = new Point(0,0);
try {
pInfo = MouseInfo.getPointerInfo();
} catch (HeadlessException e) {
pInfo = null;
} catch (SecurityException e) {
pInfo = null;
}
if (pInfo == null) return pointerLocation;
return pInfo.getLocation();
}
private Point calculatePointerLocation(Point p) {
System.out.println("Mouse Tracker:: Image=[" + captureWidth + "," + captureHeight + "] scale=[" + scaleWidth + "," + scaleHeight + "]");
if (captureWidth < scaleWidth || captureHeight < scaleHeight) {
int imgWidth = captureWidth;
int imgHeight = captureHeight;
if (imgWidth < scaleWidth && imgHeight < scaleHeight) {
System.out.println("Capture is smaller than scale dims. Just draw the image. capture=["
+ captureWidth + "," + captureHeight + "] scale=[" + scaleWidth + "," + scaleHeight + "]");
int imgX = (scaleWidth - captureWidth) / 2;
int imgY = (scaleHeight - captureHeight) / 2;
int mX = p.x - captureX + imgX;
int mY = p.y - captureY + imgY;
// System.out.println("imgX=[" + imgX + "," + imgY + "] p=[" + p.x + "," + p.y + "] capture=[" + captureX + "," + captureY + "]");
System.out.println("m=[" + mX + "," + mY + "] p=[" + p.x + "," + p.y + "] capture=[" + captureX + "," + captureY + "]");
return new Point(mX, mY);
} else {
if (imgWidth > scaleWidth) {
System.out.println("Fit to width. capture=["
+ captureWidth + "," + captureHeight + "] scale=[" + scaleWidth + "," + scaleHeight + "]");
double ratio = (double)imgHeight/(double)imgWidth;
imgWidth = scaleWidth;
imgHeight = (int)((double)imgWidth * ratio);
int imgY = (scaleHeight - imgHeight) / 2;
double mX = ((double)((double)p.x - (double)captureX) * (double)((double)scaleWidth / (double)captureWidth));
System.out.println("(p.x - captureX)=[" + (p.x - captureX) + "] (scaleWidth / captureWidth)=["
+ (double)((double)scaleWidth / (double)captureWidth) + "] mX=[" + mX + "]");
double mY = ((double)((double)p.y - (double)captureY) * (double)((double)imgHeight / (double)captureHeight)) + imgY;
// System.out.println("imgX=[" + imgX + "," + imgY + "] p=[" + p.x + "," + p.y + "] capture=[" + captureX + "," + captureY + "]");
System.out.println("m=[" + mX + "," + mY + "] p=[" + p.x + "," + p.y + "] capture=[" + captureX + "," + captureY + "]");
return new Point((int)mX, (int)mY);
} else {
- System.out.println("Fit to height. capture=["
- + captureWidth + "," + captureHeight + "] scale=[" + scaleWidth + "," + scaleHeight + "]");
+ System.out.println("Fit to height. capture=[" + captureWidth + "," + captureHeight + "] scale=[" + scaleWidth + "," + scaleHeight + "]");
// double hRatio = (double)scaleHeight/(double)captureHeight;
// imgHeight = scaleHeight;
// imgWidth = (int)((double)imgHeight * hRatio);
double ratio = (double)imgWidth/(double)imgHeight;
imgHeight = scaleHeight;
imgWidth = (int)((double)imgHeight * ratio);
int imgX = (scaleWidth - imgWidth) / 2;
- // double mX = ((double)((double)p.x - (double)captureX) * (double)((double) captureWidth / (double) imgWidth)) + imgX;
- double mX = ((double)((double)p.x - (double)captureX + imgX) * (double)(ratio)) ;
- System.out.println("(p.x - captureX)=[" + (p.x - captureX) + "] ** (captureWidth / imgWidth )=["
- + (double)((double)captureWidth / (double) imgWidth) + "] mX=[" + mX + "]");
+ double mX = ((double)((double)p.x - (double)captureX) * (double)((double) imgWidth / (double) captureWidth)) + imgX;
+ // double mX = ((double)((double)p.x - (double)captureX) * (double)(ratio)) + imgX ;
+ System.out.println("(p.x - captureX)=[" + (p.x - captureX) + "] ** (imgWidth / captureWidth)=["
+ + (double)((double)imgWidth / (double) captureWidth) + "] mX=[" + mX + "]");
double mY = ((double)((double)p.y - (double)captureY) * (double)((double)scaleHeight / (double)captureHeight));
// System.out.println("imgX=[" + imgX + "," + imgY + "] p=[" + p.x + "," + p.y + "] capture=[" + captureX + "," + captureY + "]");
System.out.println("m=[" + mX + "," + mY + "] p=[" + p.x + "," + p.y + "] capture=[" + captureX + "," + captureY + "]");
return new Point((int)mX, (int)mY);
}
}
} else {
System.out.println("Both capture sides are greater than the scaled dims. Downscale image.");
double mx = ((double)p.x / (double)captureWidth) * (double)scaleWidth;
double my = ((double)p.y / (double)captureHeight) * (double)scaleHeight;
mx = mx - captureX;
my = my - captureY;
return new Point((int)mx, (int)my);
}
}
public boolean adjustPointerLocationDueToScaling() {
return (captureWidth != scaleWidth && captureHeight != scaleHeight);
}
private void takeMouseLocation() {
Point mouseLocation = getMouseLocation();
if ( !mouseLocation.equals(oldMouseLocation) && isMouseInsideCapturedRegion(mouseLocation)) {
System.out.println("Mouse is inside captured region [" + mouseLocation.x + "," + mouseLocation.y + "]");
notifyListeners(calculatePointerLocation(mouseLocation));
oldMouseLocation = mouseLocation;
}
}
private boolean isMouseInsideCapturedRegion(Point p) {
return ( ( (p.x > captureX) && (p.x < (captureX + captureWidth) ) )
&& (p.y > captureY && p.y < captureY + captureHeight));
}
private void notifyListeners(Point location) {
listeners.onMouseLocationUpdate(location);
}
public void addListener(MouseLocationListener listener) {
listeners = listener;
}
private void pause(int dur) {
try{
Thread.sleep(dur);
} catch (Exception e){
System.out.println("Exception sleeping.");
}
}
public void start() {
trackMouseLocation = true;
mouseLocRunner = new Runnable() {
public void run() {
while (trackMouseLocation){
takeMouseLocation();
pause(250);
}
}
};
mouseLocTakerExec.execute(mouseLocRunner);
}
public void stop() {
trackMouseLocation = false;
}
public void setCaptureCoordinates(int x, int y){
captureX = x;
captureY = y;
}
}
| false | true | private Point calculatePointerLocation(Point p) {
System.out.println("Mouse Tracker:: Image=[" + captureWidth + "," + captureHeight + "] scale=[" + scaleWidth + "," + scaleHeight + "]");
if (captureWidth < scaleWidth || captureHeight < scaleHeight) {
int imgWidth = captureWidth;
int imgHeight = captureHeight;
if (imgWidth < scaleWidth && imgHeight < scaleHeight) {
System.out.println("Capture is smaller than scale dims. Just draw the image. capture=["
+ captureWidth + "," + captureHeight + "] scale=[" + scaleWidth + "," + scaleHeight + "]");
int imgX = (scaleWidth - captureWidth) / 2;
int imgY = (scaleHeight - captureHeight) / 2;
int mX = p.x - captureX + imgX;
int mY = p.y - captureY + imgY;
// System.out.println("imgX=[" + imgX + "," + imgY + "] p=[" + p.x + "," + p.y + "] capture=[" + captureX + "," + captureY + "]");
System.out.println("m=[" + mX + "," + mY + "] p=[" + p.x + "," + p.y + "] capture=[" + captureX + "," + captureY + "]");
return new Point(mX, mY);
} else {
if (imgWidth > scaleWidth) {
System.out.println("Fit to width. capture=["
+ captureWidth + "," + captureHeight + "] scale=[" + scaleWidth + "," + scaleHeight + "]");
double ratio = (double)imgHeight/(double)imgWidth;
imgWidth = scaleWidth;
imgHeight = (int)((double)imgWidth * ratio);
int imgY = (scaleHeight - imgHeight) / 2;
double mX = ((double)((double)p.x - (double)captureX) * (double)((double)scaleWidth / (double)captureWidth));
System.out.println("(p.x - captureX)=[" + (p.x - captureX) + "] (scaleWidth / captureWidth)=["
+ (double)((double)scaleWidth / (double)captureWidth) + "] mX=[" + mX + "]");
double mY = ((double)((double)p.y - (double)captureY) * (double)((double)imgHeight / (double)captureHeight)) + imgY;
// System.out.println("imgX=[" + imgX + "," + imgY + "] p=[" + p.x + "," + p.y + "] capture=[" + captureX + "," + captureY + "]");
System.out.println("m=[" + mX + "," + mY + "] p=[" + p.x + "," + p.y + "] capture=[" + captureX + "," + captureY + "]");
return new Point((int)mX, (int)mY);
} else {
System.out.println("Fit to height. capture=["
+ captureWidth + "," + captureHeight + "] scale=[" + scaleWidth + "," + scaleHeight + "]");
// double hRatio = (double)scaleHeight/(double)captureHeight;
// imgHeight = scaleHeight;
// imgWidth = (int)((double)imgHeight * hRatio);
double ratio = (double)imgWidth/(double)imgHeight;
imgHeight = scaleHeight;
imgWidth = (int)((double)imgHeight * ratio);
int imgX = (scaleWidth - imgWidth) / 2;
// double mX = ((double)((double)p.x - (double)captureX) * (double)((double) captureWidth / (double) imgWidth)) + imgX;
double mX = ((double)((double)p.x - (double)captureX + imgX) * (double)(ratio)) ;
System.out.println("(p.x - captureX)=[" + (p.x - captureX) + "] ** (captureWidth / imgWidth )=["
+ (double)((double)captureWidth / (double) imgWidth) + "] mX=[" + mX + "]");
double mY = ((double)((double)p.y - (double)captureY) * (double)((double)scaleHeight / (double)captureHeight));
// System.out.println("imgX=[" + imgX + "," + imgY + "] p=[" + p.x + "," + p.y + "] capture=[" + captureX + "," + captureY + "]");
System.out.println("m=[" + mX + "," + mY + "] p=[" + p.x + "," + p.y + "] capture=[" + captureX + "," + captureY + "]");
return new Point((int)mX, (int)mY);
}
}
} else {
System.out.println("Both capture sides are greater than the scaled dims. Downscale image.");
double mx = ((double)p.x / (double)captureWidth) * (double)scaleWidth;
double my = ((double)p.y / (double)captureHeight) * (double)scaleHeight;
mx = mx - captureX;
my = my - captureY;
return new Point((int)mx, (int)my);
}
}
| private Point calculatePointerLocation(Point p) {
System.out.println("Mouse Tracker:: Image=[" + captureWidth + "," + captureHeight + "] scale=[" + scaleWidth + "," + scaleHeight + "]");
if (captureWidth < scaleWidth || captureHeight < scaleHeight) {
int imgWidth = captureWidth;
int imgHeight = captureHeight;
if (imgWidth < scaleWidth && imgHeight < scaleHeight) {
System.out.println("Capture is smaller than scale dims. Just draw the image. capture=["
+ captureWidth + "," + captureHeight + "] scale=[" + scaleWidth + "," + scaleHeight + "]");
int imgX = (scaleWidth - captureWidth) / 2;
int imgY = (scaleHeight - captureHeight) / 2;
int mX = p.x - captureX + imgX;
int mY = p.y - captureY + imgY;
// System.out.println("imgX=[" + imgX + "," + imgY + "] p=[" + p.x + "," + p.y + "] capture=[" + captureX + "," + captureY + "]");
System.out.println("m=[" + mX + "," + mY + "] p=[" + p.x + "," + p.y + "] capture=[" + captureX + "," + captureY + "]");
return new Point(mX, mY);
} else {
if (imgWidth > scaleWidth) {
System.out.println("Fit to width. capture=["
+ captureWidth + "," + captureHeight + "] scale=[" + scaleWidth + "," + scaleHeight + "]");
double ratio = (double)imgHeight/(double)imgWidth;
imgWidth = scaleWidth;
imgHeight = (int)((double)imgWidth * ratio);
int imgY = (scaleHeight - imgHeight) / 2;
double mX = ((double)((double)p.x - (double)captureX) * (double)((double)scaleWidth / (double)captureWidth));
System.out.println("(p.x - captureX)=[" + (p.x - captureX) + "] (scaleWidth / captureWidth)=["
+ (double)((double)scaleWidth / (double)captureWidth) + "] mX=[" + mX + "]");
double mY = ((double)((double)p.y - (double)captureY) * (double)((double)imgHeight / (double)captureHeight)) + imgY;
// System.out.println("imgX=[" + imgX + "," + imgY + "] p=[" + p.x + "," + p.y + "] capture=[" + captureX + "," + captureY + "]");
System.out.println("m=[" + mX + "," + mY + "] p=[" + p.x + "," + p.y + "] capture=[" + captureX + "," + captureY + "]");
return new Point((int)mX, (int)mY);
} else {
System.out.println("Fit to height. capture=[" + captureWidth + "," + captureHeight + "] scale=[" + scaleWidth + "," + scaleHeight + "]");
// double hRatio = (double)scaleHeight/(double)captureHeight;
// imgHeight = scaleHeight;
// imgWidth = (int)((double)imgHeight * hRatio);
double ratio = (double)imgWidth/(double)imgHeight;
imgHeight = scaleHeight;
imgWidth = (int)((double)imgHeight * ratio);
int imgX = (scaleWidth - imgWidth) / 2;
double mX = ((double)((double)p.x - (double)captureX) * (double)((double) imgWidth / (double) captureWidth)) + imgX;
// double mX = ((double)((double)p.x - (double)captureX) * (double)(ratio)) + imgX ;
System.out.println("(p.x - captureX)=[" + (p.x - captureX) + "] ** (imgWidth / captureWidth)=["
+ (double)((double)imgWidth / (double) captureWidth) + "] mX=[" + mX + "]");
double mY = ((double)((double)p.y - (double)captureY) * (double)((double)scaleHeight / (double)captureHeight));
// System.out.println("imgX=[" + imgX + "," + imgY + "] p=[" + p.x + "," + p.y + "] capture=[" + captureX + "," + captureY + "]");
System.out.println("m=[" + mX + "," + mY + "] p=[" + p.x + "," + p.y + "] capture=[" + captureX + "," + captureY + "]");
return new Point((int)mX, (int)mY);
}
}
} else {
System.out.println("Both capture sides are greater than the scaled dims. Downscale image.");
double mx = ((double)p.x / (double)captureWidth) * (double)scaleWidth;
double my = ((double)p.y / (double)captureHeight) * (double)scaleHeight;
mx = mx - captureX;
my = my - captureY;
return new Point((int)mx, (int)my);
}
}
|
diff --git a/src/main/java/org/kari/io/CompactObjectOutputStream.java b/src/main/java/org/kari/io/CompactObjectOutputStream.java
index 7fcdce5..ccb7fe0 100644
--- a/src/main/java/org/kari/io/CompactObjectOutputStream.java
+++ b/src/main/java/org/kari/io/CompactObjectOutputStream.java
@@ -1,153 +1,155 @@
package org.kari.io;
import gnu.trove.map.TIntObjectMap;
import gnu.trove.map.TObjectIntMap;
import gnu.trove.map.hash.TIntObjectHashMap;
import gnu.trove.map.hash.TObjectIntHashMap;
import gnu.trove.procedure.TIntObjectProcedure;
import gnu.trove.set.hash.THashSet;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamClass;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.rmi.dgc.VMID;
import java.rmi.server.UID;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Outputstream with more compact format
*
* @author kari
*/
public final class CompactObjectOutputStream
extends ObjectOutputStream
{
public static final byte TYPE_PLAIN = 0;
public static final byte TYPE_CLASS_ID = 1;
public static final Charset SUFFIX_ENCODING = Charset.forName("UTF8");
public static final Class ARRAY_CLASS = Object[].class;
public static final TIntObjectMap<Class> CODE_TO_TYPE = new TIntObjectHashMap<Class>();
public static final TObjectIntMap<Class> TYPE_TO_CODE = new TObjectIntHashMap<Class>();
public static final TIntObjectMap<String> PREFIX_VALUES = new TIntObjectHashMap<String>();
public static final int[] PREFIX_IDS;
static {
{
char BASE = 'A';
PREFIX_VALUES.put(BASE++, "org.kari.");
PREFIX_VALUES.put(BASE++, "java.rmi.");
PREFIX_VALUES.put(BASE++, "java.lang.");
PREFIX_VALUES.put(BASE++, "java.util.");
PREFIX_VALUES.put(BASE++, "java.io.");
PREFIX_VALUES.put(BASE++, "java.");
PREFIX_VALUES.put(BASE++, "org.trove.");
PREFIX_VALUES.put(BASE++, "org.google.");
PREFIX_IDS = PREFIX_VALUES.keys();
Arrays.sort(PREFIX_IDS);
}
{
char BASE = 'Z';
CODE_TO_TYPE.put(BASE++, Throwable.class);
CODE_TO_TYPE.put(BASE++, Error.class);
CODE_TO_TYPE.put(BASE++, RuntimeException.class);
CODE_TO_TYPE.put(BASE++, Exception.class);
CODE_TO_TYPE.put(BASE++, UID.class);
CODE_TO_TYPE.put(BASE++, VMID.class);
CODE_TO_TYPE.put(BASE++, Object.class);
CODE_TO_TYPE.put(BASE++, Integer.class);
CODE_TO_TYPE.put(BASE++, Number.class);
CODE_TO_TYPE.put(BASE++, Long.class);
CODE_TO_TYPE.put(BASE++, byte[].class);
CODE_TO_TYPE.put(BASE++, int[].class);
CODE_TO_TYPE.put(BASE++, long[].class);
CODE_TO_TYPE.put(BASE++, Object[].class);
CODE_TO_TYPE.put(BASE++, String[].class);
CODE_TO_TYPE.put(BASE++, StackTraceElement.class);
CODE_TO_TYPE.put(BASE++, StackTraceElement[].class);
CODE_TO_TYPE.put(BASE++, List.class);
CODE_TO_TYPE.put(BASE++, Set.class);
CODE_TO_TYPE.put(BASE++, Map.class);
CODE_TO_TYPE.put(BASE++, ArrayList.class);
CODE_TO_TYPE.put(BASE++, HashSet.class);
CODE_TO_TYPE.put(BASE++, THashSet.class);
}
CODE_TO_TYPE.forEachEntry(new TIntObjectProcedure<Class>() {
@Override
public boolean execute(int pCode, Class pType) {
TYPE_TO_CODE.put(pType, pCode);
return true;
}
});
}
public CompactObjectOutputStream()
throws IOException,
SecurityException
{
super();
}
public CompactObjectOutputStream(OutputStream pOut)
throws IOException
{
super(pOut);
}
/**
* No magic header
*/
@Override
protected void writeStreamHeader() throws IOException {
// nothing
}
@Override
protected void writeClassDescriptor(ObjectStreamClass desc)
throws IOException
{
final Class<?> cls = desc.forClass();
+ int prefixLen = 0;
byte[] encodedSuffix = null;
int classId = 0;
int code = TYPE_TO_CODE.get(cls);
if (code != 0) {
// ok fixed type
} else {
String name = cls.getName();
code = TYPE_PLAIN;
+ encodedSuffix = name.getBytes(SUFFIX_ENCODING);
for (int prefixId : PREFIX_IDS) {
String prefix = PREFIX_VALUES.get(prefixId);
if (name.startsWith(prefix)) {
code = (byte)prefixId;
- name = name.substring(prefix.length());
+ prefixLen = prefix.length();
break;
}
}
- encodedSuffix = name.getBytes(SUFFIX_ENCODING);
}
writeByte( (byte)code );
if (classId != 0) {
writeInt(classId);
}
if (encodedSuffix != null) {
- writeShort(encodedSuffix.length);
- write(encodedSuffix);
+ int suffixLen = encodedSuffix.length - prefixLen;
+ writeShort(suffixLen);
+ write(encodedSuffix, prefixLen, suffixLen);
}
}
}
| false | true | protected void writeClassDescriptor(ObjectStreamClass desc)
throws IOException
{
final Class<?> cls = desc.forClass();
byte[] encodedSuffix = null;
int classId = 0;
int code = TYPE_TO_CODE.get(cls);
if (code != 0) {
// ok fixed type
} else {
String name = cls.getName();
code = TYPE_PLAIN;
for (int prefixId : PREFIX_IDS) {
String prefix = PREFIX_VALUES.get(prefixId);
if (name.startsWith(prefix)) {
code = (byte)prefixId;
name = name.substring(prefix.length());
break;
}
}
encodedSuffix = name.getBytes(SUFFIX_ENCODING);
}
writeByte( (byte)code );
if (classId != 0) {
writeInt(classId);
}
if (encodedSuffix != null) {
writeShort(encodedSuffix.length);
write(encodedSuffix);
}
}
| protected void writeClassDescriptor(ObjectStreamClass desc)
throws IOException
{
final Class<?> cls = desc.forClass();
int prefixLen = 0;
byte[] encodedSuffix = null;
int classId = 0;
int code = TYPE_TO_CODE.get(cls);
if (code != 0) {
// ok fixed type
} else {
String name = cls.getName();
code = TYPE_PLAIN;
encodedSuffix = name.getBytes(SUFFIX_ENCODING);
for (int prefixId : PREFIX_IDS) {
String prefix = PREFIX_VALUES.get(prefixId);
if (name.startsWith(prefix)) {
code = (byte)prefixId;
prefixLen = prefix.length();
break;
}
}
}
writeByte( (byte)code );
if (classId != 0) {
writeInt(classId);
}
if (encodedSuffix != null) {
int suffixLen = encodedSuffix.length - prefixLen;
writeShort(suffixLen);
write(encodedSuffix, prefixLen, suffixLen);
}
}
|
diff --git a/test-integration-ui/src/main/java/org/apache/directory/studio/test/integration/ui/ContextMenuHelper.java b/test-integration-ui/src/main/java/org/apache/directory/studio/test/integration/ui/ContextMenuHelper.java
index 804b29331..3594b9398 100644
--- a/test-integration-ui/src/main/java/org/apache/directory/studio/test/integration/ui/ContextMenuHelper.java
+++ b/test-integration-ui/src/main/java/org/apache/directory/studio/test/integration/ui/ContextMenuHelper.java
@@ -1,152 +1,156 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
package org.apache.directory.studio.test.integration.ui;
import static org.eclipse.swtbot.swt.finder.matchers.WidgetMatcherFactory.withMnemonic;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.instanceOf;
import java.util.Arrays;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swtbot.swt.finder.exceptions.WidgetNotFoundException;
import org.eclipse.swtbot.swt.finder.finders.UIThreadRunnable;
import org.eclipse.swtbot.swt.finder.results.VoidResult;
import org.eclipse.swtbot.swt.finder.results.WidgetResult;
import org.eclipse.swtbot.swt.finder.widgets.AbstractSWTBot;
import org.hamcrest.Matcher;
/**
* A helper to click context menus
*
* @author <a href="mailto:[email protected]">Apache Directory Project</a>
* @version $Rev$, $Date$
*/
public class ContextMenuHelper
{
/**
* Clicks the context menu matching the text.
*
* @param text
* the text on the context menu.
* @throws WidgetNotFoundException
* if the widget is not found.
*/
public static void clickContextMenu( final AbstractSWTBot<?> bot, final String... texts )
{
+ final Matcher<?>[] matchers = new Matcher<?>[texts.length];
+ for ( int i = 0; i < texts.length; i++ )
+ {
+ matchers[i] = allOf( instanceOf( MenuItem.class ), withMnemonic( texts[i] ) );
+ }
// show
final MenuItem menuItem = UIThreadRunnable.syncExec( new WidgetResult<MenuItem>()
{
public MenuItem run()
{
MenuItem menuItem = null;
Control control = ( Control ) bot.widget;
Menu menu = control.getMenu();
- for ( String text : texts )
+ for ( int i = 0; i < matchers.length; i++ )
{
- Matcher<?> matcher = allOf( instanceOf( MenuItem.class ), withMnemonic( text ) );
- menuItem = show( menu, matcher );
+ menuItem = show( menu, matchers[i] );
if ( menuItem != null )
{
menu = menuItem.getMenu();
}
else
{
hide( menu );
break;
}
}
return menuItem;
}
} );
if ( menuItem == null )
{
throw new WidgetNotFoundException( "Could not find menu: " + Arrays.asList( texts ) );
}
// click
click( menuItem );
// hide
UIThreadRunnable.syncExec( new VoidResult()
{
public void run()
{
hide( menuItem.getParent() );
}
} );
}
private static MenuItem show( final Menu menu, final Matcher<?> matcher )
{
if ( menu != null )
{
menu.notifyListeners( SWT.Show, new Event() );
MenuItem[] items = menu.getItems();
for ( final MenuItem menuItem : items )
{
if ( matcher.matches( menuItem ) )
{
return menuItem;
}
}
menu.notifyListeners( SWT.Hide, new Event() );
}
return null;
}
private static void click( final MenuItem menuItem )
{
final Event event = new Event();
event.time = ( int ) System.currentTimeMillis();
event.widget = menuItem;
event.display = menuItem.getDisplay();
event.type = SWT.Selection;
UIThreadRunnable.asyncExec( menuItem.getDisplay(), new VoidResult()
{
public void run()
{
menuItem.notifyListeners( SWT.Selection, event );
}
} );
}
private static void hide( final Menu menu )
{
menu.notifyListeners( SWT.Hide, new Event() );
if ( menu.getParentMenu() != null )
{
hide( menu.getParentMenu() );
}
}
}
| false | true | public static void clickContextMenu( final AbstractSWTBot<?> bot, final String... texts )
{
// show
final MenuItem menuItem = UIThreadRunnable.syncExec( new WidgetResult<MenuItem>()
{
public MenuItem run()
{
MenuItem menuItem = null;
Control control = ( Control ) bot.widget;
Menu menu = control.getMenu();
for ( String text : texts )
{
Matcher<?> matcher = allOf( instanceOf( MenuItem.class ), withMnemonic( text ) );
menuItem = show( menu, matcher );
if ( menuItem != null )
{
menu = menuItem.getMenu();
}
else
{
hide( menu );
break;
}
}
return menuItem;
}
} );
if ( menuItem == null )
{
throw new WidgetNotFoundException( "Could not find menu: " + Arrays.asList( texts ) );
}
// click
click( menuItem );
// hide
UIThreadRunnable.syncExec( new VoidResult()
{
public void run()
{
hide( menuItem.getParent() );
}
} );
}
| public static void clickContextMenu( final AbstractSWTBot<?> bot, final String... texts )
{
final Matcher<?>[] matchers = new Matcher<?>[texts.length];
for ( int i = 0; i < texts.length; i++ )
{
matchers[i] = allOf( instanceOf( MenuItem.class ), withMnemonic( texts[i] ) );
}
// show
final MenuItem menuItem = UIThreadRunnable.syncExec( new WidgetResult<MenuItem>()
{
public MenuItem run()
{
MenuItem menuItem = null;
Control control = ( Control ) bot.widget;
Menu menu = control.getMenu();
for ( int i = 0; i < matchers.length; i++ )
{
menuItem = show( menu, matchers[i] );
if ( menuItem != null )
{
menu = menuItem.getMenu();
}
else
{
hide( menu );
break;
}
}
return menuItem;
}
} );
if ( menuItem == null )
{
throw new WidgetNotFoundException( "Could not find menu: " + Arrays.asList( texts ) );
}
// click
click( menuItem );
// hide
UIThreadRunnable.syncExec( new VoidResult()
{
public void run()
{
hide( menuItem.getParent() );
}
} );
}
|
diff --git a/Main.java b/Main.java
index 45742b5..694b993 100644
--- a/Main.java
+++ b/Main.java
@@ -1,163 +1,163 @@
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.PrintWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Properties;
import java.util.StringTokenizer;
import javax.management.Query;
/* ga */
/* sources : http://docs.oracle.com/javase/tutorial/essential/io/charstreams.html */
/* sources : http://docs.oracle.com/javase/tutorial/essential/environment/properties.html */
public class Main {
public static void main(String[] args) throws IOException {
- if (false) {
+ if (args.length != 2) {
System.out.println("Please enter two input file names");
}
else {
File fquery = new File(args[0]);
File fconfig = new File(args[1]);
//File fquery = new File("query.txt");
//File fconfig = new File("config.txt");
/* AL queryLines holds one line from query.txt per AL's element */
ArrayList<String> queryLines = new ArrayList<String>();
BufferedReader inputStream = null;
PrintWriter outputStream = null;
/* reading query.txt into AL */
try {
inputStream = new BufferedReader(new FileReader(fquery));
String l;
while ((l = inputStream.readLine()) != null) {
queryLines.add(l);
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
if (inputStream != null) {
try {
inputStream.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
/* reading config.properties file */
Properties costProps = new Properties();
FileInputStream in = null;
try {
in = new FileInputStream(fconfig);
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
costProps.load(in);
}
catch (IOException e) {
e.printStackTrace();
}
try {
in.close();
}
catch (IOException e) {
e.printStackTrace();
}
//actual code starts here
int numPasses = queryLines.size();
ArrayList<Float> tempValues;
float[][] probs = new float[numPasses][]; //stores the probabilities in a 2D array
//builds the 2D array with all of the probabilities
for (int i = 0; i < queryLines.size(); i++) {
String line = queryLines.get(i);
StringTokenizer parse = new StringTokenizer(line);
tempValues = new ArrayList<Float>();
while(parse.hasMoreElements()){
String num = String.valueOf(parse.nextElement());
tempValues.add(Float.valueOf(num));
}
probs[i] = new float[tempValues.size()];
for (int j = 0; j < tempValues.size(); j++) {
probs[i][j] = tempValues.get(j);
}
}
outputStream = new PrintWriter(new FileWriter("output.txt"));
//int currentLevel = 0; //represents what row of probabilities we are working on
for (int currentLevel = 0; currentLevel < probs.length; currentLevel++) {
ArrayList<Term> termsArrayList = Term.generateTermArray(probs[currentLevel].length);
Term.fillArrayCosts(termsArrayList, costProps, probs[currentLevel]);
//loop that builds optimal plan
for (int i = 0; i < termsArrayList.size(); i++) {
for (int j = 0; j < termsArrayList.size(); j++) {
if(i == j){}
else if (termsArrayList.get(i).compareCMetrics(termsArrayList.get(j))) { //checks for CMetric optimization
}
else if (termsArrayList.get(i).compareDMetrics(termsArrayList.get(j)) && (termsArrayList.get(i)).calcProductivites(probs[currentLevel]) <= 0.5) {
}
else{
if (termsArrayList.get(i).canCombine(termsArrayList.get(j))) {
// checks if a && b is better than aUb
float combCost = termsArrayList.get(i).calcDoubAnd(termsArrayList.get(j), costProps, probs[currentLevel]);
int index = Term.calcValue(termsArrayList.get(i), termsArrayList.get(j)); //sequences are stored in the index of their binary value - 1 since the all 0 sequence has been removed
//int[] cmbrep = Term.combinedRep(termsArrayList.get(i), termsArrayList.get(j));
//String cmbrepString = Term.repToString(cmbrep);
//System.out.println("The && is: " + combCost + " union cost is " + termsArrayList.get(index - 1).cost + " for " + termsArrayList.get(i).repToString()+ " with " + termsArrayList.get(j).repToString() + " vs " + termsArrayList.get(index - 1).repToString() + " index: " + index);
float compVal = combCost - termsArrayList.get(index - 1).cost;
if (compVal < 0 && Math.abs(compVal) > 0.001) { //checks to see if the && plan is less than the & plan
termsArrayList.get(index - 1).leftSeq = termsArrayList.get(i);
termsArrayList.get(index - 1).rightSeq = termsArrayList.get(j);
termsArrayList.get(index - 1).cost = combCost; //sets the new cost
termsArrayList.get(index - 1).costAlgo = 2;
termsArrayList.get(i).costAlgo = 0;
//System.out.println("A replacement has been made. " + termsArrayList.get(i).repToString() + " + " + termsArrayList.get(j).repToString() + " = " + termsArrayList.get(index - 1).repToString());
}
// checks if b&&a is better than bUa
float combCost2 = termsArrayList.get(j).calcDoubAnd(termsArrayList.get(i), costProps, probs[currentLevel]);
//int index2 = Term.calcValue(termsArrayList.get(i), termsArrayList.get(j)); //sequences are stored in the index of their binary value - 1 since the all 0 sequence has been removed
//System.out.println("The && is: " + combCost + " union cost is " + termsArrayList.get(index - 1).cost + " for " + termsArrayList.get(i).repToString()+ " with " + termsArrayList.get(j).repToString() + " vs " + termsArrayList.get(index - 1).repToString() + " index: " + index);
float compVal2 = combCost2 - termsArrayList.get(index - 1).cost;
if (compVal2 < 0 && Math.abs(compVal2) > 0.001) { //checks to see if the && plan is less than the & plan
termsArrayList.get(index - 1).leftSeq = termsArrayList.get(j);
termsArrayList.get(index - 1).rightSeq = termsArrayList.get(i);
termsArrayList.get(index - 1).cost = combCost2; //sets the new cost
termsArrayList.get(index - 1).costAlgo = 2;
termsArrayList.get(j).costAlgo = 0;
//System.out.println("A replacement has been made. " + termsArrayList.get(j).repToString() + " + " + termsArrayList.get(i).repToString() + " = " + termsArrayList.get(index - 1).repToString());
}
}
}
}
}
termsArrayList.get(termsArrayList.size()-1).printCodeOutput(probs[currentLevel], outputStream);
}
outputStream.close();
}
}
}
| true | true | public static void main(String[] args) throws IOException {
if (false) {
System.out.println("Please enter two input file names");
}
else {
File fquery = new File(args[0]);
File fconfig = new File(args[1]);
//File fquery = new File("query.txt");
//File fconfig = new File("config.txt");
/* AL queryLines holds one line from query.txt per AL's element */
ArrayList<String> queryLines = new ArrayList<String>();
BufferedReader inputStream = null;
PrintWriter outputStream = null;
/* reading query.txt into AL */
try {
inputStream = new BufferedReader(new FileReader(fquery));
String l;
while ((l = inputStream.readLine()) != null) {
queryLines.add(l);
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
if (inputStream != null) {
try {
inputStream.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
/* reading config.properties file */
Properties costProps = new Properties();
FileInputStream in = null;
try {
in = new FileInputStream(fconfig);
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
costProps.load(in);
}
catch (IOException e) {
e.printStackTrace();
}
try {
in.close();
}
catch (IOException e) {
e.printStackTrace();
}
//actual code starts here
int numPasses = queryLines.size();
ArrayList<Float> tempValues;
float[][] probs = new float[numPasses][]; //stores the probabilities in a 2D array
//builds the 2D array with all of the probabilities
for (int i = 0; i < queryLines.size(); i++) {
String line = queryLines.get(i);
StringTokenizer parse = new StringTokenizer(line);
tempValues = new ArrayList<Float>();
while(parse.hasMoreElements()){
String num = String.valueOf(parse.nextElement());
tempValues.add(Float.valueOf(num));
}
probs[i] = new float[tempValues.size()];
for (int j = 0; j < tempValues.size(); j++) {
probs[i][j] = tempValues.get(j);
}
}
outputStream = new PrintWriter(new FileWriter("output.txt"));
//int currentLevel = 0; //represents what row of probabilities we are working on
for (int currentLevel = 0; currentLevel < probs.length; currentLevel++) {
ArrayList<Term> termsArrayList = Term.generateTermArray(probs[currentLevel].length);
Term.fillArrayCosts(termsArrayList, costProps, probs[currentLevel]);
//loop that builds optimal plan
for (int i = 0; i < termsArrayList.size(); i++) {
for (int j = 0; j < termsArrayList.size(); j++) {
if(i == j){}
else if (termsArrayList.get(i).compareCMetrics(termsArrayList.get(j))) { //checks for CMetric optimization
}
else if (termsArrayList.get(i).compareDMetrics(termsArrayList.get(j)) && (termsArrayList.get(i)).calcProductivites(probs[currentLevel]) <= 0.5) {
}
else{
if (termsArrayList.get(i).canCombine(termsArrayList.get(j))) {
// checks if a && b is better than aUb
float combCost = termsArrayList.get(i).calcDoubAnd(termsArrayList.get(j), costProps, probs[currentLevel]);
int index = Term.calcValue(termsArrayList.get(i), termsArrayList.get(j)); //sequences are stored in the index of their binary value - 1 since the all 0 sequence has been removed
//int[] cmbrep = Term.combinedRep(termsArrayList.get(i), termsArrayList.get(j));
//String cmbrepString = Term.repToString(cmbrep);
//System.out.println("The && is: " + combCost + " union cost is " + termsArrayList.get(index - 1).cost + " for " + termsArrayList.get(i).repToString()+ " with " + termsArrayList.get(j).repToString() + " vs " + termsArrayList.get(index - 1).repToString() + " index: " + index);
float compVal = combCost - termsArrayList.get(index - 1).cost;
if (compVal < 0 && Math.abs(compVal) > 0.001) { //checks to see if the && plan is less than the & plan
termsArrayList.get(index - 1).leftSeq = termsArrayList.get(i);
termsArrayList.get(index - 1).rightSeq = termsArrayList.get(j);
termsArrayList.get(index - 1).cost = combCost; //sets the new cost
termsArrayList.get(index - 1).costAlgo = 2;
termsArrayList.get(i).costAlgo = 0;
//System.out.println("A replacement has been made. " + termsArrayList.get(i).repToString() + " + " + termsArrayList.get(j).repToString() + " = " + termsArrayList.get(index - 1).repToString());
}
// checks if b&&a is better than bUa
float combCost2 = termsArrayList.get(j).calcDoubAnd(termsArrayList.get(i), costProps, probs[currentLevel]);
//int index2 = Term.calcValue(termsArrayList.get(i), termsArrayList.get(j)); //sequences are stored in the index of their binary value - 1 since the all 0 sequence has been removed
//System.out.println("The && is: " + combCost + " union cost is " + termsArrayList.get(index - 1).cost + " for " + termsArrayList.get(i).repToString()+ " with " + termsArrayList.get(j).repToString() + " vs " + termsArrayList.get(index - 1).repToString() + " index: " + index);
float compVal2 = combCost2 - termsArrayList.get(index - 1).cost;
if (compVal2 < 0 && Math.abs(compVal2) > 0.001) { //checks to see if the && plan is less than the & plan
termsArrayList.get(index - 1).leftSeq = termsArrayList.get(j);
termsArrayList.get(index - 1).rightSeq = termsArrayList.get(i);
termsArrayList.get(index - 1).cost = combCost2; //sets the new cost
termsArrayList.get(index - 1).costAlgo = 2;
termsArrayList.get(j).costAlgo = 0;
//System.out.println("A replacement has been made. " + termsArrayList.get(j).repToString() + " + " + termsArrayList.get(i).repToString() + " = " + termsArrayList.get(index - 1).repToString());
}
}
}
}
}
termsArrayList.get(termsArrayList.size()-1).printCodeOutput(probs[currentLevel], outputStream);
}
outputStream.close();
}
}
| public static void main(String[] args) throws IOException {
if (args.length != 2) {
System.out.println("Please enter two input file names");
}
else {
File fquery = new File(args[0]);
File fconfig = new File(args[1]);
//File fquery = new File("query.txt");
//File fconfig = new File("config.txt");
/* AL queryLines holds one line from query.txt per AL's element */
ArrayList<String> queryLines = new ArrayList<String>();
BufferedReader inputStream = null;
PrintWriter outputStream = null;
/* reading query.txt into AL */
try {
inputStream = new BufferedReader(new FileReader(fquery));
String l;
while ((l = inputStream.readLine()) != null) {
queryLines.add(l);
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
if (inputStream != null) {
try {
inputStream.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
/* reading config.properties file */
Properties costProps = new Properties();
FileInputStream in = null;
try {
in = new FileInputStream(fconfig);
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
costProps.load(in);
}
catch (IOException e) {
e.printStackTrace();
}
try {
in.close();
}
catch (IOException e) {
e.printStackTrace();
}
//actual code starts here
int numPasses = queryLines.size();
ArrayList<Float> tempValues;
float[][] probs = new float[numPasses][]; //stores the probabilities in a 2D array
//builds the 2D array with all of the probabilities
for (int i = 0; i < queryLines.size(); i++) {
String line = queryLines.get(i);
StringTokenizer parse = new StringTokenizer(line);
tempValues = new ArrayList<Float>();
while(parse.hasMoreElements()){
String num = String.valueOf(parse.nextElement());
tempValues.add(Float.valueOf(num));
}
probs[i] = new float[tempValues.size()];
for (int j = 0; j < tempValues.size(); j++) {
probs[i][j] = tempValues.get(j);
}
}
outputStream = new PrintWriter(new FileWriter("output.txt"));
//int currentLevel = 0; //represents what row of probabilities we are working on
for (int currentLevel = 0; currentLevel < probs.length; currentLevel++) {
ArrayList<Term> termsArrayList = Term.generateTermArray(probs[currentLevel].length);
Term.fillArrayCosts(termsArrayList, costProps, probs[currentLevel]);
//loop that builds optimal plan
for (int i = 0; i < termsArrayList.size(); i++) {
for (int j = 0; j < termsArrayList.size(); j++) {
if(i == j){}
else if (termsArrayList.get(i).compareCMetrics(termsArrayList.get(j))) { //checks for CMetric optimization
}
else if (termsArrayList.get(i).compareDMetrics(termsArrayList.get(j)) && (termsArrayList.get(i)).calcProductivites(probs[currentLevel]) <= 0.5) {
}
else{
if (termsArrayList.get(i).canCombine(termsArrayList.get(j))) {
// checks if a && b is better than aUb
float combCost = termsArrayList.get(i).calcDoubAnd(termsArrayList.get(j), costProps, probs[currentLevel]);
int index = Term.calcValue(termsArrayList.get(i), termsArrayList.get(j)); //sequences are stored in the index of their binary value - 1 since the all 0 sequence has been removed
//int[] cmbrep = Term.combinedRep(termsArrayList.get(i), termsArrayList.get(j));
//String cmbrepString = Term.repToString(cmbrep);
//System.out.println("The && is: " + combCost + " union cost is " + termsArrayList.get(index - 1).cost + " for " + termsArrayList.get(i).repToString()+ " with " + termsArrayList.get(j).repToString() + " vs " + termsArrayList.get(index - 1).repToString() + " index: " + index);
float compVal = combCost - termsArrayList.get(index - 1).cost;
if (compVal < 0 && Math.abs(compVal) > 0.001) { //checks to see if the && plan is less than the & plan
termsArrayList.get(index - 1).leftSeq = termsArrayList.get(i);
termsArrayList.get(index - 1).rightSeq = termsArrayList.get(j);
termsArrayList.get(index - 1).cost = combCost; //sets the new cost
termsArrayList.get(index - 1).costAlgo = 2;
termsArrayList.get(i).costAlgo = 0;
//System.out.println("A replacement has been made. " + termsArrayList.get(i).repToString() + " + " + termsArrayList.get(j).repToString() + " = " + termsArrayList.get(index - 1).repToString());
}
// checks if b&&a is better than bUa
float combCost2 = termsArrayList.get(j).calcDoubAnd(termsArrayList.get(i), costProps, probs[currentLevel]);
//int index2 = Term.calcValue(termsArrayList.get(i), termsArrayList.get(j)); //sequences are stored in the index of their binary value - 1 since the all 0 sequence has been removed
//System.out.println("The && is: " + combCost + " union cost is " + termsArrayList.get(index - 1).cost + " for " + termsArrayList.get(i).repToString()+ " with " + termsArrayList.get(j).repToString() + " vs " + termsArrayList.get(index - 1).repToString() + " index: " + index);
float compVal2 = combCost2 - termsArrayList.get(index - 1).cost;
if (compVal2 < 0 && Math.abs(compVal2) > 0.001) { //checks to see if the && plan is less than the & plan
termsArrayList.get(index - 1).leftSeq = termsArrayList.get(j);
termsArrayList.get(index - 1).rightSeq = termsArrayList.get(i);
termsArrayList.get(index - 1).cost = combCost2; //sets the new cost
termsArrayList.get(index - 1).costAlgo = 2;
termsArrayList.get(j).costAlgo = 0;
//System.out.println("A replacement has been made. " + termsArrayList.get(j).repToString() + " + " + termsArrayList.get(i).repToString() + " = " + termsArrayList.get(index - 1).repToString());
}
}
}
}
}
termsArrayList.get(termsArrayList.size()-1).printCodeOutput(probs[currentLevel], outputStream);
}
outputStream.close();
}
}
|
diff --git a/src/villebasse/gamelogic/DefaultDeckWithoutCloisters.java b/src/villebasse/gamelogic/DefaultDeckWithoutCloisters.java
index d0c3539..acff1e0 100644
--- a/src/villebasse/gamelogic/DefaultDeckWithoutCloisters.java
+++ b/src/villebasse/gamelogic/DefaultDeckWithoutCloisters.java
@@ -1,66 +1,66 @@
package villebasse.gamelogic;
import java.util.Vector;
import villebasse.gamelogic.defaultpieces.*;
public class DefaultDeckWithoutCloisters extends Deck
{
public DefaultDeckWithoutCloisters()
{
this.pieces = new Vector<Piece>(72);
for (int i = 0; i < 5; ++i)
this.pieces.add(new PieceDiagonalCity());
- for (int i = 0; i < 2; ++i)
+ for (int i = 0; i < 3; ++i)
this.pieces.add(new PieceCityEndWithIntersection());
for (int i = 0; i < 3; ++i)
this.pieces.add(new PieceFacingCities());
for (int i = 0; i < 9; ++i)
this.pieces.add(new PieceRoadTurn());
for (int i = 0; i < 8; ++i)
this.pieces.add(new PieceRoad());
for (int i = 0; i < 4; ++i)
this.pieces.add(new PieceTIntersection());
for (int i = 0; i < 4; ++i)
this.pieces.add(new PieceBigCity());
for (int i = 0; i < 3; ++i)
this.pieces.add(new PieceBigCityWithRoad());
for (int i = 0; i < 2; ++i)
this.pieces.add(new PieceCityCorner());
for (int i = 0; i < 5; ++i)
this.pieces.add(new PieceCityEnd());
- for (int i = 0; i < 4; ++i)
+ for (int i = 0; i < 3; ++i)
this.pieces.add(new PieceCityEndWithRoad());
for (int i = 0; i < 3; ++i)
this.pieces.add(new PieceCityEndWithRoadLeft());
for (int i = 0; i < 3; ++i)
this.pieces.add(new PieceCityEndWithRoadRight());
for (int i = 0; i < 3; ++i)
this.pieces.add(new PieceCityPipe());
for (int i = 0; i < 5; ++i)
this.pieces.add(new PieceDiagonalCityWithRoad());
/*
this.pieces.add(new PieceXIntersection());
this.pieces.add(new PieceFullCity());
*/
this.shuffle();
- this.pieces.add(new PieceCityEndWithIntersection());
+ this.pieces.add(new PieceCityEndWithRoad());
}
}
| false | true | public DefaultDeckWithoutCloisters()
{
this.pieces = new Vector<Piece>(72);
for (int i = 0; i < 5; ++i)
this.pieces.add(new PieceDiagonalCity());
for (int i = 0; i < 2; ++i)
this.pieces.add(new PieceCityEndWithIntersection());
for (int i = 0; i < 3; ++i)
this.pieces.add(new PieceFacingCities());
for (int i = 0; i < 9; ++i)
this.pieces.add(new PieceRoadTurn());
for (int i = 0; i < 8; ++i)
this.pieces.add(new PieceRoad());
for (int i = 0; i < 4; ++i)
this.pieces.add(new PieceTIntersection());
for (int i = 0; i < 4; ++i)
this.pieces.add(new PieceBigCity());
for (int i = 0; i < 3; ++i)
this.pieces.add(new PieceBigCityWithRoad());
for (int i = 0; i < 2; ++i)
this.pieces.add(new PieceCityCorner());
for (int i = 0; i < 5; ++i)
this.pieces.add(new PieceCityEnd());
for (int i = 0; i < 4; ++i)
this.pieces.add(new PieceCityEndWithRoad());
for (int i = 0; i < 3; ++i)
this.pieces.add(new PieceCityEndWithRoadLeft());
for (int i = 0; i < 3; ++i)
this.pieces.add(new PieceCityEndWithRoadRight());
for (int i = 0; i < 3; ++i)
this.pieces.add(new PieceCityPipe());
for (int i = 0; i < 5; ++i)
this.pieces.add(new PieceDiagonalCityWithRoad());
/*
this.pieces.add(new PieceXIntersection());
this.pieces.add(new PieceFullCity());
*/
this.shuffle();
this.pieces.add(new PieceCityEndWithIntersection());
}
| public DefaultDeckWithoutCloisters()
{
this.pieces = new Vector<Piece>(72);
for (int i = 0; i < 5; ++i)
this.pieces.add(new PieceDiagonalCity());
for (int i = 0; i < 3; ++i)
this.pieces.add(new PieceCityEndWithIntersection());
for (int i = 0; i < 3; ++i)
this.pieces.add(new PieceFacingCities());
for (int i = 0; i < 9; ++i)
this.pieces.add(new PieceRoadTurn());
for (int i = 0; i < 8; ++i)
this.pieces.add(new PieceRoad());
for (int i = 0; i < 4; ++i)
this.pieces.add(new PieceTIntersection());
for (int i = 0; i < 4; ++i)
this.pieces.add(new PieceBigCity());
for (int i = 0; i < 3; ++i)
this.pieces.add(new PieceBigCityWithRoad());
for (int i = 0; i < 2; ++i)
this.pieces.add(new PieceCityCorner());
for (int i = 0; i < 5; ++i)
this.pieces.add(new PieceCityEnd());
for (int i = 0; i < 3; ++i)
this.pieces.add(new PieceCityEndWithRoad());
for (int i = 0; i < 3; ++i)
this.pieces.add(new PieceCityEndWithRoadLeft());
for (int i = 0; i < 3; ++i)
this.pieces.add(new PieceCityEndWithRoadRight());
for (int i = 0; i < 3; ++i)
this.pieces.add(new PieceCityPipe());
for (int i = 0; i < 5; ++i)
this.pieces.add(new PieceDiagonalCityWithRoad());
/*
this.pieces.add(new PieceXIntersection());
this.pieces.add(new PieceFullCity());
*/
this.shuffle();
this.pieces.add(new PieceCityEndWithRoad());
}
|
diff --git a/src/main/ed/js/JSString.java b/src/main/ed/js/JSString.java
index 53e9752ab..50b1b8e48 100644
--- a/src/main/ed/js/JSString.java
+++ b/src/main/ed/js/JSString.java
@@ -1,746 +1,746 @@
// JSString.java
/**
* Copyright (C) 2008 10gen Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package ed.js;
import java.util.*;
import java.util.regex.*;
import com.twmacinta.util.*;
import ed.util.*;
import ed.js.func.*;
import ed.js.engine.*;
/** @expose */
public class JSString extends JSObjectBase implements Comparable {
static { JS._debugSIStart( "JSString" ); }
static { JS._debugSI( "JSString" , "0" ); }
public static class JSStringCons extends JSFunctionCalls1{
public JSObject newOne(){
return new JSString("");
}
public Object call( Scope s , Object[] args ){
return new JSString( "" );
}
public Object call( Scope s , Object fooO, Object[] args ){
JSString foo = new JSString( fooO + "" );
Object o = s.getThis();
if ( o == null || ! ( o instanceof JSString ) )
return foo;
JSString str = (JSString)o;
if ( foo != null )
str._s = foo.toString();
else
str._s = "";
return str;
}
protected void init(){
JS._debugSI( "JSString" , "JSStringCons init 0" );
final JSObject myPrototype = _prototype;
if ( ! JS.JNI ){
final StringEncrypter encrypter = new StringEncrypter( "knsd8712@!98sad" );
_prototype.set( "encrypt" , new JSFunctionCalls0(){
public Object call( Scope s , Object foo[] ){
synchronized ( encrypter ){
return new JSString( encrypter.encrypt( s.getThis().toString() ) );
}
}
} );
_prototype.set( "decrypt" , new JSFunctionCalls0(){
public Object call( Scope s , Object foo[] ){
synchronized ( encrypter ){
return new JSString( encrypter.decrypt( s.getThis().toString() ) );
}
}
} );
}
JS._debugSI( "JSString" , "JSStringCons init 1" );
_prototype.set( "trim" , new JSFunctionCalls0() {
public Object call( Scope s , Object foo[] ){
return new JSString( s.getThis().toString().trim() );
}
} );
_prototype.set( "md5" , new JSFunctionCalls0() {
public Object call( Scope s , Object extra[] ){
synchronized ( _myMd5 ){
_myMd5.Init();
_myMd5.Update( s.getThis().toString() );
return new JSString( _myMd5.asHex() );
}
}
private final MD5 _myMd5 = new MD5();
} );
_prototype.set( "to_sym" , new JSFunctionCalls0() {
public Object call( Scope s , Object extra[] ){
return s.getThis().toString();
}
private final MD5 _myMd5 = new MD5();
} );
_prototype.set( "toString" , new JSFunctionCalls0() {
public Object call( Scope s , Object extra[] ) {
Object o = s.getThis();
if( !( o instanceof JSString ) )
if ( o == myPrototype )
return new JSString( "" );
else
throw new JSException( "String.prototype.toString can only be called on Strings" );
return new JSString( ((JSString)o)._s );
}
} );
_prototype.set( "toLowerCase" , new JSFunctionCalls0() {
public Object call( Scope s , Object foo[] ){
return new JSString( s.getThis().toString().toLowerCase() );
}
} );
_prototype.set( "toUpperCase" , new JSFunctionCalls0() {
public Object call( Scope s , Object foo[] ){
return new JSString( s.getThis().toString().toUpperCase() );
}
} );
_prototype.set( "charCodeAt" , new JSFunctionCalls1() {
public Object call( Scope s , Object o , Object foo[] ){
String str = s.getThis().toString();
int idx = (int)JSNumber.getDouble( o );
if( idx >= str.length() || idx < 0 )
return Double.NaN;
return Integer.valueOf( str.charAt( idx ) );
}
} );
_prototype.set( "charAt" , new JSFunctionCalls1() {
public Object call( Scope s , Object o , Object foo[] ){
String str = s.getThis().toString();
int idx = (int)JSNumber.getDouble( o );
if ( idx >= str.length() || idx < 0 )
return EMPTY;
return new JSString( str.substring( idx , idx + 1 ) );
}
} );
_prototype.set( "indexOf" , new JSFunctionCalls1() {
public Object call( Scope s , Object o , Object foo[] ){
String str = s.getThis().toString();
if( o == null )
return -1;
String thing = o.toString();
int start = 0;
if ( foo != null && foo.length > 0 && foo[0] != null ) {
start = ((Number)foo[0]).intValue();
}
return str.indexOf( thing , start );
}
} );
_prototype.set( "contains" , new JSFunctionCalls1() {
public Object call( Scope s , Object o , Object foo[] ){
String str = s.getThis().toString();
String thing = o.toString();
return str.contains( thing );
}
} );
_prototype.set( "__rshift" , new JSFunctionCalls1() {
public Object call( Scope s , Object o , Object foo[] ){
JSString me = (JSString)(s.getThis());
String thing = o.toString();
me._s += thing;
return me;
}
} );
_prototype.set( "lastIndexOf" , new JSFunctionCalls1() {
public Object call( Scope s , Object o , Object foo[] ){
String str = s.getThis().toString();
String thing = o.toString();
int end = str.length();
if ( foo != null && foo.length > 0 )
end = ((Number)foo[0]).intValue();
return str.lastIndexOf( thing , end );
}
} );
_prototype.set( "startsWith" , new JSFunctionCalls1() {
public Object call( Scope s , Object o , Object foo[] ){
String str = s.getThis().toString();
String thing = o.toString();
return str.startsWith( thing );
}
} );
_prototype.set( "endsWith" , new JSFunctionCalls1() {
public Object call( Scope s , Object o , Object foo[] ){
String str = s.getThis().toString();
String thing = o.toString();
return str.endsWith( thing );
}
} );
_prototype.set( "substring" , new JSFunctionCalls2() {
public Object call( Scope s , Object startO , Object endO , Object foo[] ){
String str = s.getThis().toString();
int start = (int)JSNumber.getDouble( startO );
int end = endO == null ? str.length() : (int)JSNumber.getDouble( endO );
if ( start < 0 )
start = 0;
if ( start >= str.length() || start < 0 )
return EMPTY;
if ( end > str.length() )
end = str.length();
if ( end < 0 )
return new JSString( str.substring( start ) );
return new JSString( str.substring( start , end ) );
}
} );
_prototype.set( "substr" , new JSFunctionCalls2() {
public Object call( Scope s , Object startO , Object lengthO , Object foo[] ){
String str = s.getThis().toString();
int start = ((Number)startO).intValue();
if ( start < 0 )
start = 0;
if ( start >= str.length() || start < 0 )
return EMPTY;
int length = -1;
if ( lengthO != null && lengthO instanceof Number )
length = ((Number)lengthO).intValue();
if ( start + length > str.length() )
length = str.length() - start;
if ( length < 0 )
return new JSString( str.substring( start) );
return new JSString( str.substring( start , start + length ) );
}
} );
_prototype.set( "match" , new JSFunctionCalls1() {
public Object call( Scope s , Object o , Object foo[] ){
String str = s.getThis().toString();
if ( o instanceof String || o instanceof JSString )
o = new JSRegex( o.toString() , "" );
if ( ! ( o instanceof JSRegex ) )
throw new RuntimeException( "not a regex : " + o.getClass() );
JSRegex r = (JSRegex)o;
Matcher m = r._patt.matcher( str );
if ( ! m.find() )
return null;
if ( r.getFlags().contains( "g" )){
JSArray a = new JSArray();
do {
a.add(new JSString(m.group()));
} while(m.find());
return a;
}
else{
return r.exec(str);
}
}
} );
_prototype.set( "split" , new JSFunctionCalls2(){
public Object call( Scope s , Object o , Object limit, Object extra[] ){
String str = s.getThis().toString();
JSArray a = new JSArray();
if ( limit == null ) {
limit = Integer.MAX_VALUE;
}
else {
limit = StringParseUtil.parseStrict( limit.toString() );
if ( ((Number)limit).intValue() == 0 ) {
return a;
}
}
if ( o == null ) {
a.add( s.getThis() );
return a;
}
if ( o instanceof String || o instanceof JSString )
o = new JSRegex( JSRegex.quote( o.toString() ) , "" );
if ( ! ( o instanceof JSRegex ) )
throw new RuntimeException( "not a regex : " + o.getClass() );
JSRegex r = (JSRegex)o;
String spacer = null;
if ( r.getPattern().contains( "(" ) )
spacer = r.getPattern().replaceAll( "[()]" , "" );
for ( String pc : r._patt.split( str , -1 ) ){
if ( a.size() > 0 && spacer != null )
a.add( spacer );
a.add( new JSString( pc ) );
if ( a.size() >= ((Number)limit).intValue() )
break;
}
if ( r.getPattern().length() == 0 ){
a.remove( 0 );
if( a.size() > 0 ) {
a.remove( a.size() - 1 );
}
}
return a;
}
}
);
_prototype.set( "reverse" , new JSFunctionCalls0(){
public Object call(Scope s, Object [] args){
String str = s.getThis().toString();
StringBuffer buf = new StringBuffer( str.length() );
for ( int i=str.length()-1; i>=0; i--)
buf.append( str.charAt( i ) );
return new JSString( buf.toString() );
}
} );
_prototype.set("slice" , new JSFunctionCalls2(){
public Object call(Scope s, Object o1, Object o2, Object [] args){
String str = s.getThis().toString();
int start = 0;
if (o1 != null && o1 instanceof Number) {
start = ((Number)o1).intValue();
if (start < 0) {
start = str.length() + start; // add as it's negative
}
}
if ( start < 0 )
start = 0;
if (start >= str.length())
return EMPTY;
int end = str.length();
if (o2 != null && o2 instanceof Number) {
end = ((Number)o2).intValue();
if (end < 0) {
end = str.length() + end; // add as it's negative
if ( end < 0 )
end = 0;
}
if (end > str.length()) {
end = str.length();
}
if ( end < start )
end = start;
}
return new JSString(str.substring(start, end));
}
} );
_prototype.set( "pluralize" , new JSFunctionCalls0(){
public Object call(Scope s, Object [] args){
String str = s.getThis().toString();
return str + "s";
}
} );
_prototype.set( "_eq__t_" , _prototype.get( "match" ) );
_prototype.set( "__delete" , new JSFunctionCalls1(){
public Object call(Scope s, Object all , Object [] args){
String str = s.getThis().toString();
if ( all == null )
return str;
String bad = all.toString();
StringBuffer buf = new StringBuffer( str.length() );
outer:
for ( int i=0; i<str.length(); i++ ){
char c = str.charAt( i );
for ( int j=0; j<bad.length(); j++ )
if ( bad.charAt( j ) == c )
continue outer;
buf.append( c );
}
return new JSString( buf.toString() );
}
} );
_prototype.set( "_lb__rb_" , new JSFunctionCalls1(){
public Object call( Scope s , Object thing , Object args[] ){
JSString str = (JSString)s.getThis();
if ( thing instanceof Number ){
return (int)(str._s.charAt( ((Number)thing).intValue() ));
}
if ( thing instanceof JSArray ){
JSArray a = (JSArray)thing;
int start = ((Number)(a.get("start"))).intValue();
int end = ((Number)(a.get("end"))).intValue();
String sub = str._s.substring( start , end + 1 );
return new JSString( sub );
}
return null;
}
} );
_prototype.set( "each_byte" , new JSFunctionCalls1(){
public Object call(Scope s, Object funcObject , Object [] args){
if ( funcObject == null )
throw new NullPointerException( "each_byte needs a function" );
JSFunction func = (JSFunction)funcObject;
String str = s.getThis().toString();
for ( int i=0; i<str.length(); i++ ){
func.call( s , (int)str.charAt( i ) );
}
return null;
}
} );
_prototype.set( "replace" , new JSFunctionCalls2() {
public Object call( Scope s , Object o , Object repl , Object crap[] ){
String str = s.getThis().toString();
if ( o instanceof String || o instanceof JSString )
o = new JSRegex( JSRegex.quote( o.toString() ) , "" );
if ( ! ( o instanceof JSRegex ) )
throw new RuntimeException( "not a regex : " + o.getClass() );
JSRegex r = (JSRegex)o;
Matcher m = r._patt.matcher( str );
StringBuffer buf = null;
int start = 0;
final JSObject options = ( crap != null && crap.length > 0 && crap[0] instanceof JSObject ) ? (JSObject)crap[0] : null;
final boolean replaceAll = r._replaceAll || ( options != null && options.get( "all" ) != null );
Object replArgs[] = null;
while ( m.find() ){
if ( buf == null )
buf = new StringBuffer( str.length() );
buf.append( str.substring( start , m.start() ) );
if ( repl == null )
repl = "null";
if ( repl instanceof JSString || repl instanceof String){
String foo = repl.toString();
for ( int i=0; i<foo.length(); i++ ){
char c = foo.charAt( i );
if ( c != '$' ){
buf.append( c );
continue;
}
if ( i + 1 >= foo.length() ||
! Character.isDigit( foo.charAt( i + 1 ) ) ){
buf.append( c );
continue;
}
i++;
int end = i;
while ( end < foo.length() && Character.isDigit( foo.charAt( end ) ) )
end++;
int num = Integer.parseInt( foo.substring( i , end ) );
- buf.append( m.group( num ) );
+ buf.append( m.group( num ) == null ? "" : m.group( num ) );
i = end - 1;
}
}
else if ( repl instanceof JSFunction ){
if ( replArgs == null )
replArgs = new Object[ m.groupCount() + 1 ];
for ( int i=0; i<replArgs.length; i++ )
replArgs[i] = new JSString( m.group( i ) );
buf.append( ((JSFunction)repl).call( s , replArgs ) );
}
else {
throw new RuntimeException( "can't use replace with : " + repl.getClass() );
}
start = m.end();
if ( ! replaceAll )
break;
}
if ( buf == null )
return new JSString( str );
buf.append( str.substring( start ) );
return new JSString( buf.toString() );
}
} );
_prototype.set( "sub" , _prototype.get( "replace" ) );
final JSObjectBase gsubOptions = new JSObjectBase();
gsubOptions.set( "all" , "asd" );
final Object gsubOptionsArray[] = new Object[]{ gsubOptions };
_prototype.set( "gsub" , new JSFunctionCalls2() {
public Object call( Scope s , Object o , Object repl , Object crap[] ){
return ((JSFunction)myPrototype.get( "replace" )).call( s , o , repl , gsubOptionsArray );
}
} );
_prototype.set( "valueOf" , new JSFunctionCalls0() {
public Object call( Scope s , Object crap[] ){
Object o = s.getThis();
if( o == myPrototype )
return new JSString( "" );
return new JSString( ((JSString)o).toString() );
}
} );
set("fromCharCode", new JSFunctionCalls0() {
public Object call(Scope s, Object [] args){
if(args == null) return new JSString("");
StringBuffer buf = new StringBuffer();
for(int i = 0; i < args.length; i++){
Object o = args[i];
if(! (o instanceof Number) )
throw new RuntimeException( "fromCharCode only takes numbers" );
Number n = (Number)o;
char c = (char)JSNumber.toUint16( o );
buf.append(c);
}
return new JSString( buf.toString() );
}
} );
set( "isUpper" , new JSFunctionCalls1(){
public Object call( Scope s , Object thing , Object args[] ){
String str = thing.toString();
for ( int i=0; i<str.length(); i++ ){
char c = str.charAt( i );
if ( Character.isLetter( c ) &&
Character.isUpperCase( c ) )
continue;
return false;
}
return true;
}
} );
_prototype.dontEnumExisting();
}
};
static { JS._debugSI( "JSString" , "1" ); }
private static JSFunction _cons = new JSStringCons();
static { JS._debugSI( "JSString" , "2" ); }
/** The empty string: "" */
static JSString EMPTY = new JSString("");
/** Initializes a new string
* @param The value for the string.
*/
public JSString( String s ){
super( Scope.getThreadLocalFunction( "String", _cons , true ) );
_s = s;
}
/** Initializes a new string from an array of characters.
* @param The value for the string.
*/
public JSString( char [] c ){
this(new String(c));
}
/** Gets the property of this string with the key <tt>name</tt>.
* @param name The name of the property
*/
public Object get( Object name ){
if ( name instanceof JSString )
name = name.toString();
if ( name instanceof String && name.toString().equals( "length" ) )
return Integer.valueOf( _s.length() );
return super.get( name );
}
/** Returns this string.
* @return This string.
*/
public String toString(){
return _s;
}
public String toPrettyString(){
return _s;
}
/** Compare this string with an object. The empty string matches null.
* @param o The object with which to compare this string.
* @return 1, -1, or 0 if this string is semantically greater than, less than, or equal to the given object.
*/
public int compareTo( Object o ){
if ( o == null ) o = "";
return _s.compareTo( o.toString() );
}
/** Return the length of this string.
* @return The length of this string.
*/
public int length(){
return _s.length();
}
/** The character at the given position in this string.
* @param n Index of the character.
* @return A single-character string
*/
public Object getInt( int n ){
if ( n >= _s.length() )
return null;
// Eliot said that we should map characters to objects in scope.java
return new JSString(new char[]{_s.charAt( n )});
}
/** The hash code value of this array.
* @return The hash code value of this array.
*/
public int hashCode( IdentitySet seen ){
return _s.hashCode();
}
/** Test equality between this string and an object.
* @param Object to which to compare this string.
* @return If object is equal to this string.
*/
public boolean equals( Object o ){
if ( o == null )
return _s == null;
if ( _s == null )
return false;
return _s.equals( o.toString() );
}
/** Returns this string as an array of bytes.
* @return This string as an array of bytes.
*/
public byte[] getBytes(){
return _s.getBytes();
}
public Set<String> keySet( boolean includePrototype ){
Set<String> keys = new OrderedSet<String>();
for ( int i=0; i<_s.length(); i++ )
keys.add( String.valueOf( i ) );
keys.addAll( super.keySet( includePrototype ) );
return keys;
}
private void setObj( boolean b ) {
isObj = b;
}
public boolean isObj() {
return isObj;
}
String _s;
public static class Symbol extends JSString {
public Symbol( String s ){
super( s );
}
}
static { JS._debugSIDone( "JSString" ); }
private boolean isObj = false;
}
| true | true | protected void init(){
JS._debugSI( "JSString" , "JSStringCons init 0" );
final JSObject myPrototype = _prototype;
if ( ! JS.JNI ){
final StringEncrypter encrypter = new StringEncrypter( "knsd8712@!98sad" );
_prototype.set( "encrypt" , new JSFunctionCalls0(){
public Object call( Scope s , Object foo[] ){
synchronized ( encrypter ){
return new JSString( encrypter.encrypt( s.getThis().toString() ) );
}
}
} );
_prototype.set( "decrypt" , new JSFunctionCalls0(){
public Object call( Scope s , Object foo[] ){
synchronized ( encrypter ){
return new JSString( encrypter.decrypt( s.getThis().toString() ) );
}
}
} );
}
JS._debugSI( "JSString" , "JSStringCons init 1" );
_prototype.set( "trim" , new JSFunctionCalls0() {
public Object call( Scope s , Object foo[] ){
return new JSString( s.getThis().toString().trim() );
}
} );
_prototype.set( "md5" , new JSFunctionCalls0() {
public Object call( Scope s , Object extra[] ){
synchronized ( _myMd5 ){
_myMd5.Init();
_myMd5.Update( s.getThis().toString() );
return new JSString( _myMd5.asHex() );
}
}
private final MD5 _myMd5 = new MD5();
} );
_prototype.set( "to_sym" , new JSFunctionCalls0() {
public Object call( Scope s , Object extra[] ){
return s.getThis().toString();
}
private final MD5 _myMd5 = new MD5();
} );
_prototype.set( "toString" , new JSFunctionCalls0() {
public Object call( Scope s , Object extra[] ) {
Object o = s.getThis();
if( !( o instanceof JSString ) )
if ( o == myPrototype )
return new JSString( "" );
else
throw new JSException( "String.prototype.toString can only be called on Strings" );
return new JSString( ((JSString)o)._s );
}
} );
_prototype.set( "toLowerCase" , new JSFunctionCalls0() {
public Object call( Scope s , Object foo[] ){
return new JSString( s.getThis().toString().toLowerCase() );
}
} );
_prototype.set( "toUpperCase" , new JSFunctionCalls0() {
public Object call( Scope s , Object foo[] ){
return new JSString( s.getThis().toString().toUpperCase() );
}
} );
_prototype.set( "charCodeAt" , new JSFunctionCalls1() {
public Object call( Scope s , Object o , Object foo[] ){
String str = s.getThis().toString();
int idx = (int)JSNumber.getDouble( o );
if( idx >= str.length() || idx < 0 )
return Double.NaN;
return Integer.valueOf( str.charAt( idx ) );
}
} );
_prototype.set( "charAt" , new JSFunctionCalls1() {
public Object call( Scope s , Object o , Object foo[] ){
String str = s.getThis().toString();
int idx = (int)JSNumber.getDouble( o );
if ( idx >= str.length() || idx < 0 )
return EMPTY;
return new JSString( str.substring( idx , idx + 1 ) );
}
} );
_prototype.set( "indexOf" , new JSFunctionCalls1() {
public Object call( Scope s , Object o , Object foo[] ){
String str = s.getThis().toString();
if( o == null )
return -1;
String thing = o.toString();
int start = 0;
if ( foo != null && foo.length > 0 && foo[0] != null ) {
start = ((Number)foo[0]).intValue();
}
return str.indexOf( thing , start );
}
} );
_prototype.set( "contains" , new JSFunctionCalls1() {
public Object call( Scope s , Object o , Object foo[] ){
String str = s.getThis().toString();
String thing = o.toString();
return str.contains( thing );
}
} );
_prototype.set( "__rshift" , new JSFunctionCalls1() {
public Object call( Scope s , Object o , Object foo[] ){
JSString me = (JSString)(s.getThis());
String thing = o.toString();
me._s += thing;
return me;
}
} );
_prototype.set( "lastIndexOf" , new JSFunctionCalls1() {
public Object call( Scope s , Object o , Object foo[] ){
String str = s.getThis().toString();
String thing = o.toString();
int end = str.length();
if ( foo != null && foo.length > 0 )
end = ((Number)foo[0]).intValue();
return str.lastIndexOf( thing , end );
}
} );
_prototype.set( "startsWith" , new JSFunctionCalls1() {
public Object call( Scope s , Object o , Object foo[] ){
String str = s.getThis().toString();
String thing = o.toString();
return str.startsWith( thing );
}
} );
_prototype.set( "endsWith" , new JSFunctionCalls1() {
public Object call( Scope s , Object o , Object foo[] ){
String str = s.getThis().toString();
String thing = o.toString();
return str.endsWith( thing );
}
} );
_prototype.set( "substring" , new JSFunctionCalls2() {
public Object call( Scope s , Object startO , Object endO , Object foo[] ){
String str = s.getThis().toString();
int start = (int)JSNumber.getDouble( startO );
int end = endO == null ? str.length() : (int)JSNumber.getDouble( endO );
if ( start < 0 )
start = 0;
if ( start >= str.length() || start < 0 )
return EMPTY;
if ( end > str.length() )
end = str.length();
if ( end < 0 )
return new JSString( str.substring( start ) );
return new JSString( str.substring( start , end ) );
}
} );
_prototype.set( "substr" , new JSFunctionCalls2() {
public Object call( Scope s , Object startO , Object lengthO , Object foo[] ){
String str = s.getThis().toString();
int start = ((Number)startO).intValue();
if ( start < 0 )
start = 0;
if ( start >= str.length() || start < 0 )
return EMPTY;
int length = -1;
if ( lengthO != null && lengthO instanceof Number )
length = ((Number)lengthO).intValue();
if ( start + length > str.length() )
length = str.length() - start;
if ( length < 0 )
return new JSString( str.substring( start) );
return new JSString( str.substring( start , start + length ) );
}
} );
_prototype.set( "match" , new JSFunctionCalls1() {
public Object call( Scope s , Object o , Object foo[] ){
String str = s.getThis().toString();
if ( o instanceof String || o instanceof JSString )
o = new JSRegex( o.toString() , "" );
if ( ! ( o instanceof JSRegex ) )
throw new RuntimeException( "not a regex : " + o.getClass() );
JSRegex r = (JSRegex)o;
Matcher m = r._patt.matcher( str );
if ( ! m.find() )
return null;
if ( r.getFlags().contains( "g" )){
JSArray a = new JSArray();
do {
a.add(new JSString(m.group()));
} while(m.find());
return a;
}
else{
return r.exec(str);
}
}
} );
_prototype.set( "split" , new JSFunctionCalls2(){
public Object call( Scope s , Object o , Object limit, Object extra[] ){
String str = s.getThis().toString();
JSArray a = new JSArray();
if ( limit == null ) {
limit = Integer.MAX_VALUE;
}
else {
limit = StringParseUtil.parseStrict( limit.toString() );
if ( ((Number)limit).intValue() == 0 ) {
return a;
}
}
if ( o == null ) {
a.add( s.getThis() );
return a;
}
if ( o instanceof String || o instanceof JSString )
o = new JSRegex( JSRegex.quote( o.toString() ) , "" );
if ( ! ( o instanceof JSRegex ) )
throw new RuntimeException( "not a regex : " + o.getClass() );
JSRegex r = (JSRegex)o;
String spacer = null;
if ( r.getPattern().contains( "(" ) )
spacer = r.getPattern().replaceAll( "[()]" , "" );
for ( String pc : r._patt.split( str , -1 ) ){
if ( a.size() > 0 && spacer != null )
a.add( spacer );
a.add( new JSString( pc ) );
if ( a.size() >= ((Number)limit).intValue() )
break;
}
if ( r.getPattern().length() == 0 ){
a.remove( 0 );
if( a.size() > 0 ) {
a.remove( a.size() - 1 );
}
}
return a;
}
}
);
_prototype.set( "reverse" , new JSFunctionCalls0(){
public Object call(Scope s, Object [] args){
String str = s.getThis().toString();
StringBuffer buf = new StringBuffer( str.length() );
for ( int i=str.length()-1; i>=0; i--)
buf.append( str.charAt( i ) );
return new JSString( buf.toString() );
}
} );
_prototype.set("slice" , new JSFunctionCalls2(){
public Object call(Scope s, Object o1, Object o2, Object [] args){
String str = s.getThis().toString();
int start = 0;
if (o1 != null && o1 instanceof Number) {
start = ((Number)o1).intValue();
if (start < 0) {
start = str.length() + start; // add as it's negative
}
}
if ( start < 0 )
start = 0;
if (start >= str.length())
return EMPTY;
int end = str.length();
if (o2 != null && o2 instanceof Number) {
end = ((Number)o2).intValue();
if (end < 0) {
end = str.length() + end; // add as it's negative
if ( end < 0 )
end = 0;
}
if (end > str.length()) {
end = str.length();
}
if ( end < start )
end = start;
}
return new JSString(str.substring(start, end));
}
} );
_prototype.set( "pluralize" , new JSFunctionCalls0(){
public Object call(Scope s, Object [] args){
String str = s.getThis().toString();
return str + "s";
}
} );
_prototype.set( "_eq__t_" , _prototype.get( "match" ) );
_prototype.set( "__delete" , new JSFunctionCalls1(){
public Object call(Scope s, Object all , Object [] args){
String str = s.getThis().toString();
if ( all == null )
return str;
String bad = all.toString();
StringBuffer buf = new StringBuffer( str.length() );
outer:
for ( int i=0; i<str.length(); i++ ){
char c = str.charAt( i );
for ( int j=0; j<bad.length(); j++ )
if ( bad.charAt( j ) == c )
continue outer;
buf.append( c );
}
return new JSString( buf.toString() );
}
} );
_prototype.set( "_lb__rb_" , new JSFunctionCalls1(){
public Object call( Scope s , Object thing , Object args[] ){
JSString str = (JSString)s.getThis();
if ( thing instanceof Number ){
return (int)(str._s.charAt( ((Number)thing).intValue() ));
}
if ( thing instanceof JSArray ){
JSArray a = (JSArray)thing;
int start = ((Number)(a.get("start"))).intValue();
int end = ((Number)(a.get("end"))).intValue();
String sub = str._s.substring( start , end + 1 );
return new JSString( sub );
}
return null;
}
} );
_prototype.set( "each_byte" , new JSFunctionCalls1(){
public Object call(Scope s, Object funcObject , Object [] args){
if ( funcObject == null )
throw new NullPointerException( "each_byte needs a function" );
JSFunction func = (JSFunction)funcObject;
String str = s.getThis().toString();
for ( int i=0; i<str.length(); i++ ){
func.call( s , (int)str.charAt( i ) );
}
return null;
}
} );
_prototype.set( "replace" , new JSFunctionCalls2() {
public Object call( Scope s , Object o , Object repl , Object crap[] ){
String str = s.getThis().toString();
if ( o instanceof String || o instanceof JSString )
o = new JSRegex( JSRegex.quote( o.toString() ) , "" );
if ( ! ( o instanceof JSRegex ) )
throw new RuntimeException( "not a regex : " + o.getClass() );
JSRegex r = (JSRegex)o;
Matcher m = r._patt.matcher( str );
StringBuffer buf = null;
int start = 0;
final JSObject options = ( crap != null && crap.length > 0 && crap[0] instanceof JSObject ) ? (JSObject)crap[0] : null;
final boolean replaceAll = r._replaceAll || ( options != null && options.get( "all" ) != null );
Object replArgs[] = null;
while ( m.find() ){
if ( buf == null )
buf = new StringBuffer( str.length() );
buf.append( str.substring( start , m.start() ) );
if ( repl == null )
repl = "null";
if ( repl instanceof JSString || repl instanceof String){
String foo = repl.toString();
for ( int i=0; i<foo.length(); i++ ){
char c = foo.charAt( i );
if ( c != '$' ){
buf.append( c );
continue;
}
if ( i + 1 >= foo.length() ||
! Character.isDigit( foo.charAt( i + 1 ) ) ){
buf.append( c );
continue;
}
i++;
int end = i;
while ( end < foo.length() && Character.isDigit( foo.charAt( end ) ) )
end++;
int num = Integer.parseInt( foo.substring( i , end ) );
buf.append( m.group( num ) );
i = end - 1;
}
}
else if ( repl instanceof JSFunction ){
if ( replArgs == null )
replArgs = new Object[ m.groupCount() + 1 ];
for ( int i=0; i<replArgs.length; i++ )
replArgs[i] = new JSString( m.group( i ) );
buf.append( ((JSFunction)repl).call( s , replArgs ) );
}
else {
throw new RuntimeException( "can't use replace with : " + repl.getClass() );
}
start = m.end();
if ( ! replaceAll )
break;
}
if ( buf == null )
return new JSString( str );
buf.append( str.substring( start ) );
return new JSString( buf.toString() );
}
} );
_prototype.set( "sub" , _prototype.get( "replace" ) );
final JSObjectBase gsubOptions = new JSObjectBase();
gsubOptions.set( "all" , "asd" );
final Object gsubOptionsArray[] = new Object[]{ gsubOptions };
_prototype.set( "gsub" , new JSFunctionCalls2() {
public Object call( Scope s , Object o , Object repl , Object crap[] ){
return ((JSFunction)myPrototype.get( "replace" )).call( s , o , repl , gsubOptionsArray );
}
} );
_prototype.set( "valueOf" , new JSFunctionCalls0() {
public Object call( Scope s , Object crap[] ){
Object o = s.getThis();
if( o == myPrototype )
return new JSString( "" );
return new JSString( ((JSString)o).toString() );
}
} );
set("fromCharCode", new JSFunctionCalls0() {
public Object call(Scope s, Object [] args){
if(args == null) return new JSString("");
StringBuffer buf = new StringBuffer();
for(int i = 0; i < args.length; i++){
Object o = args[i];
if(! (o instanceof Number) )
throw new RuntimeException( "fromCharCode only takes numbers" );
Number n = (Number)o;
char c = (char)JSNumber.toUint16( o );
buf.append(c);
}
return new JSString( buf.toString() );
}
} );
set( "isUpper" , new JSFunctionCalls1(){
public Object call( Scope s , Object thing , Object args[] ){
String str = thing.toString();
for ( int i=0; i<str.length(); i++ ){
char c = str.charAt( i );
if ( Character.isLetter( c ) &&
Character.isUpperCase( c ) )
continue;
return false;
}
return true;
}
} );
_prototype.dontEnumExisting();
}
| protected void init(){
JS._debugSI( "JSString" , "JSStringCons init 0" );
final JSObject myPrototype = _prototype;
if ( ! JS.JNI ){
final StringEncrypter encrypter = new StringEncrypter( "knsd8712@!98sad" );
_prototype.set( "encrypt" , new JSFunctionCalls0(){
public Object call( Scope s , Object foo[] ){
synchronized ( encrypter ){
return new JSString( encrypter.encrypt( s.getThis().toString() ) );
}
}
} );
_prototype.set( "decrypt" , new JSFunctionCalls0(){
public Object call( Scope s , Object foo[] ){
synchronized ( encrypter ){
return new JSString( encrypter.decrypt( s.getThis().toString() ) );
}
}
} );
}
JS._debugSI( "JSString" , "JSStringCons init 1" );
_prototype.set( "trim" , new JSFunctionCalls0() {
public Object call( Scope s , Object foo[] ){
return new JSString( s.getThis().toString().trim() );
}
} );
_prototype.set( "md5" , new JSFunctionCalls0() {
public Object call( Scope s , Object extra[] ){
synchronized ( _myMd5 ){
_myMd5.Init();
_myMd5.Update( s.getThis().toString() );
return new JSString( _myMd5.asHex() );
}
}
private final MD5 _myMd5 = new MD5();
} );
_prototype.set( "to_sym" , new JSFunctionCalls0() {
public Object call( Scope s , Object extra[] ){
return s.getThis().toString();
}
private final MD5 _myMd5 = new MD5();
} );
_prototype.set( "toString" , new JSFunctionCalls0() {
public Object call( Scope s , Object extra[] ) {
Object o = s.getThis();
if( !( o instanceof JSString ) )
if ( o == myPrototype )
return new JSString( "" );
else
throw new JSException( "String.prototype.toString can only be called on Strings" );
return new JSString( ((JSString)o)._s );
}
} );
_prototype.set( "toLowerCase" , new JSFunctionCalls0() {
public Object call( Scope s , Object foo[] ){
return new JSString( s.getThis().toString().toLowerCase() );
}
} );
_prototype.set( "toUpperCase" , new JSFunctionCalls0() {
public Object call( Scope s , Object foo[] ){
return new JSString( s.getThis().toString().toUpperCase() );
}
} );
_prototype.set( "charCodeAt" , new JSFunctionCalls1() {
public Object call( Scope s , Object o , Object foo[] ){
String str = s.getThis().toString();
int idx = (int)JSNumber.getDouble( o );
if( idx >= str.length() || idx < 0 )
return Double.NaN;
return Integer.valueOf( str.charAt( idx ) );
}
} );
_prototype.set( "charAt" , new JSFunctionCalls1() {
public Object call( Scope s , Object o , Object foo[] ){
String str = s.getThis().toString();
int idx = (int)JSNumber.getDouble( o );
if ( idx >= str.length() || idx < 0 )
return EMPTY;
return new JSString( str.substring( idx , idx + 1 ) );
}
} );
_prototype.set( "indexOf" , new JSFunctionCalls1() {
public Object call( Scope s , Object o , Object foo[] ){
String str = s.getThis().toString();
if( o == null )
return -1;
String thing = o.toString();
int start = 0;
if ( foo != null && foo.length > 0 && foo[0] != null ) {
start = ((Number)foo[0]).intValue();
}
return str.indexOf( thing , start );
}
} );
_prototype.set( "contains" , new JSFunctionCalls1() {
public Object call( Scope s , Object o , Object foo[] ){
String str = s.getThis().toString();
String thing = o.toString();
return str.contains( thing );
}
} );
_prototype.set( "__rshift" , new JSFunctionCalls1() {
public Object call( Scope s , Object o , Object foo[] ){
JSString me = (JSString)(s.getThis());
String thing = o.toString();
me._s += thing;
return me;
}
} );
_prototype.set( "lastIndexOf" , new JSFunctionCalls1() {
public Object call( Scope s , Object o , Object foo[] ){
String str = s.getThis().toString();
String thing = o.toString();
int end = str.length();
if ( foo != null && foo.length > 0 )
end = ((Number)foo[0]).intValue();
return str.lastIndexOf( thing , end );
}
} );
_prototype.set( "startsWith" , new JSFunctionCalls1() {
public Object call( Scope s , Object o , Object foo[] ){
String str = s.getThis().toString();
String thing = o.toString();
return str.startsWith( thing );
}
} );
_prototype.set( "endsWith" , new JSFunctionCalls1() {
public Object call( Scope s , Object o , Object foo[] ){
String str = s.getThis().toString();
String thing = o.toString();
return str.endsWith( thing );
}
} );
_prototype.set( "substring" , new JSFunctionCalls2() {
public Object call( Scope s , Object startO , Object endO , Object foo[] ){
String str = s.getThis().toString();
int start = (int)JSNumber.getDouble( startO );
int end = endO == null ? str.length() : (int)JSNumber.getDouble( endO );
if ( start < 0 )
start = 0;
if ( start >= str.length() || start < 0 )
return EMPTY;
if ( end > str.length() )
end = str.length();
if ( end < 0 )
return new JSString( str.substring( start ) );
return new JSString( str.substring( start , end ) );
}
} );
_prototype.set( "substr" , new JSFunctionCalls2() {
public Object call( Scope s , Object startO , Object lengthO , Object foo[] ){
String str = s.getThis().toString();
int start = ((Number)startO).intValue();
if ( start < 0 )
start = 0;
if ( start >= str.length() || start < 0 )
return EMPTY;
int length = -1;
if ( lengthO != null && lengthO instanceof Number )
length = ((Number)lengthO).intValue();
if ( start + length > str.length() )
length = str.length() - start;
if ( length < 0 )
return new JSString( str.substring( start) );
return new JSString( str.substring( start , start + length ) );
}
} );
_prototype.set( "match" , new JSFunctionCalls1() {
public Object call( Scope s , Object o , Object foo[] ){
String str = s.getThis().toString();
if ( o instanceof String || o instanceof JSString )
o = new JSRegex( o.toString() , "" );
if ( ! ( o instanceof JSRegex ) )
throw new RuntimeException( "not a regex : " + o.getClass() );
JSRegex r = (JSRegex)o;
Matcher m = r._patt.matcher( str );
if ( ! m.find() )
return null;
if ( r.getFlags().contains( "g" )){
JSArray a = new JSArray();
do {
a.add(new JSString(m.group()));
} while(m.find());
return a;
}
else{
return r.exec(str);
}
}
} );
_prototype.set( "split" , new JSFunctionCalls2(){
public Object call( Scope s , Object o , Object limit, Object extra[] ){
String str = s.getThis().toString();
JSArray a = new JSArray();
if ( limit == null ) {
limit = Integer.MAX_VALUE;
}
else {
limit = StringParseUtil.parseStrict( limit.toString() );
if ( ((Number)limit).intValue() == 0 ) {
return a;
}
}
if ( o == null ) {
a.add( s.getThis() );
return a;
}
if ( o instanceof String || o instanceof JSString )
o = new JSRegex( JSRegex.quote( o.toString() ) , "" );
if ( ! ( o instanceof JSRegex ) )
throw new RuntimeException( "not a regex : " + o.getClass() );
JSRegex r = (JSRegex)o;
String spacer = null;
if ( r.getPattern().contains( "(" ) )
spacer = r.getPattern().replaceAll( "[()]" , "" );
for ( String pc : r._patt.split( str , -1 ) ){
if ( a.size() > 0 && spacer != null )
a.add( spacer );
a.add( new JSString( pc ) );
if ( a.size() >= ((Number)limit).intValue() )
break;
}
if ( r.getPattern().length() == 0 ){
a.remove( 0 );
if( a.size() > 0 ) {
a.remove( a.size() - 1 );
}
}
return a;
}
}
);
_prototype.set( "reverse" , new JSFunctionCalls0(){
public Object call(Scope s, Object [] args){
String str = s.getThis().toString();
StringBuffer buf = new StringBuffer( str.length() );
for ( int i=str.length()-1; i>=0; i--)
buf.append( str.charAt( i ) );
return new JSString( buf.toString() );
}
} );
_prototype.set("slice" , new JSFunctionCalls2(){
public Object call(Scope s, Object o1, Object o2, Object [] args){
String str = s.getThis().toString();
int start = 0;
if (o1 != null && o1 instanceof Number) {
start = ((Number)o1).intValue();
if (start < 0) {
start = str.length() + start; // add as it's negative
}
}
if ( start < 0 )
start = 0;
if (start >= str.length())
return EMPTY;
int end = str.length();
if (o2 != null && o2 instanceof Number) {
end = ((Number)o2).intValue();
if (end < 0) {
end = str.length() + end; // add as it's negative
if ( end < 0 )
end = 0;
}
if (end > str.length()) {
end = str.length();
}
if ( end < start )
end = start;
}
return new JSString(str.substring(start, end));
}
} );
_prototype.set( "pluralize" , new JSFunctionCalls0(){
public Object call(Scope s, Object [] args){
String str = s.getThis().toString();
return str + "s";
}
} );
_prototype.set( "_eq__t_" , _prototype.get( "match" ) );
_prototype.set( "__delete" , new JSFunctionCalls1(){
public Object call(Scope s, Object all , Object [] args){
String str = s.getThis().toString();
if ( all == null )
return str;
String bad = all.toString();
StringBuffer buf = new StringBuffer( str.length() );
outer:
for ( int i=0; i<str.length(); i++ ){
char c = str.charAt( i );
for ( int j=0; j<bad.length(); j++ )
if ( bad.charAt( j ) == c )
continue outer;
buf.append( c );
}
return new JSString( buf.toString() );
}
} );
_prototype.set( "_lb__rb_" , new JSFunctionCalls1(){
public Object call( Scope s , Object thing , Object args[] ){
JSString str = (JSString)s.getThis();
if ( thing instanceof Number ){
return (int)(str._s.charAt( ((Number)thing).intValue() ));
}
if ( thing instanceof JSArray ){
JSArray a = (JSArray)thing;
int start = ((Number)(a.get("start"))).intValue();
int end = ((Number)(a.get("end"))).intValue();
String sub = str._s.substring( start , end + 1 );
return new JSString( sub );
}
return null;
}
} );
_prototype.set( "each_byte" , new JSFunctionCalls1(){
public Object call(Scope s, Object funcObject , Object [] args){
if ( funcObject == null )
throw new NullPointerException( "each_byte needs a function" );
JSFunction func = (JSFunction)funcObject;
String str = s.getThis().toString();
for ( int i=0; i<str.length(); i++ ){
func.call( s , (int)str.charAt( i ) );
}
return null;
}
} );
_prototype.set( "replace" , new JSFunctionCalls2() {
public Object call( Scope s , Object o , Object repl , Object crap[] ){
String str = s.getThis().toString();
if ( o instanceof String || o instanceof JSString )
o = new JSRegex( JSRegex.quote( o.toString() ) , "" );
if ( ! ( o instanceof JSRegex ) )
throw new RuntimeException( "not a regex : " + o.getClass() );
JSRegex r = (JSRegex)o;
Matcher m = r._patt.matcher( str );
StringBuffer buf = null;
int start = 0;
final JSObject options = ( crap != null && crap.length > 0 && crap[0] instanceof JSObject ) ? (JSObject)crap[0] : null;
final boolean replaceAll = r._replaceAll || ( options != null && options.get( "all" ) != null );
Object replArgs[] = null;
while ( m.find() ){
if ( buf == null )
buf = new StringBuffer( str.length() );
buf.append( str.substring( start , m.start() ) );
if ( repl == null )
repl = "null";
if ( repl instanceof JSString || repl instanceof String){
String foo = repl.toString();
for ( int i=0; i<foo.length(); i++ ){
char c = foo.charAt( i );
if ( c != '$' ){
buf.append( c );
continue;
}
if ( i + 1 >= foo.length() ||
! Character.isDigit( foo.charAt( i + 1 ) ) ){
buf.append( c );
continue;
}
i++;
int end = i;
while ( end < foo.length() && Character.isDigit( foo.charAt( end ) ) )
end++;
int num = Integer.parseInt( foo.substring( i , end ) );
buf.append( m.group( num ) == null ? "" : m.group( num ) );
i = end - 1;
}
}
else if ( repl instanceof JSFunction ){
if ( replArgs == null )
replArgs = new Object[ m.groupCount() + 1 ];
for ( int i=0; i<replArgs.length; i++ )
replArgs[i] = new JSString( m.group( i ) );
buf.append( ((JSFunction)repl).call( s , replArgs ) );
}
else {
throw new RuntimeException( "can't use replace with : " + repl.getClass() );
}
start = m.end();
if ( ! replaceAll )
break;
}
if ( buf == null )
return new JSString( str );
buf.append( str.substring( start ) );
return new JSString( buf.toString() );
}
} );
_prototype.set( "sub" , _prototype.get( "replace" ) );
final JSObjectBase gsubOptions = new JSObjectBase();
gsubOptions.set( "all" , "asd" );
final Object gsubOptionsArray[] = new Object[]{ gsubOptions };
_prototype.set( "gsub" , new JSFunctionCalls2() {
public Object call( Scope s , Object o , Object repl , Object crap[] ){
return ((JSFunction)myPrototype.get( "replace" )).call( s , o , repl , gsubOptionsArray );
}
} );
_prototype.set( "valueOf" , new JSFunctionCalls0() {
public Object call( Scope s , Object crap[] ){
Object o = s.getThis();
if( o == myPrototype )
return new JSString( "" );
return new JSString( ((JSString)o).toString() );
}
} );
set("fromCharCode", new JSFunctionCalls0() {
public Object call(Scope s, Object [] args){
if(args == null) return new JSString("");
StringBuffer buf = new StringBuffer();
for(int i = 0; i < args.length; i++){
Object o = args[i];
if(! (o instanceof Number) )
throw new RuntimeException( "fromCharCode only takes numbers" );
Number n = (Number)o;
char c = (char)JSNumber.toUint16( o );
buf.append(c);
}
return new JSString( buf.toString() );
}
} );
set( "isUpper" , new JSFunctionCalls1(){
public Object call( Scope s , Object thing , Object args[] ){
String str = thing.toString();
for ( int i=0; i<str.length(); i++ ){
char c = str.charAt( i );
if ( Character.isLetter( c ) &&
Character.isUpperCase( c ) )
continue;
return false;
}
return true;
}
} );
_prototype.dontEnumExisting();
}
|
diff --git a/cadsrutil/src/java/gov/nih/nci/ncicb/cadsr/common/util/CDEBrowserParams.java b/cadsrutil/src/java/gov/nih/nci/ncicb/cadsr/common/util/CDEBrowserParams.java
index ff701ff..ce58b78 100644
--- a/cadsrutil/src/java/gov/nih/nci/ncicb/cadsr/common/util/CDEBrowserParams.java
+++ b/cadsrutil/src/java/gov/nih/nci/ncicb/cadsr/common/util/CDEBrowserParams.java
@@ -1,423 +1,423 @@
package gov.nih.nci.ncicb.cadsr.common.util;
import gov.nih.nci.ncicb.cadsr.common.servicelocator.ApplicationServiceLocator;
import gov.nih.nci.ncicb.cadsr.common.servicelocator.spring.ApplicationServiceLocatorImpl;
import gov.nih.nci.ncicb.cadsr.common.util.logging.Log;
import gov.nih.nci.ncicb.cadsr.common.util.logging.LogFactory;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Properties;
import java.util.ResourceBundle;
public class CDEBrowserParams
{
private static Log log = LogFactory.getLog(CDEBrowserParams.class.getName());
//This is used monitor application mode
public static String mode ="";
//TODO has to be moved to read from Spring Application Context
private static ApplicationServiceLocator appServiceLocator= new ApplicationServiceLocatorImpl();
//String sbrextDSN = "";
//String sbrDSN = "";
String xmlDownloadDir = "";
String xmlPaginationFlag = "no";
String xmlFileMaxRecord;
String treeURL = "";
String evsSources = "";
String showFormsAlphebetical ="no";
String excludeTestContext = "no";
String excludeTrainingContext="no";
String excludeWorkFlowStatuses = "";
String excludeRegistrationStatuses = "";
String curationToolUrl = "";
String nciMetathesaurusUrl="";
String nciTerminologyServerUrl="";
String sentinelToolUrl="";
String adminToolUrl="";
String umlBrowserUrl="";
String regStatusCsTree="";
String csTypeRegStatus="";
String csTypeContainer="container";
String sentinalAPIUrl="";
String formBuilderUrl="";
String cdeBrowserUrl="";
String contextTest = "";
String contextTraining = "";
Map evsUrlMap = new HashMap();
static CDEBrowserParams instance;
/**
* Read the resource bundle file
* propFilename - the specified resource file (fn.properties) without the extension
* (e.g., medsurv)
*/
private CDEBrowserParams()
{
}
public String getXMLDownloadDir(){
return xmlDownloadDir;
}
public static CDEBrowserParams getInstance(){
if (instance == null ) {
try
{
getDebugInstance();
log.debug("Using debug properties file");
mode="DEBUG MODE";
return instance;
}
catch (NoSuchElementException nse)
{
log.error("Cannot find property"+nse);
throw nse;
}
catch (Exception e)
{
}
Properties properties = appServiceLocator.findCDEBrowserService().getApplicationProperties(Locale.US);
instance = new CDEBrowserParams();
instance.initAttributesFromProperties(properties);
log.debug("Using database for properties");
}
return instance;
}
public static void reloadInstance(){
instance = null;
getInstance();
}
public static CDEBrowserParams getToolInstance(String toolName)
{
Properties properties = appServiceLocator.findCDEBrowserService().getApplicationProperties(Locale.US, toolName);
instance = new CDEBrowserParams();
instance.initAttributesFromProperties(properties);
return instance;
}
public static CDEBrowserParams getDebugInstance(){
if (instance == null ) {
ResourceBundle b = ResourceBundle.getBundle("cdebrowser", java.util.Locale.getDefault());
Properties properties = new Properties();
for (Enumeration e = b.getKeys() ; e.hasMoreElements() ;) {
String key = (String)e.nextElement();
if(key!=null)
{
log.debug(" Get CDEBrowser.property = "+ key );
properties.setProperty(key,b.getString(key));
}
}
instance = new CDEBrowserParams();
instance.initAttributesFromProperties(properties);
}
return instance;
}
public static void reloadInstance(String userName){
Properties properties = appServiceLocator.findCDEBrowserService().reloadApplicationProperties(Locale.US,userName);
instance = new CDEBrowserParams();
instance.initAttributesFromProperties(properties);
}
public String getTreeURL() {
return treeURL;
}
public String getXMLPaginationFlag(){
return xmlPaginationFlag;
}
public String getXMLFileMaxRecords() {
return xmlFileMaxRecord;
}
public void setEvsUrlMap(Map evsUrlMap)
{
this.evsUrlMap = evsUrlMap;
}
public void setEvsUrlMap(Properties bundle,String evsSourcesArr)
{
try
{
String[] urls = StringUtils.tokenizeCSVList(evsSourcesArr);
for(int i=0; i<urls.length;i++)
{
String key = urls[i];
String value = bundle.getProperty(key);
if(evsUrlMap==null)
evsUrlMap = new HashMap();
evsUrlMap.put(key,value);
}
}
catch (java.util.MissingResourceException mre)
{
log.error("Error getting init parameters, missing resource values");
log.error("EVS Url not mapped correctly");
log.error(mre.getMessage(), mre);
System.exit(-1);
}
catch (Exception e)
{
log.error("Exception occurred", e);
System.exit(-1);
}
}
public Map getEvsUrlMap()
{
return evsUrlMap;
}
public void setShowFormsAlphebetical(String showFormsAlphebetical)
{
this.showFormsAlphebetical = showFormsAlphebetical;
}
public String getShowFormsAlphebetical()
{
return showFormsAlphebetical;
}
public void setExcludeTestContext(String excludeTestContext)
{
this.excludeTestContext = excludeTestContext;
}
public String getExcludeTestContext()
{
return excludeTestContext;
}
public void setExcludeTrainingContext(String excludeTrainingContext)
{
this.excludeTrainingContext = excludeTrainingContext;
}
public String getExcludeTrainingContext()
{
return excludeTrainingContext;
}
public String getExcludeWorkFlowStatuses()
{
return excludeWorkFlowStatuses;
}
public void setExcludeWorkFlowStatuses(String excludeWorkFlowStatuses)
{
this.excludeWorkFlowStatuses = excludeWorkFlowStatuses;
}
public String getExcludeRegistrationStatuses()
{
return excludeRegistrationStatuses;
}
public void setExcludeRegistrationStatuses(String excludeRegistrationStatuses)
{
this.excludeRegistrationStatuses = excludeRegistrationStatuses;
}
public void setCurationToolUrl(String curationToolUrl)
{
this.curationToolUrl = curationToolUrl;
}
public String getCurationToolUrl()
{
return curationToolUrl;
}
public void setNciMetathesaurusUrl(String nciMetathesaurusUrl)
{
this.nciMetathesaurusUrl = nciMetathesaurusUrl;
}
public String getNciMetathesaurusUrl()
{
return nciMetathesaurusUrl;
}
public void setNciTerminologyServerUrl(String nciTerminologyServerUrl)
{
this.nciTerminologyServerUrl = nciTerminologyServerUrl;
}
public String getNciTerminologyServerUrl()
{
return nciTerminologyServerUrl;
}
public void setSentinelToolUrl(String sentinelToolUrl)
{
this.sentinelToolUrl = sentinelToolUrl;
}
public String getSentinelToolUrl()
{
return sentinelToolUrl;
}
public void setAdminToolUrl(String adminToolUrl)
{
this.adminToolUrl = adminToolUrl;
}
public String getAdminToolUrl()
{
return adminToolUrl;
}
private void initAttributesFromProperties(Properties properties)
{
// read the init parameters from the resource bundle
int index = 0;
try
{
xmlDownloadDir = properties.getProperty("XML_DOWNLOAD_DIR");
index++;
xmlPaginationFlag = properties.getProperty("XML_PAGINATION_FLAG");
index++;
xmlFileMaxRecord = properties.getProperty("XML_FILE_MAX_RECORDS");
index++;
treeURL = properties.getProperty("TREE_URL");
index++;
evsSources = properties.getProperty("EVS_URL_SOURCES");
index++;
setEvsUrlMap(properties,evsSources);
showFormsAlphebetical = properties.getProperty("SHOW_FORMS_ALPHEBETICAL");
index++;
excludeTestContext = properties.getProperty("EXCLUDE_TEST_CONTEXT_BY_DEFAULT");
index++;
excludeTrainingContext = properties.getProperty("EXCLUDE_TRAINING_CONTEXT_BY_DEFAULT");
index++;
excludeWorkFlowStatuses = properties.getProperty("EXCLUDE_WORKFLOW_BY_DEFAULT");
index++;
excludeRegistrationStatuses = properties.getProperty("EXCLUDE_REGISTRATION_BY_DEFAULT");
index++;
- adminToolUrl = properties.getProperty("ADMIN_TOOL_URL");
+ adminToolUrl = properties.getProperty("AdminTool_URL");
index++;
- curationToolUrl = properties.getProperty("CURATION_TOOL_URL");
+ curationToolUrl = properties.getProperty("CURATION_URL");
index++;
- nciMetathesaurusUrl = properties.getProperty("NCI_METATHESAURUS_URL");
+ nciMetathesaurusUrl = properties.getProperty("EVSBrowser_URL");
index++;
- nciTerminologyServerUrl = properties.getProperty("NCI_TERMINOLOGY_SERVER_URL");
+ nciTerminologyServerUrl = properties.getProperty("EVSBrowser_URL");
index++;
- sentinelToolUrl = properties.getProperty("SENTINEL_TOOL_URL");
+ sentinelToolUrl = properties.getProperty("SENTINEL_URL");
index++;
regStatusCsTree = properties.getProperty("CS_TYPE_REGISTRATION_STATUS");
index++;
csTypeRegStatus = properties.getProperty("REG_STATUS_CS_TREE");
index++;
csTypeContainer = properties.getProperty("CS_TYPE_CONTAINER");
index++;
- sentinalAPIUrl = properties.getProperty("SENTINAL_API_URL");
+ sentinalAPIUrl = properties.getProperty("SENTINAL_URL");
index++;
- umlBrowserUrl = properties.getProperty("UMLBROWSER_URL");
+ umlBrowserUrl = properties.getProperty("UMLBrowser_URL");
index++;
formBuilderUrl = properties.getProperty("FormBuilder_URL");
index++;
cdeBrowserUrl = properties.getProperty("CDEBrowser_URL");
index++;
contextTest = properties.getProperty("BROADCAST.EXCLUDE.CONTEXT.00.NAME");
index++;
contextTraining = properties.getProperty("BROADCAST.EXCLUDE.CONTEXT.01.NAME");
index++;
log.info("Loaded Properties"+properties);
}
catch (java.util.MissingResourceException mre)
{
log.error("Error getting init parameters, missing resource values");
log.error("Property missing index: " + index);
log.error(mre.getMessage(), mre);
}
catch (Exception e)
{
log.error("Exception occurred when loading properties", e);
}
}
public String getRegStatusCsTree() {
return regStatusCsTree;
}
public String getCsTypeRegStatus() {
return csTypeRegStatus;
}
public String getCsTypeContainer() {
return csTypeContainer;
}
public void setSentinalAPIUrl(String sentinalAPIUrl)
{
this.sentinalAPIUrl = sentinalAPIUrl;
}
public String getSentinalAPIUrl()
{
return sentinalAPIUrl;
}
public void setUmlBrowserUrl(String umlBrowserUrl) {
this.umlBrowserUrl = umlBrowserUrl;
}
public String getUmlBrowserUrl() {
return umlBrowserUrl;
}
public String getFormBuilderUrl() {
return formBuilderUrl;
}
public void setFormBuilderUrl(String formBuilderUrl) {
this.formBuilderUrl = formBuilderUrl;
}
public String getCdeBrowserUrl() {
return cdeBrowserUrl;
}
public void setCdeBrowserUrl(String cdeBrowserUrl) {
this.cdeBrowserUrl = cdeBrowserUrl;
}
public String getContextTest()
{
return contextTest;
}
public String getContextTraining()
{
return contextTraining;
}
}
| false | true | private void initAttributesFromProperties(Properties properties)
{
// read the init parameters from the resource bundle
int index = 0;
try
{
xmlDownloadDir = properties.getProperty("XML_DOWNLOAD_DIR");
index++;
xmlPaginationFlag = properties.getProperty("XML_PAGINATION_FLAG");
index++;
xmlFileMaxRecord = properties.getProperty("XML_FILE_MAX_RECORDS");
index++;
treeURL = properties.getProperty("TREE_URL");
index++;
evsSources = properties.getProperty("EVS_URL_SOURCES");
index++;
setEvsUrlMap(properties,evsSources);
showFormsAlphebetical = properties.getProperty("SHOW_FORMS_ALPHEBETICAL");
index++;
excludeTestContext = properties.getProperty("EXCLUDE_TEST_CONTEXT_BY_DEFAULT");
index++;
excludeTrainingContext = properties.getProperty("EXCLUDE_TRAINING_CONTEXT_BY_DEFAULT");
index++;
excludeWorkFlowStatuses = properties.getProperty("EXCLUDE_WORKFLOW_BY_DEFAULT");
index++;
excludeRegistrationStatuses = properties.getProperty("EXCLUDE_REGISTRATION_BY_DEFAULT");
index++;
adminToolUrl = properties.getProperty("ADMIN_TOOL_URL");
index++;
curationToolUrl = properties.getProperty("CURATION_TOOL_URL");
index++;
nciMetathesaurusUrl = properties.getProperty("NCI_METATHESAURUS_URL");
index++;
nciTerminologyServerUrl = properties.getProperty("NCI_TERMINOLOGY_SERVER_URL");
index++;
sentinelToolUrl = properties.getProperty("SENTINEL_TOOL_URL");
index++;
regStatusCsTree = properties.getProperty("CS_TYPE_REGISTRATION_STATUS");
index++;
csTypeRegStatus = properties.getProperty("REG_STATUS_CS_TREE");
index++;
csTypeContainer = properties.getProperty("CS_TYPE_CONTAINER");
index++;
sentinalAPIUrl = properties.getProperty("SENTINAL_API_URL");
index++;
umlBrowserUrl = properties.getProperty("UMLBROWSER_URL");
index++;
formBuilderUrl = properties.getProperty("FormBuilder_URL");
index++;
cdeBrowserUrl = properties.getProperty("CDEBrowser_URL");
index++;
contextTest = properties.getProperty("BROADCAST.EXCLUDE.CONTEXT.00.NAME");
index++;
contextTraining = properties.getProperty("BROADCAST.EXCLUDE.CONTEXT.01.NAME");
index++;
log.info("Loaded Properties"+properties);
}
catch (java.util.MissingResourceException mre)
{
log.error("Error getting init parameters, missing resource values");
log.error("Property missing index: " + index);
log.error(mre.getMessage(), mre);
}
catch (Exception e)
{
log.error("Exception occurred when loading properties", e);
}
}
| private void initAttributesFromProperties(Properties properties)
{
// read the init parameters from the resource bundle
int index = 0;
try
{
xmlDownloadDir = properties.getProperty("XML_DOWNLOAD_DIR");
index++;
xmlPaginationFlag = properties.getProperty("XML_PAGINATION_FLAG");
index++;
xmlFileMaxRecord = properties.getProperty("XML_FILE_MAX_RECORDS");
index++;
treeURL = properties.getProperty("TREE_URL");
index++;
evsSources = properties.getProperty("EVS_URL_SOURCES");
index++;
setEvsUrlMap(properties,evsSources);
showFormsAlphebetical = properties.getProperty("SHOW_FORMS_ALPHEBETICAL");
index++;
excludeTestContext = properties.getProperty("EXCLUDE_TEST_CONTEXT_BY_DEFAULT");
index++;
excludeTrainingContext = properties.getProperty("EXCLUDE_TRAINING_CONTEXT_BY_DEFAULT");
index++;
excludeWorkFlowStatuses = properties.getProperty("EXCLUDE_WORKFLOW_BY_DEFAULT");
index++;
excludeRegistrationStatuses = properties.getProperty("EXCLUDE_REGISTRATION_BY_DEFAULT");
index++;
adminToolUrl = properties.getProperty("AdminTool_URL");
index++;
curationToolUrl = properties.getProperty("CURATION_URL");
index++;
nciMetathesaurusUrl = properties.getProperty("EVSBrowser_URL");
index++;
nciTerminologyServerUrl = properties.getProperty("EVSBrowser_URL");
index++;
sentinelToolUrl = properties.getProperty("SENTINEL_URL");
index++;
regStatusCsTree = properties.getProperty("CS_TYPE_REGISTRATION_STATUS");
index++;
csTypeRegStatus = properties.getProperty("REG_STATUS_CS_TREE");
index++;
csTypeContainer = properties.getProperty("CS_TYPE_CONTAINER");
index++;
sentinalAPIUrl = properties.getProperty("SENTINAL_URL");
index++;
umlBrowserUrl = properties.getProperty("UMLBrowser_URL");
index++;
formBuilderUrl = properties.getProperty("FormBuilder_URL");
index++;
cdeBrowserUrl = properties.getProperty("CDEBrowser_URL");
index++;
contextTest = properties.getProperty("BROADCAST.EXCLUDE.CONTEXT.00.NAME");
index++;
contextTraining = properties.getProperty("BROADCAST.EXCLUDE.CONTEXT.01.NAME");
index++;
log.info("Loaded Properties"+properties);
}
catch (java.util.MissingResourceException mre)
{
log.error("Error getting init parameters, missing resource values");
log.error("Property missing index: " + index);
log.error(mre.getMessage(), mre);
}
catch (Exception e)
{
log.error("Exception occurred when loading properties", e);
}
}
|
diff --git a/src/com/aetrion/flickr/photos/PhotosInterface.java b/src/com/aetrion/flickr/photos/PhotosInterface.java
index d36658d..f9916d4 100644
--- a/src/com/aetrion/flickr/photos/PhotosInterface.java
+++ b/src/com/aetrion/flickr/photos/PhotosInterface.java
@@ -1,1284 +1,1285 @@
/*
* Copyright (c) 2005 Aetrion LLC.
*/
package com.aetrion.flickr.photos;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import com.aetrion.flickr.FlickrException;
import com.aetrion.flickr.Parameter;
import com.aetrion.flickr.RequestContext;
import com.aetrion.flickr.Response;
import com.aetrion.flickr.Transport;
import com.aetrion.flickr.people.User;
import com.aetrion.flickr.photos.geo.GeoInterface;
import com.aetrion.flickr.tags.Tag;
import com.aetrion.flickr.util.StringUtilities;
import com.aetrion.flickr.util.XMLUtilities;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
import org.xml.sax.SAXException;
/**
* @author Anthony Eden
*/
public class PhotosInterface {
public static final String METHOD_ADD_TAGS = "flickr.photos.addTags";
public static final String METHOD_DELETE = "flickr.photos.delete";
public static final String METHOD_GET_ALL_CONTEXTS = "flickr.photos.getAllContexts";
public static final String METHOD_GET_CONTACTS_PHOTOS = "flickr.photos.getContactsPhotos";
public static final String METHOD_GET_CONTACTS_PUBLIC_PHOTOS = "flickr.photos.getContactsPublicPhotos";
public static final String METHOD_GET_CONTEXT = "flickr.photos.getContext";
public static final String METHOD_GET_COUNTS = "flickr.photos.getCounts";
public static final String METHOD_GET_EXIF = "flickr.photos.getExif";
public static final String METHOD_GET_INFO = "flickr.photos.getInfo";
public static final String METHOD_GET_NOT_IN_SET = "flickr.photos.getNotInSet";
public static final String METHOD_GET_PERMS = "flickr.photos.getPerms";
public static final String METHOD_GET_RECENT = "flickr.photos.getRecent";
public static final String METHOD_GET_SIZES = "flickr.photos.getSizes";
public static final String METHOD_GET_UNTAGGED = "flickr.photos.getUntagged";
public static final String METHOD_GET_WITH_GEO_DATA = "flickr.photos.getWithGeoData";
public static final String METHOD_GET_WITHOUT_GEO_DATA = "flickr.photos.getWithoutGeoData";
public static final String METHOD_RECENTLY_UPLOADED ="flickr.photos.recentlyUpdated";
public static final String METHOD_REMOVE_TAG = "flickr.photos.removeTag";
public static final String METHOD_SEARCH = "flickr.photos.search";
public static final String METHOD_SET_DATES = "flickr.photos.setDates";
public static final String METHOD_SET_META = "flickr.photos.setMeta";
public static final String METHOD_SET_PERMS = "flickr.photos.setPerms";
public static final String METHOD_SET_TAGS = "flickr.photos.setTags";
public static final String METHOD_GET_INTERESTINGNESS = "flickr.interestingness.getList";
private static final DateFormat DF = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private GeoInterface geoInterface = null;
private String apiKey;
private Transport transport;
public PhotosInterface(String apiKey, Transport transport) {
this.apiKey = apiKey;
this.transport = transport;
}
/**
* Get the geo interface.
* @return Access class to the flickr.photos.geo methods.
*/
public synchronized GeoInterface getGeoInterface() {
if (geoInterface == null) {
geoInterface = new GeoInterface(apiKey, transport);
}
return geoInterface;
}
/**
* Delete a photo from flickr.
* This method requires authentication with 'delete' permission.
* @param photoId
* @throws SAXException
* @throws IOException
* @throws FlickrException
*/
public void delete(String photoId) throws IOException, SAXException, FlickrException {
List parameters = new ArrayList();
parameters.add(new Parameter("method", METHOD_DELETE));
parameters.add(new Parameter("api_key", apiKey));
parameters.add(new Parameter("photo_id", photoId));
// Note: This method requires an HTTP POST request.
Response response = transport.post(transport.getPath(), parameters);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
// This method has no specific response - It returns an empty
// sucess response if it completes without error.
}
/**
* Returns all visble sets and pools the photo belongs to.
* This method does not require authentication.
* @param photoId The photo to return information for.
* @return a list of {@link PhotoPlace} objects
* @throws IOException
* @throws SAXException
* @throws FlickrException
*/
public List getAllContexts(String photoId) throws IOException, SAXException, FlickrException {
List list = new ArrayList();
List parameters = new ArrayList();
parameters.add(new Parameter("method", METHOD_GET_ALL_CONTEXTS));
parameters.add(new Parameter("api_key", apiKey));
parameters.add(new Parameter("photo_id", photoId));
Response response = transport.get(transport.getPath(), parameters);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
Collection coll = response.getPayloadCollection();
Iterator it = coll.iterator();
while (it.hasNext()) {
Element el = (Element)it.next();
String id = el.getAttribute("id");
String title = el.getAttribute("title");
String kind = el.getTagName();
list.add(new PhotoPlace(kind, id, title));
}
return list;
}
/**
* Add tags to a photo.
*
* @param photoId The photo ID
* @param tags The tags
* @throws IOException
* @throws SAXException
* @throws FlickrException
*/
public void addTags(String photoId, String[] tags) throws IOException, SAXException, FlickrException {
List parameters = new ArrayList();
parameters.add(new Parameter("method", METHOD_ADD_TAGS));
parameters.add(new Parameter("api_key", apiKey));
parameters.add(new Parameter("photo_id", photoId));
parameters.add(new Parameter("tags", StringUtilities.join(tags, " ", true)));
Response response = transport.post(transport.getPath(), parameters);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
}
/**
* Get photos from the user's contacts.
*
* @param count The number of photos to return
* @param justFriends Set to true to only show friends photos
* @param singlePhoto Set to true to get a single photo
* @param includeSelf Set to true to include self
* @return The Collection of photos
* @throws IOException
* @throws SAXException
* @throws FlickrException
*/
public PhotoList getContactsPhotos(int count, boolean justFriends, boolean singlePhoto, boolean includeSelf)
throws IOException, SAXException, FlickrException {
PhotoList photos = new PhotoList();
List parameters = new ArrayList();
parameters.add(new Parameter("method", METHOD_GET_CONTACTS_PHOTOS));
parameters.add(new Parameter("api_key", apiKey));
if (count > 0) {
parameters.add(new Parameter("count", new Integer(count)));
}
if (justFriends) {
parameters.add(new Parameter("just_friends", "1"));
}
if (singlePhoto) {
parameters.add(new Parameter("single_photo", "1"));
}
if (includeSelf) {
parameters.add(new Parameter("include_self", "1"));
}
Response response = transport.get(transport.getPath(), parameters);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
Element photosElement = response.getPayload();
photos.setPage(photosElement.getAttribute("page"));
photos.setPages(photosElement.getAttribute("pages"));
photos.setPerPage(photosElement.getAttribute("perpage"));
photos.setTotal(photosElement.getAttribute("total"));
NodeList photoNodes = photosElement.getElementsByTagName("photo");
for (int i = 0; i < photoNodes.getLength(); i++) {
Element photoElement = (Element) photoNodes.item(i);
Photo photo = new Photo();
photo.setId(photoElement.getAttribute("id"));
User owner = new User();
owner.setId(photoElement.getAttribute("owner"));
owner.setUsername(photoElement.getAttribute("username"));
photo.setOwner(owner);
photo.setSecret(photoElement.getAttribute("secret"));
photo.setServer(photoElement.getAttribute("server"));
photo.setFarm(photoElement.getAttribute("farm"));
photo.setTitle(photoElement.getAttribute("title"));
photo.setPublicFlag("1".equals(photoElement.getAttribute("ispublic")));
photo.setFriendFlag("1".equals(photoElement.getAttribute("isfriend")));
photo.setFamilyFlag("1".equals(photoElement.getAttribute("isfamily")));
photos.add(photo);
}
return photos;
}
/**
* Get public photos from the user's contacts.
*
* @param userId The user ID
* @param count The number of photos to return
* @param justFriends True to include friends
* @param singlePhoto True to get a single photo
* @param includeSelf True to include self
* @return A collection of Photo objects
* @throws IOException
* @throws SAXException
* @throws FlickrException
*/
public PhotoList getContactsPublicPhotos(String userId, int count, boolean justFriends, boolean singlePhoto, boolean includeSelf)
throws IOException, SAXException, FlickrException {
PhotoList photos = new PhotoList();
List parameters = new ArrayList();
parameters.add(new Parameter("method", METHOD_GET_CONTACTS_PUBLIC_PHOTOS));
parameters.add(new Parameter("api_key", apiKey));
parameters.add(new Parameter("user_id", userId));
if (count > 0) {
parameters.add(new Parameter("count", new Integer(count)));
}
if (justFriends) {
parameters.add(new Parameter("just_friends", "1"));
}
if (singlePhoto) {
parameters.add(new Parameter("single_photo", "1"));
}
if (includeSelf) {
parameters.add(new Parameter("include_self", "1"));
}
Response response = transport.get(transport.getPath(), parameters);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
Element photosElement = response.getPayload();
photos.setPage(photosElement.getAttribute("page"));
photos.setPages(photosElement.getAttribute("pages"));
photos.setPerPage(photosElement.getAttribute("perpage"));
photos.setTotal(photosElement.getAttribute("total"));
NodeList photoNodes = photosElement.getElementsByTagName("photo");
for (int i = 0; i < photoNodes.getLength(); i++) {
Element photoElement = (Element) photoNodes.item(i);
Photo photo = new Photo();
photo.setId(photoElement.getAttribute("id"));
User owner = new User();
owner.setId(photoElement.getAttribute("owner"));
owner.setUsername(photoElement.getAttribute("username"));
photo.setOwner(owner);
photo.setSecret(photoElement.getAttribute("secret"));
photo.setServer(photoElement.getAttribute("server"));
photo.setFarm(photoElement.getAttribute("farm"));
photo.setTitle(photoElement.getAttribute("name"));
photos.add(photo);
}
return photos;
}
/**
* Get the context for the specified photo.
*
* @param photoId The photo ID
* @return The PhotoContext
* @throws IOException
* @throws SAXException
* @throws FlickrException
*/
public PhotoContext getContext(String photoId) throws IOException, SAXException, FlickrException {
List parameters = new ArrayList();
parameters.add(new Parameter("method", METHOD_GET_CONTEXT));
parameters.add(new Parameter("api_key", apiKey));
parameters.add(new Parameter("photo_id", photoId));
Response response = transport.get(transport.getPath(), parameters);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
PhotoContext photoContext = new PhotoContext();
Collection payload = response.getPayloadCollection();
Iterator iter = payload.iterator();
while (iter.hasNext()) {
Element payloadElement = (Element) iter.next();
String tagName = payloadElement.getTagName();
if (tagName.equals("prevphoto")) {
Photo photo = new Photo();
photo.setId(payloadElement.getAttribute("id"));
photo.setSecret(payloadElement.getAttribute("secret"));
photo.setTitle(payloadElement.getAttribute("title"));
photo.setFarm(payloadElement.getAttribute("farm"));
photo.setUrl(payloadElement.getAttribute("url"));
photoContext.setPreviousPhoto(photo);
} else if (tagName.equals("nextphoto")) {
Photo photo = new Photo();
photo.setId(payloadElement.getAttribute("id"));
photo.setSecret(payloadElement.getAttribute("secret"));
photo.setTitle(payloadElement.getAttribute("title"));
photo.setFarm(payloadElement.getAttribute("farm"));
photo.setUrl(payloadElement.getAttribute("url"));
photoContext.setNextPhoto(photo);
}
}
return photoContext;
}
/**
* Gets a collection of photo counts for the given date ranges for the calling user.
*
* @param dates An array of dates, denoting the periods to return counts for. They should be specified smallest
* first.
* @param takenDates An array of dates, denoting the periods to return counts for. They should be specified smallest
* first.
* @return A Collection of Photocount objects
*/
public Collection getCounts(Date[] dates, Date[] takenDates) throws IOException, SAXException,
FlickrException {
List photocounts = new ArrayList();
List parameters = new ArrayList();
parameters.add(new Parameter("method", METHOD_GET_COUNTS));
parameters.add(new Parameter("api_key", apiKey));
if (dates == null && takenDates == null) {
throw new IllegalArgumentException("You must provide a value for either dates or takenDates");
}
if (dates != null) {
List dateList = new ArrayList();
for (int i = 0; i < dates.length; i++) {
dateList.add(dates[i]);
}
parameters.add(new Parameter("dates", StringUtilities.join(dateList, ",")));
}
if (takenDates != null) {
List dateList = new ArrayList();
for (int i = 0; i < dates.length; i++) {
dateList.add(dates[i]);
}
parameters.add(new Parameter("taken_dates", StringUtilities.join(dateList, ",")));
}
Response response = transport.get(transport.getPath(), parameters);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
Element photocountsElement = response.getPayload();
NodeList photocountNodes = photocountsElement.getElementsByTagName("photocount");
for (int i = 0; i < photocountNodes.getLength(); i++) {
Element photocountElement = (Element) photocountNodes.item(i);
Photocount photocount = new Photocount();
photocount.setCount(photocountElement.getAttribute("count"));
photocount.setFromDate(photocountElement.getAttribute("fromdate"));
photocount.setToDate(photocountElement.getAttribute("todate"));
photocounts.add(photocount);
}
return photocounts;
}
/**
* Get the Exif data for the photo.
*
* @param photoId The photo ID
* @param secret The secret
* @return A collection of Exif objects
* @throws IOException
* @throws SAXException
* @throws FlickrException
*/
public Collection getExif(String photoId, String secret) throws IOException, SAXException, FlickrException {
List parameters = new ArrayList();
parameters.add(new Parameter("method", METHOD_GET_EXIF));
parameters.add(new Parameter("api_key", apiKey));
parameters.add(new Parameter("photo_id", photoId));
if (secret != null) {
parameters.add(new Parameter("secret", secret));
}
Response response = transport.get(transport.getPath(), parameters);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
List exifs = new ArrayList();
Element photoElement = response.getPayload();
NodeList exifElements = photoElement.getElementsByTagName("exif");
for (int i = 0; i < exifElements.getLength(); i++) {
Element exifElement = (Element) exifElements.item(i);
Exif exif = new Exif();
exif.setTagspace(exifElement.getAttribute("tagspace"));
exif.setTagspaceId(exifElement.getAttribute("tagspaceid"));
exif.setTag(exifElement.getAttribute("tag"));
exif.setLabel(exifElement.getAttribute("label"));
exif.setRaw(XMLUtilities.getChildValue(exifElement, "raw"));
exif.setClean(XMLUtilities.getChildValue(exifElement, "clean"));
exifs.add(exif);
}
return exifs;
}
/**
* Get all info for the specified photo.
*
* @param photoId The photo Id
* @param secret The optional secret String
* @return The Photo
* @throws IOException
* @throws SAXException
* @throws FlickrException
*/
public Photo getInfo(String photoId, String secret) throws IOException, SAXException, FlickrException {
List parameters = new ArrayList();
parameters.add(new Parameter("method", METHOD_GET_INFO));
parameters.add(new Parameter("api_key", apiKey));
parameters.add(new Parameter("photo_id", photoId));
if (secret != null) {
parameters.add(new Parameter("secret", secret));
}
Response response = transport.get(transport.getPath(), parameters);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
Element photoElement = (Element)response.getPayload();
Photo photo = new Photo();
photo.setId(photoElement.getAttribute("id"));
photo.setSecret(photoElement.getAttribute("secret"));
photo.setServer(photoElement.getAttribute("server"));
photo.setFarm(photoElement.getAttribute("farm"));
photo.setFavorite("1".equals(photoElement.getAttribute("isfavorite")));
photo.setLicense(photoElement.getAttribute("license"));
Element ownerElement = (Element) photoElement.getElementsByTagName("owner").item(0);
User owner = new User();
owner.setId(ownerElement.getAttribute("nsid"));
owner.setUsername(ownerElement.getAttribute("username"));
owner.setRealName(ownerElement.getAttribute("realname"));
owner.setLocation(ownerElement.getAttribute("location"));
photo.setOwner(owner);
photo.setTitle(XMLUtilities.getChildValue(photoElement, "title"));
photo.setDescription(XMLUtilities.getChildValue(photoElement, "description"));
Element visibilityElement = (Element) photoElement.getElementsByTagName("visibility").item(0);
photo.setPublicFlag("1".equals(visibilityElement.getAttribute("ispublic")));
photo.setFriendFlag("1".equals(visibilityElement.getAttribute("isfriend")));
photo.setFamilyFlag("1".equals(visibilityElement.getAttribute("isfamily")));
Element datesElement = XMLUtilities.getChild(photoElement, "dates");
photo.setDatePosted(datesElement.getAttribute("posted"));
photo.setDateTaken(datesElement.getAttribute("taken"));
photo.setTakenGranularity(datesElement.getAttribute("takengranularity"));
NodeList permissionsNodes = photoElement.getElementsByTagName("permissions");
if (permissionsNodes.getLength() > 0) {
Element permissionsElement = (Element) permissionsNodes.item(0);
Permissions permissions = new Permissions();
permissions.setComment(permissionsElement.getAttribute("permcomment"));
permissions.setAddmeta(permissionsElement.getAttribute("permaddmeta"));
}
Element editabilityElement = (Element) photoElement.getElementsByTagName("editability").item(0);
Editability editability = new Editability();
editability.setComment("1".equals(editabilityElement.getAttribute("cancomment")));
editability.setAddmeta("1".equals(editabilityElement.getAttribute("canaddmeta")));
Element commentsElement = (Element) photoElement.getElementsByTagName("comments").item(0);
photo.setComments(((Text) commentsElement.getFirstChild()).getData());
Element notesElement = (Element) photoElement.getElementsByTagName("notes").item(0);
List notes = new ArrayList();
NodeList noteNodes = notesElement.getElementsByTagName("note");
for (int i = 0; i < noteNodes.getLength(); i++) {
Element noteElement = (Element) noteNodes.item(i);
Note note = new Note();
note.setId(noteElement.getAttribute("id"));
note.setAuthor(noteElement.getAttribute("author"));
note.setAuthorName(noteElement.getAttribute("authorname"));
note.setBounds(noteElement.getAttribute("x"), noteElement.getAttribute("y"),
- noteElement.getAttribute("w"), noteElement.getAttribute("h"));
+ noteElement.getAttribute("w"), noteElement.getAttribute("h"));
+ note.setText(noteElement.getTextContent());
notes.add(note);
}
photo.setNotes(notes);
Element tagsElement = (Element) photoElement.getElementsByTagName("tags").item(0);
List tags = new ArrayList();
NodeList tagNodes = tagsElement.getElementsByTagName("tag");
for (int i = 0; i < tagNodes.getLength(); i++) {
Element tagElement = (Element) tagNodes.item(i);
Tag tag = new Tag();
tag.setId(tagElement.getAttribute("id"));
tag.setAuthor(tagElement.getAttribute("author"));
tag.setRaw(tagElement.getAttribute("raw"));
tag.setValue(((Text) tagElement.getFirstChild()).getData());
tags.add(tag);
}
photo.setTags(tags);
Element urlsElement = (Element) photoElement.getElementsByTagName("urls").item(0);
List urls = new ArrayList();
NodeList urlNodes = urlsElement.getElementsByTagName("url");
for (int i = 0; i < urlNodes.getLength(); i++) {
Element urlElement = (Element) urlNodes.item(i);
PhotoUrl photoUrl = new PhotoUrl();
photoUrl.setType(urlElement.getAttribute("type"));
photoUrl.setUrl(XMLUtilities.getValue(urlElement));
if (photoUrl.getType().equals("photopage")) {
photo.setUrl(photoUrl.getUrl());
}
}
photo.setUrls(urls);
return photo;
}
/**
* Return a collection of Photo objects not in part of any sets.
*
* @param perPage The per page
* @param page The page
* @return The collection of Photo objects
* @throws IOException
* @throws SAXException
* @throws FlickrException
*/
public PhotoList getNotInSet(int perPage, int page) throws IOException, SAXException, FlickrException {
PhotoList photos = new PhotoList();
List parameters = new ArrayList();
parameters.add(new Parameter("method", PhotosInterface.METHOD_GET_NOT_IN_SET));
parameters.add(new Parameter("api_key", apiKey));
RequestContext requestContext = RequestContext.getRequestContext();
List extras = requestContext.getExtras();
if (extras.size() > 0) {
parameters.add(new Parameter("extras", StringUtilities.join(extras, ",")));
}
if (perPage > 0) {
parameters.add(new Parameter("per_page", new Integer(perPage)));
}
if (page > 0) {
parameters.add(new Parameter("page", new Integer(page)));
}
Response response = transport.get(transport.getPath(), parameters);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
Element photosElement = response.getPayload();
photos.setPage(photosElement.getAttribute("page"));
photos.setPages(photosElement.getAttribute("pages"));
photos.setPerPage(photosElement.getAttribute("perpage"));
photos.setTotal(photosElement.getAttribute("total"));
NodeList photoElements = photosElement.getElementsByTagName("photo");
for (int i = 0; i < photoElements.getLength(); i++) {
Element photoElement = (Element) photoElements.item(i);
Photo photo = new Photo();
photo.setId(photoElement.getAttribute("id"));
photo.setSecret(photoElement.getAttribute("secret"));
photo.setServer(photoElement.getAttribute("server"));
photo.setFarm(photoElement.getAttribute("farm"));
photo.setTitle(photoElement.getAttribute("title"));
photo.setPublicFlag("1".equals(photoElement.getAttribute("ispublic")));
photo.setFriendFlag("1".equals(photoElement.getAttribute("isfriend")));
photo.setFamilyFlag("1".equals(photoElement.getAttribute("isfamily")));
User user = new User();
user.setId(photoElement.getAttribute("owner"));
photo.setOwner(user);
photos.add(photo);
}
return photos;
}
/**
* Get the permission information for the specified photo.
*
* @param photoId The photo id
* @return The Permissions object
* @throws IOException
* @throws SAXException
* @throws FlickrException
*/
public Permissions getPerms(String photoId) throws IOException, SAXException, FlickrException {
List parameters = new ArrayList();
parameters.add(new Parameter("method", METHOD_GET_PERMS));
parameters.add(new Parameter("api_key", apiKey));
parameters.add(new Parameter("photo_id", photoId));
Response response = transport.get(transport.getPath(), parameters);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
Element permissionsElement = response.getPayload();
Permissions permissions = new Permissions();
permissions.setId(permissionsElement.getAttribute("id"));
permissions.setPublicFlag("1".equals(permissionsElement.getAttribute("ispublic")));
permissions.setFamilyFlag("1".equals(permissionsElement.getAttribute("isfamily")));
permissions.setComment(permissionsElement.getAttribute("permcomment"));
permissions.setAddmeta(permissionsElement.getAttribute("permaddmeta"));
return permissions;
}
/**
* Get a collection of recent photos.
*
* @param perPage The number of photos per page
* @param page The page offset
* @return A collection of Photo objects
* @throws IOException
* @throws SAXException
* @throws FlickrException
*/
public PhotoList getRecent(int perPage, int page) throws IOException, SAXException, FlickrException {
PhotoList photos = new PhotoList();
List parameters = new ArrayList();
parameters.add(new Parameter("method", METHOD_GET_RECENT));
parameters.add(new Parameter("api_key", apiKey));
if (perPage > 0) {
parameters.add(new Parameter("per_page", new Integer(perPage)));
}
if (page > 0) {
parameters.add(new Parameter("page", new Integer(page)));
}
Response response = transport.get(transport.getPath(), parameters);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
Element photosElement = response.getPayload();
photos.setPage(photosElement.getAttribute("page"));
photos.setPages(photosElement.getAttribute("pages"));
photos.setPerPage(photosElement.getAttribute("perpage"));
photos.setTotal(photosElement.getAttribute("total"));
NodeList photoNodes = photosElement.getElementsByTagName("photo");
for (int i = 0; i < photoNodes.getLength(); i++) {
Element photoElement = (Element) photoNodes.item(i);
Photo photo = new Photo();
photo.setId(photoElement.getAttribute("id"));
User owner = new User();
owner.setId(photoElement.getAttribute("owner"));
photo.setOwner(owner);
photo.setSecret(photoElement.getAttribute("secret"));
photo.setServer(photoElement.getAttribute("server"));
photo.setFarm(photoElement.getAttribute("farm"));
photo.setTitle(photoElement.getAttribute("name"));
photo.setPublicFlag("1".equals(photoElement.getAttribute("ispublic")));
photo.setFriendFlag("1".equals(photoElement.getAttribute("isfriend")));
photo.setFamilyFlag("1".equals(photoElement.getAttribute("isfamily")));
photos.add(photo);
}
return photos;
}
/**
* Get the available sizes for sizes.
*
* @param photoId The photo ID
* @return The size collection
* @throws IOException
* @throws SAXException
* @throws FlickrException
*/
public Collection getSizes(String photoId) throws IOException, SAXException, FlickrException {
List sizes = new ArrayList();
List parameters = new ArrayList();
parameters.add(new Parameter("method", METHOD_GET_SIZES));
parameters.add(new Parameter("api_key", apiKey));
parameters.add(new Parameter("photo_id", photoId));
Response response = transport.get(transport.getPath(), parameters);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
Element sizesElement = response.getPayload();
NodeList sizeNodes = sizesElement.getElementsByTagName("size");
for (int i = 0; i < sizeNodes.getLength(); i++) {
Element sizeElement = (Element) sizeNodes.item(i);
Size size = new Size();
size.setLabel(sizeElement.getAttribute("label"));
size.setWidth(sizeElement.getAttribute("width"));
size.setHeight(sizeElement.getAttribute("height"));
size.setSource(sizeElement.getAttribute("source"));
size.setUrl(sizeElement.getAttribute("url"));
sizes.add(size);
}
return sizes;
}
/**
* Get the collection of untagged photos.
*
* @param perPage
* @param page
* @return A Collection of Photos
* @throws IOException
* @throws SAXException
* @throws FlickrException
*/
public PhotoList getUntagged(int perPage, int page) throws IOException, SAXException,
FlickrException {
PhotoList photos = new PhotoList();
List parameters = new ArrayList();
parameters.add(new Parameter("method", METHOD_GET_UNTAGGED));
parameters.add(new Parameter("api_key", apiKey));
if (perPage > 0) {
parameters.add(new Parameter("per_page", new Integer(perPage)));
}
if (page > 0) {
parameters.add(new Parameter("page", new Integer(page)));
}
Response response = transport.get(transport.getPath(), parameters);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
Element photosElement = response.getPayload();
photos.setPage(photosElement.getAttribute("page"));
photos.setPages(photosElement.getAttribute("pages"));
photos.setPerPage(photosElement.getAttribute("perpage"));
photos.setTotal(photosElement.getAttribute("total"));
NodeList photoNodes = photosElement.getElementsByTagName("photo");
for (int i = 0; i < photoNodes.getLength(); i++) {
Element photoElement = (Element) photoNodes.item(i);
Photo photo = new Photo();
photo.setId(photoElement.getAttribute("id"));
User owner = new User();
owner.setId(photoElement.getAttribute("owner"));
photo.setOwner(owner);
photo.setSecret(photoElement.getAttribute("secret"));
photo.setServer(photoElement.getAttribute("server"));
photo.setFarm(photoElement.getAttribute("farm"));
photo.setTitle(photoElement.getAttribute("title"));
photo.setPublicFlag("1".equals(photoElement.getAttribute("ispublic")));
photo.setFriendFlag("1".equals(photoElement.getAttribute("isfriend")));
photo.setFamilyFlag("1".equals(photoElement.getAttribute("isfamily")));
photos.add(photo);
}
return photos;
}
/**
* Returns a list of your geo-tagged photos.
* This method requires authentication with 'read' permission.
* @param minUploadDate Minimum upload date. Photos with an upload date greater than or equal to this value will be returned. Set to null to not specify a date.
* @param maxUploadDate Maximum upload date. Photos with an upload date less than or equal to this value will be returned. Set to null to not specify a date.
* @param minTakenDate Minimum taken date. Photos with an taken date greater than or equal to this value will be returned. Set to null to not specify a date.
* @param maxTakenDate Maximum taken date. Photos with an taken date less than or equal to this value will be returned. Set to null to not specify a date.
* @param privacyFilter Return photos only matching a certain privacy level. Valid values are:
* <ul>
* <li>1 public photos</li>
* <li>2 private photos visible to friends</li>
* <li>3 private photos visible to family</li>
* <li>4 private photos visible to friends & family</li>
* <li>5 completely private photos</li>
* </ul>
* Set to 0 to not specify a privacy Filter.
* @param sort The order in which to sort returned photos. Deafults to date-posted-desc. The possible values are: date-posted-asc, date-posted-desc, date-taken-asc, date-taken-desc, interestingness-desc, and interestingness-asc.
* @param extras A set of Strings controlling the extra information to fetch for each returned record. Currently supported fields are: license, date_upload, date_taken, owner_name, icon_server, original_format, last_update, geo. Set to null or an empty set to not specify any extras.
* @param perPage Number of photos to return per page. If this argument is 0, it defaults to 100. The maximum allowed value is 500.
* @param page The page of results to return. If this argument is 0, it defaults to 1.
* @return
* @throws FlickrException
* @throws IOException
* @throws SAXException
*/
public PhotoList getWithGeoData(Date minUploadDate, Date maxUploadDate, Date minTakenDate, Date maxTakenDate, int privacyFilter, String sort, Set extras, int perPage, int page) throws FlickrException, IOException, SAXException {
List parameters = new ArrayList();
parameters.add(new Parameter("method", METHOD_GET_WITH_GEO_DATA));
parameters.add(new Parameter("api_key", apiKey));
if (minUploadDate != null) {
parameters.add(new Parameter("min_upload_date", minUploadDate.getTime() / 1000L));
}
if (maxUploadDate != null) {
parameters.add(new Parameter("max_upload_date", maxUploadDate.getTime() / 1000L));
}
if (minTakenDate != null) {
parameters.add(new Parameter("min_taken_date", minTakenDate.getTime() / 1000L));
}
if (maxTakenDate != null) {
parameters.add(new Parameter("max_taken_date", maxTakenDate.getTime() / 1000L));
}
if (privacyFilter > 0) {
parameters.add(new Parameter("privacy_filter", privacyFilter));
}
if (sort != null) {
parameters.add(new Parameter("sort", sort));
}
if (extras != null && !extras.isEmpty()) {
StringBuffer sb = new StringBuffer();
Iterator it = extras.iterator();
while (it.hasNext()) {
if (sb.length() > 0) {
sb.append(",");
}
sb.append(it.next());
}
parameters.add(new Parameter("extras", sb.toString()));
}
if (perPage > 0) {
parameters.add(new Parameter("per_page", perPage));
}
if (page > 0) {
parameters.add(new Parameter("page", page));
}
Response response = transport.get(transport.getPath(), parameters);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
Element photosElement = response.getPayload();
PhotoList photos = PhotoUtils.createPhotoList(photosElement);
return photos;
}
/**
* Returns a list of your photos which haven't been geo-tagged.
* This method requires authentication with 'read' permission.
* @param minUploadDate Minimum upload date. Photos with an upload date greater than or equal to this value will be returned. Set to null to not specify a date.
* @param maxUploadDate Maximum upload date. Photos with an upload date less than or equal to this value will be returned. Set to null to not specify a date.
* @param minTakenDate Minimum taken date. Photos with an taken date greater than or equal to this value will be returned. Set to null to not specify a date.
* @param maxTakenDate Maximum taken date. Photos with an taken date less than or equal to this value will be returned. Set to null to not specify a date.
* @param privacyFilter Return photos only matching a certain privacy level. Valid values are:
* <ul>
* <li>1 public photos</li>
* <li>2 private photos visible to friends</li>
* <li>3 private photos visible to family</li>
* <li>4 private photos visible to friends & family</li>
* <li>5 completely private photos</li>
* </ul>
* Set to 0 to not specify a privacy Filter.
* @param sort The order in which to sort returned photos. Deafults to date-posted-desc. The possible values are: date-posted-asc, date-posted-desc, date-taken-asc, date-taken-desc, interestingness-desc, and interestingness-asc.
* @param extras A set of Strings controlling the extra information to fetch for each returned record. Currently supported fields are: license, date_upload, date_taken, owner_name, icon_server, original_format, last_update, geo. Set to null or an empty set to not specify any extras.
* @param perPage Number of photos to return per page. If this argument is 0, it defaults to 100. The maximum allowed value is 500.
* @param page The page of results to return. If this argument is 0, it defaults to 1.
* @return a photo list
* @throws FlickrException
* @throws IOException
* @throws SAXException
*/
public PhotoList getWithoutGeoData(Date minUploadDate, Date maxUploadDate, Date minTakenDate, Date maxTakenDate, int privacyFilter, String sort, Set extras, int perPage, int page) throws FlickrException, IOException, SAXException {
List parameters = new ArrayList();
parameters.add(new Parameter("method", METHOD_GET_WITHOUT_GEO_DATA));
parameters.add(new Parameter("api_key", apiKey));
if (minUploadDate != null) {
parameters.add(new Parameter("min_upload_date", minUploadDate.getTime() / 1000L));
}
if (maxUploadDate != null) {
parameters.add(new Parameter("max_upload_date", maxUploadDate.getTime() / 1000L));
}
if (minTakenDate != null) {
parameters.add(new Parameter("min_taken_date", minTakenDate.getTime() / 1000L));
}
if (maxTakenDate != null) {
parameters.add(new Parameter("max_taken_date", maxTakenDate.getTime() / 1000L));
}
if (privacyFilter > 0) {
parameters.add(new Parameter("privacy_filter", privacyFilter));
}
if (sort != null) {
parameters.add(new Parameter("sort", sort));
}
if (extras != null && !extras.isEmpty()) {
StringBuffer sb = new StringBuffer();
Iterator it = extras.iterator();
while (it.hasNext()) {
if (sb.length() > 0) {
sb.append(",");
}
sb.append(it.next());
}
parameters.add(new Parameter("extras", sb.toString()));
}
if (perPage > 0) {
parameters.add(new Parameter("per_page", perPage));
}
if (page > 0) {
parameters.add(new Parameter("page", page));
}
Response response = transport.get(transport.getPath(), parameters);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
Element photosElement = response.getPayload();
PhotoList photos = PhotoUtils.createPhotoList(photosElement);
return photos;
}
/**
* Return a list of your photos that have been recently created or which have been recently modified.
* Recently modified may mean that the photo's metadata (title, description, tags) may have been changed or a comment has been added (or just modified somehow :-)
* @param minDate Date indicating the date from which modifications should be compared. Must be given.
* @param extras A set of Strings controlling the extra information to fetch for each returned record. Currently supported fields are: license, date_upload, date_taken, owner_name, icon_server, original_format, last_update, geo. Set to null or an empty set to not specify any extras.
* @param perPage Number of photos to return per page. If this argument is 0, it defaults to 100. The maximum allowed value is 500.
* @param page The page of results to return. If this argument is 0, it defaults to 1.
* @return a list of photos
* @throws SAXException
* @throws IOException
* @throws FlickrException
*/
public PhotoList recentlyUpdated(Date minDate, Set extras, int perPage, int page) throws IOException, SAXException, FlickrException {
List parameters = new ArrayList();
parameters.add(new Parameter("method", METHOD_GET_WITHOUT_GEO_DATA));
parameters.add(new Parameter("api_key", apiKey));
parameters.add(new Parameter("min_date", minDate.getTime() / 1000L));
if (extras != null && !extras.isEmpty()) {
StringBuffer sb = new StringBuffer();
Iterator it = extras.iterator();
while (it.hasNext()) {
if (sb.length() > 0) {
sb.append(",");
}
sb.append(it.next());
}
parameters.add(new Parameter("extras", sb.toString()));
}
if (perPage > 0) {
parameters.add(new Parameter("per_page", perPage));
}
if (page > 0) {
parameters.add(new Parameter("page", page));
}
Response response = transport.get(transport.getPath(), parameters);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
Element photosElement = response.getPayload();
PhotoList photos = PhotoUtils.createPhotoList(photosElement);
return photos;
}
/**
* Remove a tag from a photo.
*
* @param tagId The tag ID
* @throws IOException
* @throws SAXException
* @throws FlickrException
*/
public void removeTag(String tagId) throws IOException, SAXException, FlickrException {
List parameters = new ArrayList();
parameters.add(new Parameter("method", METHOD_REMOVE_TAG));
parameters.add(new Parameter("api_key", apiKey));
parameters.add(new Parameter("tag_id", tagId));
Response response = transport.post(transport.getPath(), parameters);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
}
/**
* Search for photos which match the given search parameters.
*
* @param params The search parameters
* @param perPage The number of photos to show per page
* @param page The page offset
* @return A PhotoList
* @throws IOException
* @throws SAXException
* @throws FlickrException
*/
public PhotoList search(SearchParameters params, int perPage, int page) throws IOException, SAXException,
FlickrException {
PhotoList photos = new PhotoList();
List parameters = new ArrayList();
parameters.add(new Parameter("method", METHOD_SEARCH));
parameters.add(new Parameter("api_key", apiKey));
parameters.addAll(params.getAsParameters());
if (perPage > 0) {
parameters.add(new Parameter("per_page", new Integer(perPage)));
}
if (page > 0) {
parameters.add(new Parameter("page", new Integer(page)));
}
Response response = transport.get(transport.getPath(), parameters);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
Element photosElement = response.getPayload();
photos.setPage(photosElement.getAttribute("page"));
photos.setPages(photosElement.getAttribute("pages"));
photos.setPerPage(photosElement.getAttribute("perpage"));
photos.setTotal(photosElement.getAttribute("total"));
NodeList photoNodes = photosElement.getElementsByTagName("photo");
for (int i = 0; i < photoNodes.getLength(); i++) {
Element photoElement = (Element) photoNodes.item(i);
Photo photo = new Photo();
photo.setId(photoElement.getAttribute("id"));
User owner = new User();
owner.setId(photoElement.getAttribute("owner"));
photo.setOwner(owner);
photo.setSecret(photoElement.getAttribute("secret"));
photo.setServer(photoElement.getAttribute("server"));
photo.setFarm(photoElement.getAttribute("farm"));
photo.setTitle(photoElement.getAttribute("title"));
photo.setPublicFlag("1".equals(photoElement.getAttribute("ispublic")));
photo.setFriendFlag("1".equals(photoElement.getAttribute("isfriend")));
photo.setFamilyFlag("1".equals(photoElement.getAttribute("isfamily")));
photos.add(photo);
}
return photos;
}
/**
* Search for interesting photos using the Flickr Interestingness algorithm.
*
* @param params Any search parameters
* @param perPage Number of items per page
* @param page The page to start on
* @return A PhotoList
* @throws IOException
* @throws SAXException
* @throws FlickrException
*/
public PhotoList searchInterestingness(SearchParameters params, int perPage, int page)
throws IOException, SAXException, FlickrException {
PhotoList photos = new PhotoList();
List parameters = new ArrayList();
parameters.add(new Parameter("method", METHOD_GET_INTERESTINGNESS));
parameters.add(new Parameter("api_key", apiKey));
parameters.addAll(params.getAsParameters());
if (perPage > 0) {
parameters.add(new Parameter("per_page", new Integer(perPage)));
}
if (page > 0) {
parameters.add(new Parameter("page", new Integer(page)));
}
Response response = transport.get(transport.getPath(), parameters);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response
.getErrorMessage());
}
Element photosElement = response.getPayload();
photos.setPage(photosElement.getAttribute("page"));
photos.setPages(photosElement.getAttribute("pages"));
photos.setPerPage(photosElement.getAttribute("perpage"));
photos.setTotal(photosElement.getAttribute("total"));
NodeList photoNodes = photosElement.getElementsByTagName("photo");
for (int i = 0; i < photoNodes.getLength(); i++) {
Element photoElement = (Element) photoNodes.item(i);
Photo photo = new Photo();
photo.setId(photoElement.getAttribute("id"));
User owner = new User();
owner.setId(photoElement.getAttribute("owner"));
photo.setOwner(owner);
photo.setSecret(photoElement.getAttribute("secret"));
photo.setServer(photoElement.getAttribute("server"));
photo.setFarm(photoElement.getAttribute("farm"));
photo.setTitle(photoElement.getAttribute("title"));
photo.setPublicFlag("1".equals(photoElement
.getAttribute("ispublic")));
photo.setFriendFlag("1".equals(photoElement
.getAttribute("isfriend")));
photo.setFamilyFlag("1".equals(photoElement
.getAttribute("isfamily")));
photos.add(photo);
}
return photos;
}
/**
* Set the dates for the specified photo.
*
* @param photoId The photo ID
* @param datePosted The date the photo was posted or null
* @param dateTaken The date the photo was taken or null
* @param dateTakenGranularity The granularity of the taken date or null
* @throws IOException
* @throws SAXException
* @throws FlickrException
*/
public void setDates(String photoId, Date datePosted, Date dateTaken, String dateTakenGranularity)
throws IOException, SAXException, FlickrException {
List parameters = new ArrayList();
parameters.add(new Parameter("method", METHOD_SET_DATES));
parameters.add(new Parameter("api_key", apiKey));
parameters.add(new Parameter("photo_id", photoId));
if (datePosted != null) {
parameters.add(new Parameter("date_posted", new Long(datePosted.getTime() / 1000)));
}
if (dateTaken != null) {
parameters.add(new Parameter("date_taken", DF.format(dateTaken)));
}
if (dateTakenGranularity != null) {
parameters.add(new Parameter("date_taken_granularity", dateTakenGranularity));
}
Response response = transport.post(transport.getPath(), parameters);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
}
/**
* Set the meta data for the photo.
*
* @param photoId The photo ID
* @param title The new title
* @param description The new description
* @throws IOException
* @throws SAXException
* @throws FlickrException
*/
public void setMeta(String photoId, String title, String description) throws IOException,
SAXException, FlickrException {
List parameters = new ArrayList();
parameters.add(new Parameter("method", METHOD_SET_META));
parameters.add(new Parameter("api_key", apiKey));
parameters.add(new Parameter("photo_id", photoId));
parameters.add(new Parameter("title", title));
parameters.add(new Parameter("description", description));
Response response = transport.post(transport.getPath(), parameters);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
}
/**
* Set the permissions for the photo.
*
* @param photoId The photo ID
* @param permissions The permissions object
* @throws IOException
* @throws SAXException
* @throws FlickrException
*/
public void setPerms(String photoId, Permissions permissions) throws IOException,
SAXException, FlickrException {
List parameters = new ArrayList();
parameters.add(new Parameter("method", METHOD_SET_META));
parameters.add(new Parameter("api_key", apiKey));
parameters.add(new Parameter("photo_id", photoId));
parameters.add(new Parameter("is_public", permissions.isPublicFlag() ? "1" : "0"));
parameters.add(new Parameter("is_friend", permissions.isFriendFlag() ? "1" : "0"));
parameters.add(new Parameter("is_family", permissions.isFamilyFlag() ? "1" : "0"));
parameters.add(new Parameter("perm_comment", new Integer(permissions.getComment())));
parameters.add(new Parameter("perm_addmeta", new Integer(permissions.getAddmeta())));
Response response = transport.post(transport.getPath(), parameters);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
}
/**
* Set the tags for a photo.
*
* @param photoId The photo ID
* @param tags The tag array
* @throws IOException
* @throws SAXException
* @throws FlickrException
*/
public void setTags(String photoId, String[] tags) throws IOException, SAXException,
FlickrException {
List parameters = new ArrayList();
parameters.add(new Parameter("method", METHOD_SET_TAGS));
parameters.add(new Parameter("api_key", apiKey));
parameters.add(new Parameter("photo_id", photoId));
parameters.add(new Parameter("tags", StringUtilities.join(tags, " ", true)));
Response response = transport.post(transport.getPath(), parameters);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
}
/**
* Get the photo for the specified ID. Currently maps to the getInfo() method.
*
* @param id The ID
* @return The Photo
* @throws IOException
* @throws FlickrException
* @throws SAXException
*/
public Photo getPhoto(String id) throws IOException, FlickrException, SAXException {
return getPhoto(id, null);
}
/**
* Get the photo for the specified ID with the given secret. Currently maps to the getInfo() method.
*
* @param id The ID
* @param secret The secret
* @return The Photo
* @throws IOException
* @throws FlickrException
* @throws SAXException
*/
public Photo getPhoto(String id, String secret) throws IOException, FlickrException, SAXException {
return getInfo(id, secret);
}
}
| true | true | public Photo getInfo(String photoId, String secret) throws IOException, SAXException, FlickrException {
List parameters = new ArrayList();
parameters.add(new Parameter("method", METHOD_GET_INFO));
parameters.add(new Parameter("api_key", apiKey));
parameters.add(new Parameter("photo_id", photoId));
if (secret != null) {
parameters.add(new Parameter("secret", secret));
}
Response response = transport.get(transport.getPath(), parameters);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
Element photoElement = (Element)response.getPayload();
Photo photo = new Photo();
photo.setId(photoElement.getAttribute("id"));
photo.setSecret(photoElement.getAttribute("secret"));
photo.setServer(photoElement.getAttribute("server"));
photo.setFarm(photoElement.getAttribute("farm"));
photo.setFavorite("1".equals(photoElement.getAttribute("isfavorite")));
photo.setLicense(photoElement.getAttribute("license"));
Element ownerElement = (Element) photoElement.getElementsByTagName("owner").item(0);
User owner = new User();
owner.setId(ownerElement.getAttribute("nsid"));
owner.setUsername(ownerElement.getAttribute("username"));
owner.setRealName(ownerElement.getAttribute("realname"));
owner.setLocation(ownerElement.getAttribute("location"));
photo.setOwner(owner);
photo.setTitle(XMLUtilities.getChildValue(photoElement, "title"));
photo.setDescription(XMLUtilities.getChildValue(photoElement, "description"));
Element visibilityElement = (Element) photoElement.getElementsByTagName("visibility").item(0);
photo.setPublicFlag("1".equals(visibilityElement.getAttribute("ispublic")));
photo.setFriendFlag("1".equals(visibilityElement.getAttribute("isfriend")));
photo.setFamilyFlag("1".equals(visibilityElement.getAttribute("isfamily")));
Element datesElement = XMLUtilities.getChild(photoElement, "dates");
photo.setDatePosted(datesElement.getAttribute("posted"));
photo.setDateTaken(datesElement.getAttribute("taken"));
photo.setTakenGranularity(datesElement.getAttribute("takengranularity"));
NodeList permissionsNodes = photoElement.getElementsByTagName("permissions");
if (permissionsNodes.getLength() > 0) {
Element permissionsElement = (Element) permissionsNodes.item(0);
Permissions permissions = new Permissions();
permissions.setComment(permissionsElement.getAttribute("permcomment"));
permissions.setAddmeta(permissionsElement.getAttribute("permaddmeta"));
}
Element editabilityElement = (Element) photoElement.getElementsByTagName("editability").item(0);
Editability editability = new Editability();
editability.setComment("1".equals(editabilityElement.getAttribute("cancomment")));
editability.setAddmeta("1".equals(editabilityElement.getAttribute("canaddmeta")));
Element commentsElement = (Element) photoElement.getElementsByTagName("comments").item(0);
photo.setComments(((Text) commentsElement.getFirstChild()).getData());
Element notesElement = (Element) photoElement.getElementsByTagName("notes").item(0);
List notes = new ArrayList();
NodeList noteNodes = notesElement.getElementsByTagName("note");
for (int i = 0; i < noteNodes.getLength(); i++) {
Element noteElement = (Element) noteNodes.item(i);
Note note = new Note();
note.setId(noteElement.getAttribute("id"));
note.setAuthor(noteElement.getAttribute("author"));
note.setAuthorName(noteElement.getAttribute("authorname"));
note.setBounds(noteElement.getAttribute("x"), noteElement.getAttribute("y"),
noteElement.getAttribute("w"), noteElement.getAttribute("h"));
notes.add(note);
}
photo.setNotes(notes);
Element tagsElement = (Element) photoElement.getElementsByTagName("tags").item(0);
List tags = new ArrayList();
NodeList tagNodes = tagsElement.getElementsByTagName("tag");
for (int i = 0; i < tagNodes.getLength(); i++) {
Element tagElement = (Element) tagNodes.item(i);
Tag tag = new Tag();
tag.setId(tagElement.getAttribute("id"));
tag.setAuthor(tagElement.getAttribute("author"));
tag.setRaw(tagElement.getAttribute("raw"));
tag.setValue(((Text) tagElement.getFirstChild()).getData());
tags.add(tag);
}
photo.setTags(tags);
Element urlsElement = (Element) photoElement.getElementsByTagName("urls").item(0);
List urls = new ArrayList();
NodeList urlNodes = urlsElement.getElementsByTagName("url");
for (int i = 0; i < urlNodes.getLength(); i++) {
Element urlElement = (Element) urlNodes.item(i);
PhotoUrl photoUrl = new PhotoUrl();
photoUrl.setType(urlElement.getAttribute("type"));
photoUrl.setUrl(XMLUtilities.getValue(urlElement));
if (photoUrl.getType().equals("photopage")) {
photo.setUrl(photoUrl.getUrl());
}
}
photo.setUrls(urls);
return photo;
}
| public Photo getInfo(String photoId, String secret) throws IOException, SAXException, FlickrException {
List parameters = new ArrayList();
parameters.add(new Parameter("method", METHOD_GET_INFO));
parameters.add(new Parameter("api_key", apiKey));
parameters.add(new Parameter("photo_id", photoId));
if (secret != null) {
parameters.add(new Parameter("secret", secret));
}
Response response = transport.get(transport.getPath(), parameters);
if (response.isError()) {
throw new FlickrException(response.getErrorCode(), response.getErrorMessage());
}
Element photoElement = (Element)response.getPayload();
Photo photo = new Photo();
photo.setId(photoElement.getAttribute("id"));
photo.setSecret(photoElement.getAttribute("secret"));
photo.setServer(photoElement.getAttribute("server"));
photo.setFarm(photoElement.getAttribute("farm"));
photo.setFavorite("1".equals(photoElement.getAttribute("isfavorite")));
photo.setLicense(photoElement.getAttribute("license"));
Element ownerElement = (Element) photoElement.getElementsByTagName("owner").item(0);
User owner = new User();
owner.setId(ownerElement.getAttribute("nsid"));
owner.setUsername(ownerElement.getAttribute("username"));
owner.setRealName(ownerElement.getAttribute("realname"));
owner.setLocation(ownerElement.getAttribute("location"));
photo.setOwner(owner);
photo.setTitle(XMLUtilities.getChildValue(photoElement, "title"));
photo.setDescription(XMLUtilities.getChildValue(photoElement, "description"));
Element visibilityElement = (Element) photoElement.getElementsByTagName("visibility").item(0);
photo.setPublicFlag("1".equals(visibilityElement.getAttribute("ispublic")));
photo.setFriendFlag("1".equals(visibilityElement.getAttribute("isfriend")));
photo.setFamilyFlag("1".equals(visibilityElement.getAttribute("isfamily")));
Element datesElement = XMLUtilities.getChild(photoElement, "dates");
photo.setDatePosted(datesElement.getAttribute("posted"));
photo.setDateTaken(datesElement.getAttribute("taken"));
photo.setTakenGranularity(datesElement.getAttribute("takengranularity"));
NodeList permissionsNodes = photoElement.getElementsByTagName("permissions");
if (permissionsNodes.getLength() > 0) {
Element permissionsElement = (Element) permissionsNodes.item(0);
Permissions permissions = new Permissions();
permissions.setComment(permissionsElement.getAttribute("permcomment"));
permissions.setAddmeta(permissionsElement.getAttribute("permaddmeta"));
}
Element editabilityElement = (Element) photoElement.getElementsByTagName("editability").item(0);
Editability editability = new Editability();
editability.setComment("1".equals(editabilityElement.getAttribute("cancomment")));
editability.setAddmeta("1".equals(editabilityElement.getAttribute("canaddmeta")));
Element commentsElement = (Element) photoElement.getElementsByTagName("comments").item(0);
photo.setComments(((Text) commentsElement.getFirstChild()).getData());
Element notesElement = (Element) photoElement.getElementsByTagName("notes").item(0);
List notes = new ArrayList();
NodeList noteNodes = notesElement.getElementsByTagName("note");
for (int i = 0; i < noteNodes.getLength(); i++) {
Element noteElement = (Element) noteNodes.item(i);
Note note = new Note();
note.setId(noteElement.getAttribute("id"));
note.setAuthor(noteElement.getAttribute("author"));
note.setAuthorName(noteElement.getAttribute("authorname"));
note.setBounds(noteElement.getAttribute("x"), noteElement.getAttribute("y"),
noteElement.getAttribute("w"), noteElement.getAttribute("h"));
note.setText(noteElement.getTextContent());
notes.add(note);
}
photo.setNotes(notes);
Element tagsElement = (Element) photoElement.getElementsByTagName("tags").item(0);
List tags = new ArrayList();
NodeList tagNodes = tagsElement.getElementsByTagName("tag");
for (int i = 0; i < tagNodes.getLength(); i++) {
Element tagElement = (Element) tagNodes.item(i);
Tag tag = new Tag();
tag.setId(tagElement.getAttribute("id"));
tag.setAuthor(tagElement.getAttribute("author"));
tag.setRaw(tagElement.getAttribute("raw"));
tag.setValue(((Text) tagElement.getFirstChild()).getData());
tags.add(tag);
}
photo.setTags(tags);
Element urlsElement = (Element) photoElement.getElementsByTagName("urls").item(0);
List urls = new ArrayList();
NodeList urlNodes = urlsElement.getElementsByTagName("url");
for (int i = 0; i < urlNodes.getLength(); i++) {
Element urlElement = (Element) urlNodes.item(i);
PhotoUrl photoUrl = new PhotoUrl();
photoUrl.setType(urlElement.getAttribute("type"));
photoUrl.setUrl(XMLUtilities.getValue(urlElement));
if (photoUrl.getType().equals("photopage")) {
photo.setUrl(photoUrl.getUrl());
}
}
photo.setUrls(urls);
return photo;
}
|
diff --git a/app/controllers/DimensionDiagramController.java b/app/controllers/DimensionDiagramController.java
index 23b6c2b..cf02121 100644
--- a/app/controllers/DimensionDiagramController.java
+++ b/app/controllers/DimensionDiagramController.java
@@ -1,44 +1,53 @@
/*
* Copyright (C) 2012 by Eero Laukkanen, Risto Virtanen, Jussi Patana, Juha Viljanen,
* Joona Koistinen, Pekka Rihtniemi, Mika Kekäle, Roope Hovi, Mikko Valjus,
* Timo Lehtinen, Jaakko Harjuhahto
*
* 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 controllers;
import models.ClassificationRelationMap;
import models.RCACase;
import play.mvc.Controller;
import play.mvc.With;
import java.util.HashMap;
@With(LanguageController.class)
public class DimensionDiagramController extends Controller {
public static void show(String URLHash) {
RCACase rcaCase = RCACase.getRCACase(URLHash);
notFoundIfNull(rcaCase);
rcaCase = PublicRCACaseController.checkIfCurrentUserHasRightsForRCACase(rcaCase.id);
+ notFoundIfNull(rcaCase);
ClassificationRelationMap relations = ClassificationRelationMap.fromCase(rcaCase);
- HashMap<Long, Integer> classificationRelevance = relations.getClassificationRelevances();
+ HashMap<Long, Integer> classificationRelevance = new HashMap<Long, Integer>();
+ if (relations == null) {
+ relations = new ClassificationRelationMap();
+ } else {
+ classificationRelevance = relations.getClassificationRelevances();
+ }
+ if (classificationRelevance == null) {
+ classificationRelevance = new HashMap<Long, Integer>();
+ }
render(rcaCase, relations, classificationRelevance);
}
}
| false | true | public static void show(String URLHash) {
RCACase rcaCase = RCACase.getRCACase(URLHash);
notFoundIfNull(rcaCase);
rcaCase = PublicRCACaseController.checkIfCurrentUserHasRightsForRCACase(rcaCase.id);
ClassificationRelationMap relations = ClassificationRelationMap.fromCase(rcaCase);
HashMap<Long, Integer> classificationRelevance = relations.getClassificationRelevances();
render(rcaCase, relations, classificationRelevance);
}
| public static void show(String URLHash) {
RCACase rcaCase = RCACase.getRCACase(URLHash);
notFoundIfNull(rcaCase);
rcaCase = PublicRCACaseController.checkIfCurrentUserHasRightsForRCACase(rcaCase.id);
notFoundIfNull(rcaCase);
ClassificationRelationMap relations = ClassificationRelationMap.fromCase(rcaCase);
HashMap<Long, Integer> classificationRelevance = new HashMap<Long, Integer>();
if (relations == null) {
relations = new ClassificationRelationMap();
} else {
classificationRelevance = relations.getClassificationRelevances();
}
if (classificationRelevance == null) {
classificationRelevance = new HashMap<Long, Integer>();
}
render(rcaCase, relations, classificationRelevance);
}
|
diff --git a/src/com/android/settings/wifi/AccessPoint.java b/src/com/android/settings/wifi/AccessPoint.java
index f6581a5fa..20146eb27 100644
--- a/src/com/android/settings/wifi/AccessPoint.java
+++ b/src/com/android/settings/wifi/AccessPoint.java
@@ -1,398 +1,398 @@
/*
* 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.settings.wifi;
import android.content.Context;
import android.net.NetworkInfo.DetailedState;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiConfiguration.KeyMgmt;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.preference.Preference;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import com.android.settings.R;
class AccessPoint extends Preference {
static final String TAG = "Settings.AccessPoint";
private static final String KEY_DETAILEDSTATE = "key_detailedstate";
private static final String KEY_WIFIINFO = "key_wifiinfo";
private static final String KEY_SCANRESULT = "key_scanresult";
private static final String KEY_CONFIG = "key_config";
private static final int[] STATE_SECURED = {
R.attr.state_encrypted
};
private static final int[] STATE_NONE = {};
/** These values are matched in string arrays -- changes must be kept in sync */
static final int SECURITY_NONE = 0;
static final int SECURITY_WEP = 1;
static final int SECURITY_PSK = 2;
static final int SECURITY_EAP = 3;
enum PskType {
UNKNOWN,
WPA,
WPA2,
WPA_WPA2
}
String ssid;
String bssid;
int security;
int networkId;
boolean wpsAvailable = false;
PskType pskType = PskType.UNKNOWN;
private WifiConfiguration mConfig;
/* package */ScanResult mScanResult;
private int mRssi;
private WifiInfo mInfo;
private DetailedState mState;
static int getSecurity(WifiConfiguration config) {
if (config.allowedKeyManagement.get(KeyMgmt.WPA_PSK)) {
return SECURITY_PSK;
}
if (config.allowedKeyManagement.get(KeyMgmt.WPA_EAP) ||
config.allowedKeyManagement.get(KeyMgmt.IEEE8021X)) {
return SECURITY_EAP;
}
return (config.wepKeys[0] != null) ? SECURITY_WEP : SECURITY_NONE;
}
private static int getSecurity(ScanResult result) {
if (result.capabilities.contains("WEP")) {
return SECURITY_WEP;
} else if (result.capabilities.contains("PSK")) {
return SECURITY_PSK;
} else if (result.capabilities.contains("EAP")) {
return SECURITY_EAP;
}
return SECURITY_NONE;
}
public String getSecurityString(boolean concise) {
Context context = getContext();
switch(security) {
case SECURITY_EAP:
return concise ? context.getString(R.string.wifi_security_short_eap) :
context.getString(R.string.wifi_security_eap);
case SECURITY_PSK:
switch (pskType) {
case WPA:
return concise ? context.getString(R.string.wifi_security_short_wpa) :
context.getString(R.string.wifi_security_wpa);
case WPA2:
return concise ? context.getString(R.string.wifi_security_short_wpa2) :
context.getString(R.string.wifi_security_wpa2);
case WPA_WPA2:
return concise ? context.getString(R.string.wifi_security_short_wpa_wpa2) :
context.getString(R.string.wifi_security_wpa_wpa2);
case UNKNOWN:
default:
return concise ? context.getString(R.string.wifi_security_short_psk_generic)
: context.getString(R.string.wifi_security_psk_generic);
}
case SECURITY_WEP:
return concise ? context.getString(R.string.wifi_security_short_wep) :
context.getString(R.string.wifi_security_wep);
case SECURITY_NONE:
default:
return concise ? "" : context.getString(R.string.wifi_security_none);
}
}
private static PskType getPskType(ScanResult result) {
boolean wpa = result.capabilities.contains("WPA-PSK");
boolean wpa2 = result.capabilities.contains("WPA2-PSK");
if (wpa2 && wpa) {
return PskType.WPA_WPA2;
} else if (wpa2) {
return PskType.WPA2;
} else if (wpa) {
return PskType.WPA;
} else {
Log.w(TAG, "Received abnormal flag string: " + result.capabilities);
return PskType.UNKNOWN;
}
}
AccessPoint(Context context, WifiConfiguration config) {
super(context);
setWidgetLayoutResource(R.layout.preference_widget_wifi_signal);
loadConfig(config);
refresh();
}
AccessPoint(Context context, ScanResult result) {
super(context);
setWidgetLayoutResource(R.layout.preference_widget_wifi_signal);
loadResult(result);
refresh();
}
AccessPoint(Context context, Bundle savedState) {
super(context);
setWidgetLayoutResource(R.layout.preference_widget_wifi_signal);
mConfig = savedState.getParcelable(KEY_CONFIG);
if (mConfig != null) {
loadConfig(mConfig);
}
mScanResult = (ScanResult) savedState.getParcelable(KEY_SCANRESULT);
if (mScanResult != null) {
loadResult(mScanResult);
}
mInfo = (WifiInfo) savedState.getParcelable(KEY_WIFIINFO);
if (savedState.containsKey(KEY_DETAILEDSTATE)) {
mState = DetailedState.valueOf(savedState.getString(KEY_DETAILEDSTATE));
}
update(mInfo, mState);
}
public void saveWifiState(Bundle savedState) {
savedState.putParcelable(KEY_CONFIG, mConfig);
savedState.putParcelable(KEY_SCANRESULT, mScanResult);
savedState.putParcelable(KEY_WIFIINFO, mInfo);
if (mState != null) {
savedState.putString(KEY_DETAILEDSTATE, mState.toString());
}
}
private void loadConfig(WifiConfiguration config) {
ssid = (config.SSID == null ? "" : removeDoubleQuotes(config.SSID));
bssid = config.BSSID;
security = getSecurity(config);
networkId = config.networkId;
mRssi = Integer.MAX_VALUE;
mConfig = config;
}
private void loadResult(ScanResult result) {
ssid = result.SSID;
bssid = result.BSSID;
security = getSecurity(result);
wpsAvailable = security != SECURITY_EAP && result.capabilities.contains("WPS");
if (security == SECURITY_PSK)
pskType = getPskType(result);
networkId = -1;
mRssi = result.level;
mScanResult = result;
}
@Override
protected void onBindView(View view) {
super.onBindView(view);
ImageView signal = (ImageView) view.findViewById(R.id.signal);
if (mRssi == Integer.MAX_VALUE) {
signal.setImageDrawable(null);
} else {
signal.setImageLevel(getLevel());
signal.setImageResource(R.drawable.wifi_signal);
signal.setImageState((security != SECURITY_NONE) ?
STATE_SECURED : STATE_NONE, true);
}
}
@Override
public int compareTo(Preference preference) {
if (!(preference instanceof AccessPoint)) {
return 1;
}
AccessPoint other = (AccessPoint) preference;
// Active one goes first.
if (mInfo != null && other.mInfo == null) return -1;
if (mInfo == null && other.mInfo != null) return 1;
// Reachable one goes before unreachable one.
if (mRssi != Integer.MAX_VALUE && other.mRssi == Integer.MAX_VALUE) return -1;
if (mRssi == Integer.MAX_VALUE && other.mRssi != Integer.MAX_VALUE) return 1;
// Configured one goes before unconfigured one.
if (networkId != WifiConfiguration.INVALID_NETWORK_ID
&& other.networkId == WifiConfiguration.INVALID_NETWORK_ID) return -1;
if (networkId == WifiConfiguration.INVALID_NETWORK_ID
&& other.networkId != WifiConfiguration.INVALID_NETWORK_ID) return 1;
// Sort by signal strength.
int difference = WifiManager.compareSignalLevel(other.mRssi, mRssi);
if (difference != 0) {
return difference;
}
// Sort by ssid.
return ssid.compareToIgnoreCase(other.ssid);
}
@Override
public boolean equals(Object other) {
if (!(other instanceof AccessPoint)) return false;
return (this.compareTo((AccessPoint) other) == 0);
}
@Override
public int hashCode() {
int result = 0;
if (mInfo != null) result += 13 * mInfo.hashCode();
result += 19 * mRssi;
result += 23 * networkId;
result += 29 * ssid.hashCode();
return result;
}
boolean update(ScanResult result) {
if (ssid.equals(result.SSID) && security == getSecurity(result)) {
if (WifiManager.compareSignalLevel(result.level, mRssi) > 0) {
int oldLevel = getLevel();
mRssi = result.level;
if (getLevel() != oldLevel) {
notifyChanged();
}
}
// This flag only comes from scans, is not easily saved in config
if (security == SECURITY_PSK) {
pskType = getPskType(result);
}
refresh();
return true;
}
return false;
}
void update(WifiInfo info, DetailedState state) {
boolean reorder = false;
if (info != null && networkId != WifiConfiguration.INVALID_NETWORK_ID
&& networkId == info.getNetworkId()) {
reorder = (mInfo == null);
mRssi = info.getRssi();
mInfo = info;
mState = state;
refresh();
} else if (mInfo != null) {
reorder = true;
mInfo = null;
mState = null;
refresh();
}
if (reorder) {
notifyHierarchyChanged();
}
}
int getLevel() {
if (mRssi == Integer.MAX_VALUE) {
return -1;
}
return WifiManager.calculateSignalLevel(mRssi, 4);
}
WifiConfiguration getConfig() {
return mConfig;
}
WifiInfo getInfo() {
return mInfo;
}
DetailedState getState() {
return mState;
}
static String removeDoubleQuotes(String string) {
int length = string.length();
if ((length > 1) && (string.charAt(0) == '"')
&& (string.charAt(length - 1) == '"')) {
return string.substring(1, length - 1);
}
return string;
}
static String convertToQuotedString(String string) {
return "\"" + string + "\"";
}
/** Updates the title and summary; may indirectly call notifyChanged() */
private void refresh() {
setTitle(ssid);
Context context = getContext();
- if (mState != null) { // This is the active connection
- setSummary(Summary.get(context, mState));
- } else if (mRssi == Integer.MAX_VALUE) { // Wifi out of range
- setSummary(context.getString(R.string.wifi_not_in_range));
- } else if (mConfig != null && mConfig.status == WifiConfiguration.Status.DISABLED) {
+ if (mConfig != null && mConfig.status == WifiConfiguration.Status.DISABLED) {
switch (mConfig.disableReason) {
case WifiConfiguration.DISABLED_AUTH_FAILURE:
setSummary(context.getString(R.string.wifi_disabled_password_failure));
break;
case WifiConfiguration.DISABLED_DHCP_FAILURE:
case WifiConfiguration.DISABLED_DNS_FAILURE:
setSummary(context.getString(R.string.wifi_disabled_network_failure));
break;
case WifiConfiguration.DISABLED_UNKNOWN_REASON:
setSummary(context.getString(R.string.wifi_disabled_generic));
}
+ } else if (mRssi == Integer.MAX_VALUE) { // Wifi out of range
+ setSummary(context.getString(R.string.wifi_not_in_range));
+ } else if (mState != null) { // This is the active connection
+ setSummary(Summary.get(context, mState));
} else { // In range, not disabled.
StringBuilder summary = new StringBuilder();
if (mConfig != null) { // Is saved network
summary.append(context.getString(R.string.wifi_remembered));
}
if (security != SECURITY_NONE) {
String securityStrFormat;
if (summary.length() == 0) {
securityStrFormat = context.getString(R.string.wifi_secured_first_item);
} else {
securityStrFormat = context.getString(R.string.wifi_secured_second_item);
}
summary.append(String.format(securityStrFormat, getSecurityString(true)));
}
if (mConfig == null && wpsAvailable) { // Only list WPS available for unsaved networks
if (summary.length() == 0) {
summary.append(context.getString(R.string.wifi_wps_available_first_item));
} else {
summary.append(context.getString(R.string.wifi_wps_available_second_item));
}
}
setSummary(summary.toString());
}
}
/**
* Generate and save a default wifiConfiguration with common values.
* Can only be called for unsecured networks.
* @hide
*/
protected void generateOpenNetworkConfig() {
if (security != SECURITY_NONE)
throw new IllegalStateException();
if (mConfig != null)
return;
mConfig = new WifiConfiguration();
mConfig.SSID = AccessPoint.convertToQuotedString(ssid);
mConfig.allowedKeyManagement.set(KeyMgmt.NONE);
}
}
| false | true | private void refresh() {
setTitle(ssid);
Context context = getContext();
if (mState != null) { // This is the active connection
setSummary(Summary.get(context, mState));
} else if (mRssi == Integer.MAX_VALUE) { // Wifi out of range
setSummary(context.getString(R.string.wifi_not_in_range));
} else if (mConfig != null && mConfig.status == WifiConfiguration.Status.DISABLED) {
switch (mConfig.disableReason) {
case WifiConfiguration.DISABLED_AUTH_FAILURE:
setSummary(context.getString(R.string.wifi_disabled_password_failure));
break;
case WifiConfiguration.DISABLED_DHCP_FAILURE:
case WifiConfiguration.DISABLED_DNS_FAILURE:
setSummary(context.getString(R.string.wifi_disabled_network_failure));
break;
case WifiConfiguration.DISABLED_UNKNOWN_REASON:
setSummary(context.getString(R.string.wifi_disabled_generic));
}
} else { // In range, not disabled.
StringBuilder summary = new StringBuilder();
if (mConfig != null) { // Is saved network
summary.append(context.getString(R.string.wifi_remembered));
}
if (security != SECURITY_NONE) {
String securityStrFormat;
if (summary.length() == 0) {
securityStrFormat = context.getString(R.string.wifi_secured_first_item);
} else {
securityStrFormat = context.getString(R.string.wifi_secured_second_item);
}
summary.append(String.format(securityStrFormat, getSecurityString(true)));
}
if (mConfig == null && wpsAvailable) { // Only list WPS available for unsaved networks
if (summary.length() == 0) {
summary.append(context.getString(R.string.wifi_wps_available_first_item));
} else {
summary.append(context.getString(R.string.wifi_wps_available_second_item));
}
}
setSummary(summary.toString());
}
}
| private void refresh() {
setTitle(ssid);
Context context = getContext();
if (mConfig != null && mConfig.status == WifiConfiguration.Status.DISABLED) {
switch (mConfig.disableReason) {
case WifiConfiguration.DISABLED_AUTH_FAILURE:
setSummary(context.getString(R.string.wifi_disabled_password_failure));
break;
case WifiConfiguration.DISABLED_DHCP_FAILURE:
case WifiConfiguration.DISABLED_DNS_FAILURE:
setSummary(context.getString(R.string.wifi_disabled_network_failure));
break;
case WifiConfiguration.DISABLED_UNKNOWN_REASON:
setSummary(context.getString(R.string.wifi_disabled_generic));
}
} else if (mRssi == Integer.MAX_VALUE) { // Wifi out of range
setSummary(context.getString(R.string.wifi_not_in_range));
} else if (mState != null) { // This is the active connection
setSummary(Summary.get(context, mState));
} else { // In range, not disabled.
StringBuilder summary = new StringBuilder();
if (mConfig != null) { // Is saved network
summary.append(context.getString(R.string.wifi_remembered));
}
if (security != SECURITY_NONE) {
String securityStrFormat;
if (summary.length() == 0) {
securityStrFormat = context.getString(R.string.wifi_secured_first_item);
} else {
securityStrFormat = context.getString(R.string.wifi_secured_second_item);
}
summary.append(String.format(securityStrFormat, getSecurityString(true)));
}
if (mConfig == null && wpsAvailable) { // Only list WPS available for unsaved networks
if (summary.length() == 0) {
summary.append(context.getString(R.string.wifi_wps_available_first_item));
} else {
summary.append(context.getString(R.string.wifi_wps_available_second_item));
}
}
setSummary(summary.toString());
}
}
|
diff --git a/src/Model/trunk/SEG/src/model/LoadXMLFile.java b/src/Model/trunk/SEG/src/model/LoadXMLFile.java
index a43792c..49ca720 100644
--- a/src/Model/trunk/SEG/src/model/LoadXMLFile.java
+++ b/src/Model/trunk/SEG/src/model/LoadXMLFile.java
@@ -1,106 +1,106 @@
package model;
import javax.swing.JFileChooser;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.w3c.dom.Node;
import org.w3c.dom.Element;
import java.io.File;
import java.util.ArrayList;
public class LoadXMLFile {
File fXmlFile;
Airport arpt = null;
ArrayList<Runway> rways;
int index = 0; //used to iterate over rways
public LoadXMLFile() {
// this.loadFile();
}
public Airport loadFile() throws Exception {
rways = new ArrayList<Runway>();
JFileChooser fc = new JFileChooser();
XMLFileFilter ff = new XMLFileFilter();
fc.setFileFilter(ff);
int returnVal = fc.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
fXmlFile = fc.getSelectedFile();
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
String root = doc.getDocumentElement().getNodeName();
// can add an if statement here to make sure its the right kind of file
// Creating an Airport object using the name from the xml file
NodeList airportName = doc.getElementsByTagName("AirportName");
Node n = airportName.item(0);
Element e = (Element) n;
String an = e.getTextContent();
arpt = new Airport(an);
// System.out.println(arpt.getName());
NodeList nList = doc.getElementsByTagName("Runway");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
- String name = getTagValue("Name", eElement);
- int tora = Integer.parseInt(getTagValue("TORA", eElement));
- int asda = Integer.parseInt(getTagValue("ASDA", eElement));
- int toda = Integer.parseInt(getTagValue("TODA", eElement));
- int lda = Integer.parseInt(getTagValue("LDA", eElement));
- int dt = Integer.parseInt(getTagValue("DisplacedThreshold", eElement));
+ String name = getTagValue("RunwayName", eElement);
+ double tora = Double.parseDouble(getTagValue("TORA", eElement));//Integer.parseInt(getTagValue("TORA", eElement));
+ double asda = Double.parseDouble(getTagValue("ASDA", eElement));
+ double toda = Double.parseDouble(getTagValue("TODA", eElement));
+ double lda = Double.parseDouble(getTagValue("LDA", eElement));
+ double dt = Double.parseDouble(getTagValue("DisplacedThreshold", eElement));
Runway r = new Runway(name, tora, asda, toda, lda, dt);
rways.add(r);//arpt.addRunway(r);
}
}
NodeList physicalRun = doc.getElementsByTagName("PhysicalRunway");
for (int temp = 0; temp < physicalRun.getLength(); temp++){
Node nNode = physicalRun.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
- String name = getTagValue("RunwayName", eElement);
+ String name = getTagValue("Name", eElement);
PhysicalRunway pr = new PhysicalRunway(name, rways.get(index), rways.get(index+1));
arpt.addPhysicalRunway(pr);
index = index + 2;
}
}
} else {
System.out.println("Open command cancelled by user.");
}
return arpt;
}
private static String getTagValue(String sTag, Element eElement) {
NodeList nlList = eElement.getElementsByTagName(sTag).item(0)
.getChildNodes();
Node nValue = (Node) nlList.item(0);
return nValue.getNodeValue();
}
}
| false | true | public Airport loadFile() throws Exception {
rways = new ArrayList<Runway>();
JFileChooser fc = new JFileChooser();
XMLFileFilter ff = new XMLFileFilter();
fc.setFileFilter(ff);
int returnVal = fc.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
fXmlFile = fc.getSelectedFile();
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
String root = doc.getDocumentElement().getNodeName();
// can add an if statement here to make sure its the right kind of file
// Creating an Airport object using the name from the xml file
NodeList airportName = doc.getElementsByTagName("AirportName");
Node n = airportName.item(0);
Element e = (Element) n;
String an = e.getTextContent();
arpt = new Airport(an);
// System.out.println(arpt.getName());
NodeList nList = doc.getElementsByTagName("Runway");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
String name = getTagValue("Name", eElement);
int tora = Integer.parseInt(getTagValue("TORA", eElement));
int asda = Integer.parseInt(getTagValue("ASDA", eElement));
int toda = Integer.parseInt(getTagValue("TODA", eElement));
int lda = Integer.parseInt(getTagValue("LDA", eElement));
int dt = Integer.parseInt(getTagValue("DisplacedThreshold", eElement));
Runway r = new Runway(name, tora, asda, toda, lda, dt);
rways.add(r);//arpt.addRunway(r);
}
}
NodeList physicalRun = doc.getElementsByTagName("PhysicalRunway");
for (int temp = 0; temp < physicalRun.getLength(); temp++){
Node nNode = physicalRun.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
String name = getTagValue("RunwayName", eElement);
PhysicalRunway pr = new PhysicalRunway(name, rways.get(index), rways.get(index+1));
arpt.addPhysicalRunway(pr);
index = index + 2;
}
}
} else {
System.out.println("Open command cancelled by user.");
}
return arpt;
}
| public Airport loadFile() throws Exception {
rways = new ArrayList<Runway>();
JFileChooser fc = new JFileChooser();
XMLFileFilter ff = new XMLFileFilter();
fc.setFileFilter(ff);
int returnVal = fc.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
fXmlFile = fc.getSelectedFile();
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(fXmlFile);
doc.getDocumentElement().normalize();
String root = doc.getDocumentElement().getNodeName();
// can add an if statement here to make sure its the right kind of file
// Creating an Airport object using the name from the xml file
NodeList airportName = doc.getElementsByTagName("AirportName");
Node n = airportName.item(0);
Element e = (Element) n;
String an = e.getTextContent();
arpt = new Airport(an);
// System.out.println(arpt.getName());
NodeList nList = doc.getElementsByTagName("Runway");
for (int temp = 0; temp < nList.getLength(); temp++) {
Node nNode = nList.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
String name = getTagValue("RunwayName", eElement);
double tora = Double.parseDouble(getTagValue("TORA", eElement));//Integer.parseInt(getTagValue("TORA", eElement));
double asda = Double.parseDouble(getTagValue("ASDA", eElement));
double toda = Double.parseDouble(getTagValue("TODA", eElement));
double lda = Double.parseDouble(getTagValue("LDA", eElement));
double dt = Double.parseDouble(getTagValue("DisplacedThreshold", eElement));
Runway r = new Runway(name, tora, asda, toda, lda, dt);
rways.add(r);//arpt.addRunway(r);
}
}
NodeList physicalRun = doc.getElementsByTagName("PhysicalRunway");
for (int temp = 0; temp < physicalRun.getLength(); temp++){
Node nNode = physicalRun.item(temp);
if (nNode.getNodeType() == Node.ELEMENT_NODE) {
Element eElement = (Element) nNode;
String name = getTagValue("Name", eElement);
PhysicalRunway pr = new PhysicalRunway(name, rways.get(index), rways.get(index+1));
arpt.addPhysicalRunway(pr);
index = index + 2;
}
}
} else {
System.out.println("Open command cancelled by user.");
}
return arpt;
}
|
diff --git a/Osm2GpsMid/src/de/ueller/osmToGpsMid/RouteData.java b/Osm2GpsMid/src/de/ueller/osmToGpsMid/RouteData.java
index cea262ae..113cf99d 100644
--- a/Osm2GpsMid/src/de/ueller/osmToGpsMid/RouteData.java
+++ b/Osm2GpsMid/src/de/ueller/osmToGpsMid/RouteData.java
@@ -1,858 +1,857 @@
/**
* This file is part of OSM2GpsMid
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*
* Copyright (C) 2007 2008 Harald Mueller
*
*/
package de.ueller.osmToGpsMid;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintWriter;
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.Vector;
import de.ueller.osmToGpsMid.model.Connection;
import de.ueller.osmToGpsMid.model.Node;
import de.ueller.osmToGpsMid.model.RouteNode;
import de.ueller.osmToGpsMid.model.TravelMode;
import de.ueller.osmToGpsMid.model.TravelModes;
import de.ueller.osmToGpsMid.model.TurnRestriction;
import de.ueller.osmToGpsMid.model.Way;
import de.ueller.osmToGpsMid.model.WayDescription;
import de.ueller.osmToGpsMid.tools.FileTools;
/**
* @author hmueller
*
*/
public class RouteData {
private OsmParser parser;
private String path;
private Configuration config;
public Map<Long, RouteNode> nodes = new HashMap<Long, RouteNode>();
public RouteData(OsmParser parser, String path) {
super();
this.parser = parser;
this.path = path;
}
public void create(Configuration config) {
if (config.sourceIsApk) {
this.path = this.path + "/assets";
}
this.config = config;
// reset connectedLineCount for each Node to 0
for (Node n:parser.getNodes()) {
n.resetConnectedLineCount();
}
boolean neverTrafficSignalsRouteNode = false;
// count all connections for all nodes
for (Way w:parser.getWays()) {
if (! w.isAccessForAnyRouting()) {
continue;
}
// mark nodes in tunnels / on bridges / on motorways to not get later marked as traffic signal delay route node by nearby traffic signals
WayDescription wayDesc = config.getWayDesc(w.type);
neverTrafficSignalsRouteNode = (w.isBridge() || w.isTunnel() || (wayDesc.isMotorway() && !wayDesc.isHighwayLink()) );
Node lastNode = null;
for (Node n:w.getNodes()) {
n.incConnectedLineCount();
if (lastNode != null) {
n.incConnectedLineCount();
}
lastNode = n;
if (neverTrafficSignalsRouteNode) {
n.markAsNeverTrafficSignalsRouteNode();
//System.out.println("Mark to never become a traffic signal delay route node: " + n.toString());
}
}
if (lastNode != null) {
lastNode.decConnectedLineCount();
}
}
for (Way w:parser.getWays()) {
if (!w.isAccessForAnyRouting()) {
continue;
}
addConnections(w.getNodes(), w);
}
System.out.println("Created " + nodes.size() + " route nodes.");
createIds();
calculateTurnRestrictions();
}
/**
* calculate turn restrictions
*/
private void calculateTurnRestrictions() {
resolveViaWays();
System.out.println("info: Calculating turn restrictions");
int numTurnRestrictions = 0;
for (RouteNode n: nodes.values()) {
TurnRestriction turn = (TurnRestriction) parser.getTurnRestrictionHashMap().get(new Long(n.node.id));
while (turn != null) {
Way restrictionFromWay = parser.getWayHashMap().get(new Long(turn.fromWayRef));
// skip if restrictionFromWay is not in available wayData
if (restrictionFromWay == null) {
System.out.println(" no fromWay");
turn = turn.nextTurnRestrictionAtThisNode;
continue;
}
// skip if restrictionToWay is not in available wayData
Way restrictionToWay = parser.getWayHashMap().get(new Long(turn.toWayRef));
if (restrictionToWay == null) {
System.out.println(" no toWay");
turn = turn.nextTurnRestrictionAtThisNode;
continue;
}
turn.viaRouteNode = n;
turn.viaLat = n.node.lat;
turn.viaLon = n.node.lon;
turn.affectedTravelModes = TravelModes.applyTurnRestrictionsTravelModes;
// search the from way for the RouteNode connected to the viaWay
RouteNode nViaFrom = n;
if (turn.isViaTypeWay()) {
nViaFrom = turn.additionalViaRouteNodes[0];
}
//System.out.println(turn.toString(parser.getWayHashMap()));
int numFromConnections = 0;
long lastId = -1;
for (Connection c:nViaFrom.getConnectedFrom()) { // TODO: Strange: there are sometimes multiple connections connecting to the same node, filter those out by checking lastId
/* [ gpsmid-Bugs-3159017 ] Can't parse turn restriction
* rather than only checking if the restrictionFromWay contains the from node
* compare the travel length on the way between from node and via node
* with the connection length to make more sure this is the right connection
* with the via way
* FIXME: we need to check for the right connection with this workaround
* for not having to store the way in the connection, otherwise we could check for c.way == restrictionWay
*/
if (getDistOnWay(restrictionFromWay, nViaFrom.node, c.from.node) == c.length && c.from.id != lastId) {
turn.fromRouteNode = c.from;
numFromConnections++;
lastId = c.from.id;
}
}
if (numFromConnections != 1) {
if (restrictionFromWay.isAccessForRoutingInAnyTurnRestrictionTravelMode()) {
System.out.println("warning: ignoring map data: Can't parse turn restriction: " + numFromConnections + " from_connections matched for: " + turn.toString(parser.getWayHashMap()));
if (numFromConnections == 0) {
System.out.println("warning: ignoring map data: Reason may be: from/to swapped on oneways or a gap between viaNode and fromWay");
} else {
System.out.println("warning: ignoring map data: Reason may be: fromWay not split at via member");
turn.fromRouteNode = null; // make the turn restriction incomplete so it won't get passed to GpsMid
}
for (Connection c:nViaFrom.getConnectedFrom()) {
if (restrictionFromWay.containsNode(c.from.node)) {
System.out.println(" FromNode: " + c.from.node.id);
}
}
System.out.println("warning: ignoring map data: URL for via node: " + n.node.toUrl());
}
}
// search the RouteNode following the viaRouteNode on the toWay
int numToConnections = 0;
lastId = -1;
for (Connection c:n.getConnected()) {
/* FIXME: we do not store the way in the connection, otherwise we could check for c.way == restrictionWay */
if (getDistOnWay(restrictionToWay, n.node, c.to.node) == c.length && c.to.id != lastId) {
// TODO: Strange: there are sometimes multiple connections connecting to the same node, filter those out by checking lastId
turn.toRouteNode = c.to;
numToConnections++;
lastId = c.to.id;
}
}
if (numToConnections != 1) {
if (restrictionToWay.isAccessForRoutingInAnyTurnRestrictionTravelMode()) {
System.out.println("warning: ignoring map data: Can't parse turn restriction: " + numToConnections + " to_connections matched for: " + turn.toString(parser.getWayHashMap()));
if (numToConnections == 0) {
System.out.println("warning: ignoring map data: Reason may be: from/to swapped on oneways or a gap between viaNode and toWay");
} else {
System.out.println("warning: ignoring map data: Reason may be: toWay not split at via member");
turn.toRouteNode = null; // make the turn restriction incomplete so it won't get passed to GpsMid
}
for (Connection c:n.getConnected()) {
if (restrictionToWay.containsNode(c.to.node)) {
System.out.println("warning: ignoring map data: ToNode: " + c.to.node.id);
}
}
System.out.println("warning: ignoring map data: URL for via node: " + n.node.toUrl());
}
}
if (numFromConnections == 1 && numToConnections == 1) {
numTurnRestrictions++;
}
turn = turn.nextTurnRestrictionAtThisNode;
}
}
System.out.println("info: " + numTurnRestrictions + " turn restrictions valid");
}
/**
* Resolve viaWays to route nodes
*/
private void resolveViaWays() {
int numViaWaysResolved = 0;
System.out.println("info: Resolving " + parser.getTurnRestrictionsWithViaWays().size() + " viaWays for turn restrictions");
for (TurnRestriction turn: parser.getTurnRestrictionsWithViaWays()) {
Way restrictionFromWay = parser.getWayHashMap().get(new Long(turn.fromWayRef));
// skip if restrictionFromWay is not in available wayData
if (restrictionFromWay == null) {
continue;
}
// skip if restrictionToWay is not in available wayData
Way restrictionToWay = parser.getWayHashMap().get(new Long(turn.toWayRef));
if (restrictionToWay == null) {
continue;
}
// skip if restrictionViaWay is not in available wayData
Way restrictionViaWay = parser.getWayHashMap().get(new Long(turn.viaWayRef));
if (restrictionViaWay == null) {
continue;
}
ArrayList<RouteNode> viaWayRouteNodes = restrictionViaWay.getAllRouteNodesOnTheWay();
// if it's a circle way remove the first viaRouteNode
if (viaWayRouteNodes.size()>0 && viaWayRouteNodes.get(0).id == viaWayRouteNodes.get(viaWayRouteNodes.size() -1 ).id) {
viaWayRouteNodes.remove(0);
}
ArrayList<RouteNode> additionalViaRouteNodesCache = new ArrayList<RouteNode>();
int startEntry = 0;
// find the index of the element crossing the fromWay (start entry)
for (RouteNode n:viaWayRouteNodes) {
if (restrictionFromWay.containsNode(n.node)) { // this is where viaWay and fromWay are connected
additionalViaRouteNodesCache.add(n); // and becomes the first entry in the additionalViaRouteNode array
System.out.println("info: Resolved viaWay x fromWay to node " + n.node.id);
break;
}
startEntry++;
}
// find the index of the element crossing the toWay (the end entry)
int endEntry = 0;
RouteNode rn = null;
// the direction to fill in the remaining viaRouteNodes into the array so the result is ordered with route nodes from the fromWay to the toWay exclusively
int direction = 1;
for (int i = startEntry; i < viaWayRouteNodes.size() * 2; i++) {
// use index with modulo because of circle ways in roundabouts
rn = viaWayRouteNodes.get(i % viaWayRouteNodes.size());
if (restrictionToWay.containsNode(rn.node)) {
turn.viaRouteNode = rn;
endEntry = i % viaWayRouteNodes.size();
if (i == endEntry || restrictionViaWay.isOneWay()) {
direction = 1;
} else {
direction = -1;
}
System.out.println("info: Resolved viaWay x toWay to node " + rn.node.id);
break;
} else {
}
}
// fill in routeNodes between start and end entry
if (turn.viaRouteNode != null && additionalViaRouteNodesCache.size() != 0) {
// fill in the remaining viaRouteNodes into the array so the result is ordered with route nodes from the fromWay to the toWay exclusively
for (int i = startEntry + direction; i != startEntry && i % viaWayRouteNodes.size() != endEntry; i += direction) {
// use index with modulo because of circle ways in roundabouts
i %= viaWayRouteNodes.size();
// System.out.println(i + " " + startEntry + " " + endEntry + " dir " + direction );
rn = viaWayRouteNodes.get(i);
additionalViaRouteNodesCache.add(rn);
}
// transfer the route nodes from the ArrayList to the additionalViaRouteNodes array
turn.additionalViaRouteNodes = new RouteNode[additionalViaRouteNodesCache.size()];
for (int i=0; i < turn.additionalViaRouteNodes.length; i++) {
turn.additionalViaRouteNodes[i] = additionalViaRouteNodesCache.get(i);
}
System.out.println("info: viaRouteNodes on viaWay " + restrictionViaWay.toUrl() + ":");
for (RouteNode n:turn.additionalViaRouteNodes) {
if (n != null && n.node != null) {
System.out.println("info: " + n.node.toUrl());
} else {
if (n == null) {
System.out.println("info: n is null");
} else {
System.out.println("info: n.node is null");
}
continue;
}
}
System.out.println("info: " + turn.viaRouteNode.node.toUrl());
// add the resolved viaWay turn restriction to its viaRouteNode
parser.addTurnRestriction(new Long(turn.viaRouteNode.node.id), turn);
numViaWaysResolved++;
} else {
System.out.println(" WARNING: Could not resolve viaRouteNodes");
System.out.println(" for viaWay " + restrictionViaWay.toUrl());
if ( turn.additionalViaRouteNodes == null) {
System.out.println(" viaWay " + restrictionFromWay.toUrl() + " does not end at start of toWay");
} else if (turn.additionalViaRouteNodes[0] == null) {
System.out.println(" fromWay " + restrictionFromWay.toUrl() + " is not connected");
}
if (turn.viaRouteNode == null) {
System.out.println(" toWay " + restrictionToWay.toUrl() + " is not connected");
}
}
}
System.out.println(" " + numViaWaysResolved + " viaWays resolved");
parser.getTurnRestrictionsWithViaWays().clear();
}
/**
* @param w
* @param n1 - a node on the way
* @param n2 - another node on the way
* @return distance for travelling from n1 to n2 on w or -1 if no match
*/
private int getDistOnWay(Way w, Node n1, Node n2) {
boolean startNodeFound = false;
Node lastNode = null;
int dist = 0;
for (Node n:w.getNodes()) {
if (startNodeFound) {
dist += MyMath.dist(lastNode, n);
if (n.id == n1.id || n.id == n2.id) {
return dist;
}
}
if (n.id == n1.id || n.id == n2.id) {
// start measuring distance
startNodeFound = true;
}
lastNode = n;
}
return -1;
}
/**
* @param nl
*/
// TODO: explain
private void addConnections(List<Node> nl, Way w) {
RouteNode from = null;
int lastIndex = nl.size();
Node lastNode = null;
int thisIndex = 0;
int dist = 0;
int count = 0;
byte bearing = 0;
for (Node n:nl) {
thisIndex++;
if (from == null) {
lastNode = n;
from = getRouteNode(n);
count++;
dist = 0;
} else {
dist += MyMath.dist(lastNode, n);
count++;
if (count == 2) {
bearing = MyMath.bearing_start(lastNode, n);
}
if (thisIndex == lastIndex || (n.getConnectedLineCount() != 2)) {
RouteNode next = getRouteNode(n);
byte endBearing = MyMath.bearing_start(lastNode, n);
addConnection(from, next, dist, w, bearing, endBearing);
from = next;
dist = 0;
count = 1;
}
lastNode = n;
}
}
nl = new ArrayList<Node>();
}
/**
* @param l
*/
private RouteNode getRouteNode(Node n) {
RouteNode routeNode;
if (! nodes.containsKey(n.id)) {
routeNode = new RouteNode(n);
n.routeNode = routeNode;
} else {
routeNode = nodes.get(n.id);
}
return routeNode;
}
/**
* @param from
* @param f
* @param dist
* @param routeNode
*/
private void addConnection(RouteNode from, RouteNode to, int dist, Way w, byte bs, byte be) {
/** travel modes with no barrier detected */
int noBarrierTravelModes = 0xFFFFFFFF;
byte againstDirectionTravelModes = 0;
// create an array of routing times with an entry for each travel mode
int times[] = new int[TravelModes.travelModeCount];
for (int i = 0; i < TravelModes.travelModeCount; i++) {
if (w.isAccessForRouting(i)) {
/*
* Removing route connections because of barriers is disabled for now.
* It requires a solution first for too many POIs becoming unreachable
* because of barriers before the destination way
*/
- if (config.useBarriers) {
// check for barriers in non-area ways
-// if (!w.isArea()) {
+ if (config.useBarriers && !w.isArea()) {
int a = 0;
boolean fromNodeFound = false;
boolean toNodeFound = false;
for (Iterator<Node> si = w.path.iterator(); si.hasNext();) {
Node t = si.next();
if (from.node.id == t.id /* && a != 0 && si.hasNext() */) {
fromNodeFound = true;
}
if (to.node.id == t.id /* && a != 0 && si.hasNext() */) {
toNodeFound = true;
}
if (
(
(fromNodeFound && !toNodeFound)
||
(toNodeFound && !fromNodeFound)
)
&&
t.isBarrier()
) {
if (t.isAccessPermittedOrForbiddenFor(i) <= 0) {
// if (noBarrierTravelModes == 0xFFFFFFFF) {
// System.out.println("Barrier found on " + w.toString() + " at \n" + t.toUrl());
// }
// System.out.println(" affects route mode " + i);
noBarrierTravelModes &= ~(1 << i);
break;
}
}
a++;
}
}
TravelMode tm = TravelModes.getTravelMode(i);
if (w.isExplicitArea()) {
tm.numAreaCrossConnections++;
}
tm.numOneWayConnections++;
float speed = w.getRoutingSpeed(i);
float time = dist * 10.0f / speed;
times[i] = (int)time;
boolean bicycleOppositeDirection = (tm.travelModeFlags & TravelMode.BICYLE_OPPOSITE_EXCEPTIONS) > 0 && w.isOppositeDirectionForBicycleAllowed();
// you can go against the direction of the way if it's not a oneway or an against direction rule applies
if (
!w.isRoundabout() // FIXME: workaround to never route against direction in roundabouts, not even walk because we have no routing instruction for this
&&
(
! w.isOneWay()
||
(tm.travelModeFlags & TravelMode.AGAINST_ALL_ONEWAYS) > 0
||
bicycleOppositeDirection
)
) {
againstDirectionTravelModes |= (1<<i);
if (bicycleOppositeDirection) {
tm.numBicycleOppositeConnections++;
}
}
} else {
times[i] = 0;
}
}
boolean allBarriered = true;
for (int i = 0; i < TravelModes.travelModeCount; i++) {
if ( (noBarrierTravelModes & (1<<i)) > 0) {
allBarriered = false;
}
}
if (allBarriered) {
// System.out.println("Connection barriered for all route modes");
// avoid to create a connection that cannot be travelled in any route mode
return;
}
nodes.put(from.node.id, from);
nodes.put(to.node.id, to);
Connection c = new Connection(to, dist, times, bs, be, w);
c.connTravelModes &= noBarrierTravelModes; // disable connection for travelmodes that are barriered
from.addConnected(c);
to.addConnectedFrom(c);
// roundabouts don't need to be explicitly tagged as oneways in OSM according to http://wiki.openstreetmap.org/wiki/Tag:junction%3Droundabout
if (againstDirectionTravelModes != 0 ) {
// add connection in the other direction as well, if this is no oneWay
// TODO: explain Doesn't this add duplicates when addconnection() is called later on with from and to exchanged or does this not happen?
Connection cr = new Connection(from, dist, times, MyMath.inverseBearing(be),
MyMath.inverseBearing(bs), w);
cr.from = to;
to.addConnected(cr);
from.addConnectedFrom(cr);
// flag connections useable for travel modes you can go against the ways direction
cr.connTravelModes = againstDirectionTravelModes;
cr.connTravelModes &= noBarrierTravelModes; // disable connection for travelmodes that are barriered
cr.connTravelModes |= w.wayTravelModes & (Connection.CONNTYPE_MAINSTREET_NET | Connection.CONNTYPE_MOTORWAY | Connection.CONNTYPE_TRUNK_OR_PRIMARY);
for (int i=0; i < TravelModes.travelModeCount; i++) {
if ( (againstDirectionTravelModes & (1<<i)) != 0 ) {
TravelMode tm = TravelModes.getTravelMode(i);
tm.numDualConnections++;
tm.numOneWayConnections--;
}
}
}
// need only for debugging not for live
c.from = from;
}
@Deprecated
public boolean isRelevant(Node n) {
int count = 0;
// for (Line l:parser.lines.values()) {
// if (n.id == l.from.id) {
// count++;
// }
// if (n.id == l.to.id) {
// count++;
// }
// }
if (count == 2) {
return false;
} else {
return true;
}
}
private void createIds() {
int id = 1;
for (RouteNode n: nodes.values()) {
n.id = id++;
}
}
public void optimise() {
// System.out.println("Optimizing route data");
// System.out.println("RouteNodes for optimise " + nodes.size());
// ArrayList<RouteNode> removeNodes = new ArrayList<RouteNode>();
// for (RouteNode n:nodes.values()) {
// // find nodes that are only a point between to nodes without
// // any junction. This test does not cover one ways
// // for normal ways the second connection will removed
// if (n.connected.size() == 2 && n.connectedFrom.size() == 2) {
// Connection c1 = n.connected.get(0);
// RouteNode n1 = c1.to;
// Connection c2 = null;
// Connection c3 = n.connected.get(1);
// RouteNode n2 = c3.to;
// Connection c4 = null;
// for (Connection ct:n.connectedFrom) {
// if (ct.from == n2 ) {
// c2 = ct;
// }
// if (ct.from == n1) {
// c4 = ct;
// }
// }
// if (c2 != null && c4 != null) {
// if (c2.to != n) {
// System.out.println("c2.to != n");
// }
// if (c4.to != n) {
// System.out.println("c4.to != n");
// }
// if (c1.to != c4.from) {
// System.out.println("c1.to != c4.from");
// }
// if (c2.from != c3.to) {
// System.out.println("c2.from != c3.to");
// }
// c2.endBearing = c1.endBearing;
// c2.time += c1.time;
// c2.length += c1.length;
// c2.to = c1.to;
// c3.from = c1.to;
// c3.startBearing = MyMath.inversBearing(c1.endBearing);
// c3.time += c1.time;
// c3.length += c1.length;
// n1.connectedFrom.remove(c1);
// n1.connected.remove(c4);
// n1.connectedFrom.add(c2);
// n1.connected.add(c3);
// connections.remove(c1);
// connections.remove(c4);
// removeNodes.add(n);
// }
//
// }
// // for one ways
// if (n.connected.size() == 1 && n.connectedFrom.size() == 1) {
// Connection c1 = n.connected.get(0);
// RouteNode n1 = c1.to;
// Connection c2 = n.connectedFrom.get(0);
// RouteNode n2 = c2.from;
// if (n2 != n1) {
// c2.endBearing = c1.endBearing;
// c2.time += c1.time;
// c2.length += c1.length;
// c2.to = c1.to;
// n1.connectedFrom.remove(c1);
// n1.connectedFrom.add(c2);
// n.connected.remove(c1);
// n.connectedFrom.remove(c2);
// connections.remove(c1);
// removeNodes.add(n);
//
// }
// }
// }
// System.out.println("Removed " + removeNodes.size() + " RouteNodes due to optimization");
// for (RouteNode n:removeNodes) {
// n.node.routeNode = null;
// nodes.remove(n.node.id);
// }
}
/**
* normaly not used, only for test
* @param args
*/
public static void main(String[] args) {
try {
Configuration conf = new Configuration(args);
FileInputStream fr = new FileInputStream("/Massenspeicher/myStreetMap0.5.osm");
// FileInputStream fr = new FileInputStream("/Massenspeicher/planet-070725.osm");
OxParser parser = new OxParser(fr, conf);
System.out.println("Read nodes " + parser.getNodes().size());
System.out.println("Read ways " + parser.getNodes().size());
new CleanUpData(parser, conf);
RouteData rd = new RouteData(parser, "");
rd.create(conf);
int rid = 10000;
// for (RouteNode r:rd.nodes.values()) {
// r.node.renumberdId=rid++;
// }
rid = 1;
rd.optimise();
for (RouteNode r:rd.nodes.values()) {
r.node.renumberdId = rid++;
}
// rd.write("/Temp");
System.out.println("RelNodes contain " + rd.nodes.size());
//System.out.println("Connections contain " + rd.connections.size());
RouteNode start = rd.nodes.get(new Long(1955808));
System.out.println("Start " + start);
// RouteNode dest = rd.nodes.get(new Long(25844378));
// RouteNode dest = rd.nodes.get(new Long(33141402));
// RouteNode dest = rd.nodes.get(new Long(28380647));
// System.out.println("Destination " + dest);
// AStar2 astar = new AStar2();
// Vector<Connection> solve = astar.solve(start, dest);
// System.out.println("\n\nSolution:");
PrintWriter fo = new PrintWriter("/Massenspeicher/routetestErg.osm");
// exportResultOSM(fo, rd, solve);
fo = new PrintWriter("/Massenspeicher/routetestConnections.osm");
exportResultOSM(fo, rd, null);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
/**
* @param fo
* @param rd
* @param solve
*/
private static void exportResultOSM(PrintWriter fo, RouteData rd,
Vector<Connection> solve) {
fo.write("<?xml version='1.0' encoding='UTF-8'?>\n");
fo.write("<osm version='0.5' generator='JOSM'>\n");
for (RouteNode r:rd.nodes.values()) {
fo.write("<node id='" + r.node.renumberdId);
fo.write("' timestamp='2007-02-15 10:32:17' visible='true' lat='" + r.node.lat);
fo.write("' lon='" + r.node.lon + "'>\n");
fo.write(" <tag k='connectCount' v='" + r.node.getConnectedLineCount() + "'/>\n");
fo.write(" <tag k='connectTo' v='");
for (Connection c:r.getConnected()) {
fo.write("," + c.to.node.renumberdId);
}
fo.write("'/>\n");
fo.write(" <tag k='connectFrom' v='");
for (Connection c:r.getConnectedFrom()) {
fo.write("," + c.from.node.renumberdId);
}
fo.write("'/>\n");
fo.write("</node>\n");
}
int id = 1;
for (RouteNode r:rd.nodes.values()) {
for (Connection c:r.getConnected()) {
fo.write("<way id='" + id++ + "' timestamp='2007-02-14 23:41:43' visible='true' >\n");
fo.write(" <nd ref='" + c.from.node.renumberdId + "'/>\n");
fo.write(" <nd ref='" + c.to.node.renumberdId + "'/>\n");
fo.write(" <tag k='name' v='laenge=" + c.length + "' />\n");
System.out.println("RouteData.exportResultOSM(): only first route mode");
fo.write(" <tag k='time' v='" + c.times[0] + "' />\n");
fo.write(" <tag k='bs' v='" + c.startBearing * 2 + "' />\n");
fo.write(" <tag k='be' v='" + c.endBearing * 2 + "' />\n");
fo.write("</way>\n");
}
}
// RouteNode last = null;
// Connection lastCon = null;
// int lb = 0;
// if (solve != null) {
// for (Connection c:solve) {
// if (last == null) {
// last = c.to;
// lastCon = c;
// lb = c.endBearing;
// } else {
// System.out.println(c.printTurn(lastCon));
// fo.write("<segment id='" + id++ + "' timestamp='2007-02-14 23:41:43' visible='true' from='" +
// last.node.renumberdId
// + "' to='"
// + c.to.node.renumberdId
// + "'>\n");
// fo.write(" <tag k='length' v='" + c.length + "' />\n");
// fo.write(" <tag k='time' v='" + c.time + "' />\n");
// fo.write(" <tag k='bs' v='" + c.startBearing * 2 + "' />\n");
// fo.write(" <tag k='be' v='" + c.endBearing * 2 + "' />\n");
// fo.write("</segment>\n");
// last = c.to;
// lastCon = c;
// }
// }
// }
fo.write("</osm>");
fo.close();
}
/**
* @param zl
* @param fid
* @param nodes2
* @throws FileNotFoundException
*/
public void write(int zl, int fid, Collection<Node> nodes2) throws FileNotFoundException {
FileOutputStream fo = FileTools.createFileOutputStream(path + "/t" + zl +"/"+ fid + ".d");
DataOutputStream tds = new DataOutputStream(fo);
for (Node n: nodes2) {
if (nodes.containsKey(n.id)) {
RouteNode rn = nodes.get(n.id);
}
}
}
// /**
// * deprecated but still used by routeTiles
// * @param canonicalPath
// * @throws IOException
// */
// @Deprecated
// public void write(String canonicalPath) throws IOException {
// DataOutputStream nodeStream = new DataOutputStream(new FileOutputStream(canonicalPath + "/rn.d"));
// File f = new File(canonicalPath + "/rc");
// f.mkdir();
//// DataOutputStream connStream = new DataOutputStream(new FileOutputStream(canonicalPath + "/rc.d"));
// int[] connectionIndex = new int[nodes.size()];
// int i = 0;
// for (RouteNode rde : nodes.values()) {
// rde.node.renumberdId = i++;
// rde.id = rde.node.renumberdId;
// }
// i = 0;
// nodeStream.writeInt(nodes.size());
// for (RouteNode rde : nodes.values()) {
// connectionIndex[i++] = nodeStream.size();
// nodeStream.writeFloat(MyMath.degToRad(rde.node.lat));
// nodeStream.writeFloat(MyMath.degToRad(rde.node.lon));
// nodeStream.writeInt(rde.node.renumberdId);
// System.out.println("id=" + rde.node.renumberdId);
// nodeStream.writeByte(rde.connected.size());
// DataOutputStream connStream = new DataOutputStream(new FileOutputStream(canonicalPath + "/" + rde.node.renumberdId + ".d"));
// for (Connection c : rde.connected) {
// connStream.writeInt(c.to.node.renumberdId);
// System.out.println("RouteData.write(): only first route mode");
// connStream.writeShort((int) c.times[0]); // only first route mode
// connStream.writeShort((int) c.length);
// connStream.writeByte(c.startBearing);
// connStream.writeByte(c.endBearing);
// }
// connStream.close();
// }
//// System.out.println("size " + ro.size());
// nodeStream.close();
// DataOutputStream indexStream = new DataOutputStream(new FileOutputStream(canonicalPath + "/rd.idx"));
// for (int il : connectionIndex) {
// indexStream.write(il);
// }
// indexStream.close();
// }
/** Remember traffic signals nodes in own array so they can be removed by CleanupData
* (traffic signals nodes must not be marked as used because otherwise they are written to the midlet)
*/
public void rememberDelayingNodes() {
Node[] delayingNodes = new Node[parser.trafficSignalCount];
int i = 0;
for (Node n:parser.getNodes()) {
if (n.isTrafficSignals()) {
delayingNodes[i++] = n;
}
}
parser.setDelayingNodes(delayingNodes);
}
}
| false | true | private void addConnection(RouteNode from, RouteNode to, int dist, Way w, byte bs, byte be) {
/** travel modes with no barrier detected */
int noBarrierTravelModes = 0xFFFFFFFF;
byte againstDirectionTravelModes = 0;
// create an array of routing times with an entry for each travel mode
int times[] = new int[TravelModes.travelModeCount];
for (int i = 0; i < TravelModes.travelModeCount; i++) {
if (w.isAccessForRouting(i)) {
/*
* Removing route connections because of barriers is disabled for now.
* It requires a solution first for too many POIs becoming unreachable
* because of barriers before the destination way
*/
if (config.useBarriers) {
// check for barriers in non-area ways
// if (!w.isArea()) {
int a = 0;
boolean fromNodeFound = false;
boolean toNodeFound = false;
for (Iterator<Node> si = w.path.iterator(); si.hasNext();) {
Node t = si.next();
if (from.node.id == t.id /* && a != 0 && si.hasNext() */) {
fromNodeFound = true;
}
if (to.node.id == t.id /* && a != 0 && si.hasNext() */) {
toNodeFound = true;
}
if (
(
(fromNodeFound && !toNodeFound)
||
(toNodeFound && !fromNodeFound)
)
&&
t.isBarrier()
) {
if (t.isAccessPermittedOrForbiddenFor(i) <= 0) {
// if (noBarrierTravelModes == 0xFFFFFFFF) {
// System.out.println("Barrier found on " + w.toString() + " at \n" + t.toUrl());
// }
// System.out.println(" affects route mode " + i);
noBarrierTravelModes &= ~(1 << i);
break;
}
}
a++;
}
}
TravelMode tm = TravelModes.getTravelMode(i);
if (w.isExplicitArea()) {
tm.numAreaCrossConnections++;
}
tm.numOneWayConnections++;
float speed = w.getRoutingSpeed(i);
float time = dist * 10.0f / speed;
times[i] = (int)time;
boolean bicycleOppositeDirection = (tm.travelModeFlags & TravelMode.BICYLE_OPPOSITE_EXCEPTIONS) > 0 && w.isOppositeDirectionForBicycleAllowed();
// you can go against the direction of the way if it's not a oneway or an against direction rule applies
if (
!w.isRoundabout() // FIXME: workaround to never route against direction in roundabouts, not even walk because we have no routing instruction for this
&&
(
! w.isOneWay()
||
(tm.travelModeFlags & TravelMode.AGAINST_ALL_ONEWAYS) > 0
||
bicycleOppositeDirection
)
) {
againstDirectionTravelModes |= (1<<i);
if (bicycleOppositeDirection) {
tm.numBicycleOppositeConnections++;
}
}
} else {
times[i] = 0;
}
}
boolean allBarriered = true;
for (int i = 0; i < TravelModes.travelModeCount; i++) {
if ( (noBarrierTravelModes & (1<<i)) > 0) {
allBarriered = false;
}
}
if (allBarriered) {
// System.out.println("Connection barriered for all route modes");
// avoid to create a connection that cannot be travelled in any route mode
return;
}
nodes.put(from.node.id, from);
nodes.put(to.node.id, to);
Connection c = new Connection(to, dist, times, bs, be, w);
c.connTravelModes &= noBarrierTravelModes; // disable connection for travelmodes that are barriered
from.addConnected(c);
to.addConnectedFrom(c);
// roundabouts don't need to be explicitly tagged as oneways in OSM according to http://wiki.openstreetmap.org/wiki/Tag:junction%3Droundabout
if (againstDirectionTravelModes != 0 ) {
// add connection in the other direction as well, if this is no oneWay
// TODO: explain Doesn't this add duplicates when addconnection() is called later on with from and to exchanged or does this not happen?
Connection cr = new Connection(from, dist, times, MyMath.inverseBearing(be),
MyMath.inverseBearing(bs), w);
cr.from = to;
to.addConnected(cr);
from.addConnectedFrom(cr);
// flag connections useable for travel modes you can go against the ways direction
cr.connTravelModes = againstDirectionTravelModes;
cr.connTravelModes &= noBarrierTravelModes; // disable connection for travelmodes that are barriered
cr.connTravelModes |= w.wayTravelModes & (Connection.CONNTYPE_MAINSTREET_NET | Connection.CONNTYPE_MOTORWAY | Connection.CONNTYPE_TRUNK_OR_PRIMARY);
for (int i=0; i < TravelModes.travelModeCount; i++) {
if ( (againstDirectionTravelModes & (1<<i)) != 0 ) {
TravelMode tm = TravelModes.getTravelMode(i);
tm.numDualConnections++;
tm.numOneWayConnections--;
}
}
}
// need only for debugging not for live
c.from = from;
}
| private void addConnection(RouteNode from, RouteNode to, int dist, Way w, byte bs, byte be) {
/** travel modes with no barrier detected */
int noBarrierTravelModes = 0xFFFFFFFF;
byte againstDirectionTravelModes = 0;
// create an array of routing times with an entry for each travel mode
int times[] = new int[TravelModes.travelModeCount];
for (int i = 0; i < TravelModes.travelModeCount; i++) {
if (w.isAccessForRouting(i)) {
/*
* Removing route connections because of barriers is disabled for now.
* It requires a solution first for too many POIs becoming unreachable
* because of barriers before the destination way
*/
// check for barriers in non-area ways
if (config.useBarriers && !w.isArea()) {
int a = 0;
boolean fromNodeFound = false;
boolean toNodeFound = false;
for (Iterator<Node> si = w.path.iterator(); si.hasNext();) {
Node t = si.next();
if (from.node.id == t.id /* && a != 0 && si.hasNext() */) {
fromNodeFound = true;
}
if (to.node.id == t.id /* && a != 0 && si.hasNext() */) {
toNodeFound = true;
}
if (
(
(fromNodeFound && !toNodeFound)
||
(toNodeFound && !fromNodeFound)
)
&&
t.isBarrier()
) {
if (t.isAccessPermittedOrForbiddenFor(i) <= 0) {
// if (noBarrierTravelModes == 0xFFFFFFFF) {
// System.out.println("Barrier found on " + w.toString() + " at \n" + t.toUrl());
// }
// System.out.println(" affects route mode " + i);
noBarrierTravelModes &= ~(1 << i);
break;
}
}
a++;
}
}
TravelMode tm = TravelModes.getTravelMode(i);
if (w.isExplicitArea()) {
tm.numAreaCrossConnections++;
}
tm.numOneWayConnections++;
float speed = w.getRoutingSpeed(i);
float time = dist * 10.0f / speed;
times[i] = (int)time;
boolean bicycleOppositeDirection = (tm.travelModeFlags & TravelMode.BICYLE_OPPOSITE_EXCEPTIONS) > 0 && w.isOppositeDirectionForBicycleAllowed();
// you can go against the direction of the way if it's not a oneway or an against direction rule applies
if (
!w.isRoundabout() // FIXME: workaround to never route against direction in roundabouts, not even walk because we have no routing instruction for this
&&
(
! w.isOneWay()
||
(tm.travelModeFlags & TravelMode.AGAINST_ALL_ONEWAYS) > 0
||
bicycleOppositeDirection
)
) {
againstDirectionTravelModes |= (1<<i);
if (bicycleOppositeDirection) {
tm.numBicycleOppositeConnections++;
}
}
} else {
times[i] = 0;
}
}
boolean allBarriered = true;
for (int i = 0; i < TravelModes.travelModeCount; i++) {
if ( (noBarrierTravelModes & (1<<i)) > 0) {
allBarriered = false;
}
}
if (allBarriered) {
// System.out.println("Connection barriered for all route modes");
// avoid to create a connection that cannot be travelled in any route mode
return;
}
nodes.put(from.node.id, from);
nodes.put(to.node.id, to);
Connection c = new Connection(to, dist, times, bs, be, w);
c.connTravelModes &= noBarrierTravelModes; // disable connection for travelmodes that are barriered
from.addConnected(c);
to.addConnectedFrom(c);
// roundabouts don't need to be explicitly tagged as oneways in OSM according to http://wiki.openstreetmap.org/wiki/Tag:junction%3Droundabout
if (againstDirectionTravelModes != 0 ) {
// add connection in the other direction as well, if this is no oneWay
// TODO: explain Doesn't this add duplicates when addconnection() is called later on with from and to exchanged or does this not happen?
Connection cr = new Connection(from, dist, times, MyMath.inverseBearing(be),
MyMath.inverseBearing(bs), w);
cr.from = to;
to.addConnected(cr);
from.addConnectedFrom(cr);
// flag connections useable for travel modes you can go against the ways direction
cr.connTravelModes = againstDirectionTravelModes;
cr.connTravelModes &= noBarrierTravelModes; // disable connection for travelmodes that are barriered
cr.connTravelModes |= w.wayTravelModes & (Connection.CONNTYPE_MAINSTREET_NET | Connection.CONNTYPE_MOTORWAY | Connection.CONNTYPE_TRUNK_OR_PRIMARY);
for (int i=0; i < TravelModes.travelModeCount; i++) {
if ( (againstDirectionTravelModes & (1<<i)) != 0 ) {
TravelMode tm = TravelModes.getTravelMode(i);
tm.numDualConnections++;
tm.numOneWayConnections--;
}
}
}
// need only for debugging not for live
c.from = from;
}
|
diff --git a/testSrc/main/MainTest2.java b/testSrc/main/MainTest2.java
index 338114e..f745ae7 100644
--- a/testSrc/main/MainTest2.java
+++ b/testSrc/main/MainTest2.java
@@ -1,22 +1,22 @@
package main;
import org.testng.annotations.Test;
import java.util.Random;
@Test
public class MainTest2 extends BaseTestCase {
public void test_success() {
assertEquals(1, 1);
}
public void test_failure() {
fail();
- // comment
+ // comment2
}
@Test(invocationCount = 10)
public void test_random() {
assertTrue(new Random().nextBoolean());
}
}
| true | true | public void test_failure() {
fail();
// comment
}
| public void test_failure() {
fail();
// comment2
}
|
diff --git a/gui/src/main/java/org/jboss/as/console/client/shared/subsys/logging/LoggingView.java b/gui/src/main/java/org/jboss/as/console/client/shared/subsys/logging/LoggingView.java
index 5842743f..6a534c4f 100644
--- a/gui/src/main/java/org/jboss/as/console/client/shared/subsys/logging/LoggingView.java
+++ b/gui/src/main/java/org/jboss/as/console/client/shared/subsys/logging/LoggingView.java
@@ -1,142 +1,143 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2011 Red Hat Inc. and/or its affiliates and other contributors
* as indicated by the @author tags. All rights reserved.
* See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU Lesser General Public License, v. 2.1.
* This program is distributed in the hope that it will be useful, but WITHOUT A
* 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,
* v.2.1 along with this distribution; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
package org.jboss.as.console.client.shared.subsys.logging;
import com.google.gwt.dom.client.Style;
import com.google.gwt.user.client.ui.DeckPanel;
import com.google.gwt.user.client.ui.TabLayoutPanel;
import com.google.gwt.user.client.ui.Widget;
import org.jboss.as.console.client.Console;
import org.jboss.as.console.client.core.SuspendableViewImpl;
import org.jboss.as.console.client.shared.dispatch.DispatchAsync;
import org.jboss.as.console.client.widgets.forms.ApplicationMetaData;
import javax.inject.Inject;
/**
* Main view class for the Logging subsystem.
*
* @author Stan Silvert
*/
public class LoggingView extends SuspendableViewImpl implements LoggingPresenter.MyView {
private DispatchAsync dispatcher;
private RootLoggerSubview rootLoggerSubview;
private LoggerSubview loggerSubview;
private ConsoleHandlerSubview consoleHandlerSubview;
private FileHandlerSubview fileHandlerSubview;
private PeriodicRotatingFileHandlerSubview periodicRotatingFileHandlerSubview;
private SizeRotatingFileHandlerSubview sizeRotatingFileHandlerSubview;
private AsyncHandlerSubview asyncHandlerSubview;
private CustomHandlerSubview customHandlerSubview;
private DeckPanel deck;
private int page = 0;
@Inject
public LoggingView(ApplicationMetaData applicationMetaData, DispatchAsync dispatcher, HandlerListManager handlerListManager) {
this.dispatcher = dispatcher;
rootLoggerSubview = new RootLoggerSubview(applicationMetaData, dispatcher);
loggerSubview = new LoggerSubview(applicationMetaData, dispatcher);
consoleHandlerSubview = new ConsoleHandlerSubview(applicationMetaData, dispatcher, handlerListManager);
fileHandlerSubview = new FileHandlerSubview(applicationMetaData, dispatcher, handlerListManager);
periodicRotatingFileHandlerSubview = new PeriodicRotatingFileHandlerSubview(applicationMetaData, dispatcher, handlerListManager);
sizeRotatingFileHandlerSubview = new SizeRotatingFileHandlerSubview(applicationMetaData, dispatcher, handlerListManager);
asyncHandlerSubview = new AsyncHandlerSubview(applicationMetaData, dispatcher, handlerListManager);
customHandlerSubview = new CustomHandlerSubview(applicationMetaData, dispatcher, handlerListManager);
handlerListManager.addHandlerConsumers(rootLoggerSubview, loggerSubview, asyncHandlerSubview);
handlerListManager.addHandlerProducers(consoleHandlerSubview,
fileHandlerSubview,
periodicRotatingFileHandlerSubview,
sizeRotatingFileHandlerSubview,
asyncHandlerSubview,
customHandlerSubview);
}
@Override
public Widget createWidget() {
deck = new DeckPanel();
deck.setStyleName("fill-layout");
TabLayoutPanel loggersTabs = new TabLayoutPanel(25, Style.Unit.PX);
loggersTabs.addStyleName("default-tabpanel");
loggersTabs.add(rootLoggerSubview.asWidget(), rootLoggerSubview.getEntityDisplayName());
loggersTabs.add(loggerSubview.asWidget(), loggerSubview.getEntityDisplayName());
loggersTabs.selectTab(0);
TabLayoutPanel handlersTabs = new TabLayoutPanel(25, Style.Unit.PX);
handlersTabs.addStyleName("default-tabpanel");
handlersTabs.add(consoleHandlerSubview.asWidget(), Console.CONSTANTS.subsys_logging_console());
handlersTabs.add(fileHandlerSubview.asWidget(), Console.CONSTANTS.subsys_logging_file());
handlersTabs.add(periodicRotatingFileHandlerSubview.asWidget(), Console.CONSTANTS.subsys_logging_periodic());
handlersTabs.add(sizeRotatingFileHandlerSubview.asWidget(), Console.CONSTANTS.subsys_logging_size());
handlersTabs.add(asyncHandlerSubview.asWidget(), Console.CONSTANTS.subsys_logging_async());
handlersTabs.add(customHandlerSubview.asWidget(), Console.CONSTANTS.subsys_logging_custom());
handlersTabs.selectTab(0);
deck.add(loggersTabs);
deck.add(handlersTabs);
// default
deck.showWidget(page);
LoggingLevelProducer.setLogLevels(
dispatcher, rootLoggerSubview,
+ consoleHandlerSubview,
loggerSubview,
fileHandlerSubview,
periodicRotatingFileHandlerSubview,
sizeRotatingFileHandlerSubview,
asyncHandlerSubview,
customHandlerSubview
);
return deck;
}
public void initialLoad() {
rootLoggerSubview.initialLoad();
loggerSubview.initialLoad();
consoleHandlerSubview.initialLoad();
fileHandlerSubview.initialLoad();
periodicRotatingFileHandlerSubview.initialLoad();
sizeRotatingFileHandlerSubview.initialLoad();
asyncHandlerSubview.initialLoad();
customHandlerSubview.initialLoad();
}
@Override
public void setPage(int page) {
if(deck!=null)
deck.showWidget(page);
this.page = page;
}
}
| true | true | public Widget createWidget() {
deck = new DeckPanel();
deck.setStyleName("fill-layout");
TabLayoutPanel loggersTabs = new TabLayoutPanel(25, Style.Unit.PX);
loggersTabs.addStyleName("default-tabpanel");
loggersTabs.add(rootLoggerSubview.asWidget(), rootLoggerSubview.getEntityDisplayName());
loggersTabs.add(loggerSubview.asWidget(), loggerSubview.getEntityDisplayName());
loggersTabs.selectTab(0);
TabLayoutPanel handlersTabs = new TabLayoutPanel(25, Style.Unit.PX);
handlersTabs.addStyleName("default-tabpanel");
handlersTabs.add(consoleHandlerSubview.asWidget(), Console.CONSTANTS.subsys_logging_console());
handlersTabs.add(fileHandlerSubview.asWidget(), Console.CONSTANTS.subsys_logging_file());
handlersTabs.add(periodicRotatingFileHandlerSubview.asWidget(), Console.CONSTANTS.subsys_logging_periodic());
handlersTabs.add(sizeRotatingFileHandlerSubview.asWidget(), Console.CONSTANTS.subsys_logging_size());
handlersTabs.add(asyncHandlerSubview.asWidget(), Console.CONSTANTS.subsys_logging_async());
handlersTabs.add(customHandlerSubview.asWidget(), Console.CONSTANTS.subsys_logging_custom());
handlersTabs.selectTab(0);
deck.add(loggersTabs);
deck.add(handlersTabs);
// default
deck.showWidget(page);
LoggingLevelProducer.setLogLevels(
dispatcher, rootLoggerSubview,
loggerSubview,
fileHandlerSubview,
periodicRotatingFileHandlerSubview,
sizeRotatingFileHandlerSubview,
asyncHandlerSubview,
customHandlerSubview
);
return deck;
}
| public Widget createWidget() {
deck = new DeckPanel();
deck.setStyleName("fill-layout");
TabLayoutPanel loggersTabs = new TabLayoutPanel(25, Style.Unit.PX);
loggersTabs.addStyleName("default-tabpanel");
loggersTabs.add(rootLoggerSubview.asWidget(), rootLoggerSubview.getEntityDisplayName());
loggersTabs.add(loggerSubview.asWidget(), loggerSubview.getEntityDisplayName());
loggersTabs.selectTab(0);
TabLayoutPanel handlersTabs = new TabLayoutPanel(25, Style.Unit.PX);
handlersTabs.addStyleName("default-tabpanel");
handlersTabs.add(consoleHandlerSubview.asWidget(), Console.CONSTANTS.subsys_logging_console());
handlersTabs.add(fileHandlerSubview.asWidget(), Console.CONSTANTS.subsys_logging_file());
handlersTabs.add(periodicRotatingFileHandlerSubview.asWidget(), Console.CONSTANTS.subsys_logging_periodic());
handlersTabs.add(sizeRotatingFileHandlerSubview.asWidget(), Console.CONSTANTS.subsys_logging_size());
handlersTabs.add(asyncHandlerSubview.asWidget(), Console.CONSTANTS.subsys_logging_async());
handlersTabs.add(customHandlerSubview.asWidget(), Console.CONSTANTS.subsys_logging_custom());
handlersTabs.selectTab(0);
deck.add(loggersTabs);
deck.add(handlersTabs);
// default
deck.showWidget(page);
LoggingLevelProducer.setLogLevels(
dispatcher, rootLoggerSubview,
consoleHandlerSubview,
loggerSubview,
fileHandlerSubview,
periodicRotatingFileHandlerSubview,
sizeRotatingFileHandlerSubview,
asyncHandlerSubview,
customHandlerSubview
);
return deck;
}
|
diff --git a/src/com/voet/datasetcreator/DatasetCreatorView.java b/src/com/voet/datasetcreator/DatasetCreatorView.java
index e9ddf1f..5051e6f 100755
--- a/src/com/voet/datasetcreator/DatasetCreatorView.java
+++ b/src/com/voet/datasetcreator/DatasetCreatorView.java
@@ -1,485 +1,486 @@
/*
* DatasetCreatorView.java
*/
package com.voet.datasetcreator;
import com.voet.datasetcreator.util.ConnectionStringUtil;
import com.voet.datasetcreator.util.Tuple;
import org.jdesktop.application.Action;
import org.jdesktop.application.ResourceMap;
import org.jdesktop.application.SingleFrameApplication;
import org.jdesktop.application.FrameView;
import org.jdesktop.application.TaskMonitor;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
import javax.swing.Icon;
import javax.swing.JDialog;
import javax.swing.JFrame;
/**
* The application's main frame.
*/
public class DatasetCreatorView extends FrameView {
public DatasetCreatorView( SingleFrameApplication app ) {
super( app );
initComponents();
// hide the panels upon initial load
pnlConnInfo.setVisible( false );
pnlTableNames.setVisible( false );
// scrlPnlTableNames.setVisible( false );
// status bar initialization - message timeout, idle icon and busy animation, etc
ResourceMap resourceMap = getResourceMap();
int messageTimeout = resourceMap.getInteger( "StatusBar.messageTimeout" );
messageTimer = new Timer( messageTimeout, new ActionListener() {
public void actionPerformed( ActionEvent e ) {
statusMessageLabel.setText( "" );
}
} );
messageTimer.setRepeats( false );
int busyAnimationRate = resourceMap.getInteger( "StatusBar.busyAnimationRate" );
for ( int i = 0; i < busyIcons.length; i++ ) {
busyIcons[i] = resourceMap.getIcon( "StatusBar.busyIcons[" + i + "]" );
}
busyIconTimer = new Timer( busyAnimationRate, new ActionListener() {
public void actionPerformed( ActionEvent e ) {
busyIconIndex = ( busyIconIndex + 1 ) % busyIcons.length;
statusAnimationLabel.setIcon( busyIcons[busyIconIndex] );
}
} );
idleIcon = resourceMap.getIcon( "StatusBar.idleIcon" );
statusAnimationLabel.setIcon( idleIcon );
progressBar.setVisible( false );
// connecting action tasks to status bar via TaskMonitor
TaskMonitor taskMonitor = new TaskMonitor( getApplication().getContext() );
taskMonitor.addPropertyChangeListener( new java.beans.PropertyChangeListener() {
public void propertyChange( java.beans.PropertyChangeEvent evt ) {
String propertyName = evt.getPropertyName();
if ( "started".equals( propertyName ) ) {
if ( !busyIconTimer.isRunning() ) {
statusAnimationLabel.setIcon( busyIcons[0] );
busyIconIndex = 0;
busyIconTimer.start();
}
progressBar.setVisible( true );
progressBar.setIndeterminate( true );
} else if ( "done".equals( propertyName ) ) {
busyIconTimer.stop();
statusAnimationLabel.setIcon( idleIcon );
progressBar.setVisible( false );
progressBar.setValue( 0 );
} else if ( "message".equals( propertyName ) ) {
String text = (String) ( evt.getNewValue() );
statusMessageLabel.setText( ( text == null ) ? "" : text );
messageTimer.restart();
} else if ( "progress".equals( propertyName ) ) {
int value = (Integer) ( evt.getNewValue() );
progressBar.setVisible( true );
progressBar.setIndeterminate( false );
progressBar.setValue( value );
}
}
} );
}
@Action
public void showAboutBox() {
if ( aboutBox == null ) {
JFrame mainFrame = DatasetCreatorApp.getApplication().getMainFrame();
aboutBox = new DatasetCreatorAboutBox( mainFrame );
aboutBox.setLocationRelativeTo( mainFrame );
}
DatasetCreatorApp.getApplication().show( aboutBox );
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings( "unchecked" )
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
mainPanel = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
cboDrivers = new javax.swing.JComboBox();
pnlConnInfo = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
txtHost = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
txtDbName = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
txtPort = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
txtUsername = new javax.swing.JTextField();
jLabel6 = new javax.swing.JLabel();
txtPassword = new javax.swing.JTextField();
btnGetTableList = new javax.swing.JButton();
jLabel7 = new javax.swing.JLabel();
txtConnString = new javax.swing.JTextField();
btnConnString = new javax.swing.JButton();
pnlTableNames = new javax.swing.JPanel();
scrlPnlTableNames = new javax.swing.JScrollPane();
tblTableNames = new javax.swing.JTable();
jPanel1 = new javax.swing.JPanel();
menuBar = new javax.swing.JMenuBar();
javax.swing.JMenu fileMenu = new javax.swing.JMenu();
javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
javax.swing.JMenu helpMenu = new javax.swing.JMenu();
javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
statusPanel = new javax.swing.JPanel();
javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
statusMessageLabel = new javax.swing.JLabel();
statusAnimationLabel = new javax.swing.JLabel();
progressBar = new javax.swing.JProgressBar();
mainPanel.setName("mainPanel"); // NOI18N
mainPanel.setPreferredSize(new java.awt.Dimension(570, 600));
org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(com.voet.datasetcreator.DatasetCreatorApp.class).getContext().getResourceMap(DatasetCreatorView.class);
jLabel1.setText(resourceMap.getString("lbl_drivers.text")); // NOI18N
jLabel1.setName("lbl_drivers"); // NOI18N
cboDrivers.setModel(DatasetCreatorApp.getDriverList());
cboDrivers.setName("cboDrivers"); // NOI18N
cboDrivers.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
driverSelectionChanged(evt);
}
});
pnlConnInfo.setBorder(javax.swing.BorderFactory.createEtchedBorder());
pnlConnInfo.setToolTipText(resourceMap.getString("pnlConnInfo.toolTipText")); // NOI18N
pnlConnInfo.setName("pnlConnInfo"); // NOI18N
jLabel2.setText(resourceMap.getString("lblHostName.text")); // NOI18N
jLabel2.setName("lblHostName"); // NOI18N
txtHost.setText(resourceMap.getString("txtHost.text")); // NOI18N
txtHost.setName("txtHost"); // NOI18N
jLabel3.setText(resourceMap.getString("lblDbName.text")); // NOI18N
jLabel3.setName("lblDbName"); // NOI18N
txtDbName.setText(resourceMap.getString("txtDbName.text")); // NOI18N
txtDbName.setName("txtDbName"); // NOI18N
jLabel4.setText(resourceMap.getString("lblHost.text")); // NOI18N
jLabel4.setName("lblHost"); // NOI18N
txtPort.setText(resourceMap.getString("txtPort.text")); // NOI18N
txtPort.setName("txtPort"); // NOI18N
jLabel5.setText(resourceMap.getString("lblUsername.text")); // NOI18N
jLabel5.setName("lblUsername"); // NOI18N
txtUsername.setText(resourceMap.getString("txtUsername.text")); // NOI18N
txtUsername.setName("txtUsername"); // NOI18N
jLabel6.setText(resourceMap.getString("lblUsername.text")); // NOI18N
jLabel6.setName("lblUsername"); // NOI18N
txtPassword.setText(resourceMap.getString("txtPassword.text")); // NOI18N
txtPassword.setName("txtPassword"); // NOI18N
btnGetTableList.setText(resourceMap.getString("btnListTableNames.text")); // NOI18N
btnGetTableList.setName("btnListTableNames"); // NOI18N
btnGetTableList.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnListTableNames(evt);
}
});
jLabel7.setText(resourceMap.getString("lblConnString.text")); // NOI18N
jLabel7.setName("lblConnString"); // NOI18N
txtConnString.setText(resourceMap.getString("txtConnString.text")); // NOI18N
txtConnString.setName("txtConnString"); // NOI18N
btnConnString.setText(resourceMap.getString("btnConnString.text")); // NOI18N
btnConnString.setName("btnConnString"); // NOI18N
btnConnString.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buildConnectionStringHandler(evt);
}
});
javax.swing.GroupLayout pnlConnInfoLayout = new javax.swing.GroupLayout(pnlConnInfo);
pnlConnInfo.setLayout(pnlConnInfoLayout);
pnlConnInfoLayout.setHorizontalGroup(
pnlConnInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlConnInfoLayout.createSequentialGroup()
.addContainerGap()
.addGroup(pnlConnInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel6)
.addGroup(pnlConnInfoLayout.createSequentialGroup()
.addGroup(pnlConnInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3)
.addComponent(jLabel5)
.addComponent(jLabel7)
.addComponent(jLabel2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(pnlConnInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtHost, javax.swing.GroupLayout.PREFERRED_SIZE, 216, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtConnString, javax.swing.GroupLayout.DEFAULT_SIZE, 216, Short.MAX_VALUE)
.addComponent(txtUsername, javax.swing.GroupLayout.DEFAULT_SIZE, 216, Short.MAX_VALUE)
.addComponent(txtDbName, javax.swing.GroupLayout.DEFAULT_SIZE, 216, Short.MAX_VALUE)
.addComponent(txtPassword, javax.swing.GroupLayout.DEFAULT_SIZE, 216, Short.MAX_VALUE))))
.addGap(18, 18, 18)
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(pnlConnInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtPort, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnGetTableList)
.addComponent(btnConnString))
.addGap(41, 41, 41))
);
pnlConnInfoLayout.setVerticalGroup(
pnlConnInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlConnInfoLayout.createSequentialGroup()
.addGroup(pnlConnInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(txtPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtHost, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(pnlConnInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(pnlConnInfoLayout.createSequentialGroup()
.addGroup(pnlConnInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(txtDbName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(pnlConnInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(txtUsername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(pnlConnInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6)
.addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(btnConnString))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(pnlConnInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel7)
.addComponent(btnGetTableList)
.addComponent(txtConnString, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(19, Short.MAX_VALUE))
);
pnlTableNames.setBorder(javax.swing.BorderFactory.createEtchedBorder());
pnlTableNames.setName("pnlTableNames"); // NOI18N
+ pnlTableNames.setPreferredSize(new java.awt.Dimension(315, 300));
scrlPnlTableNames.setName("scrlPnlTableNames"); // NOI18N
tblTableNames.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null},
{null, null},
{null, null},
{null, null}
},
new String [] {
"Title 1", "Title 2"
}
));
tblTableNames.setName("tblTableNames"); // NOI18N
scrlPnlTableNames.setViewportView(tblTableNames);
javax.swing.GroupLayout pnlTableNamesLayout = new javax.swing.GroupLayout(pnlTableNames);
pnlTableNames.setLayout(pnlTableNamesLayout);
pnlTableNamesLayout.setHorizontalGroup(
pnlTableNamesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
- .addGap(0, 296, Short.MAX_VALUE)
+ .addGap(0, 311, Short.MAX_VALUE)
.addGroup(pnlTableNamesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlTableNamesLayout.createSequentialGroup()
- .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
+ .addContainerGap(13, Short.MAX_VALUE)
.addComponent(scrlPnlTableNames, javax.swing.GroupLayout.PREFERRED_SIZE, 284, javax.swing.GroupLayout.PREFERRED_SIZE)
- .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
+ .addContainerGap(14, Short.MAX_VALUE)))
);
pnlTableNamesLayout.setVerticalGroup(
pnlTableNamesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
- .addGap(0, 445, Short.MAX_VALUE)
+ .addGap(0, 296, Short.MAX_VALUE)
.addGroup(pnlTableNamesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlTableNamesLayout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
- .addComponent(scrlPnlTableNames, javax.swing.GroupLayout.DEFAULT_SIZE, 423, Short.MAX_VALUE)
+ .addComponent(scrlPnlTableNames, javax.swing.GroupLayout.DEFAULT_SIZE, 272, Short.MAX_VALUE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
);
jPanel1.setName("jPanel1"); // NOI18N
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
- .addGap(0, 240, Short.MAX_VALUE)
+ .addGap(0, 314, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 430, Short.MAX_VALUE)
);
javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
mainPanel.setLayout(mainPanelLayout);
mainPanelLayout.setHorizontalGroup(
mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(mainPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(mainPanelLayout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addComponent(cboDrivers, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
- .addContainerGap(569, Short.MAX_VALUE))
+ .addContainerGap(595, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, mainPanelLayout.createSequentialGroup()
- .addComponent(pnlTableNames, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE)
- .addGap(27, 27, 27)
+ .addComponent(pnlTableNames, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addGap(18, 18, 18)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addComponent(pnlConnInfo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(142, 142, 142))))
);
mainPanelLayout.setVerticalGroup(
mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(mainPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(cboDrivers, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(1, 1, 1)
.addComponent(pnlConnInfo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
- .addComponent(pnlTableNames, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
- .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
+ .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
+ .addComponent(pnlTableNames, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
menuBar.setName("menuBar"); // NOI18N
fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
fileMenu.setName("fileMenu"); // NOI18N
javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(com.voet.datasetcreator.DatasetCreatorApp.class).getContext().getActionMap(DatasetCreatorView.class, this);
exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
exitMenuItem.setName("exitMenuItem"); // NOI18N
fileMenu.add(exitMenuItem);
menuBar.add(fileMenu);
helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
helpMenu.setName("helpMenu"); // NOI18N
aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
aboutMenuItem.setName("aboutMenuItem"); // NOI18N
helpMenu.add(aboutMenuItem);
menuBar.add(helpMenu);
statusPanel.setName("statusPanel"); // NOI18N
statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N
statusMessageLabel.setName("statusMessageLabel"); // NOI18N
statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N
progressBar.setName("progressBar"); // NOI18N
javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
statusPanel.setLayout(statusPanelLayout);
statusPanelLayout.setHorizontalGroup(
statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
- .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 705, Short.MAX_VALUE)
+ .addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 772, Short.MAX_VALUE)
.addGroup(statusPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(statusMessageLabel)
- .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 535, Short.MAX_VALUE)
+ .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 590, Short.MAX_VALUE)
.addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(statusAnimationLabel)
.addContainerGap())
);
statusPanelLayout.setVerticalGroup(
statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(statusPanelLayout.createSequentialGroup()
.addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(statusMessageLabel)
.addComponent(statusAnimationLabel)
.addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(3, 3, 3))
);
setComponent(mainPanel);
setMenuBar(menuBar);
setStatusBar(statusPanel);
}// </editor-fold>//GEN-END:initComponents
private void driverSelectionChanged(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_driverSelectionChanged
Tuple<String, String> choice = (Tuple<String, String>) cboDrivers.getSelectedItem();
if ( choice.getFirst() == null || choice.getFirst().trim().length() == 0 ) {
pnlConnInfo.setVisible( false );
scrlPnlTableNames.setVisible( false );
} else {
pnlConnInfo.setVisible( true );
}
}//GEN-LAST:event_driverSelectionChanged
private void btnListTableNames(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnListTableNames
pnlTableNames.setVisible( true );
// scrlPnlTableNames.setVisible( true );
}//GEN-LAST:event_btnListTableNames
private void buildConnectionStringHandler(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buildConnectionStringHandler
Tuple<String, String> cboItem = (Tuple<String, String>) cboDrivers.getSelectedItem();
String connectionString = ConnectionStringUtil.getConnectionString( txtHost.getText(), txtPort.getText(), cboItem.getFirst(), txtDbName.getText(), txtUsername.getText(), txtPassword.getText() );
txtConnString.setText( connectionString );
}//GEN-LAST:event_buildConnectionStringHandler
// Variables declaration - do not modify//GEN-BEGIN:variables
private javax.swing.JButton btnConnString;
private javax.swing.JButton btnGetTableList;
private javax.swing.JComboBox cboDrivers;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel4;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
private javax.swing.JLabel jLabel7;
private javax.swing.JPanel jPanel1;
private javax.swing.JPanel mainPanel;
private javax.swing.JMenuBar menuBar;
private javax.swing.JPanel pnlConnInfo;
private javax.swing.JPanel pnlTableNames;
private javax.swing.JProgressBar progressBar;
private javax.swing.JScrollPane scrlPnlTableNames;
private javax.swing.JLabel statusAnimationLabel;
private javax.swing.JLabel statusMessageLabel;
private javax.swing.JPanel statusPanel;
private javax.swing.JTable tblTableNames;
private javax.swing.JTextField txtConnString;
private javax.swing.JTextField txtDbName;
private javax.swing.JTextField txtHost;
private javax.swing.JTextField txtPassword;
private javax.swing.JTextField txtPort;
private javax.swing.JTextField txtUsername;
// End of variables declaration//GEN-END:variables
private final Timer messageTimer;
private final Timer busyIconTimer;
private final Icon idleIcon;
private final Icon[] busyIcons = new Icon[15];
private int busyIconIndex = 0;
private JDialog aboutBox;
}
| false | true | private void initComponents() {
mainPanel = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
cboDrivers = new javax.swing.JComboBox();
pnlConnInfo = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
txtHost = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
txtDbName = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
txtPort = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
txtUsername = new javax.swing.JTextField();
jLabel6 = new javax.swing.JLabel();
txtPassword = new javax.swing.JTextField();
btnGetTableList = new javax.swing.JButton();
jLabel7 = new javax.swing.JLabel();
txtConnString = new javax.swing.JTextField();
btnConnString = new javax.swing.JButton();
pnlTableNames = new javax.swing.JPanel();
scrlPnlTableNames = new javax.swing.JScrollPane();
tblTableNames = new javax.swing.JTable();
jPanel1 = new javax.swing.JPanel();
menuBar = new javax.swing.JMenuBar();
javax.swing.JMenu fileMenu = new javax.swing.JMenu();
javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
javax.swing.JMenu helpMenu = new javax.swing.JMenu();
javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
statusPanel = new javax.swing.JPanel();
javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
statusMessageLabel = new javax.swing.JLabel();
statusAnimationLabel = new javax.swing.JLabel();
progressBar = new javax.swing.JProgressBar();
mainPanel.setName("mainPanel"); // NOI18N
mainPanel.setPreferredSize(new java.awt.Dimension(570, 600));
org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(com.voet.datasetcreator.DatasetCreatorApp.class).getContext().getResourceMap(DatasetCreatorView.class);
jLabel1.setText(resourceMap.getString("lbl_drivers.text")); // NOI18N
jLabel1.setName("lbl_drivers"); // NOI18N
cboDrivers.setModel(DatasetCreatorApp.getDriverList());
cboDrivers.setName("cboDrivers"); // NOI18N
cboDrivers.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
driverSelectionChanged(evt);
}
});
pnlConnInfo.setBorder(javax.swing.BorderFactory.createEtchedBorder());
pnlConnInfo.setToolTipText(resourceMap.getString("pnlConnInfo.toolTipText")); // NOI18N
pnlConnInfo.setName("pnlConnInfo"); // NOI18N
jLabel2.setText(resourceMap.getString("lblHostName.text")); // NOI18N
jLabel2.setName("lblHostName"); // NOI18N
txtHost.setText(resourceMap.getString("txtHost.text")); // NOI18N
txtHost.setName("txtHost"); // NOI18N
jLabel3.setText(resourceMap.getString("lblDbName.text")); // NOI18N
jLabel3.setName("lblDbName"); // NOI18N
txtDbName.setText(resourceMap.getString("txtDbName.text")); // NOI18N
txtDbName.setName("txtDbName"); // NOI18N
jLabel4.setText(resourceMap.getString("lblHost.text")); // NOI18N
jLabel4.setName("lblHost"); // NOI18N
txtPort.setText(resourceMap.getString("txtPort.text")); // NOI18N
txtPort.setName("txtPort"); // NOI18N
jLabel5.setText(resourceMap.getString("lblUsername.text")); // NOI18N
jLabel5.setName("lblUsername"); // NOI18N
txtUsername.setText(resourceMap.getString("txtUsername.text")); // NOI18N
txtUsername.setName("txtUsername"); // NOI18N
jLabel6.setText(resourceMap.getString("lblUsername.text")); // NOI18N
jLabel6.setName("lblUsername"); // NOI18N
txtPassword.setText(resourceMap.getString("txtPassword.text")); // NOI18N
txtPassword.setName("txtPassword"); // NOI18N
btnGetTableList.setText(resourceMap.getString("btnListTableNames.text")); // NOI18N
btnGetTableList.setName("btnListTableNames"); // NOI18N
btnGetTableList.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnListTableNames(evt);
}
});
jLabel7.setText(resourceMap.getString("lblConnString.text")); // NOI18N
jLabel7.setName("lblConnString"); // NOI18N
txtConnString.setText(resourceMap.getString("txtConnString.text")); // NOI18N
txtConnString.setName("txtConnString"); // NOI18N
btnConnString.setText(resourceMap.getString("btnConnString.text")); // NOI18N
btnConnString.setName("btnConnString"); // NOI18N
btnConnString.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buildConnectionStringHandler(evt);
}
});
javax.swing.GroupLayout pnlConnInfoLayout = new javax.swing.GroupLayout(pnlConnInfo);
pnlConnInfo.setLayout(pnlConnInfoLayout);
pnlConnInfoLayout.setHorizontalGroup(
pnlConnInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlConnInfoLayout.createSequentialGroup()
.addContainerGap()
.addGroup(pnlConnInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel6)
.addGroup(pnlConnInfoLayout.createSequentialGroup()
.addGroup(pnlConnInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3)
.addComponent(jLabel5)
.addComponent(jLabel7)
.addComponent(jLabel2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(pnlConnInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtHost, javax.swing.GroupLayout.PREFERRED_SIZE, 216, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtConnString, javax.swing.GroupLayout.DEFAULT_SIZE, 216, Short.MAX_VALUE)
.addComponent(txtUsername, javax.swing.GroupLayout.DEFAULT_SIZE, 216, Short.MAX_VALUE)
.addComponent(txtDbName, javax.swing.GroupLayout.DEFAULT_SIZE, 216, Short.MAX_VALUE)
.addComponent(txtPassword, javax.swing.GroupLayout.DEFAULT_SIZE, 216, Short.MAX_VALUE))))
.addGap(18, 18, 18)
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(pnlConnInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtPort, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnGetTableList)
.addComponent(btnConnString))
.addGap(41, 41, 41))
);
pnlConnInfoLayout.setVerticalGroup(
pnlConnInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlConnInfoLayout.createSequentialGroup()
.addGroup(pnlConnInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(txtPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtHost, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(pnlConnInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(pnlConnInfoLayout.createSequentialGroup()
.addGroup(pnlConnInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(txtDbName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(pnlConnInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(txtUsername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(pnlConnInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6)
.addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(btnConnString))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(pnlConnInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel7)
.addComponent(btnGetTableList)
.addComponent(txtConnString, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(19, Short.MAX_VALUE))
);
pnlTableNames.setBorder(javax.swing.BorderFactory.createEtchedBorder());
pnlTableNames.setName("pnlTableNames"); // NOI18N
scrlPnlTableNames.setName("scrlPnlTableNames"); // NOI18N
tblTableNames.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null},
{null, null},
{null, null},
{null, null}
},
new String [] {
"Title 1", "Title 2"
}
));
tblTableNames.setName("tblTableNames"); // NOI18N
scrlPnlTableNames.setViewportView(tblTableNames);
javax.swing.GroupLayout pnlTableNamesLayout = new javax.swing.GroupLayout(pnlTableNames);
pnlTableNames.setLayout(pnlTableNamesLayout);
pnlTableNamesLayout.setHorizontalGroup(
pnlTableNamesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 296, Short.MAX_VALUE)
.addGroup(pnlTableNamesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlTableNamesLayout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(scrlPnlTableNames, javax.swing.GroupLayout.PREFERRED_SIZE, 284, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
);
pnlTableNamesLayout.setVerticalGroup(
pnlTableNamesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 445, Short.MAX_VALUE)
.addGroup(pnlTableNamesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlTableNamesLayout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(scrlPnlTableNames, javax.swing.GroupLayout.DEFAULT_SIZE, 423, Short.MAX_VALUE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
);
jPanel1.setName("jPanel1"); // NOI18N
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 240, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 430, Short.MAX_VALUE)
);
javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
mainPanel.setLayout(mainPanelLayout);
mainPanelLayout.setHorizontalGroup(
mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(mainPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(mainPanelLayout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addComponent(cboDrivers, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(569, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, mainPanelLayout.createSequentialGroup()
.addComponent(pnlTableNames, javax.swing.GroupLayout.PREFERRED_SIZE, 300, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(27, 27, 27)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addComponent(pnlConnInfo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(142, 142, 142))))
);
mainPanelLayout.setVerticalGroup(
mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(mainPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(cboDrivers, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(1, 1, 1)
.addComponent(pnlConnInfo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(pnlTableNames, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
menuBar.setName("menuBar"); // NOI18N
fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
fileMenu.setName("fileMenu"); // NOI18N
javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(com.voet.datasetcreator.DatasetCreatorApp.class).getContext().getActionMap(DatasetCreatorView.class, this);
exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
exitMenuItem.setName("exitMenuItem"); // NOI18N
fileMenu.add(exitMenuItem);
menuBar.add(fileMenu);
helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
helpMenu.setName("helpMenu"); // NOI18N
aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
aboutMenuItem.setName("aboutMenuItem"); // NOI18N
helpMenu.add(aboutMenuItem);
menuBar.add(helpMenu);
statusPanel.setName("statusPanel"); // NOI18N
statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N
statusMessageLabel.setName("statusMessageLabel"); // NOI18N
statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N
progressBar.setName("progressBar"); // NOI18N
javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
statusPanel.setLayout(statusPanelLayout);
statusPanelLayout.setHorizontalGroup(
statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 705, Short.MAX_VALUE)
.addGroup(statusPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(statusMessageLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 535, Short.MAX_VALUE)
.addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(statusAnimationLabel)
.addContainerGap())
);
statusPanelLayout.setVerticalGroup(
statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(statusPanelLayout.createSequentialGroup()
.addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(statusMessageLabel)
.addComponent(statusAnimationLabel)
.addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(3, 3, 3))
);
setComponent(mainPanel);
setMenuBar(menuBar);
setStatusBar(statusPanel);
}// </editor-fold>//GEN-END:initComponents
| private void initComponents() {
mainPanel = new javax.swing.JPanel();
jLabel1 = new javax.swing.JLabel();
cboDrivers = new javax.swing.JComboBox();
pnlConnInfo = new javax.swing.JPanel();
jLabel2 = new javax.swing.JLabel();
txtHost = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
txtDbName = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
txtPort = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
txtUsername = new javax.swing.JTextField();
jLabel6 = new javax.swing.JLabel();
txtPassword = new javax.swing.JTextField();
btnGetTableList = new javax.swing.JButton();
jLabel7 = new javax.swing.JLabel();
txtConnString = new javax.swing.JTextField();
btnConnString = new javax.swing.JButton();
pnlTableNames = new javax.swing.JPanel();
scrlPnlTableNames = new javax.swing.JScrollPane();
tblTableNames = new javax.swing.JTable();
jPanel1 = new javax.swing.JPanel();
menuBar = new javax.swing.JMenuBar();
javax.swing.JMenu fileMenu = new javax.swing.JMenu();
javax.swing.JMenuItem exitMenuItem = new javax.swing.JMenuItem();
javax.swing.JMenu helpMenu = new javax.swing.JMenu();
javax.swing.JMenuItem aboutMenuItem = new javax.swing.JMenuItem();
statusPanel = new javax.swing.JPanel();
javax.swing.JSeparator statusPanelSeparator = new javax.swing.JSeparator();
statusMessageLabel = new javax.swing.JLabel();
statusAnimationLabel = new javax.swing.JLabel();
progressBar = new javax.swing.JProgressBar();
mainPanel.setName("mainPanel"); // NOI18N
mainPanel.setPreferredSize(new java.awt.Dimension(570, 600));
org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(com.voet.datasetcreator.DatasetCreatorApp.class).getContext().getResourceMap(DatasetCreatorView.class);
jLabel1.setText(resourceMap.getString("lbl_drivers.text")); // NOI18N
jLabel1.setName("lbl_drivers"); // NOI18N
cboDrivers.setModel(DatasetCreatorApp.getDriverList());
cboDrivers.setName("cboDrivers"); // NOI18N
cboDrivers.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
driverSelectionChanged(evt);
}
});
pnlConnInfo.setBorder(javax.swing.BorderFactory.createEtchedBorder());
pnlConnInfo.setToolTipText(resourceMap.getString("pnlConnInfo.toolTipText")); // NOI18N
pnlConnInfo.setName("pnlConnInfo"); // NOI18N
jLabel2.setText(resourceMap.getString("lblHostName.text")); // NOI18N
jLabel2.setName("lblHostName"); // NOI18N
txtHost.setText(resourceMap.getString("txtHost.text")); // NOI18N
txtHost.setName("txtHost"); // NOI18N
jLabel3.setText(resourceMap.getString("lblDbName.text")); // NOI18N
jLabel3.setName("lblDbName"); // NOI18N
txtDbName.setText(resourceMap.getString("txtDbName.text")); // NOI18N
txtDbName.setName("txtDbName"); // NOI18N
jLabel4.setText(resourceMap.getString("lblHost.text")); // NOI18N
jLabel4.setName("lblHost"); // NOI18N
txtPort.setText(resourceMap.getString("txtPort.text")); // NOI18N
txtPort.setName("txtPort"); // NOI18N
jLabel5.setText(resourceMap.getString("lblUsername.text")); // NOI18N
jLabel5.setName("lblUsername"); // NOI18N
txtUsername.setText(resourceMap.getString("txtUsername.text")); // NOI18N
txtUsername.setName("txtUsername"); // NOI18N
jLabel6.setText(resourceMap.getString("lblUsername.text")); // NOI18N
jLabel6.setName("lblUsername"); // NOI18N
txtPassword.setText(resourceMap.getString("txtPassword.text")); // NOI18N
txtPassword.setName("txtPassword"); // NOI18N
btnGetTableList.setText(resourceMap.getString("btnListTableNames.text")); // NOI18N
btnGetTableList.setName("btnListTableNames"); // NOI18N
btnGetTableList.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnListTableNames(evt);
}
});
jLabel7.setText(resourceMap.getString("lblConnString.text")); // NOI18N
jLabel7.setName("lblConnString"); // NOI18N
txtConnString.setText(resourceMap.getString("txtConnString.text")); // NOI18N
txtConnString.setName("txtConnString"); // NOI18N
btnConnString.setText(resourceMap.getString("btnConnString.text")); // NOI18N
btnConnString.setName("btnConnString"); // NOI18N
btnConnString.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
buildConnectionStringHandler(evt);
}
});
javax.swing.GroupLayout pnlConnInfoLayout = new javax.swing.GroupLayout(pnlConnInfo);
pnlConnInfo.setLayout(pnlConnInfoLayout);
pnlConnInfoLayout.setHorizontalGroup(
pnlConnInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlConnInfoLayout.createSequentialGroup()
.addContainerGap()
.addGroup(pnlConnInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel6)
.addGroup(pnlConnInfoLayout.createSequentialGroup()
.addGroup(pnlConnInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel3)
.addComponent(jLabel5)
.addComponent(jLabel7)
.addComponent(jLabel2))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(pnlConnInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtHost, javax.swing.GroupLayout.PREFERRED_SIZE, 216, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtConnString, javax.swing.GroupLayout.DEFAULT_SIZE, 216, Short.MAX_VALUE)
.addComponent(txtUsername, javax.swing.GroupLayout.DEFAULT_SIZE, 216, Short.MAX_VALUE)
.addComponent(txtDbName, javax.swing.GroupLayout.DEFAULT_SIZE, 216, Short.MAX_VALUE)
.addComponent(txtPassword, javax.swing.GroupLayout.DEFAULT_SIZE, 216, Short.MAX_VALUE))))
.addGap(18, 18, 18)
.addComponent(jLabel4)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(pnlConnInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(txtPort, javax.swing.GroupLayout.PREFERRED_SIZE, 69, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnGetTableList)
.addComponent(btnConnString))
.addGap(41, 41, 41))
);
pnlConnInfoLayout.setVerticalGroup(
pnlConnInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlConnInfoLayout.createSequentialGroup()
.addGroup(pnlConnInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(txtPort, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(txtHost, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel4))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(pnlConnInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(pnlConnInfoLayout.createSequentialGroup()
.addGroup(pnlConnInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel3)
.addComponent(txtDbName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(pnlConnInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel5)
.addComponent(txtUsername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(pnlConnInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel6)
.addComponent(txtPassword, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addComponent(btnConnString))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(pnlConnInfoLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel7)
.addComponent(btnGetTableList)
.addComponent(txtConnString, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap(19, Short.MAX_VALUE))
);
pnlTableNames.setBorder(javax.swing.BorderFactory.createEtchedBorder());
pnlTableNames.setName("pnlTableNames"); // NOI18N
pnlTableNames.setPreferredSize(new java.awt.Dimension(315, 300));
scrlPnlTableNames.setName("scrlPnlTableNames"); // NOI18N
tblTableNames.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
{null, null},
{null, null},
{null, null},
{null, null}
},
new String [] {
"Title 1", "Title 2"
}
));
tblTableNames.setName("tblTableNames"); // NOI18N
scrlPnlTableNames.setViewportView(tblTableNames);
javax.swing.GroupLayout pnlTableNamesLayout = new javax.swing.GroupLayout(pnlTableNames);
pnlTableNames.setLayout(pnlTableNamesLayout);
pnlTableNamesLayout.setHorizontalGroup(
pnlTableNamesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 311, Short.MAX_VALUE)
.addGroup(pnlTableNamesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(pnlTableNamesLayout.createSequentialGroup()
.addContainerGap(13, Short.MAX_VALUE)
.addComponent(scrlPnlTableNames, javax.swing.GroupLayout.PREFERRED_SIZE, 284, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(14, Short.MAX_VALUE)))
);
pnlTableNamesLayout.setVerticalGroup(
pnlTableNamesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 296, Short.MAX_VALUE)
.addGroup(pnlTableNamesLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlTableNamesLayout.createSequentialGroup()
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(scrlPnlTableNames, javax.swing.GroupLayout.DEFAULT_SIZE, 272, Short.MAX_VALUE)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
);
jPanel1.setName("jPanel1"); // NOI18N
javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 314, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 430, Short.MAX_VALUE)
);
javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
mainPanel.setLayout(mainPanelLayout);
mainPanelLayout.setHorizontalGroup(
mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(mainPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(mainPanelLayout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addComponent(cboDrivers, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addContainerGap(595, Short.MAX_VALUE))
.addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(javax.swing.GroupLayout.Alignment.LEADING, mainPanelLayout.createSequentialGroup()
.addComponent(pnlTableNames, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addComponent(pnlConnInfo, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(142, 142, 142))))
);
mainPanelLayout.setVerticalGroup(
mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(mainPanelLayout.createSequentialGroup()
.addContainerGap()
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(cboDrivers, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(1, 1, 1)
.addComponent(pnlConnInfo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(pnlTableNames, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
menuBar.setName("menuBar"); // NOI18N
fileMenu.setText(resourceMap.getString("fileMenu.text")); // NOI18N
fileMenu.setName("fileMenu"); // NOI18N
javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(com.voet.datasetcreator.DatasetCreatorApp.class).getContext().getActionMap(DatasetCreatorView.class, this);
exitMenuItem.setAction(actionMap.get("quit")); // NOI18N
exitMenuItem.setName("exitMenuItem"); // NOI18N
fileMenu.add(exitMenuItem);
menuBar.add(fileMenu);
helpMenu.setText(resourceMap.getString("helpMenu.text")); // NOI18N
helpMenu.setName("helpMenu"); // NOI18N
aboutMenuItem.setAction(actionMap.get("showAboutBox")); // NOI18N
aboutMenuItem.setName("aboutMenuItem"); // NOI18N
helpMenu.add(aboutMenuItem);
menuBar.add(helpMenu);
statusPanel.setName("statusPanel"); // NOI18N
statusPanelSeparator.setName("statusPanelSeparator"); // NOI18N
statusMessageLabel.setName("statusMessageLabel"); // NOI18N
statusAnimationLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
statusAnimationLabel.setName("statusAnimationLabel"); // NOI18N
progressBar.setName("progressBar"); // NOI18N
javax.swing.GroupLayout statusPanelLayout = new javax.swing.GroupLayout(statusPanel);
statusPanel.setLayout(statusPanelLayout);
statusPanelLayout.setHorizontalGroup(
statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(statusPanelSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 772, Short.MAX_VALUE)
.addGroup(statusPanelLayout.createSequentialGroup()
.addContainerGap()
.addComponent(statusMessageLabel)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 590, Short.MAX_VALUE)
.addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(statusAnimationLabel)
.addContainerGap())
);
statusPanelLayout.setVerticalGroup(
statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(statusPanelLayout.createSequentialGroup()
.addComponent(statusPanelSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, 2, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(statusPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(statusMessageLabel)
.addComponent(statusAnimationLabel)
.addComponent(progressBar, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(3, 3, 3))
);
setComponent(mainPanel);
setMenuBar(menuBar);
setStatusBar(statusPanel);
}// </editor-fold>//GEN-END:initComponents
|
diff --git a/src/gov/nist/javax/sip/stack/IOHandler.java b/src/gov/nist/javax/sip/stack/IOHandler.java
index 76373e63..d1341d52 100755
--- a/src/gov/nist/javax/sip/stack/IOHandler.java
+++ b/src/gov/nist/javax/sip/stack/IOHandler.java
@@ -1,304 +1,305 @@
/*
* Conditions Of Use
*
* This software was developed by employees of the National Institute of
* Standards and Technology (NIST), an agency of the Federal Government.
* Pursuant to title 15 Untied States Code Section 105, works of NIST
* employees are not subject to copyright protection in the United States
* and are considered to be in the public domain. As a result, a formal
* license is not needed to use the software.
*
* This software is provided by NIST as a service and is expressly
* provided "AS IS." NIST MAKES NO WARRANTY OF ANY KIND, EXPRESS, IMPLIED
* OR STATUTORY, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTY OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT
* AND DATA ACCURACY. NIST does not warrant or make any representations
* regarding the use of the software or the results thereof, including but
* not limited to the correctness, accuracy, reliability or usefulness of
* the software.
*
* Permission to use this software is contingent upon your acceptance
* of the terms of this agreement
*
* .
*
*/
/*******************************************************************************
* Product of NIST/ITL Advanced Networking Technologies Division (ANTD). *
*******************************************************************************/
package gov.nist.javax.sip.stack;
import gov.nist.javax.sip.SipStackImpl;
import java.io.*;
import java.net.*;
import java.util.Hashtable;
import java.util.Enumeration;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
/*
* TLS support Added by Daniel J.Martinez Manzano <[email protected]>
*
*/
/**
* Low level Input output to a socket. Caches TCP connections and takes care of
* re-connecting to the remote party if the other end drops the connection
*
* @version 1.2
*
* @author M. Ranganathan <br/>
*
*
*/
class IOHandler {
private Semaphore ioSemaphore = new Semaphore(1);
private SipStackImpl sipStack;
private static String TCP = "tcp";
// Added by Daniel J. Martinez Manzano <[email protected]>
private static String TLS = "tls";
// A cache of client sockets that can be re-used for
// sending tcp messages.
private ConcurrentHashMap<String, Socket> socketTable;
protected static String makeKey(InetAddress addr, int port) {
return addr.getHostAddress() + ":" + port;
}
protected IOHandler(SIPTransactionStack sipStack) {
this.sipStack = (SipStackImpl) sipStack;
this.socketTable = new ConcurrentHashMap<String, Socket>();
}
protected void putSocket(String key, Socket sock) {
socketTable.put(key, sock);
}
protected Socket getSocket(String key) {
return (Socket) socketTable.get(key);
}
protected void removeSocket(String key) {
socketTable.remove(key);
}
/**
* A private function to write things out. This needs to be syncrhonized as
* writes can occur from multiple threads. We write in chunks to allow the
* other side to synchronize for large sized writes.
*/
private void writeChunks(OutputStream outputStream, byte[] bytes, int length)
throws IOException {
// Chunk size is 16K - this hack is for large
// writes over slow connections.
synchronized (outputStream) {
// outputStream.write(bytes,0,length);
int chunksize = 8 * 1024;
for (int p = 0; p < length; p += chunksize) {
int chunk = p + chunksize < length ? chunksize : length - p;
outputStream.write(bytes, p, chunk);
}
}
outputStream.flush();
}
/**
* Send an array of bytes.
*
* @param receiverAddress --
* inet address
* @param contactPort --
* port to connect to.
* @param transport --
* tcp or udp.
* @param retry --
* retry to connect if the other end closed connection
* @throws IOException --
* if there is an IO exception sending message.
*/
public Socket sendBytes(InetAddress senderAddress,
InetAddress receiverAddress, int contactPort, String transport,
byte[] bytes, boolean retry) throws IOException {
int retry_count = 0;
int max_retry = retry ? 2 : 1;
// Server uses TCP transport. TCP client sockets are cached
int length = bytes.length;
if (sipStack.isLoggingEnabled()) {
sipStack.logWriter.logDebug("sendBytes " + transport + " inAddr "
+ receiverAddress.getHostAddress() + " port = "
+ contactPort + " length = " + length);
}
if (transport.compareToIgnoreCase(TCP) == 0) {
String key = makeKey(receiverAddress, contactPort);
// This should be in a synchronized block ( reported by
// Jayashenkhar ( lucent ).
try {
boolean retval = this.ioSemaphore.tryAcquire(10000, TimeUnit.MILLISECONDS); // TODO - make this a stack config parameter?
if ( !retval ) {
throw new IOException("Could not acquire IO Semaphore after 10 second -- giving up ");
}
} catch (InterruptedException ex) {
throw new IOException("exception in aquiring sem");
}
Socket clientSock = getSocket(key);
try {
while (retry_count < max_retry) {
if (clientSock == null) {
if (sipStack.isLoggingEnabled()) {
sipStack.logWriter.logDebug("inaddr = "
+ receiverAddress);
sipStack.logWriter
.logDebug("port = " + contactPort);
}
// note that the IP Address for stack may not be
// assigned.
// sender address is the address of the listening point.
// in version 1.1 all listening points have the same IP
// address (i.e. that of the stack). In version 1.2
// the IP address is on a per listening point basis.
clientSock = sipStack.getNetworkLayer().createSocket(
receiverAddress, contactPort, senderAddress);
OutputStream outputStream = clientSock
.getOutputStream();
writeChunks(outputStream, bytes, length);
putSocket(key, clientSock);
break;
} else {
try {
OutputStream outputStream = clientSock
.getOutputStream();
writeChunks(outputStream, bytes, length);
break;
} catch (IOException ex) {
if (sipStack.isLoggingEnabled())
sipStack.logWriter.logException(ex);
// old connection is bad.
// remove from our table.
removeSocket(key);
try {
clientSock.close();
} catch (Exception e) {
}
clientSock = null;
retry_count++;
}
}
}
} finally {
ioSemaphore.release();
}
if (clientSock == null) {
throw new IOException("Could not connect to " + receiverAddress
+ ":" + contactPort);
} else
return clientSock;
// Added by Daniel J. Martinez Manzano <[email protected]>
// Copied and modified from the former section for TCP
} else if (transport.compareToIgnoreCase(TLS) == 0) {
String key = makeKey(receiverAddress, contactPort);
try {
- this.ioSemaphore.tryAcquire(10000, TimeUnit.MILLISECONDS);
+ boolean retval = this.ioSemaphore.tryAcquire(10000, TimeUnit.MILLISECONDS);
+ if ( ! retval ) throw new IOException ("Timeout aquiring IO SEM");
} catch (InterruptedException ex) {
throw new IOException("exception in aquiring sem");
}
Socket clientSock = getSocket(key);
try {
while (retry_count < max_retry) {
if (clientSock == null) {
if (sipStack.isLoggingEnabled()) {
sipStack.logWriter.logDebug("inaddr = "
+ receiverAddress);
sipStack.logWriter
.logDebug("port = " + contactPort);
}
if (!sipStack.useTlsAccelerator) {
clientSock = sipStack.getNetworkLayer()
.createSSLSocket(receiverAddress,
contactPort, senderAddress);
} else {
clientSock = sipStack.getNetworkLayer()
.createSocket(receiverAddress, contactPort,
senderAddress);
}
OutputStream outputStream = clientSock
.getOutputStream();
writeChunks(outputStream, bytes, length);
putSocket(key, clientSock);
break;
} else {
try {
OutputStream outputStream = clientSock
.getOutputStream();
writeChunks(outputStream, bytes, length);
break;
} catch (IOException ex) {
if (sipStack.isLoggingEnabled())
sipStack.logWriter.logException(ex);
// old connection is bad.
// remove from our table.
removeSocket(key);
try {
clientSock.close();
} catch (Exception e) {
}
clientSock = null;
retry_count++;
}
}
}
} finally {
ioSemaphore.release();
}
if (clientSock == null) {
throw new IOException("Could not connect to " + receiverAddress
+ ":" + contactPort);
} else
return clientSock;
} else {
// This is a UDP transport...
DatagramSocket datagramSock = sipStack.getNetworkLayer()
.createDatagramSocket();
datagramSock.connect(receiverAddress, contactPort);
DatagramPacket dgPacket = new DatagramPacket(bytes, 0, length,
receiverAddress, contactPort);
datagramSock.send(dgPacket);
datagramSock.close();
return null;
}
}
/**
* Close all the cached connections.
*/
public void closeAll() {
for (Enumeration<Socket> values = socketTable.elements(); values
.hasMoreElements();) {
Socket s = (Socket) values.nextElement();
try {
s.close();
} catch (IOException ex) {
}
}
}
}
| true | true | public Socket sendBytes(InetAddress senderAddress,
InetAddress receiverAddress, int contactPort, String transport,
byte[] bytes, boolean retry) throws IOException {
int retry_count = 0;
int max_retry = retry ? 2 : 1;
// Server uses TCP transport. TCP client sockets are cached
int length = bytes.length;
if (sipStack.isLoggingEnabled()) {
sipStack.logWriter.logDebug("sendBytes " + transport + " inAddr "
+ receiverAddress.getHostAddress() + " port = "
+ contactPort + " length = " + length);
}
if (transport.compareToIgnoreCase(TCP) == 0) {
String key = makeKey(receiverAddress, contactPort);
// This should be in a synchronized block ( reported by
// Jayashenkhar ( lucent ).
try {
boolean retval = this.ioSemaphore.tryAcquire(10000, TimeUnit.MILLISECONDS); // TODO - make this a stack config parameter?
if ( !retval ) {
throw new IOException("Could not acquire IO Semaphore after 10 second -- giving up ");
}
} catch (InterruptedException ex) {
throw new IOException("exception in aquiring sem");
}
Socket clientSock = getSocket(key);
try {
while (retry_count < max_retry) {
if (clientSock == null) {
if (sipStack.isLoggingEnabled()) {
sipStack.logWriter.logDebug("inaddr = "
+ receiverAddress);
sipStack.logWriter
.logDebug("port = " + contactPort);
}
// note that the IP Address for stack may not be
// assigned.
// sender address is the address of the listening point.
// in version 1.1 all listening points have the same IP
// address (i.e. that of the stack). In version 1.2
// the IP address is on a per listening point basis.
clientSock = sipStack.getNetworkLayer().createSocket(
receiverAddress, contactPort, senderAddress);
OutputStream outputStream = clientSock
.getOutputStream();
writeChunks(outputStream, bytes, length);
putSocket(key, clientSock);
break;
} else {
try {
OutputStream outputStream = clientSock
.getOutputStream();
writeChunks(outputStream, bytes, length);
break;
} catch (IOException ex) {
if (sipStack.isLoggingEnabled())
sipStack.logWriter.logException(ex);
// old connection is bad.
// remove from our table.
removeSocket(key);
try {
clientSock.close();
} catch (Exception e) {
}
clientSock = null;
retry_count++;
}
}
}
} finally {
ioSemaphore.release();
}
if (clientSock == null) {
throw new IOException("Could not connect to " + receiverAddress
+ ":" + contactPort);
} else
return clientSock;
// Added by Daniel J. Martinez Manzano <[email protected]>
// Copied and modified from the former section for TCP
} else if (transport.compareToIgnoreCase(TLS) == 0) {
String key = makeKey(receiverAddress, contactPort);
try {
this.ioSemaphore.tryAcquire(10000, TimeUnit.MILLISECONDS);
} catch (InterruptedException ex) {
throw new IOException("exception in aquiring sem");
}
Socket clientSock = getSocket(key);
try {
while (retry_count < max_retry) {
if (clientSock == null) {
if (sipStack.isLoggingEnabled()) {
sipStack.logWriter.logDebug("inaddr = "
+ receiverAddress);
sipStack.logWriter
.logDebug("port = " + contactPort);
}
if (!sipStack.useTlsAccelerator) {
clientSock = sipStack.getNetworkLayer()
.createSSLSocket(receiverAddress,
contactPort, senderAddress);
} else {
clientSock = sipStack.getNetworkLayer()
.createSocket(receiverAddress, contactPort,
senderAddress);
}
OutputStream outputStream = clientSock
.getOutputStream();
writeChunks(outputStream, bytes, length);
putSocket(key, clientSock);
break;
} else {
try {
OutputStream outputStream = clientSock
.getOutputStream();
writeChunks(outputStream, bytes, length);
break;
} catch (IOException ex) {
if (sipStack.isLoggingEnabled())
sipStack.logWriter.logException(ex);
// old connection is bad.
// remove from our table.
removeSocket(key);
try {
clientSock.close();
} catch (Exception e) {
}
clientSock = null;
retry_count++;
}
}
}
} finally {
ioSemaphore.release();
}
if (clientSock == null) {
throw new IOException("Could not connect to " + receiverAddress
+ ":" + contactPort);
} else
return clientSock;
} else {
// This is a UDP transport...
DatagramSocket datagramSock = sipStack.getNetworkLayer()
.createDatagramSocket();
datagramSock.connect(receiverAddress, contactPort);
DatagramPacket dgPacket = new DatagramPacket(bytes, 0, length,
receiverAddress, contactPort);
datagramSock.send(dgPacket);
datagramSock.close();
return null;
}
}
| public Socket sendBytes(InetAddress senderAddress,
InetAddress receiverAddress, int contactPort, String transport,
byte[] bytes, boolean retry) throws IOException {
int retry_count = 0;
int max_retry = retry ? 2 : 1;
// Server uses TCP transport. TCP client sockets are cached
int length = bytes.length;
if (sipStack.isLoggingEnabled()) {
sipStack.logWriter.logDebug("sendBytes " + transport + " inAddr "
+ receiverAddress.getHostAddress() + " port = "
+ contactPort + " length = " + length);
}
if (transport.compareToIgnoreCase(TCP) == 0) {
String key = makeKey(receiverAddress, contactPort);
// This should be in a synchronized block ( reported by
// Jayashenkhar ( lucent ).
try {
boolean retval = this.ioSemaphore.tryAcquire(10000, TimeUnit.MILLISECONDS); // TODO - make this a stack config parameter?
if ( !retval ) {
throw new IOException("Could not acquire IO Semaphore after 10 second -- giving up ");
}
} catch (InterruptedException ex) {
throw new IOException("exception in aquiring sem");
}
Socket clientSock = getSocket(key);
try {
while (retry_count < max_retry) {
if (clientSock == null) {
if (sipStack.isLoggingEnabled()) {
sipStack.logWriter.logDebug("inaddr = "
+ receiverAddress);
sipStack.logWriter
.logDebug("port = " + contactPort);
}
// note that the IP Address for stack may not be
// assigned.
// sender address is the address of the listening point.
// in version 1.1 all listening points have the same IP
// address (i.e. that of the stack). In version 1.2
// the IP address is on a per listening point basis.
clientSock = sipStack.getNetworkLayer().createSocket(
receiverAddress, contactPort, senderAddress);
OutputStream outputStream = clientSock
.getOutputStream();
writeChunks(outputStream, bytes, length);
putSocket(key, clientSock);
break;
} else {
try {
OutputStream outputStream = clientSock
.getOutputStream();
writeChunks(outputStream, bytes, length);
break;
} catch (IOException ex) {
if (sipStack.isLoggingEnabled())
sipStack.logWriter.logException(ex);
// old connection is bad.
// remove from our table.
removeSocket(key);
try {
clientSock.close();
} catch (Exception e) {
}
clientSock = null;
retry_count++;
}
}
}
} finally {
ioSemaphore.release();
}
if (clientSock == null) {
throw new IOException("Could not connect to " + receiverAddress
+ ":" + contactPort);
} else
return clientSock;
// Added by Daniel J. Martinez Manzano <[email protected]>
// Copied and modified from the former section for TCP
} else if (transport.compareToIgnoreCase(TLS) == 0) {
String key = makeKey(receiverAddress, contactPort);
try {
boolean retval = this.ioSemaphore.tryAcquire(10000, TimeUnit.MILLISECONDS);
if ( ! retval ) throw new IOException ("Timeout aquiring IO SEM");
} catch (InterruptedException ex) {
throw new IOException("exception in aquiring sem");
}
Socket clientSock = getSocket(key);
try {
while (retry_count < max_retry) {
if (clientSock == null) {
if (sipStack.isLoggingEnabled()) {
sipStack.logWriter.logDebug("inaddr = "
+ receiverAddress);
sipStack.logWriter
.logDebug("port = " + contactPort);
}
if (!sipStack.useTlsAccelerator) {
clientSock = sipStack.getNetworkLayer()
.createSSLSocket(receiverAddress,
contactPort, senderAddress);
} else {
clientSock = sipStack.getNetworkLayer()
.createSocket(receiverAddress, contactPort,
senderAddress);
}
OutputStream outputStream = clientSock
.getOutputStream();
writeChunks(outputStream, bytes, length);
putSocket(key, clientSock);
break;
} else {
try {
OutputStream outputStream = clientSock
.getOutputStream();
writeChunks(outputStream, bytes, length);
break;
} catch (IOException ex) {
if (sipStack.isLoggingEnabled())
sipStack.logWriter.logException(ex);
// old connection is bad.
// remove from our table.
removeSocket(key);
try {
clientSock.close();
} catch (Exception e) {
}
clientSock = null;
retry_count++;
}
}
}
} finally {
ioSemaphore.release();
}
if (clientSock == null) {
throw new IOException("Could not connect to " + receiverAddress
+ ":" + contactPort);
} else
return clientSock;
} else {
// This is a UDP transport...
DatagramSocket datagramSock = sipStack.getNetworkLayer()
.createDatagramSocket();
datagramSock.connect(receiverAddress, contactPort);
DatagramPacket dgPacket = new DatagramPacket(bytes, 0, length,
receiverAddress, contactPort);
datagramSock.send(dgPacket);
datagramSock.close();
return null;
}
}
|
diff --git a/src/net/mayateck/OldEdenCore/EconomyHandler.java b/src/net/mayateck/OldEdenCore/EconomyHandler.java
index d524cdc..c94709e 100644
--- a/src/net/mayateck/OldEdenCore/EconomyHandler.java
+++ b/src/net/mayateck/OldEdenCore/EconomyHandler.java
@@ -1,142 +1,147 @@
package net.mayateck.OldEdenCore;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class EconomyHandler implements CommandExecutor {
private OldEdenCore plugin;
public EconomyHandler(OldEdenCore plugin) {
this.plugin = plugin;
}
public boolean onCommand(CommandSender s, Command cmd, String l, String[] args) {
String name = s.getName();
if (cmd.getName().equalsIgnoreCase("money")){
if (!(s instanceof Player)){
s.sendMessage("The economy commands are player-executible only.");
} else {
if (args.length==0){
- int funds = plugin.getConfig().getInt("players."+name+".funds");
- s.sendMessage(OldEdenCore.serverHead+"You have "+ChatColor.BLUE+funds+" Bits"+ChatColor.RESET+".");
- return true;
+ if (s.hasPermission("eden.eco.check")){
+ int funds = plugin.getConfig().getInt("players."+name+".funds");
+ s.sendMessage(OldEdenCore.serverHead+"You have "+ChatColor.BLUE+funds+" Bits"+ChatColor.RESET+".");
+ return true;
+ } else {
+ s.sendMessage(OldEdenCore.head+ChatColor.RED+"You don't have permission to do that!");
+ return true;
+ }
} else {
if (args[0].equalsIgnoreCase("admin")){
if (args.length==1){
s.sendMessage(OldEdenCore.head+ChatColor.RED+"Invalid parameter number. Usage: /money admin [args]");
return true;
} if (args[1].equalsIgnoreCase("set")){
if (args.length==4){
if (plugin.getConfig().contains("players."+args[2]) && s.hasPermission("eden.eco.set")){
int funds = Integer.parseInt(args[3]);
plugin.getConfig().set("players."+args[2]+".funds", funds);
plugin.saveConfig();
s.sendMessage(OldEdenCore.head+"Success! "+ChatColor.BLUE+args[2]+ChatColor.RESET+" now has "+ChatColor.BLUE+funds+" Bits"+ChatColor.RESET+".");
return true;
} else {
s.sendMessage(OldEdenCore.head+ChatColor.RED+"Player not found or invalid permissions.");
return true;
}
} else {
s.sendMessage(OldEdenCore.head+ChatColor.RED+"Invalid parameter number.");
s.sendMessage(OldEdenCore.head+ChatColor.RED+"Usage: /money admin set [player] [amount]");
return true;
}
} else if (args[1].equalsIgnoreCase("add")){
if (args.length==4){
if (plugin.getConfig().contains("players."+args[2]) && s.hasPermission("eden.eco.add")){
int funds = plugin.getConfig().getInt("players."+args[2]+".funds") + Integer.parseInt(args[3]);
plugin.getConfig().set("players."+args[2]+".funds", funds);
plugin.saveConfig();
s.sendMessage(OldEdenCore.head+"Success! "+ChatColor.BLUE+args[2]+ChatColor.RESET+" now has "+ChatColor.BLUE+funds+" Bits"+ChatColor.RESET+".");
return true;
} else {
s.sendMessage(OldEdenCore.head+ChatColor.RED+"Player not found or invalid permissions.");
return true;
}
} else {
s.sendMessage(OldEdenCore.head+ChatColor.RED+"Invalid parameter number.");
s.sendMessage(OldEdenCore.head+ChatColor.RED+"Usage: /money admin add [player] [amount]");
return true;
}
} else if (args[1].equalsIgnoreCase("subtract")){
if (args.length==4){
if (plugin.getConfig().contains("players."+args[2]) && s.hasPermission("eden.eco.add")){
int funds = plugin.getConfig().getInt("players."+args[2]+".funds") - Integer.parseInt(args[3]);
// WARNING! THIS CAN CREATE NEGATIVE VALUES! CAREFUL WHEN SUBTRACTING!
plugin.getConfig().set("players."+args[2]+".funds", funds);
plugin.saveConfig();
s.sendMessage(OldEdenCore.head+"Success! "+ChatColor.BLUE+args[2]+ChatColor.RESET+" now has "+ChatColor.BLUE+funds+" Bits"+ChatColor.RESET+".");
return true;
} else {
s.sendMessage(OldEdenCore.head+ChatColor.RED+"Player not found or invalid permissions.");
return true;
}
} else {
s.sendMessage(OldEdenCore.head+ChatColor.RED+"Invalid parameter number.");
s.sendMessage(OldEdenCore.head+ChatColor.RED+"Usage: /money admin add [player] [amount]");
return true;
}
} else if (args[1].equalsIgnoreCase("check")){
if (args.length==2){
if (plugin.getConfig().contains("players."+args[1]) && s.hasPermission("eden.eco.check")){
int funds = plugin.getConfig().getInt("players."+args[1]+".funds");
s.sendMessage(OldEdenCore.head+ChatColor.BLUE+args[2]+ChatColor.RESET+" has "+ChatColor.BLUE+funds+" Bits"+ChatColor.RESET+".");
return true;
} else {
s.sendMessage(OldEdenCore.head+ChatColor.RED+"Player not found or invalid permissions.");
return true;
}
} else {
s.sendMessage(OldEdenCore.head+ChatColor.RED+"Invalid parameter number.");
s.sendMessage(OldEdenCore.head+ChatColor.RED+"Usage: /money check [player]");
return true;
}
} else {
s.sendMessage(OldEdenCore.head+ChatColor.RED+"Unknown sub-command.");
return true;
}
} else if(args[0].equalsIgnoreCase("pay")) {
if (args.length==3){
if (s.hasPermission("eden.eco.pay")){
int senderFunds = plugin.getConfig().getInt("players."+name+".funds");
int funds = Integer.parseInt(args[2]);
if (funds<=senderFunds){
if (plugin.getConfig().contains("players."+args[1])){
plugin.getConfig().set("players."+name+".funds", senderFunds-funds);
int pFunds = plugin.getConfig().getInt("players."+args[1]+".funds");
plugin.getConfig().set("players."+args[1]+".funds", pFunds+funds);
plugin.saveConfig();
s.sendMessage(OldEdenCore.head+"Success! Sent "+ChatColor.BLUE+funds+" Bits"+ChatColor.RESET+" to "+ChatColor.BLUE+args[1]+ChatColor.RESET+".");
Player target = (Bukkit.getServer().getPlayer(args[1]));
if (!(target==null)){
target.sendMessage(OldEdenCore.head+"You recieved "+ChatColor.BLUE+funds+" Bits"+ChatColor.RESET+" from "+ChatColor.BLUE+name+ChatColor.RESET+".");
}
} else {
s.sendMessage(OldEdenCore.head+"That player doesn't exist.");
}
} else {
- s.sendMessage(OldEdenCore.head+"You can't give you you don't have!");
+ s.sendMessage(OldEdenCore.head+"You can't give what you don't have!");
}
} else {
s.sendMessage(OldEdenCore.head+ChatColor.RED+"You do not have permission to pay other people.");
}
} else {
s.sendMessage(OldEdenCore.head+ChatColor.RED+"Invalid arguments.");
s.sendMessage(OldEdenCore.head+ChatColor.RED+"Usage: /money pay [player] [amount].");
}
return true;
} else {
s.sendMessage(OldEdenCore.head+ChatColor.RED+"Unknown sub-command.");
return true;
}
}
}
}
return false;
}
}
| false | true | public boolean onCommand(CommandSender s, Command cmd, String l, String[] args) {
String name = s.getName();
if (cmd.getName().equalsIgnoreCase("money")){
if (!(s instanceof Player)){
s.sendMessage("The economy commands are player-executible only.");
} else {
if (args.length==0){
int funds = plugin.getConfig().getInt("players."+name+".funds");
s.sendMessage(OldEdenCore.serverHead+"You have "+ChatColor.BLUE+funds+" Bits"+ChatColor.RESET+".");
return true;
} else {
if (args[0].equalsIgnoreCase("admin")){
if (args.length==1){
s.sendMessage(OldEdenCore.head+ChatColor.RED+"Invalid parameter number. Usage: /money admin [args]");
return true;
} if (args[1].equalsIgnoreCase("set")){
if (args.length==4){
if (plugin.getConfig().contains("players."+args[2]) && s.hasPermission("eden.eco.set")){
int funds = Integer.parseInt(args[3]);
plugin.getConfig().set("players."+args[2]+".funds", funds);
plugin.saveConfig();
s.sendMessage(OldEdenCore.head+"Success! "+ChatColor.BLUE+args[2]+ChatColor.RESET+" now has "+ChatColor.BLUE+funds+" Bits"+ChatColor.RESET+".");
return true;
} else {
s.sendMessage(OldEdenCore.head+ChatColor.RED+"Player not found or invalid permissions.");
return true;
}
} else {
s.sendMessage(OldEdenCore.head+ChatColor.RED+"Invalid parameter number.");
s.sendMessage(OldEdenCore.head+ChatColor.RED+"Usage: /money admin set [player] [amount]");
return true;
}
} else if (args[1].equalsIgnoreCase("add")){
if (args.length==4){
if (plugin.getConfig().contains("players."+args[2]) && s.hasPermission("eden.eco.add")){
int funds = plugin.getConfig().getInt("players."+args[2]+".funds") + Integer.parseInt(args[3]);
plugin.getConfig().set("players."+args[2]+".funds", funds);
plugin.saveConfig();
s.sendMessage(OldEdenCore.head+"Success! "+ChatColor.BLUE+args[2]+ChatColor.RESET+" now has "+ChatColor.BLUE+funds+" Bits"+ChatColor.RESET+".");
return true;
} else {
s.sendMessage(OldEdenCore.head+ChatColor.RED+"Player not found or invalid permissions.");
return true;
}
} else {
s.sendMessage(OldEdenCore.head+ChatColor.RED+"Invalid parameter number.");
s.sendMessage(OldEdenCore.head+ChatColor.RED+"Usage: /money admin add [player] [amount]");
return true;
}
} else if (args[1].equalsIgnoreCase("subtract")){
if (args.length==4){
if (plugin.getConfig().contains("players."+args[2]) && s.hasPermission("eden.eco.add")){
int funds = plugin.getConfig().getInt("players."+args[2]+".funds") - Integer.parseInt(args[3]);
// WARNING! THIS CAN CREATE NEGATIVE VALUES! CAREFUL WHEN SUBTRACTING!
plugin.getConfig().set("players."+args[2]+".funds", funds);
plugin.saveConfig();
s.sendMessage(OldEdenCore.head+"Success! "+ChatColor.BLUE+args[2]+ChatColor.RESET+" now has "+ChatColor.BLUE+funds+" Bits"+ChatColor.RESET+".");
return true;
} else {
s.sendMessage(OldEdenCore.head+ChatColor.RED+"Player not found or invalid permissions.");
return true;
}
} else {
s.sendMessage(OldEdenCore.head+ChatColor.RED+"Invalid parameter number.");
s.sendMessage(OldEdenCore.head+ChatColor.RED+"Usage: /money admin add [player] [amount]");
return true;
}
} else if (args[1].equalsIgnoreCase("check")){
if (args.length==2){
if (plugin.getConfig().contains("players."+args[1]) && s.hasPermission("eden.eco.check")){
int funds = plugin.getConfig().getInt("players."+args[1]+".funds");
s.sendMessage(OldEdenCore.head+ChatColor.BLUE+args[2]+ChatColor.RESET+" has "+ChatColor.BLUE+funds+" Bits"+ChatColor.RESET+".");
return true;
} else {
s.sendMessage(OldEdenCore.head+ChatColor.RED+"Player not found or invalid permissions.");
return true;
}
} else {
s.sendMessage(OldEdenCore.head+ChatColor.RED+"Invalid parameter number.");
s.sendMessage(OldEdenCore.head+ChatColor.RED+"Usage: /money check [player]");
return true;
}
} else {
s.sendMessage(OldEdenCore.head+ChatColor.RED+"Unknown sub-command.");
return true;
}
} else if(args[0].equalsIgnoreCase("pay")) {
if (args.length==3){
if (s.hasPermission("eden.eco.pay")){
int senderFunds = plugin.getConfig().getInt("players."+name+".funds");
int funds = Integer.parseInt(args[2]);
if (funds<=senderFunds){
if (plugin.getConfig().contains("players."+args[1])){
plugin.getConfig().set("players."+name+".funds", senderFunds-funds);
int pFunds = plugin.getConfig().getInt("players."+args[1]+".funds");
plugin.getConfig().set("players."+args[1]+".funds", pFunds+funds);
plugin.saveConfig();
s.sendMessage(OldEdenCore.head+"Success! Sent "+ChatColor.BLUE+funds+" Bits"+ChatColor.RESET+" to "+ChatColor.BLUE+args[1]+ChatColor.RESET+".");
Player target = (Bukkit.getServer().getPlayer(args[1]));
if (!(target==null)){
target.sendMessage(OldEdenCore.head+"You recieved "+ChatColor.BLUE+funds+" Bits"+ChatColor.RESET+" from "+ChatColor.BLUE+name+ChatColor.RESET+".");
}
} else {
s.sendMessage(OldEdenCore.head+"That player doesn't exist.");
}
} else {
s.sendMessage(OldEdenCore.head+"You can't give you you don't have!");
}
} else {
s.sendMessage(OldEdenCore.head+ChatColor.RED+"You do not have permission to pay other people.");
}
} else {
s.sendMessage(OldEdenCore.head+ChatColor.RED+"Invalid arguments.");
s.sendMessage(OldEdenCore.head+ChatColor.RED+"Usage: /money pay [player] [amount].");
}
return true;
} else {
s.sendMessage(OldEdenCore.head+ChatColor.RED+"Unknown sub-command.");
return true;
}
}
}
}
return false;
}
| public boolean onCommand(CommandSender s, Command cmd, String l, String[] args) {
String name = s.getName();
if (cmd.getName().equalsIgnoreCase("money")){
if (!(s instanceof Player)){
s.sendMessage("The economy commands are player-executible only.");
} else {
if (args.length==0){
if (s.hasPermission("eden.eco.check")){
int funds = plugin.getConfig().getInt("players."+name+".funds");
s.sendMessage(OldEdenCore.serverHead+"You have "+ChatColor.BLUE+funds+" Bits"+ChatColor.RESET+".");
return true;
} else {
s.sendMessage(OldEdenCore.head+ChatColor.RED+"You don't have permission to do that!");
return true;
}
} else {
if (args[0].equalsIgnoreCase("admin")){
if (args.length==1){
s.sendMessage(OldEdenCore.head+ChatColor.RED+"Invalid parameter number. Usage: /money admin [args]");
return true;
} if (args[1].equalsIgnoreCase("set")){
if (args.length==4){
if (plugin.getConfig().contains("players."+args[2]) && s.hasPermission("eden.eco.set")){
int funds = Integer.parseInt(args[3]);
plugin.getConfig().set("players."+args[2]+".funds", funds);
plugin.saveConfig();
s.sendMessage(OldEdenCore.head+"Success! "+ChatColor.BLUE+args[2]+ChatColor.RESET+" now has "+ChatColor.BLUE+funds+" Bits"+ChatColor.RESET+".");
return true;
} else {
s.sendMessage(OldEdenCore.head+ChatColor.RED+"Player not found or invalid permissions.");
return true;
}
} else {
s.sendMessage(OldEdenCore.head+ChatColor.RED+"Invalid parameter number.");
s.sendMessage(OldEdenCore.head+ChatColor.RED+"Usage: /money admin set [player] [amount]");
return true;
}
} else if (args[1].equalsIgnoreCase("add")){
if (args.length==4){
if (plugin.getConfig().contains("players."+args[2]) && s.hasPermission("eden.eco.add")){
int funds = plugin.getConfig().getInt("players."+args[2]+".funds") + Integer.parseInt(args[3]);
plugin.getConfig().set("players."+args[2]+".funds", funds);
plugin.saveConfig();
s.sendMessage(OldEdenCore.head+"Success! "+ChatColor.BLUE+args[2]+ChatColor.RESET+" now has "+ChatColor.BLUE+funds+" Bits"+ChatColor.RESET+".");
return true;
} else {
s.sendMessage(OldEdenCore.head+ChatColor.RED+"Player not found or invalid permissions.");
return true;
}
} else {
s.sendMessage(OldEdenCore.head+ChatColor.RED+"Invalid parameter number.");
s.sendMessage(OldEdenCore.head+ChatColor.RED+"Usage: /money admin add [player] [amount]");
return true;
}
} else if (args[1].equalsIgnoreCase("subtract")){
if (args.length==4){
if (plugin.getConfig().contains("players."+args[2]) && s.hasPermission("eden.eco.add")){
int funds = plugin.getConfig().getInt("players."+args[2]+".funds") - Integer.parseInt(args[3]);
// WARNING! THIS CAN CREATE NEGATIVE VALUES! CAREFUL WHEN SUBTRACTING!
plugin.getConfig().set("players."+args[2]+".funds", funds);
plugin.saveConfig();
s.sendMessage(OldEdenCore.head+"Success! "+ChatColor.BLUE+args[2]+ChatColor.RESET+" now has "+ChatColor.BLUE+funds+" Bits"+ChatColor.RESET+".");
return true;
} else {
s.sendMessage(OldEdenCore.head+ChatColor.RED+"Player not found or invalid permissions.");
return true;
}
} else {
s.sendMessage(OldEdenCore.head+ChatColor.RED+"Invalid parameter number.");
s.sendMessage(OldEdenCore.head+ChatColor.RED+"Usage: /money admin add [player] [amount]");
return true;
}
} else if (args[1].equalsIgnoreCase("check")){
if (args.length==2){
if (plugin.getConfig().contains("players."+args[1]) && s.hasPermission("eden.eco.check")){
int funds = plugin.getConfig().getInt("players."+args[1]+".funds");
s.sendMessage(OldEdenCore.head+ChatColor.BLUE+args[2]+ChatColor.RESET+" has "+ChatColor.BLUE+funds+" Bits"+ChatColor.RESET+".");
return true;
} else {
s.sendMessage(OldEdenCore.head+ChatColor.RED+"Player not found or invalid permissions.");
return true;
}
} else {
s.sendMessage(OldEdenCore.head+ChatColor.RED+"Invalid parameter number.");
s.sendMessage(OldEdenCore.head+ChatColor.RED+"Usage: /money check [player]");
return true;
}
} else {
s.sendMessage(OldEdenCore.head+ChatColor.RED+"Unknown sub-command.");
return true;
}
} else if(args[0].equalsIgnoreCase("pay")) {
if (args.length==3){
if (s.hasPermission("eden.eco.pay")){
int senderFunds = plugin.getConfig().getInt("players."+name+".funds");
int funds = Integer.parseInt(args[2]);
if (funds<=senderFunds){
if (plugin.getConfig().contains("players."+args[1])){
plugin.getConfig().set("players."+name+".funds", senderFunds-funds);
int pFunds = plugin.getConfig().getInt("players."+args[1]+".funds");
plugin.getConfig().set("players."+args[1]+".funds", pFunds+funds);
plugin.saveConfig();
s.sendMessage(OldEdenCore.head+"Success! Sent "+ChatColor.BLUE+funds+" Bits"+ChatColor.RESET+" to "+ChatColor.BLUE+args[1]+ChatColor.RESET+".");
Player target = (Bukkit.getServer().getPlayer(args[1]));
if (!(target==null)){
target.sendMessage(OldEdenCore.head+"You recieved "+ChatColor.BLUE+funds+" Bits"+ChatColor.RESET+" from "+ChatColor.BLUE+name+ChatColor.RESET+".");
}
} else {
s.sendMessage(OldEdenCore.head+"That player doesn't exist.");
}
} else {
s.sendMessage(OldEdenCore.head+"You can't give what you don't have!");
}
} else {
s.sendMessage(OldEdenCore.head+ChatColor.RED+"You do not have permission to pay other people.");
}
} else {
s.sendMessage(OldEdenCore.head+ChatColor.RED+"Invalid arguments.");
s.sendMessage(OldEdenCore.head+ChatColor.RED+"Usage: /money pay [player] [amount].");
}
return true;
} else {
s.sendMessage(OldEdenCore.head+ChatColor.RED+"Unknown sub-command.");
return true;
}
}
}
}
return false;
}
|
diff --git a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/AbstractDB2Dictionary.java b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/AbstractDB2Dictionary.java
index 22af396ea..5000e8ac3 100644
--- a/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/AbstractDB2Dictionary.java
+++ b/openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/AbstractDB2Dictionary.java
@@ -1,97 +1,101 @@
/*
* Copyright 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.openjpa.jdbc.sql;
import org.apache.openjpa.jdbc.kernel.exps.FilterValue;
/**
* Base dictionary for the IBM DB2 family of databases.
*/
public abstract class AbstractDB2Dictionary
extends DBDictionary {
public AbstractDB2Dictionary() {
numericTypeName = "DOUBLE";
bitTypeName = "SMALLINT";
smallintTypeName = "SMALLINT";
tinyintTypeName = "SMALLINT";
longVarbinaryTypeName = "BLOB";
varbinaryTypeName = "BLOB";
+ // DB2-based databases have restrictions on having uncast parameters
+ // in string functions
toUpperCaseFunction = "UPPER(CAST({0} AS VARCHAR(1000)))";
toLowerCaseFunction = "LOWER(CAST({0} AS VARCHAR(1000)))";
stringLengthFunction = "LENGTH(CAST({0} AS VARCHAR(1000)))";
+ concatenateFunction = "(CAST({0} AS VARCHAR(1000)))||"
+ + "(CAST({1} AS VARCHAR(1000)))";
trimLeadingFunction = "LTRIM({0})";
trimTrailingFunction = "RTRIM({0})";
trimBothFunction = "LTRIM(RTRIM({0}))";
// in DB2, "for update" seems to be ignored with isolation
// levels below REPEATABLE_READ... force isolation to behave like RR
forUpdateClause = "FOR UPDATE WITH RR";
supportsLockingWithDistinctClause = false;
supportsLockingWithMultipleTables = false;
supportsLockingWithOrderClause = false;
supportsLockingWithOuterJoin = false;
supportsLockingWithInnerJoin = false;
supportsLockingWithSelectRange = false;
requiresAutoCommitForMetaData = true;
requiresAliasForSubselect = true;
supportsAutoAssign = true;
autoAssignClause = "GENERATED BY DEFAULT AS IDENTITY";
lastGeneratedKeyQuery = "VALUES(IDENTITY_VAL_LOCAL())";
// DB2 doesn't understand "X CROSS JOIN Y", but it does understand
// the equivalent "X JOIN Y ON 1 = 1"
crossJoinClause = "JOIN";
requiresConditionForCrossJoin = true;
}
public void indexOf(SQLBuffer buf, FilterValue str, FilterValue find,
FilterValue start) {
buf.append("(LOCATE(CAST((");
find.appendTo(buf);
buf.append(") AS VARCHAR(1000)), CAST((");
str.appendTo(buf);
buf.append(") AS VARCHAR(1000))");
if (start != null) {
buf.append(", CAST((");
start.appendTo(buf);
buf.append(") AS INTEGER) + 1");
}
buf.append(") - 1)");
}
public void substring(SQLBuffer buf, FilterValue str, FilterValue start,
FilterValue end) {
buf.append("SUBSTR(CAST((");
str.appendTo(buf);
buf.append(") AS VARCHAR(1000)), CAST((");
start.appendTo(buf);
buf.append(") AS INTEGER) + 1");
if (end != null) {
buf.append(", CAST((");
end.appendTo(buf);
buf.append(") AS INTEGER) - CAST((");
start.appendTo(buf);
buf.append(") AS INTEGER)");
}
buf.append(")");
}
}
| false | true | public AbstractDB2Dictionary() {
numericTypeName = "DOUBLE";
bitTypeName = "SMALLINT";
smallintTypeName = "SMALLINT";
tinyintTypeName = "SMALLINT";
longVarbinaryTypeName = "BLOB";
varbinaryTypeName = "BLOB";
toUpperCaseFunction = "UPPER(CAST({0} AS VARCHAR(1000)))";
toLowerCaseFunction = "LOWER(CAST({0} AS VARCHAR(1000)))";
stringLengthFunction = "LENGTH(CAST({0} AS VARCHAR(1000)))";
trimLeadingFunction = "LTRIM({0})";
trimTrailingFunction = "RTRIM({0})";
trimBothFunction = "LTRIM(RTRIM({0}))";
// in DB2, "for update" seems to be ignored with isolation
// levels below REPEATABLE_READ... force isolation to behave like RR
forUpdateClause = "FOR UPDATE WITH RR";
supportsLockingWithDistinctClause = false;
supportsLockingWithMultipleTables = false;
supportsLockingWithOrderClause = false;
supportsLockingWithOuterJoin = false;
supportsLockingWithInnerJoin = false;
supportsLockingWithSelectRange = false;
requiresAutoCommitForMetaData = true;
requiresAliasForSubselect = true;
supportsAutoAssign = true;
autoAssignClause = "GENERATED BY DEFAULT AS IDENTITY";
lastGeneratedKeyQuery = "VALUES(IDENTITY_VAL_LOCAL())";
// DB2 doesn't understand "X CROSS JOIN Y", but it does understand
// the equivalent "X JOIN Y ON 1 = 1"
crossJoinClause = "JOIN";
requiresConditionForCrossJoin = true;
}
| public AbstractDB2Dictionary() {
numericTypeName = "DOUBLE";
bitTypeName = "SMALLINT";
smallintTypeName = "SMALLINT";
tinyintTypeName = "SMALLINT";
longVarbinaryTypeName = "BLOB";
varbinaryTypeName = "BLOB";
// DB2-based databases have restrictions on having uncast parameters
// in string functions
toUpperCaseFunction = "UPPER(CAST({0} AS VARCHAR(1000)))";
toLowerCaseFunction = "LOWER(CAST({0} AS VARCHAR(1000)))";
stringLengthFunction = "LENGTH(CAST({0} AS VARCHAR(1000)))";
concatenateFunction = "(CAST({0} AS VARCHAR(1000)))||"
+ "(CAST({1} AS VARCHAR(1000)))";
trimLeadingFunction = "LTRIM({0})";
trimTrailingFunction = "RTRIM({0})";
trimBothFunction = "LTRIM(RTRIM({0}))";
// in DB2, "for update" seems to be ignored with isolation
// levels below REPEATABLE_READ... force isolation to behave like RR
forUpdateClause = "FOR UPDATE WITH RR";
supportsLockingWithDistinctClause = false;
supportsLockingWithMultipleTables = false;
supportsLockingWithOrderClause = false;
supportsLockingWithOuterJoin = false;
supportsLockingWithInnerJoin = false;
supportsLockingWithSelectRange = false;
requiresAutoCommitForMetaData = true;
requiresAliasForSubselect = true;
supportsAutoAssign = true;
autoAssignClause = "GENERATED BY DEFAULT AS IDENTITY";
lastGeneratedKeyQuery = "VALUES(IDENTITY_VAL_LOCAL())";
// DB2 doesn't understand "X CROSS JOIN Y", but it does understand
// the equivalent "X JOIN Y ON 1 = 1"
crossJoinClause = "JOIN";
requiresConditionForCrossJoin = true;
}
|
diff --git a/src/main/java/de/bbe_consulting/mavento/MagentoDeployMojo.java b/src/main/java/de/bbe_consulting/mavento/MagentoDeployMojo.java
index 68d0ca7..f23286d 100644
--- a/src/main/java/de/bbe_consulting/mavento/MagentoDeployMojo.java
+++ b/src/main/java/de/bbe_consulting/mavento/MagentoDeployMojo.java
@@ -1,89 +1,88 @@
/**
* Copyright 2011-2012 BBe Consulting GmbH
*
* 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 de.bbe_consulting.mavento;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import de.bbe_consulting.mavento.helper.FileUtil;
import de.bbe_consulting.mavento.helper.MagentoUtil;
/**
* Deploy current build artifact to Magento instance.<br/>
* If run manually call it together with the package phase:<br/>
* <pre>mvn package magento:deploy</pre>
*
* @goal deploy
* @requiresDependencyResolution compile
* @author Erik Dannenberg
*/
public final class MagentoDeployMojo extends AbstractMagentoMojo {
public void execute() throws MojoExecutionException, MojoFailureException {
File buildArtifact = new File(project.getBuild().getDirectory()+"/"+project.getArtifactId()+"-"+project.getVersion()+".zip");
if ( buildArtifact.exists() ) {
if (magentoDeployType.equals("local")) {
getLog().info("Checking for symlinks..");
- String srcDirName = project.getBasedir().getAbsolutePath()+"/src/main/php/app";
- String magentoDirName = magentoRootLocal+"/app";
- File f = new File(magentoDirName+"/etc/local.xml");
+ String srcDirName = project.getBasedir().getAbsolutePath()+"/src/main/php";
+ File f = new File(magentoRootLocal+"/app/etc/local.xml");
if (!f.exists()) {
throw new MojoExecutionException("Could not find Magento root, did you forget to run 'mvn magento:install'? ;)");
}
Map<String,String> linkMap = new HashMap<String, String>();
try {
- linkMap = MagentoUtil.collectSymlinks(srcDirName, magentoDirName);
+ linkMap = MagentoUtil.collectSymlinks(srcDirName, magentoRootLocal);
} catch (IOException e) {
throw new MojoExecutionException(e.getMessage(), e);
}
for ( Map.Entry<String,String> fileNames : linkMap.entrySet()) {
File t = new File(fileNames.getValue());
if (t.exists()) {
getLog().info("..deleting: "+fileNames.getValue());
t.delete();
}
}
getLog().info("..done.");
getLog().info("Deploying local to: "+magentoRootLocal);
try {
FileUtil.unzipFile(buildArtifact.getAbsolutePath(), magentoRootLocal);
} catch (IOException e) {
throw new MojoExecutionException(e.getMessage(), e);
}
getLog().info("..extracting: "+buildArtifact.getName());
getLog().info("..done.");
} else {
getLog().info("Deploying remote to: "+magentoRootRemote);
throw new MojoExecutionException("oops, remote deploy not implemented yet :(");
}
} else if (project.getPackaging().equals("php")) {
throw new MojoExecutionException("Could not find build artifact, forgot 'mvn package'? ;)");
}
}
}
| false | true | public void execute() throws MojoExecutionException, MojoFailureException {
File buildArtifact = new File(project.getBuild().getDirectory()+"/"+project.getArtifactId()+"-"+project.getVersion()+".zip");
if ( buildArtifact.exists() ) {
if (magentoDeployType.equals("local")) {
getLog().info("Checking for symlinks..");
String srcDirName = project.getBasedir().getAbsolutePath()+"/src/main/php/app";
String magentoDirName = magentoRootLocal+"/app";
File f = new File(magentoDirName+"/etc/local.xml");
if (!f.exists()) {
throw new MojoExecutionException("Could not find Magento root, did you forget to run 'mvn magento:install'? ;)");
}
Map<String,String> linkMap = new HashMap<String, String>();
try {
linkMap = MagentoUtil.collectSymlinks(srcDirName, magentoDirName);
} catch (IOException e) {
throw new MojoExecutionException(e.getMessage(), e);
}
for ( Map.Entry<String,String> fileNames : linkMap.entrySet()) {
File t = new File(fileNames.getValue());
if (t.exists()) {
getLog().info("..deleting: "+fileNames.getValue());
t.delete();
}
}
getLog().info("..done.");
getLog().info("Deploying local to: "+magentoRootLocal);
try {
FileUtil.unzipFile(buildArtifact.getAbsolutePath(), magentoRootLocal);
} catch (IOException e) {
throw new MojoExecutionException(e.getMessage(), e);
}
getLog().info("..extracting: "+buildArtifact.getName());
getLog().info("..done.");
} else {
getLog().info("Deploying remote to: "+magentoRootRemote);
throw new MojoExecutionException("oops, remote deploy not implemented yet :(");
}
} else if (project.getPackaging().equals("php")) {
throw new MojoExecutionException("Could not find build artifact, forgot 'mvn package'? ;)");
}
}
| public void execute() throws MojoExecutionException, MojoFailureException {
File buildArtifact = new File(project.getBuild().getDirectory()+"/"+project.getArtifactId()+"-"+project.getVersion()+".zip");
if ( buildArtifact.exists() ) {
if (magentoDeployType.equals("local")) {
getLog().info("Checking for symlinks..");
String srcDirName = project.getBasedir().getAbsolutePath()+"/src/main/php";
File f = new File(magentoRootLocal+"/app/etc/local.xml");
if (!f.exists()) {
throw new MojoExecutionException("Could not find Magento root, did you forget to run 'mvn magento:install'? ;)");
}
Map<String,String> linkMap = new HashMap<String, String>();
try {
linkMap = MagentoUtil.collectSymlinks(srcDirName, magentoRootLocal);
} catch (IOException e) {
throw new MojoExecutionException(e.getMessage(), e);
}
for ( Map.Entry<String,String> fileNames : linkMap.entrySet()) {
File t = new File(fileNames.getValue());
if (t.exists()) {
getLog().info("..deleting: "+fileNames.getValue());
t.delete();
}
}
getLog().info("..done.");
getLog().info("Deploying local to: "+magentoRootLocal);
try {
FileUtil.unzipFile(buildArtifact.getAbsolutePath(), magentoRootLocal);
} catch (IOException e) {
throw new MojoExecutionException(e.getMessage(), e);
}
getLog().info("..extracting: "+buildArtifact.getName());
getLog().info("..done.");
} else {
getLog().info("Deploying remote to: "+magentoRootRemote);
throw new MojoExecutionException("oops, remote deploy not implemented yet :(");
}
} else if (project.getPackaging().equals("php")) {
throw new MojoExecutionException("Could not find build artifact, forgot 'mvn package'? ;)");
}
}
|
diff --git a/apps/i2psnark/java/src/org/klomp/snark/web/I2PSnarkServlet.java b/apps/i2psnark/java/src/org/klomp/snark/web/I2PSnarkServlet.java
index b9634d2a6..ce8e82cd9 100644
--- a/apps/i2psnark/java/src/org/klomp/snark/web/I2PSnarkServlet.java
+++ b/apps/i2psnark/java/src/org/klomp/snark/web/I2PSnarkServlet.java
@@ -1,2674 +1,2675 @@
package org.klomp.snark.web;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.text.Collator;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.i2p.I2PAppContext;
import net.i2p.data.Base64;
import net.i2p.data.DataHelper;
import net.i2p.util.I2PAppThread;
import net.i2p.util.Log;
import org.klomp.snark.I2PSnarkUtil;
import org.klomp.snark.MagnetURI;
import org.klomp.snark.MetaInfo;
import org.klomp.snark.Peer;
import org.klomp.snark.Snark;
import org.klomp.snark.SnarkManager;
import org.klomp.snark.Storage;
import org.klomp.snark.Tracker;
import org.klomp.snark.TrackerClient;
import org.klomp.snark.dht.DHT;
/**
* Refactored to eliminate Jetty dependencies.
*/
public class I2PSnarkServlet extends BasicServlet {
/** generally "/i2psnark" */
private String _contextPath;
/** generally "i2psnark" */
private String _contextName;
private SnarkManager _manager;
private static long _nonce;
private String _themePath;
private String _imgPath;
private String _lastAnnounceURL;
private static final String DEFAULT_NAME = "i2psnark";
public static final String PROP_CONFIG_FILE = "i2psnark.configFile";
public I2PSnarkServlet() {
super();
}
@Override
public void init(ServletConfig cfg) throws ServletException {
super.init(cfg);
String cpath = getServletContext().getContextPath();
_contextPath = cpath == "" ? "/" : cpath;
_contextName = cpath == "" ? DEFAULT_NAME : cpath.substring(1).replace("/", "_");
_nonce = _context.random().nextLong();
// limited protection against overwriting other config files or directories
// in case you named your war "router.war"
String configName = _contextName;
if (!configName.equals(DEFAULT_NAME))
configName = DEFAULT_NAME + '_' + _contextName;
_manager = new SnarkManager(_context, _contextPath, configName);
String configFile = _context.getProperty(PROP_CONFIG_FILE);
if ( (configFile == null) || (configFile.trim().length() <= 0) )
configFile = configName + ".config";
_manager.loadConfig(configFile);
_manager.start();
loadMimeMap("org/klomp/snark/web/mime");
setResourceBase(_manager.getDataDir());
setWarBase("/.icons/");
}
@Override
public void destroy() {
if (_manager != null)
_manager.stop();
super.destroy();
}
/**
* We override this instead of passing a resource base to super(), because
* if a resource base is set, super.getResource() always uses that base,
* and we can't get any resources (like icons) out of the .war
*/
@Override
public File getResource(String pathInContext)
{
if (pathInContext == null || pathInContext.equals("/") || pathInContext.equals("/index.jsp") ||
pathInContext.equals("/index.html") || pathInContext.startsWith("/.icons/"))
return super.getResource(pathInContext);
// files in the i2psnark/ directory
return new File(_resourceBase, pathInContext);
}
/**
* Handle what we can here, calling super.doGet() for the rest.
* @since 0.8.3
*/
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGetAndPost(request, response);
}
/**
* Handle what we can here, calling super.doPost() for the rest.
* @since Jetty 7
*/
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGetAndPost(request, response);
}
/**
* Handle what we can here, calling super.doGet() or super.doPost() for the rest.
*
* Some parts modified from:
* <pre>
// ========================================================================
// $Id: Default.java,v 1.51 2006/10/08 14:13:18 gregwilkins Exp $
// Copyright 199-2004 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.
// ========================================================================
* </pre>
*
*/
private void doGetAndPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//if (_log.shouldLog(Log.DEBUG))
// _log.debug("Service " + req.getMethod() + " \"" + req.getContextPath() + "\" \"" + req.getServletPath() + "\" \"" + req.getPathInfo() + '"');
// since we are not overriding handle*(), do this here
String method = req.getMethod();
_themePath = "/themes/snark/" + _manager.getTheme() + '/';
_imgPath = _themePath + "images/";
// this is the part after /i2psnark
String path = req.getServletPath();
resp.setHeader("X-Frame-Options", "SAMEORIGIN");
String peerParam = req.getParameter("p");
String stParam = req.getParameter("st");
String peerString;
if (peerParam == null || (!_manager.util().connected()) ||
peerParam.replaceAll("[a-zA-Z0-9~=-]", "").length() > 0) { // XSS
peerString = "";
} else {
peerString = "?p=" + peerParam;
}
if (stParam != null && !stParam.equals("0")) {
if (peerString.length() > 0)
peerString += "&st=" + stParam;
else
peerString = "?st="+ stParam;
}
// AJAX for mainsection
if ("/.ajax/xhr1.html".equals(path)) {
resp.setCharacterEncoding("UTF-8");
resp.setContentType("text/html; charset=UTF-8");
PrintWriter out = resp.getWriter();
//if (_log.shouldLog(Log.DEBUG))
// _manager.addMessage((_context.clock().now() / 1000) + " xhr1 p=" + req.getParameter("p"));
writeMessages(out, false, peerString);
writeTorrents(out, req);
return;
}
boolean isConfigure = "/configure".equals(path);
// index.jsp doesn't work, it is grabbed by the war handler before here
if (!(path == null || path.equals("/") || path.equals("/index.jsp") || path.equals("/index.html") || path.equals("/_post") || isConfigure)) {
if (path.endsWith("/")) {
// Listing of a torrent (torrent detail page)
// bypass the horrid Resource.getListHTML()
String pathInfo = req.getPathInfo();
String pathInContext = addPaths(path, pathInfo);
req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");
resp.setContentType("text/html; charset=UTF-8");
File resource = getResource(pathInContext);
if (resource == null) {
resp.sendError(404);
} else {
String base = addPaths(req.getRequestURI(), "/");
String listing = getListHTML(resource, base, true, method.equals("POST") ? req.getParameterMap() : null);
if (method.equals("POST")) {
// P-R-G
sendRedirect(req, resp, "");
} else if (listing != null) {
resp.getWriter().write(listing);
} else { // shouldn't happen
resp.sendError(404);
}
}
} else {
// local completed files in torrent directories
if (method.equals("GET") || method.equals("HEAD"))
super.doGet(req, resp);
else if (method.equals("POST"))
super.doPost(req, resp);
else
resp.sendError(405);
}
return;
}
// Either the main page or /configure
req.setCharacterEncoding("UTF-8");
resp.setCharacterEncoding("UTF-8");
resp.setContentType("text/html; charset=UTF-8");
String nonce = req.getParameter("nonce");
if (nonce != null) {
if (nonce.equals(String.valueOf(_nonce)))
processRequest(req);
else // nonce is constant, shouldn't happen
_manager.addMessage("Please retry form submission (bad nonce)");
// P-R-G (or G-R-G to hide the params from the address bar)
sendRedirect(req, resp, peerString);
return;
}
PrintWriter out = resp.getWriter();
out.write(DOCTYPE + "<html>\n" +
"<head><link rel=\"shortcut icon\" href=\"" + _themePath + "favicon.ico\">\n" +
"<title>");
out.write(_("I2PSnark - Anonymous BitTorrent Client"));
if ("2".equals(peerParam))
out.write(" | Debug Mode");
out.write("</title>\n");
// we want it to go to the base URI so we don't refresh with some funky action= value
int delay = 0;
if (!isConfigure) {
delay = _manager.getRefreshDelaySeconds();
if (delay > 0) {
//out.write("<meta http-equiv=\"refresh\" content=\"" + delay + ";/i2psnark/" + peerString + "\">\n");
out.write("<script src=\"/js/ajax.js\" type=\"text/javascript\"></script>\n" +
"<script type=\"text/javascript\">\n" +
"var failMessage = \"<div class=\\\"routerdown\\\"><b>" + _("Router is down") + "<\\/b><\\/div>\";\n" +
"function requestAjax1() { ajax(\"" + _contextPath + "/.ajax/xhr1.html" +
peerString.replace("&", "&") + // don't html escape in js
"\", \"mainsection\", " + (delay*1000) + "); }\n" +
"function initAjax() { setTimeout(requestAjax1, " + (delay*1000) +"); }\n" +
"</script>\n");
}
}
out.write(HEADER_A + _themePath + HEADER_B + "</head>\n");
if (isConfigure || delay <= 0)
out.write("<body>");
else
out.write("<body onload=\"initAjax()\">");
out.write("<center>");
List<Tracker> sortedTrackers = null;
if (isConfigure) {
out.write("<div class=\"snarknavbar\"><a href=\"" + _contextPath + "/\" title=\"");
out.write(_("Torrents"));
out.write("\" class=\"snarkRefresh\">");
out.write("<img alt=\"\" border=\"0\" src=\"" + _imgPath + "arrow_refresh.png\"> ");
if (_contextName.equals(DEFAULT_NAME))
out.write(_("I2PSnark"));
else
out.write(_contextName);
out.write("</a>");
} else {
out.write("<div class=\"snarknavbar\"><a href=\"" + _contextPath + '/' + peerString + "\" title=\"");
out.write(_("Refresh page"));
out.write("\" class=\"snarkRefresh\">");
out.write("<img alt=\"\" border=\"0\" src=\"" + _imgPath + "arrow_refresh.png\"> ");
if (_contextName.equals(DEFAULT_NAME))
out.write(_("I2PSnark"));
else
out.write(_contextName);
out.write("</a> <a href=\"http://forum.i2p/viewforum.php?f=21\" class=\"snarkRefresh\" target=\"_blank\">");
out.write(_("Forum"));
out.write("</a>\n");
sortedTrackers = _manager.getSortedTrackers();
for (Tracker t : sortedTrackers) {
if (t.baseURL == null || !t.baseURL.startsWith("http"))
continue;
out.write(" <a href=\"" + t.baseURL + "\" class=\"snarkRefresh\" target=\"_blank\">" + t.name + "</a>");
}
}
out.write("</div>\n");
String newURL = req.getParameter("newURL");
if (newURL != null && newURL.trim().length() > 0 && req.getMethod().equals("GET"))
_manager.addMessage(_("Click \"Add torrent\" button to fetch torrent"));
out.write("<div class=\"page\"><div id=\"mainsection\" class=\"mainsection\">");
writeMessages(out, isConfigure, peerString);
if (isConfigure) {
// end of mainsection div
out.write("<div class=\"logshim\"></div></div>\n");
writeConfigForm(out, req);
writeTrackerForm(out, req);
} else {
boolean pageOne = writeTorrents(out, req);
// end of mainsection div
if (pageOne) {
out.write("</div><div id=\"lowersection\">\n");
writeAddForm(out, req);
writeSeedForm(out, req, sortedTrackers);
writeConfigLink(out);
// end of lowersection div
}
out.write("</div>\n");
}
out.write(FOOTER);
}
private void writeMessages(PrintWriter out, boolean isConfigure, String peerString) throws IOException {
List<String> msgs = _manager.getMessages();
if (!msgs.isEmpty()) {
out.write("<div class=\"snarkMessages\">");
out.write("<a href=\"" + _contextPath + '/');
if (isConfigure)
out.write("configure");
if (peerString.length() > 0)
out.write(peerString + "&");
else
out.write("?");
out.write("action=Clear&nonce=" + _nonce + "\">" +
"<img src=\"" + _imgPath + "delete.png\" title=\"" + _("clear messages") +
"\" alt=\"" + _("clear messages") + "\"></a>" +
"<ul>");
for (int i = msgs.size()-1; i >= 0; i--) {
String msg = msgs.get(i);
out.write("<li>" + msg + "</li>\n");
}
out.write("</ul></div>");
}
}
/**
* @return true if on first page
*/
private boolean writeTorrents(PrintWriter out, HttpServletRequest req) throws IOException {
/** dl, ul, down rate, up rate, peers, size */
final long stats[] = {0,0,0,0,0,0};
String peerParam = req.getParameter("p");
String stParam = req.getParameter("st");
List<Snark> snarks = getSortedSnarks(req);
boolean isForm = _manager.util().connected() || !snarks.isEmpty();
if (isForm) {
out.write("<form action=\"_post\" method=\"POST\">\n");
out.write("<input type=\"hidden\" name=\"nonce\" value=\"" + _nonce + "\" >\n");
// don't lose peer setting
if (peerParam != null)
out.write("<input type=\"hidden\" name=\"p\" value=\"" + peerParam + "\" >\n");
// ...or st setting
if (stParam != null)
out.write("<input type=\"hidden\" name=\"st\" value=\"" + stParam + "\" >\n");
}
out.write(TABLE_HEADER);
// Opera and text-mode browsers: no   and no input type=image values submitted
// Using a unique name fixes Opera, except for the buttons with js confirms, see below
String ua = req.getHeader("User-Agent");
boolean isDegraded = ua != null && (ua.startsWith("Lynx") || ua.startsWith("w3m") ||
ua.startsWith("ELinks") || ua.startsWith("Links") ||
ua.startsWith("Dillo"));
boolean noThinsp = isDegraded || (ua != null && ua.startsWith("Opera"));
// pages
int start = 0;
int total = snarks.size();
if (stParam != null) {
try {
start = Math.max(0, Math.min(total - 1, Integer.parseInt(stParam)));
} catch (NumberFormatException nfe) {}
}
int pageSize = Math.max(_manager.getPageSize(), 5);
out.write("<tr><th><img border=\"0\" src=\"" + _imgPath + "status.png\" title=\"");
out.write(_("Status"));
out.write("\" alt=\"");
out.write(_("Status"));
out.write("\"></th>\n<th>");
if (_manager.util().connected() && !snarks.isEmpty()) {
out.write(" <a href=\"" + _contextPath + '/');
if (peerParam != null) {
if (stParam != null) {
out.write("?st=");
out.write(stParam);
}
out.write("\">");
out.write("<img border=\"0\" src=\"" + _imgPath + "hidepeers.png\" title=\"");
out.write(_("Hide Peers"));
out.write("\" alt=\"");
out.write(_("Hide Peers"));
out.write("\">");
} else {
out.write("?p=1");
if (stParam != null) {
out.write("&st=");
out.write(stParam);
}
out.write("\">");
out.write("<img border=\"0\" src=\"" + _imgPath + "showpeers.png\" title=\"");
out.write(_("Show Peers"));
out.write("\" alt=\"");
out.write(_("Show Peers"));
out.write("\">");
}
out.write("</a><br>\n");
}
out.write("</th>\n<th colspan=\"2\" align=\"left\">");
out.write("<img border=\"0\" src=\"" + _imgPath + "torrent.png\" title=\"");
out.write(_("Torrent"));
out.write("\" alt=\"");
out.write(_("Torrent"));
out.write("\"></th>\n<th align=\"center\">");
if (total > 0 && (start > 0 || total > pageSize)) {
writePageNav(out, start, pageSize, total, peerParam, noThinsp);
}
out.write("</th>\n<th align=\"right\">");
if (_manager.util().connected() && !snarks.isEmpty()) {
out.write("<img border=\"0\" src=\"" + _imgPath + "eta.png\" title=\"");
out.write(_("Estimated time remaining"));
out.write("\" alt=\"");
// Translators: Please keep short or translate as " "
out.write(_("ETA"));
out.write("\">");
}
out.write("</th>\n<th align=\"right\">");
out.write("<img border=\"0\" src=\"" + _imgPath + "head_rx.png\" title=\"");
out.write(_("Downloaded"));
out.write("\" alt=\"");
// Translators: Please keep short or translate as " "
out.write(_("RX"));
out.write("\">");
out.write("</th>\n<th align=\"right\">");
if (_manager.util().connected() && !snarks.isEmpty()) {
out.write("<img border=\"0\" src=\"" + _imgPath + "head_tx.png\" title=\"");
out.write(_("Uploaded"));
out.write("\" alt=\"");
// Translators: Please keep short or translate as " "
out.write(_("TX"));
out.write("\">");
}
out.write("</th>\n<th align=\"right\">");
if (_manager.util().connected() && !snarks.isEmpty()) {
out.write("<img border=\"0\" src=\"" + _imgPath + "head_rxspeed.png\" title=\"");
out.write(_("Down Rate"));
out.write("\" alt=\"");
// Translators: Please keep short or translate as " "
out.write(_("RX Rate"));
out.write(" \">");
}
out.write("</th>\n<th align=\"right\">");
if (_manager.util().connected() && !snarks.isEmpty()) {
out.write("<img border=\"0\" src=\"" + _imgPath + "head_txspeed.png\" title=\"");
out.write(_("Up Rate"));
out.write("\" alt=\"");
// Translators: Please keep short or translate as " "
out.write(_("TX Rate"));
out.write(" \">");
}
out.write("</th>\n<th align=\"center\">");
if (_manager.isStopping()) {
out.write(" ");
} else if (_manager.util().connected()) {
if (isDegraded)
out.write("<a href=\"" + _contextPath + "/?action=StopAll&nonce=" + _nonce + "\"><img title=\"");
else {
// http://www.onenaught.com/posts/382/firefox-4-change-input-type-image-only-submits-x-and-y-not-name
//out.write("<input type=\"image\" name=\"action\" value=\"StopAll\" title=\"");
out.write("<input type=\"image\" name=\"action_StopAll\" value=\"foo\" title=\"");
}
out.write(_("Stop all torrents and the I2P tunnel"));
out.write("\" src=\"" + _imgPath + "stop_all.png\" alt=\"");
out.write(_("Stop All"));
out.write("\">");
if (isDegraded)
out.write("</a>");
for (Snark s : snarks) {
if (s.isStopped()) {
// show startall too
out.write("<br>");
if (isDegraded)
out.write("<a href=\"" + _contextPath + "/?action=StartAll&nonce=" + _nonce + "\"><img title=\"");
else
out.write("<input type=\"image\" name=\"action_StartAll\" value=\"foo\" title=\"");
out.write(_("Start all stopped torrents"));
out.write("\" src=\"" + _imgPath + "start_all.png\" alt=\"");
out.write(_("Start All"));
out.write("\">");
if (isDegraded)
out.write("</a>");
break;
}
}
} else if ((!_manager.util().isConnecting()) && !snarks.isEmpty()) {
if (isDegraded)
out.write("<a href=\"" + _contextPath + "/?action=StartAll&nonce=" + _nonce + "\"><img title=\"");
else
out.write("<input type=\"image\" name=\"action_StartAll\" value=\"foo\" title=\"");
out.write(_("Start all torrents and the I2P tunnel"));
out.write("\" src=\"" + _imgPath + "start_all.png\" alt=\"");
out.write(_("Start All"));
out.write("\">");
if (isDegraded)
out.write("</a>");
} else {
out.write(" ");
}
out.write("</th></tr>\n");
out.write("</thead>\n");
String uri = _contextPath + '/';
boolean showDebug = "2".equals(peerParam);
String stParamStr = stParam == null ? "" : "&st=" + stParam;
for (int i = 0; i < total; i++) {
Snark snark = (Snark)snarks.get(i);
boolean showPeers = showDebug || "1".equals(peerParam) || Base64.encode(snark.getInfoHash()).equals(peerParam);
boolean hide = i < start || i >= start + pageSize;
displaySnark(out, snark, uri, i, stats, showPeers, isDegraded, noThinsp, showDebug, hide, stParamStr);
}
if (total == 0) {
out.write("<tr class=\"snarkTorrentNoneLoaded\">" +
"<td class=\"snarkTorrentNoneLoaded\"" +
" colspan=\"11\"><i>");
out.write(_("No torrents loaded."));
out.write("</i></td></tr>\n");
} else /** if (snarks.size() > 1) */ {
out.write("<tfoot><tr>\n" +
" <th align=\"left\" colspan=\"6\">");
out.write(" ");
out.write(_("Totals"));
out.write(": ");
out.write(ngettext("1 torrent", "{0} torrents", total));
out.write(", ");
out.write(DataHelper.formatSize2(stats[5]) + "B");
if (_manager.util().connected() && total > 0) {
out.write(", ");
out.write(ngettext("1 connected peer", "{0} connected peers", (int) stats[4]));
}
DHT dht = _manager.util().getDHT();
if (dht != null) {
int dhts = dht.size();
if (dhts > 0) {
out.write(", ");
out.write(ngettext("1 DHT peer", "{0} DHT peers", dhts));
}
if (showDebug)
out.write(dht.renderStatusHTML());
}
out.write("</th>\n");
if (_manager.util().connected() && total > 0) {
out.write(" <th align=\"right\">" + formatSize(stats[0]) + "</th>\n" +
" <th align=\"right\">" + formatSize(stats[1]) + "</th>\n" +
" <th align=\"right\">" + formatSize(stats[2]) + "ps</th>\n" +
" <th align=\"right\">" + formatSize(stats[3]) + "ps</th>\n" +
" <th></th>");
} else {
out.write("<th colspan=\"5\"></th>");
}
out.write("</tr></tfoot>\n");
}
out.write("</table>");
if (isForm)
out.write("</form>\n");
return start == 0;
}
/**
* @since 0.9.6
*/
private void writePageNav(PrintWriter out, int start, int pageSize, int total,
String peerParam, boolean noThinsp) {
// Page nav
if (start > 0) {
// First
out.write("<a href=\"" + _contextPath);
if (peerParam != null)
out.write("?p=" + peerParam);
out.write("\">" +
"<img alt=\"" + _("First") + "\" title=\"" + _("First page") + "\" border=\"0\" src=\"" +
_imgPath + "control_rewind_blue.png\">" +
"</a> ");
int prev = Math.max(0, start - pageSize);
//if (prev > 0) {
if (true) {
// Back
out.write(" <a href=\"" + _contextPath + "?st=" + prev);
if (peerParam != null)
out.write("&p=" + peerParam);
out.write("\">" +
"<img alt=\"" + _("Prev") + "\" title=\"" + _("Previous page") + "\" border=\"0\" src=\"" +
_imgPath + "control_back_blue.png\">" +
"</a> ");
}
} else {
out.write(
"<img alt=\"\" border=\"0\" class=\"disable\" src=\"" +
_imgPath + "control_rewind_blue.png\">" +
" " +
"<img alt=\"\" border=\"0\" class=\"disable\" src=\"" +
_imgPath + "control_back_blue.png\">" +
" ");
}
// Page count
int pages = 1 + ((total - 1) / pageSize);
if (pages == 1 && start > 0)
pages = 2;
if (pages > 1) {
int page;
if (start + pageSize >= total)
page = pages;
else
page = 1 + (start / pageSize);
//out.write(" " + _("Page {0}", page) + thinsp(noThinsp) + pages + " ");
out.write(" " + page + thinsp(noThinsp) + pages + " ");
}
if (start + pageSize < total) {
int next = start + pageSize;
//if (next + pageSize < total) {
if (true) {
// Next
out.write(" <a href=\"" + _contextPath + "?st=" + next);
if (peerParam != null)
out.write("&p=" + peerParam);
out.write("\">" +
"<img alt=\"" + _("Next") + "\" title=\"" + _("Next page") + "\" border=\"0\" src=\"" +
_imgPath + "control_play_blue.png\">" +
"</a> ");
}
// Last
int last = ((total - 1) / pageSize) * pageSize;
out.write(" <a href=\"" + _contextPath + "?st=" + last);
if (peerParam != null)
out.write("&p=" + peerParam);
out.write("\">" +
"<img alt=\"" + _("Last") + "\" title=\"" + _("Last page") + "\" border=\"0\" src=\"" +
_imgPath + "control_fastforward_blue.png\">" +
"</a> ");
} else {
out.write(" " +
"<img alt=\"\" border=\"0\" class=\"disable\" src=\"" +
_imgPath + "control_play_blue.png\">" +
" " +
"<img alt=\"\" border=\"0\" class=\"disable\" src=\"" +
_imgPath + "control_fastforward_blue.png\">");
}
}
/**
* Do what they ask, adding messages to _manager.addMessage as necessary
*/
private void processRequest(HttpServletRequest req) {
String action = req.getParameter("action");
if (action == null) {
// http://www.onenaught.com/posts/382/firefox-4-change-input-type-image-only-submits-x-and-y-not-name
Map params = req.getParameterMap();
for (Object o : params.keySet()) {
String key = (String) o;
if (key.startsWith("action_") && key.endsWith(".x")) {
action = key.substring(0, key.length() - 2).substring(7);
break;
}
}
if (action == null) {
_manager.addMessage("No action specified");
return;
}
}
// sadly, Opera doesn't send value with input type=image, so we have to use GET there
//if (!"POST".equals(req.getMethod())) {
// _manager.addMessage("Action must be with POST");
// return;
//}
if ("Add".equals(action)) {
String newURL = req.getParameter("newURL");
/******
// NOTE - newFile currently disabled in HTML form - see below
File f = null;
if ( (newFile != null) && (newFile.trim().length() > 0) )
f = new File(newFile.trim());
if ( (f != null) && (!f.exists()) ) {
_manager.addMessage(_("Torrent file {0} does not exist", newFile));
}
if ( (f != null) && (f.exists()) ) {
// NOTE - All this is disabled - load from local file disabled
File local = new File(_manager.getDataDir(), f.getName());
String canonical = null;
try {
canonical = local.getCanonicalPath();
if (local.exists()) {
if (_manager.getTorrent(canonical) != null)
_manager.addMessage(_("Torrent already running: {0}", newFile));
else
_manager.addMessage(_("Torrent already in the queue: {0}", newFile));
} else {
boolean ok = FileUtil.copy(f.getAbsolutePath(), local.getAbsolutePath(), true);
if (ok) {
_manager.addMessage(_("Copying torrent to {0}", local.getAbsolutePath()));
_manager.addTorrent(canonical);
} else {
_manager.addMessage(_("Unable to copy the torrent to {0}", local.getAbsolutePath()) + ' ' + _("from {0}", f.getAbsolutePath()));
}
}
} catch (IOException ioe) {
_log.warn("hrm: " + local, ioe);
}
} else
*****/
if (newURL != null) {
if (newURL.startsWith("http://")) {
FetchAndAdd fetch = new FetchAndAdd(_context, _manager, newURL);
_manager.addDownloader(fetch);
} else if (newURL.startsWith(MagnetURI.MAGNET) || newURL.startsWith(MagnetURI.MAGGOT)) {
addMagnet(newURL);
} else if (newURL.length() == 40 && newURL.replaceAll("[a-fA-F0-9]", "").length() == 0) {
addMagnet(MagnetURI.MAGNET_FULL + newURL);
} else {
_manager.addMessage(_("Invalid URL: Must start with \"http://\", \"{0}\", or \"{1}\"",
MagnetURI.MAGNET, MagnetURI.MAGGOT));
}
} else {
// no file or URL specified
}
} else if (action.startsWith("Stop_")) {
String torrent = action.substring(5);
if (torrent != null) {
byte infoHash[] = Base64.decode(torrent);
if ( (infoHash != null) && (infoHash.length == 20) ) { // valid sha1
for (Iterator iter = _manager.listTorrentFiles().iterator(); iter.hasNext(); ) {
String name = (String)iter.next();
Snark snark = _manager.getTorrent(name);
if ( (snark != null) && (DataHelper.eq(infoHash, snark.getInfoHash())) ) {
_manager.stopTorrent(snark, false);
break;
}
}
}
}
} else if (action.startsWith("Start_")) {
String torrent = action.substring(6);
if (torrent != null) {
byte infoHash[] = Base64.decode(torrent);
if ( (infoHash != null) && (infoHash.length == 20) ) { // valid sha1
_manager.startTorrent(infoHash);
}
}
} else if (action.startsWith("Remove_")) {
String torrent = action.substring(7);
if (torrent != null) {
byte infoHash[] = Base64.decode(torrent);
if ( (infoHash != null) && (infoHash.length == 20) ) { // valid sha1
for (Iterator iter = _manager.listTorrentFiles().iterator(); iter.hasNext(); ) {
String name = (String)iter.next();
Snark snark = _manager.getTorrent(name);
if ( (snark != null) && (DataHelper.eq(infoHash, snark.getInfoHash())) ) {
MetaInfo meta = snark.getMetaInfo();
if (meta == null) {
// magnet - remove and delete are the same thing
// Remove not shown on UI so we shouldn't get here
_manager.deleteMagnet(snark);
_manager.addMessage(_("Magnet deleted: {0}", name));
return;
}
_manager.stopTorrent(snark, true);
// should we delete the torrent file?
// yeah, need to, otherwise it'll get autoadded again (at the moment
File f = new File(name);
f.delete();
_manager.addMessage(_("Torrent file deleted: {0}", f.getAbsolutePath()));
break;
}
}
}
}
} else if (action.startsWith("Delete_")) {
String torrent = action.substring(7);
if (torrent != null) {
byte infoHash[] = Base64.decode(torrent);
if ( (infoHash != null) && (infoHash.length == 20) ) { // valid sha1
for (Iterator iter = _manager.listTorrentFiles().iterator(); iter.hasNext(); ) {
String name = (String)iter.next();
Snark snark = _manager.getTorrent(name);
if ( (snark != null) && (DataHelper.eq(infoHash, snark.getInfoHash())) ) {
MetaInfo meta = snark.getMetaInfo();
if (meta == null) {
// magnet - remove and delete are the same thing
_manager.deleteMagnet(snark);
if (snark instanceof FetchAndAdd)
_manager.addMessage(_("Download deleted: {0}", name));
else
_manager.addMessage(_("Magnet deleted: {0}", name));
return;
}
_manager.stopTorrent(snark, true);
File f = new File(name);
f.delete();
_manager.addMessage(_("Torrent file deleted: {0}", f.getAbsolutePath()));
List<List<String>> files = meta.getFiles();
String dataFile = snark.getBaseName();
f = new File(_manager.getDataDir(), dataFile);
if (files == null) { // single file torrent
if (f.delete())
_manager.addMessage(_("Data file deleted: {0}", f.getAbsolutePath()));
else
_manager.addMessage(_("Data file could not be deleted: {0}", f.getAbsolutePath()));
break;
}
// step 1 delete files
for (int i = 0; i < files.size(); i++) {
// multifile torrents have the getFiles() return lists of lists of filenames, but
// each of those lists just contain a single file afaict...
File df = Storage.getFileFromNames(f, files.get(i));
if (df.delete()) {
//_manager.addMessage(_("Data file deleted: {0}", df.getAbsolutePath()));
} else {
_manager.addMessage(_("Data file could not be deleted: {0}", df.getAbsolutePath()));
}
}
// step 2 make Set of dirs with reverse sort
Set<File> dirs = new TreeSet(Collections.reverseOrder());
for (List<String> list : files) {
for (int i = 1; i < list.size(); i++) {
dirs.add(Storage.getFileFromNames(f, list.subList(0, i)));
}
}
// step 3 delete dirs bottom-up
for (File df : dirs) {
if (df.delete()) {
//_manager.addMessage(_("Data dir deleted: {0}", df.getAbsolutePath()));
} else {
_manager.addMessage(_("Directory could not be deleted: {0}", df.getAbsolutePath()));
if (_log.shouldLog(Log.WARN))
_log.warn("Could not delete dir " + df);
}
}
// step 4 delete base
if (f.delete()) {
_manager.addMessage(_("Directory deleted: {0}", f.getAbsolutePath()));
} else {
_manager.addMessage(_("Directory could not be deleted: {0}", f.getAbsolutePath()));
if (_log.shouldLog(Log.WARN))
_log.warn("Could not delete dir " + f);
}
break;
}
}
}
}
} else if ("Save".equals(action)) {
String dataDir = req.getParameter("dataDir");
boolean filesPublic = req.getParameter("filesPublic") != null;
boolean autoStart = req.getParameter("autoStart") != null;
String seedPct = req.getParameter("seedPct");
String eepHost = req.getParameter("eepHost");
String eepPort = req.getParameter("eepPort");
String i2cpHost = req.getParameter("i2cpHost");
String i2cpPort = req.getParameter("i2cpPort");
String i2cpOpts = buildI2CPOpts(req);
String upLimit = req.getParameter("upLimit");
String upBW = req.getParameter("upBW");
String refreshDel = req.getParameter("refreshDelay");
String startupDel = req.getParameter("startupDelay");
String pageSize = req.getParameter("pageSize");
boolean useOpenTrackers = req.getParameter("useOpenTrackers") != null;
boolean useDHT = req.getParameter("useDHT") != null;
//String openTrackers = req.getParameter("openTrackers");
String theme = req.getParameter("theme");
_manager.updateConfig(dataDir, filesPublic, autoStart, refreshDel, startupDel, pageSize,
seedPct, eepHost, eepPort, i2cpHost, i2cpPort, i2cpOpts,
upLimit, upBW, useOpenTrackers, useDHT, theme);
// update servlet
try {
setResourceBase(_manager.getDataDir());
} catch (ServletException se) {}
} else if ("Save2".equals(action)) {
String taction = req.getParameter("taction");
if (taction != null)
processTrackerForm(taction, req);
} else if ("Create".equals(action)) {
String baseData = req.getParameter("baseFile");
if (baseData != null && baseData.trim().length() > 0) {
File baseFile = new File(_manager.getDataDir(), baseData);
String announceURL = req.getParameter("announceURL");
// make the user add a tracker on the config form now
//String announceURLOther = req.getParameter("announceURLOther");
//if ( (announceURLOther != null) && (announceURLOther.trim().length() > "http://.i2p/announce".length()) )
// announceURL = announceURLOther;
if (baseFile.exists()) {
if (announceURL.equals("none"))
announceURL = null;
_lastAnnounceURL = announceURL;
List<String> backupURLs = new ArrayList();
Enumeration e = req.getParameterNames();
while (e.hasMoreElements()) {
Object o = e.nextElement();
if (!(o instanceof String))
continue;
String k = (String) o;
if (k.startsWith("backup_")) {
String url = k.substring(7);
if (!url.equals(announceURL))
backupURLs.add(url);
}
}
List<List<String>> announceList = null;
if (!backupURLs.isEmpty()) {
// BEP 12 - Put primary first, then the others, each as the sole entry in their own list
if (announceURL == null) {
_manager.addMessage(_("Error - Cannot include alternate trackers without a primary tracker"));
return;
}
backupURLs.add(0, announceURL);
boolean hasPrivate = false;
boolean hasPublic = false;
for (String url : backupURLs) {
if (_manager.getPrivateTrackers().contains(announceURL))
hasPrivate = true;
else
hasPublic = true;
}
if (hasPrivate && hasPublic) {
_manager.addMessage(_("Error - Cannot mix private and public trackers in a torrent"));
return;
}
announceList = new ArrayList(backupURLs.size());
for (String url : backupURLs) {
announceList.add(Collections.singletonList(url));
}
}
try {
// This may take a long time to check the storage, but since it already exists,
// it shouldn't be THAT bad, so keep it in this thread.
// TODO thread it for big torrents, perhaps a la FetchAndAdd
boolean isPrivate = _manager.getPrivateTrackers().contains(announceURL);
Storage s = new Storage(_manager.util(), baseFile, announceURL, announceList, isPrivate, null);
s.close(); // close the files... maybe need a way to pass this Storage to addTorrent rather than starting over
MetaInfo info = s.getMetaInfo();
File torrentFile = new File(_manager.getDataDir(), s.getBaseName() + ".torrent");
// FIXME is the storage going to stay around thanks to the info reference?
// now add it, but don't automatically start it
_manager.addTorrent(info, s.getBitField(), torrentFile.getAbsolutePath(), true);
_manager.addMessage(_("Torrent created for \"{0}\"", baseFile.getName()) + ": " + torrentFile.getAbsolutePath());
if (announceURL != null && !_manager.util().getOpenTrackers().contains(announceURL))
_manager.addMessage(_("Many I2P trackers require you to register new torrents before seeding - please do so before starting \"{0}\"", baseFile.getName()));
} catch (IOException ioe) {
_manager.addMessage(_("Error creating a torrent for \"{0}\"", baseFile.getAbsolutePath()) + ": " + ioe);
_log.error("Error creating a torrent", ioe);
}
} else {
_manager.addMessage(_("Cannot create a torrent for the nonexistent data: {0}", baseFile.getAbsolutePath()));
}
} else {
_manager.addMessage(_("Error creating torrent - you must enter a file or directory"));
}
} else if ("StopAll".equals(action)) {
_manager.stopAllTorrents(false);
} else if ("StartAll".equals(action)) {
_manager.startAllTorrents();
} else if ("Clear".equals(action)) {
_manager.clearMessages();
} else {
_manager.addMessage("Unknown POST action: \"" + action + '\"');
}
}
/**
* Redirect a POST to a GET (P-R-G), preserving the peer string
* @since 0.9.5
*/
private void sendRedirect(HttpServletRequest req, HttpServletResponse resp, String p) throws IOException {
String url = req.getRequestURL().toString();
StringBuilder buf = new StringBuilder(128);
if (url.endsWith("_post"))
url = url.substring(0, url.length() - 5);
buf.append(url);
if (p.length() > 0)
buf.append(p.replace("&", "&")); // no you don't html escape the redirect header
resp.setHeader("Location", buf.toString());
resp.sendError(302, "Moved");
}
/** @since 0.9 */
private void processTrackerForm(String action, HttpServletRequest req) {
if (action.equals(_("Delete selected")) || action.equals(_("Save tracker configuration"))) {
boolean changed = false;
Map<String, Tracker> trackers = _manager.getTrackerMap();
List<String> removed = new ArrayList();
List<String> open = new ArrayList();
List<String> priv = new ArrayList();
Enumeration e = req.getParameterNames();
while (e.hasMoreElements()) {
Object o = e.nextElement();
if (!(o instanceof String))
continue;
String k = (String) o;
if (k.startsWith("delete_")) {
k = k.substring(7);
Tracker t;
if ((t = trackers.remove(k)) != null) {
removed.add(t.announceURL);
_manager.addMessage(_("Removed") + ": " + k);
changed = true;
}
} else if (k.startsWith("open_")) {
open.add(k.substring(5));
} else if (k.startsWith("private_")) {
priv.add(k.substring(8));
}
}
if (changed) {
_manager.saveTrackerMap();
}
open.removeAll(removed);
List<String> oldOpen = new ArrayList(_manager.util().getOpenTrackers());
Collections.sort(oldOpen);
Collections.sort(open);
if (!open.equals(oldOpen))
_manager.saveOpenTrackers(open);
priv.removeAll(removed);
// open trumps private
priv.removeAll(open);
List<String> oldPriv = new ArrayList(_manager.getPrivateTrackers());
Collections.sort(oldPriv);
Collections.sort(priv);
if (!priv.equals(oldPriv))
_manager.savePrivateTrackers(priv);
} else if (action.equals(_("Add tracker"))) {
String name = req.getParameter("tname");
String hurl = req.getParameter("thurl");
String aurl = req.getParameter("taurl");
if (name != null && hurl != null && aurl != null) {
name = name.trim();
hurl = hurl.trim();
aurl = aurl.trim().replace("=", "=");
if (name.length() > 0 && hurl.startsWith("http://") && TrackerClient.isValidAnnounce(aurl)) {
Map<String, Tracker> trackers = _manager.getTrackerMap();
trackers.put(name, new Tracker(name, aurl, hurl));
_manager.saveTrackerMap();
// open trumps private
if (req.getParameter("_add_open_") != null) {
List newOpen = new ArrayList(_manager.util().getOpenTrackers());
newOpen.add(aurl);
_manager.saveOpenTrackers(newOpen);
} else if (req.getParameter("_add_private_") != null) {
List newPriv = new ArrayList(_manager.getPrivateTrackers());
newPriv.add(aurl);
_manager.savePrivateTrackers(newPriv);
}
} else {
_manager.addMessage(_("Enter valid tracker name and URLs"));
}
} else {
_manager.addMessage(_("Enter valid tracker name and URLs"));
}
} else if (action.equals(_("Restore defaults"))) {
_manager.setDefaultTrackerMap();
_manager.saveOpenTrackers(null);
_manager.addMessage(_("Restored default trackers"));
} else {
_manager.addMessage("Unknown POST action: \"" + action + '\"');
}
}
private static final String iopts[] = {"inbound.length", "inbound.quantity",
"outbound.length", "outbound.quantity" };
/** put the individual i2cp selections into the option string */
private static String buildI2CPOpts(HttpServletRequest req) {
StringBuilder buf = new StringBuilder(128);
String p = req.getParameter("i2cpOpts");
if (p != null)
buf.append(p);
for (int i = 0; i < iopts.length; i++) {
p = req.getParameter(iopts[i]);
if (p != null)
buf.append(' ').append(iopts[i]).append('=').append(p);
}
return buf.toString();
}
/**
* Sort alphabetically in current locale, ignore case, ignore leading "the "
* (I guess this is worth it, a lot of torrents start with "The "
* @since 0.7.14
*/
private static class TorrentNameComparator implements Comparator<Snark> {
private final Comparator collator = Collator.getInstance();
public int compare(Snark l, Snark r) {
// put downloads and magnets first
if (l.getStorage() == null && r.getStorage() != null)
return -1;
if (l.getStorage() != null && r.getStorage() == null)
return 1;
String ls = l.getBaseName();
String llc = ls.toLowerCase(Locale.US);
if (llc.startsWith("the ") || llc.startsWith("the.") || llc.startsWith("the_"))
ls = ls.substring(4);
String rs = r.getBaseName();
String rlc = rs.toLowerCase(Locale.US);
if (rlc.startsWith("the ") || rlc.startsWith("the.") || rlc.startsWith("the_"))
rs = rs.substring(4);
return collator.compare(ls, rs);
}
}
private List<Snark> getSortedSnarks(HttpServletRequest req) {
ArrayList<Snark> rv = new ArrayList(_manager.getTorrents());
Collections.sort(rv, new TorrentNameComparator());
return rv;
}
private static final int MAX_DISPLAYED_FILENAME_LENGTH = 50;
private static final int MAX_DISPLAYED_ERROR_LENGTH = 43;
/**
* Display one snark (one line in table, unless showPeers is true)
*
* @param stats in/out param (totals)
* @param statsOnly if true, output nothing, update stats only
* @param stParam non null; empty or e.g. &st=10
*/
private void displaySnark(PrintWriter out, Snark snark, String uri, int row, long stats[], boolean showPeers,
boolean isDegraded, boolean noThinsp, boolean showDebug, boolean statsOnly,
String stParam) throws IOException {
// stats
long uploaded = snark.getUploaded();
stats[0] += snark.getDownloaded();
stats[1] += uploaded;
long downBps = snark.getDownloadRate();
long upBps = snark.getUploadRate();
boolean isRunning = !snark.isStopped();
if (isRunning) {
stats[2] += downBps;
stats[3] += upBps;
}
int curPeers = snark.getPeerCount();
stats[4] += curPeers;
long total = snark.getTotalLength();
if (total > 0)
stats[5] += total;
if (statsOnly)
return;
String basename = snark.getBaseName();
+ String fullBasename = basename;
if (basename.length() > MAX_DISPLAYED_FILENAME_LENGTH) {
String start = basename.substring(0, MAX_DISPLAYED_FILENAME_LENGTH);
if (start.indexOf(" ") < 0 && start.indexOf("-") < 0) {
// browser has nowhere to break it
basename = start + "…";
}
}
// includes skipped files, -1 for magnet mode
long remaining = snark.getRemainingLength();
if (remaining > total)
remaining = total;
// does not include skipped files, -1 for magnet mode or when not running.
long needed = snark.getNeededLength();
if (needed > total)
needed = total;
long remainingSeconds;
if (downBps > 0 && needed > 0)
remainingSeconds = needed / downBps;
else
remainingSeconds = -1;
MetaInfo meta = snark.getMetaInfo();
// isValid means isNotMagnet
boolean isValid = meta != null;
boolean isMultiFile = isValid && meta.getFiles() != null;
String err = snark.getTrackerProblems();
int knownPeers = Math.max(curPeers, snark.getTrackerSeenPeers());
String rowClass = (row % 2 == 0 ? "snarkTorrentEven" : "snarkTorrentOdd");
String statusString;
if (snark.isChecking()) {
statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "stalled.png\" title=\"" + _("Checking") + "\"></td>" +
"<td class=\"snarkTorrentStatus\">" + _("Checking");
} else if (snark.isAllocating()) {
statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "stalled.png\" title=\"" + _("Allocating") + "\"></td>" +
"<td class=\"snarkTorrentStatus\">" + _("Allocating");
} else if (err != null && curPeers == 0) {
// Also don't show if seeding... but then we won't see the not-registered error
// && remaining != 0 && needed != 0) {
// let's only show this if we have no peers, otherwise PEX and DHT should bail us out, user doesn't care
//if (isRunning && curPeers > 0 && !showPeers)
// statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "trackererror.png\" title=\"" + err + "\"></td>" +
// "<td class=\"snarkTorrentStatus " + rowClass + "\">" + _("Tracker Error") +
// ": <a href=\"" + uri + "?p=" + Base64.encode(snark.getInfoHash()) + "\">" +
// curPeers + thinsp(noThinsp) +
// ngettext("1 peer", "{0} peers", knownPeers) + "</a>";
//else if (isRunning)
if (isRunning)
statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "trackererror.png\" title=\"" + err + "\"></td>" +
"<td class=\"snarkTorrentStatus\">" + _("Tracker Error") +
": " + curPeers + thinsp(noThinsp) +
ngettext("1 peer", "{0} peers", knownPeers);
else {
if (err.length() > MAX_DISPLAYED_ERROR_LENGTH)
err = err.substring(0, MAX_DISPLAYED_ERROR_LENGTH) + "…";
statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "trackererror.png\" title=\"" + err + "\"></td>" +
"<td class=\"snarkTorrentStatus\">" + _("Tracker Error");
}
} else if (snark.isStarting()) {
statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "stalled.png\" title=\"" + _("Starting") + "\"></td>" +
"<td class=\"snarkTorrentStatus\">" + _("Starting");
} else if (remaining == 0 || needed == 0) { // < 0 means no meta size yet
// partial complete or seeding
if (isRunning) {
String img;
String txt;
if (remaining == 0) {
img = "seeding";
txt = _("Seeding");
} else {
// partial
img = "complete";
txt = _("Complete");
}
if (curPeers > 0 && !showPeers)
statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + img + ".png\" title=\"" + txt + "\"></td>" +
"<td class=\"snarkTorrentStatus\">" + txt +
": <a href=\"" + uri + "?p=" + Base64.encode(snark.getInfoHash()) + stParam + "\">" +
curPeers + thinsp(noThinsp) +
ngettext("1 peer", "{0} peers", knownPeers) + "</a>";
else
statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + img + ".png\" title=\"" + txt + "\"></td>" +
"<td class=\"snarkTorrentStatus\">" + txt +
": " + curPeers + thinsp(noThinsp) +
ngettext("1 peer", "{0} peers", knownPeers);
} else {
statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "complete.png\" title=\"" + _("Complete") + "\"></td>" +
"<td class=\"snarkTorrentStatus\">" + _("Complete");
}
} else {
if (isRunning && curPeers > 0 && downBps > 0 && !showPeers)
statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "downloading.png\" title=\"" + _("OK") + "\"></td>" +
"<td class=\"snarkTorrentStatus\">" + _("OK") +
": <a href=\"" + uri + "?p=" + Base64.encode(snark.getInfoHash()) + stParam + "\">" +
curPeers + thinsp(noThinsp) +
ngettext("1 peer", "{0} peers", knownPeers) + "</a>";
else if (isRunning && curPeers > 0 && downBps > 0)
statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "downloading.png\" title=\"" + _("OK") + "\"></td>" +
"<td class=\"snarkTorrentStatus\">" + _("OK") +
": " + curPeers + thinsp(noThinsp) +
ngettext("1 peer", "{0} peers", knownPeers);
else if (isRunning && curPeers > 0 && !showPeers)
statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "stalled.png\" title=\"" + _("Stalled") + "\"></td>" +
"<td class=\"snarkTorrentStatus\">" + _("Stalled") +
": <a href=\"" + uri + "?p=" + Base64.encode(snark.getInfoHash()) + stParam + "\">" +
curPeers + thinsp(noThinsp) +
ngettext("1 peer", "{0} peers", knownPeers) + "</a>";
else if (isRunning && curPeers > 0)
statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "stalled.png\" title=\"" + _("Stalled") + "\"></td>" +
"<td class=\"snarkTorrentStatus\">" + _("Stalled") +
": " + curPeers + thinsp(noThinsp) +
ngettext("1 peer", "{0} peers", knownPeers);
else if (isRunning && knownPeers > 0)
statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "nopeers.png\" title=\"" + _("No Peers") + "\"></td>" +
"<td class=\"snarkTorrentStatus\">" + _("No Peers") +
": 0" + thinsp(noThinsp) + knownPeers ;
else if (isRunning)
statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "nopeers.png\" title=\"" + _("No Peers") + "\"></td>" +
"<td class=\"snarkTorrentStatus\">" + _("No Peers");
else
statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "stopped.png\" title=\"" + _("Stopped") + "\"></td>" +
"<td class=\"snarkTorrentStatus\">" + _("Stopped");
}
out.write("<tr class=\"" + rowClass + "\">");
out.write("<td class=\"center\">");
out.write(statusString + "</td>\n\t");
// (i) icon column
out.write("<td>");
if (isValid && meta.getAnnounce() != null) {
// Link to local details page - note that trailing slash on a single-file torrent
// gets us to the details page instead of the file.
//StringBuilder buf = new StringBuilder(128);
//buf.append("<a href=\"").append(snark.getBaseName())
// .append("/\" title=\"").append(_("Torrent details"))
// .append("\"><img alt=\"").append(_("Info")).append("\" border=\"0\" src=\"")
// .append(_imgPath).append("details.png\"></a>");
//out.write(buf.toString());
// Link to tracker details page
String trackerLink = getTrackerLink(meta.getAnnounce(), snark.getInfoHash());
if (trackerLink != null)
out.write(trackerLink);
}
- String encodedBaseName = urlEncode(basename);
+ String encodedBaseName = urlEncode(fullBasename);
// File type icon column
out.write("</td>\n<td>");
if (isValid) {
// Link to local details page - note that trailing slash on a single-file torrent
// gets us to the details page instead of the file.
StringBuilder buf = new StringBuilder(128);
buf.append("<a href=\"").append(encodedBaseName)
.append("/\" title=\"").append(_("Torrent details"))
.append("\">");
out.write(buf.toString());
}
String icon;
if (isMultiFile)
icon = "folder";
else if (isValid)
icon = toIcon(meta.getName());
else if (snark instanceof FetchAndAdd)
icon = "basket_put";
else
icon = "magnet";
if (isValid) {
out.write(toImg(icon));
out.write("</a>");
} else {
out.write(toImg(icon));
}
// Torrent name column
out.write("</td><td class=\"snarkTorrentName\">");
if (remaining == 0 || isMultiFile) {
StringBuilder buf = new StringBuilder(128);
buf.append("<a href=\"").append(encodedBaseName);
if (isMultiFile)
buf.append('/');
buf.append("\" title=\"");
if (isMultiFile)
buf.append(_("View files"));
else
buf.append(_("Open file"));
buf.append("\">");
out.write(buf.toString());
}
out.write(basename);
if (remaining == 0 || isMultiFile)
out.write("</a>");
out.write("<td align=\"right\" class=\"snarkTorrentETA\">");
if(isRunning && remainingSeconds > 0 && !snark.isChecking())
out.write(DataHelper.formatDuration2(Math.max(remainingSeconds, 10) * 1000)); // (eta 6h)
out.write("</td>\n\t");
out.write("<td align=\"right\" class=\"snarkTorrentDownloaded\">");
if (remaining > 0)
out.write(formatSize(total-remaining) + thinsp(noThinsp) + formatSize(total));
else if (remaining == 0)
out.write(formatSize(total)); // 3GB
//else
// out.write("??"); // no meta size yet
out.write("</td>\n\t");
out.write("<td align=\"right\" class=\"snarkTorrentUploaded\">");
if(isRunning && isValid)
out.write(formatSize(uploaded));
out.write("</td>\n\t");
out.write("<td align=\"right\" class=\"snarkTorrentRateDown\">");
if(isRunning && needed > 0)
out.write(formatSize(downBps) + "ps");
out.write("</td>\n\t");
out.write("<td align=\"right\" class=\"snarkTorrentRateUp\">");
if(isRunning && isValid)
out.write(formatSize(upBps) + "ps");
out.write("</td>\n\t");
out.write("<td align=\"center\" class=\"snarkTorrentAction\">");
String b64 = Base64.encode(snark.getInfoHash());
if (snark.isChecking()) {
// show no buttons
} else if (isRunning) {
// Stop Button
if (isDegraded)
out.write("<a href=\"" + _contextPath + "/?action=Stop_" + b64 + "&nonce=" + _nonce + stParam + "\"><img title=\"");
else
out.write("<input type=\"image\" name=\"action_Stop_" + b64 + "\" value=\"foo\" title=\"");
out.write(_("Stop the torrent"));
out.write("\" src=\"" + _imgPath + "stop.png\" alt=\"");
out.write(_("Stop"));
out.write("\">");
if (isDegraded)
out.write("</a>");
} else if (!snark.isStarting()) {
if (!_manager.isStopping()) {
// Start Button
// This works in Opera but it's displayed a little differently, so use noThinsp here too so all 3 icons are consistent
if (noThinsp)
out.write("<a href=\"" + _contextPath + "/?action=Start_" + b64 + "&nonce=" + _nonce + stParam + "\"><img title=\"");
else
out.write("<input type=\"image\" name=\"action_Start_" + b64 + "\" value=\"foo\" title=\"");
out.write(_("Start the torrent"));
out.write("\" src=\"" + _imgPath + "start.png\" alt=\"");
out.write(_("Start"));
out.write("\">");
if (isDegraded)
out.write("</a>");
}
if (isValid) {
// Remove Button
// Doesnt work with Opera so use noThinsp instead of isDegraded
if (noThinsp)
out.write("<a href=\"" + _contextPath + "/?action=Remove_" + b64 + "&nonce=" + _nonce + stParam + "\"><img title=\"");
else
out.write("<input type=\"image\" name=\"action_Remove_" + b64 + "\" value=\"foo\" title=\"");
out.write(_("Remove the torrent from the active list, deleting the .torrent file"));
out.write("\" onclick=\"if (!confirm('");
// Can't figure out how to escape double quotes inside the onclick string.
// Single quotes in translate strings with parameters must be doubled.
// Then the remaining single quote must be escaped
- out.write(_("Are you sure you want to delete the file \\''{0}.torrent\\'' (downloaded data will not be deleted) ?", basename));
+ out.write(_("Are you sure you want to delete the file \\''{0}\\'' (downloaded data will not be deleted) ?", snark.getName()));
out.write("')) { return false; }\"");
out.write(" src=\"" + _imgPath + "remove.png\" alt=\"");
out.write(_("Remove"));
out.write("\">");
if (isDegraded)
out.write("</a>");
}
// Delete Button
// Doesnt work with Opera so use noThinsp instead of isDegraded
if (noThinsp)
out.write("<a href=\"" + _contextPath + "/?action=Delete_" + b64 + "&nonce=" + _nonce + stParam + "\"><img title=\"");
else
out.write("<input type=\"image\" name=\"action_Delete_" + b64 + "\" value=\"foo\" title=\"");
out.write(_("Delete the .torrent file and the associated data file(s)"));
out.write("\" onclick=\"if (!confirm('");
// Can't figure out how to escape double quotes inside the onclick string.
// Single quotes in translate strings with parameters must be doubled.
// Then the remaining single quote must be escaped
- out.write(_("Are you sure you want to delete the torrent \\''{0}\\'' and all downloaded data?", basename));
+ out.write(_("Are you sure you want to delete the torrent \\''{0}\\'' and all downloaded data?", fullBasename));
out.write("')) { return false; }\"");
out.write(" src=\"" + _imgPath + "delete.png\" alt=\"");
out.write(_("Delete"));
out.write("\">");
if (isDegraded)
out.write("</a>");
}
out.write("</td>\n</tr>\n");
if(showPeers && isRunning && curPeers > 0) {
List<Peer> peers = snark.getPeerList();
if (!showDebug)
Collections.sort(peers, new PeerComparator());
for (Peer peer : peers) {
if (!peer.isConnected())
continue;
out.write("<tr class=\"" + rowClass + "\"><td></td>");
out.write("<td colspan=\"4\" align=\"right\">");
String ch = peer.toString().substring(0, 4);
String client;
if ("AwMD".equals(ch))
client = _("I2PSnark");
else if ("BFJT".equals(ch))
client = "I2PRufus";
else if ("TTMt".equals(ch))
client = "I2P-BT";
else if ("LUFa".equals(ch))
client = "Azureus";
else if ("CwsL".equals(ch))
client = "I2PSnarkXL";
else if ("ZV".equals(ch.substring(2,4)) || "VUZP".equals(ch))
client = "Robert";
else if (ch.startsWith("LV")) // LVCS 1.0.2?; LVRS 1.0.4
client = "Transmission";
else if ("LUtU".equals(ch))
client = "KTorrent";
else
client = _("Unknown") + " (" + ch + ')';
out.write(client + " <tt>" + peer.toString().substring(5, 9)+ "</tt>");
if (showDebug)
out.write(" inactive " + (peer.getInactiveTime() / 1000) + "s");
out.write("</td>\n\t");
out.write("<td class=\"snarkTorrentStatus\">");
out.write("</td>\n\t");
out.write("<td align=\"right\" class=\"snarkTorrentStatus\">");
float pct;
if (isValid) {
pct = (float) (100.0 * peer.completed() / meta.getPieces());
if (pct >= 100.0)
out.write(_("Seed"));
else {
String ps = String.valueOf(pct);
if (ps.length() > 5)
ps = ps.substring(0, 5);
out.write(ps + "%");
}
} else {
pct = (float) 101.0;
// until we get the metainfo we don't know how many pieces there are
//out.write("??");
}
out.write("</td>\n\t");
out.write("<td class=\"snarkTorrentStatus\">");
out.write("</td>\n\t");
out.write("<td align=\"right\" class=\"snarkTorrentStatus\">");
if (needed > 0) {
if (peer.isInteresting() && !peer.isChoked()) {
out.write("<span class=\"unchoked\">");
out.write(formatSize(peer.getDownloadRate()) + "ps</span>");
} else {
out.write("<span class=\"choked\"><a title=\"");
if (!peer.isInteresting())
out.write(_("Uninteresting (The peer has no pieces we need)"));
else
out.write(_("Choked (The peer is not allowing us to request pieces)"));
out.write("\">");
out.write(formatSize(peer.getDownloadRate()) + "ps</a></span>");
}
} else if (!isValid) {
//if (peer supports metadata extension) {
out.write("<span class=\"unchoked\">");
out.write(formatSize(peer.getDownloadRate()) + "ps</span>");
//} else {
//}
}
out.write("</td>\n\t");
out.write("<td align=\"right\" class=\"snarkTorrentStatus\">");
if (isValid && pct < 100.0) {
if (peer.isInterested() && !peer.isChoking()) {
out.write("<span class=\"unchoked\">");
out.write(formatSize(peer.getUploadRate()) + "ps</span>");
} else {
out.write("<span class=\"choked\"><a title=\"");
if (!peer.isInterested())
out.write(_("Uninterested (We have no pieces the peer needs)"));
else
out.write(_("Choking (We are not allowing the peer to request pieces)"));
out.write("\">");
out.write(formatSize(peer.getUploadRate()) + "ps</a></span>");
}
}
out.write("</td>\n\t");
out.write("<td class=\"snarkTorrentStatus\">");
out.write("</td></tr>\n\t");
if (showDebug)
out.write("<tr class=\"" + rowClass + "\"><td></td><td colspan=\"10\" align=\"right\">" + peer.getSocket() + "</td></tr>");
}
}
}
/** @since 0.8.2 */
private static String thinsp(boolean disable) {
if (disable)
return " / ";
return (" / ");
}
/**
* Sort by completeness (seeds first), then by ID
* @since 0.8.1
*/
private static class PeerComparator implements Comparator<Peer> {
public int compare(Peer l, Peer r) {
int diff = r.completed() - l.completed(); // reverse
if (diff != 0)
return diff;
return l.toString().substring(5, 9).compareTo(r.toString().substring(5, 9));
}
}
/**
* Start of anchor only, caller must add anchor text or img and close anchor
* @return string or null
* @since 0.8.4
*/
private String getTrackerLinkUrl(String announce, byte[] infohash) {
// temporarily hardcoded for postman* and anonymity, requires bytemonsoon patch for lookup by info_hash
if (announce != null && (announce.startsWith("http://YRgrgTLG") || announce.startsWith("http://8EoJZIKr") ||
announce.startsWith("http://lnQ6yoBT") || announce.startsWith("http://tracker2.postman.i2p/") ||
announce.startsWith("http://ahsplxkbhemefwvvml7qovzl5a2b5xo5i7lyai7ntdunvcyfdtna.b32.i2p/"))) {
for (Tracker t : _manager.getTrackers()) {
String aURL = t.announceURL;
if (!(aURL.startsWith(announce) || // vvv hack for non-b64 announce in list vvv
(announce.startsWith("http://lnQ6yoBT") && aURL.startsWith("http://tracker2.postman.i2p/")) ||
(announce.startsWith("http://ahsplxkbhemefwvvml7qovzl5a2b5xo5i7lyai7ntdunvcyfdtna.b32.i2p/") && aURL.startsWith("http://tracker2.postman.i2p/"))))
continue;
String baseURL = t.baseURL;
String name = t.name;
StringBuilder buf = new StringBuilder(128);
buf.append("<a href=\"").append(baseURL).append("details.php?dllist=1&filelist=1&info_hash=")
.append(TrackerClient.urlencode(infohash))
.append("\" title=\"").append(_("Details at {0} tracker", name)).append("\" target=\"_blank\">");
return buf.toString();
}
}
return null;
}
/**
* Full anchor with img
* @return string or null
* @since 0.8.4
*/
private String getTrackerLink(String announce, byte[] infohash) {
String linkUrl = getTrackerLinkUrl(announce, infohash);
if (linkUrl != null) {
StringBuilder buf = new StringBuilder(128);
buf.append(linkUrl)
.append("<img alt=\"").append(_("Info")).append("\" border=\"0\" src=\"")
.append(_imgPath).append("details.png\"></a>");
return buf.toString();
}
return null;
}
/**
* Full anchor with shortened URL as anchor text
* @return string, non-null
* @since 0.9.5
*/
private String getShortTrackerLink(String announce, byte[] infohash) {
StringBuilder buf = new StringBuilder(128);
String trackerLinkUrl = getTrackerLinkUrl(announce, infohash);
if (trackerLinkUrl != null)
buf.append(trackerLinkUrl);
if (announce.startsWith("http://"))
announce = announce.substring(7);
int slsh = announce.indexOf('/');
if (slsh > 0)
announce = announce.substring(0, slsh);
if (announce.length() > 67)
announce = announce.substring(0, 40) + "…" + announce.substring(announce.length() - 8);
buf.append(announce);
if (trackerLinkUrl != null)
buf.append("</a>");
return buf.toString();
}
private void writeAddForm(PrintWriter out, HttpServletRequest req) throws IOException {
// display incoming parameter if a GET so links will work
String newURL = req.getParameter("newURL");
if (newURL == null || newURL.trim().length() <= 0 || req.getMethod().equals("POST"))
newURL = "";
else
newURL = DataHelper.stripHTML(newURL); // XSS
//String newFile = req.getParameter("newFile");
//if ( (newFile == null) || (newFile.trim().length() <= 0) ) newFile = "";
out.write("<div class=\"snarkNewTorrent\">\n");
// *not* enctype="multipart/form-data", so that the input type=file sends the filename, not the file
out.write("<form action=\"_post\" method=\"POST\">\n");
out.write("<input type=\"hidden\" name=\"nonce\" value=\"" + _nonce + "\" >\n");
out.write("<input type=\"hidden\" name=\"action\" value=\"Add\" >\n");
// don't lose peer setting
String peerParam = req.getParameter("p");
if (peerParam != null)
out.write("<input type=\"hidden\" name=\"p\" value=\"" + peerParam + "\" >\n");
out.write("<div class=\"addtorrentsection\"><span class=\"snarkConfigTitle\">");
out.write("<img alt=\"\" border=\"0\" src=\"" + _imgPath + "add.png\"> ");
out.write(_("Add Torrent"));
out.write("</span><hr>\n<table border=\"0\"><tr><td>");
out.write(_("From URL"));
out.write(":<td><input type=\"text\" name=\"newURL\" size=\"85\" value=\"" + newURL + "\" spellcheck=\"false\"");
out.write(" title=\"");
out.write(_("Enter the torrent file download URL (I2P only), magnet link, maggot link, or info hash"));
out.write("\"> \n");
// not supporting from file at the moment, since the file name passed isn't always absolute (so it may not resolve)
//out.write("From file: <input type=\"file\" name=\"newFile\" size=\"50\" value=\"" + newFile + "\" /><br>");
out.write("<input type=\"submit\" class=\"add\" value=\"");
out.write(_("Add torrent"));
out.write("\" name=\"foo\" ><br>\n");
out.write("<tr><td> <td><span class=\"snarkAddInfo\">");
out.write(_("You can also copy .torrent files to: {0}.", "<code>" + _manager.getDataDir().getAbsolutePath () + "</code>"));
out.write("\n");
out.write(_("Removing a .torrent will cause it to stop."));
out.write("<br></span></table>\n");
out.write("</div></form></div>");
}
private void writeSeedForm(PrintWriter out, HttpServletRequest req, List<Tracker> sortedTrackers) throws IOException {
String baseFile = req.getParameter("baseFile");
if (baseFile == null || baseFile.trim().length() <= 0)
baseFile = "";
else
baseFile = DataHelper.stripHTML(baseFile); // XSS
out.write("<a name=\"add\"></a><div class=\"newtorrentsection\"><div class=\"snarkNewTorrent\">\n");
// *not* enctype="multipart/form-data", so that the input type=file sends the filename, not the file
out.write("<form action=\"_post\" method=\"POST\">\n");
out.write("<input type=\"hidden\" name=\"nonce\" value=\"" + _nonce + "\" >\n");
out.write("<input type=\"hidden\" name=\"action\" value=\"Create\" >\n");
// don't lose peer setting
String peerParam = req.getParameter("p");
if (peerParam != null)
out.write("<input type=\"hidden\" name=\"p\" value=\"" + peerParam + "\" >\n");
out.write("<span class=\"snarkConfigTitle\">");
out.write("<img alt=\"\" border=\"0\" src=\"" + _imgPath + "create.png\"> ");
out.write(_("Create Torrent"));
out.write("</span><hr>\n<table border=\"0\"><tr><td>");
//out.write("From file: <input type=\"file\" name=\"newFile\" size=\"50\" value=\"" + newFile + "\" /><br>\n");
out.write(_("Data to seed"));
out.write(":<td><code>" + _manager.getDataDir().getAbsolutePath() + File.separatorChar
+ "</code><input type=\"text\" name=\"baseFile\" size=\"58\" value=\"" + baseFile
+ "\" spellcheck=\"false\" title=\"");
out.write(_("File or directory to seed (must be within the specified path)"));
out.write("\" ><tr><td>\n");
out.write(_("Trackers"));
out.write(":<td><table style=\"width: 30%;\"><tr><td></td><td align=\"center\">");
out.write(_("Primary"));
out.write("</td><td align=\"center\">");
out.write(_("Alternates"));
out.write("</td><td rowspan=\"0\">" +
" <input type=\"submit\" class=\"create\" value=\"");
out.write(_("Create torrent"));
out.write("\" name=\"foo\" >" +
"</td></tr>\n");
for (Tracker t : sortedTrackers) {
String name = t.name;
String announceURL = t.announceURL.replace("=", "=");
out.write("<tr><td>");
out.write(name);
out.write("</td><td align=\"center\"><input type=\"radio\" name=\"announceURL\" value=\"");
out.write(announceURL);
out.write("\"");
if (announceURL.equals(_lastAnnounceURL))
out.write(" checked");
out.write("></td><td align=\"center\"><input type=\"checkbox\" name=\"backup_");
out.write(announceURL);
out.write("\" value=\"foo\"></td></tr>\n");
}
out.write("<tr><td><i>");
out.write(_("none"));
out.write("</i></td><td align=\"center\"><input type=\"radio\" name=\"announceURL\" value=\"none\"");
if (_lastAnnounceURL == null)
out.write(" checked");
out.write("></td><td></td></tr></table>\n");
// make the user add a tracker on the config form now
//out.write(_("or"));
//out.write(" <input type=\"text\" name=\"announceURLOther\" size=\"57\" value=\"http://\" " +
// "title=\"");
//out.write(_("Specify custom tracker announce URL"));
//out.write("\" > " +
out.write("</td></tr>" +
"</table>\n" +
"</form></div></div>");
}
private static final int[] times = { 5, 15, 30, 60, 2*60, 5*60, 10*60, 30*60, -1 };
private void writeConfigForm(PrintWriter out, HttpServletRequest req) throws IOException {
String dataDir = _manager.getDataDir().getAbsolutePath();
boolean filesPublic = _manager.areFilesPublic();
boolean autoStart = _manager.shouldAutoStart();
boolean useOpenTrackers = _manager.util().shouldUseOpenTrackers();
//String openTrackers = _manager.util().getOpenTrackerString();
boolean useDHT = _manager.util().shouldUseDHT();
//int seedPct = 0;
out.write("<form action=\"" + _contextPath + "/configure\" method=\"POST\">\n" +
"<div class=\"configsectionpanel\"><div class=\"snarkConfig\">\n" +
"<input type=\"hidden\" name=\"nonce\" value=\"" + _nonce + "\" >\n" +
"<input type=\"hidden\" name=\"action\" value=\"Save\" >\n" +
"<span class=\"snarkConfigTitle\">" +
"<img alt=\"\" border=\"0\" src=\"" + _imgPath + "config.png\"> ");
out.write(_("Configuration"));
out.write("</span><hr>\n" +
"<table border=\"0\"><tr><td>");
out.write(_("Data directory"));
out.write(": <td><input name=\"dataDir\" size=\"80\" value=\"" + dataDir + "\" spellcheck=\"false\"></td>\n" +
"<tr><td>");
out.write(_("Files readable by all"));
out.write(": <td><input type=\"checkbox\" class=\"optbox\" name=\"filesPublic\" value=\"true\" "
+ (filesPublic ? "checked " : "")
+ "title=\"");
out.write(_("If checked, other users may access the downloaded files"));
out.write("\" >" +
"<tr><td>");
out.write(_("Auto start"));
out.write(": <td><input type=\"checkbox\" class=\"optbox\" name=\"autoStart\" value=\"true\" "
+ (autoStart ? "checked " : "")
+ "title=\"");
out.write(_("If checked, automatically start torrents that are added"));
out.write("\" >" +
"<tr><td>");
out.write(_("Theme"));
out.write(": <td><select name='theme'>");
String theme = _manager.getTheme();
String[] themes = _manager.getThemes();
for(int i = 0; i < themes.length; i++) {
if(themes[i].equals(theme))
out.write("\n<OPTION value=\"" + themes[i] + "\" SELECTED>" + themes[i]);
else
out.write("\n<OPTION value=\"" + themes[i] + "\">" + themes[i]);
}
out.write("</select>\n" +
"<tr><td>");
out.write(_("Refresh time"));
out.write(": <td><select name=\"refreshDelay\">");
int delay = _manager.getRefreshDelaySeconds();
for (int i = 0; i < times.length; i++) {
out.write("<option value=\"");
out.write(Integer.toString(times[i]));
out.write("\"");
if (times[i] == delay)
out.write(" selected=\"selected\"");
out.write(">");
if (times[i] > 0)
out.write(DataHelper.formatDuration2(times[i] * 1000));
else
out.write(_("Never"));
out.write("</option>\n");
}
out.write("</select><br>" +
"<tr><td>");
out.write(_("Startup delay"));
out.write(": <td><input name=\"startupDelay\" size=\"4\" class=\"r\" value=\"" + _manager.util().getStartupDelay() + "\"> ");
out.write(_("minutes"));
out.write("<br>\n" +
"<tr><td>");
out.write(_("Page size"));
out.write(": <td><input name=\"pageSize\" size=\"4\" maxlength=\"6\" class=\"r\" value=\"" + _manager.getPageSize() + "\"> ");
out.write(_("torrents"));
out.write("<br>\n");
//Auto add: <input type="checkbox" name="autoAdd" value="true" title="If true, automatically add torrents that are found in the data directory" />
//Auto stop: <input type="checkbox" name="autoStop" value="true" title="If true, automatically stop torrents that are removed from the data directory" />
//out.write("<br>\n");
/*
out.write("Seed percentage: <select name=\"seedPct\" disabled=\"true\" >\n\t");
if (seedPct <= 0)
out.write("<option value=\"0\" selected=\"selected\">Unlimited</option>\n\t");
else
out.write("<option value=\"0\">Unlimited</option>\n\t");
if (seedPct == 100)
out.write("<option value=\"100\" selected=\"selected\">100%</option>\n\t");
else
out.write("<option value=\"100\">100%</option>\n\t");
if (seedPct == 150)
out.write("<option value=\"150\" selected=\"selected\">150%</option>\n\t");
else
out.write("<option value=\"150\">150%</option>\n\t");
out.write("</select><br>\n");
*/
out.write("<tr><td>");
out.write(_("Total uploader limit"));
out.write(": <td><input type=\"text\" name=\"upLimit\" class=\"r\" value=\""
+ _manager.util().getMaxUploaders() + "\" size=\"4\" maxlength=\"3\" > ");
out.write(_("peers"));
out.write("<br>\n" +
"<tr><td>");
out.write(_("Up bandwidth limit"));
out.write(": <td><input type=\"text\" name=\"upBW\" class=\"r\" value=\""
+ _manager.util().getMaxUpBW() + "\" size=\"4\" maxlength=\"4\" > KBps <i>");
out.write(_("Half available bandwidth recommended."));
out.write(" [<a href=\"/config.jsp\" target=\"blank\">");
out.write(_("View or change router bandwidth"));
out.write("</a>]</i><br>\n" +
"<tr><td>");
out.write(_("Use open trackers also"));
out.write(": <td><input type=\"checkbox\" class=\"optbox\" name=\"useOpenTrackers\" value=\"true\" "
+ (useOpenTrackers ? "checked " : "")
+ "title=\"");
out.write(_("If checked, announce torrents to open trackers as well as the tracker listed in the torrent file"));
out.write("\" ></td></tr>\n" +
"<tr><td>");
out.write(_("Enable DHT"));
out.write(": <td><input type=\"checkbox\" class=\"optbox\" name=\"useDHT\" value=\"true\" "
+ (useDHT ? "checked " : "")
+ "title=\"");
out.write(_("If checked, use DHT"));
out.write("\" ></td></tr>\n");
// "<tr><td>");
//out.write(_("Open tracker announce URLs"));
//out.write(": <td><input type=\"text\" name=\"openTrackers\" value=\""
// + openTrackers + "\" size=\"50\" ><br>\n");
//out.write("\n");
//out.write("EepProxy host: <input type=\"text\" name=\"eepHost\" value=\""
// + _manager.util().getEepProxyHost() + "\" size=\"15\" /> ");
//out.write("port: <input type=\"text\" name=\"eepPort\" value=\""
// + _manager.util().getEepProxyPort() + "\" size=\"5\" maxlength=\"5\" /><br>\n");
Map<String, String> options = new TreeMap(_manager.util().getI2CPOptions());
out.write("<tr><td>");
out.write(_("Inbound Settings"));
out.write(":<td>");
out.write(renderOptions(1, 6, options.remove("inbound.quantity"), "inbound.quantity", TUNNEL));
out.write(" ");
out.write(renderOptions(0, 4, options.remove("inbound.length"), "inbound.length", HOP));
out.write("<tr><td>");
out.write(_("Outbound Settings"));
out.write(":<td>");
out.write(renderOptions(1, 6, options.remove("outbound.quantity"), "outbound.quantity", TUNNEL));
out.write(" ");
out.write(renderOptions(0, 4, options.remove("outbound.length"), "outbound.length", HOP));
if (!_context.isRouterContext()) {
out.write("<tr><td>");
out.write(_("I2CP host"));
out.write(": <td><input type=\"text\" name=\"i2cpHost\" value=\""
+ _manager.util().getI2CPHost() + "\" size=\"15\" > " +
"<tr><td>");
out.write(_("I2CP port"));
out.write(": <td><input type=\"text\" name=\"i2cpPort\" class=\"r\" value=\"" +
+ _manager.util().getI2CPPort() + "\" size=\"5\" maxlength=\"5\" > <br>\n");
}
options.remove(I2PSnarkUtil.PROP_MAX_BW);
// was accidentally in the I2CP options prior to 0.8.9 so it will be in old config files
options.remove(SnarkManager.PROP_OPENTRACKERS);
StringBuilder opts = new StringBuilder(64);
for (Map.Entry<String, String> e : options.entrySet()) {
String key = e.getKey();
String val = e.getValue();
opts.append(key).append('=').append(val).append(' ');
}
out.write("<tr><td>");
out.write(_("I2CP options"));
out.write(": <td><textarea name=\"i2cpOpts\" cols=\"60\" rows=\"1\" wrap=\"off\" spellcheck=\"false\" >"
+ opts.toString() + "</textarea><br>\n" +
"<tr><td colspan=\"2\"> \n" + // spacer
"<tr><td> <td><input type=\"submit\" class=\"accept\" value=\"");
out.write(_("Save configuration"));
out.write("\" name=\"foo\" >\n" +
"<tr><td colspan=\"2\"> \n" + // spacer
"</table></div></div></form>");
}
/** @since 0.9 */
private void writeTrackerForm(PrintWriter out, HttpServletRequest req) throws IOException {
StringBuilder buf = new StringBuilder(1024);
buf.append("<form action=\"" + _contextPath + "/configure\" method=\"POST\">\n" +
"<div class=\"configsectionpanel\"><div class=\"snarkConfig\">\n" +
"<input type=\"hidden\" name=\"nonce\" value=\"" + _nonce + "\" >\n" +
"<input type=\"hidden\" name=\"action\" value=\"Save2\" >\n" +
"<span class=\"snarkConfigTitle\">" +
"<img alt=\"\" border=\"0\" src=\"" + _imgPath + "config.png\"> ");
buf.append(_("Trackers"));
buf.append("</span><hr>\n" +
"<table class=\"trackerconfig\"><tr><th>")
//.append(_("Remove"))
.append("</th><th>")
.append(_("Name"))
.append("</th><th>")
.append(_("Website URL"))
.append("</th><th>")
.append(_("Open"))
.append("</th><th>")
.append(_("Private"))
.append("</th><th>")
.append(_("Announce URL"))
.append("</th></tr>\n");
List<String> openTrackers = _manager.util().getOpenTrackers();
List<String> privateTrackers = _manager.getPrivateTrackers();
for (Tracker t : _manager.getSortedTrackers()) {
String name = t.name;
String homeURL = t.baseURL;
String announceURL = t.announceURL.replace("=", "=");
buf.append("<tr><td><input type=\"checkbox\" class=\"optbox\" name=\"delete_")
.append(name).append("\" title=\"").append(_("Delete")).append("\">" +
"</td><td>").append(name)
.append("</td><td>").append(urlify(homeURL, 35))
.append("</td><td><input type=\"checkbox\" class=\"optbox\" name=\"open_")
.append(announceURL).append("\"");
if (openTrackers.contains(t.announceURL))
buf.append(" checked=\"checked\"");
buf.append(">" +
"</td><td><input type=\"checkbox\" class=\"optbox\" name=\"private_")
.append(announceURL).append("\"");
if (privateTrackers.contains(t.announceURL)) {
buf.append(" checked=\"checked\"");
} else {
for (int i = 1; i < SnarkManager.DEFAULT_TRACKERS.length; i += 2) {
if (SnarkManager.DEFAULT_TRACKERS[i].contains(t.announceURL)) {
buf.append(" disabled=\"disabled\"");
break;
}
}
}
buf.append(">" +
"</td><td>").append(urlify(announceURL, 35))
.append("</td></tr>\n");
}
buf.append("<tr><td><b>")
.append(_("Add")).append(":</b></td>" +
"<td><input type=\"text\" class=\"trackername\" name=\"tname\" spellcheck=\"false\"></td>" +
"<td><input type=\"text\" class=\"trackerhome\" name=\"thurl\" spellcheck=\"false\"></td>" +
"<td><input type=\"checkbox\" class=\"optbox\" name=\"_add_open_\"></td>" +
"<td><input type=\"checkbox\" class=\"optbox\" name=\"_add_private_\"></td>" +
"<td><input type=\"text\" class=\"trackerannounce\" name=\"taurl\" spellcheck=\"false\"></td></tr>\n" +
"<tr><td colspan=\"6\"> </td></tr>\n" + // spacer
"<tr><td colspan=\"2\"></td><td colspan=\"4\">\n" +
"<input type=\"submit\" name=\"taction\" class=\"default\" value=\"").append(_("Add tracker")).append("\">\n" +
"<input type=\"submit\" name=\"taction\" class=\"delete\" value=\"").append(_("Delete selected")).append("\">\n" +
"<input type=\"submit\" name=\"taction\" class=\"accept\" value=\"").append(_("Save tracker configuration")).append("\">\n" +
// "<input type=\"reset\" class=\"cancel\" value=\"").append(_("Cancel")).append("\">\n" +
"<input type=\"submit\" name=\"taction\" class=\"reload\" value=\"").append(_("Restore defaults")).append("\">\n" +
"<input type=\"submit\" name=\"taction\" class=\"add\" value=\"").append(_("Add tracker")).append("\">\n" +
"</td></tr>" +
"<tr><td colspan=\"6\"> </td></tr>\n" + // spacer
"</table></div></div></form>\n");
out.write(buf.toString());
}
private void writeConfigLink(PrintWriter out) throws IOException {
out.write("<div class=\"configsection\"><span class=\"snarkConfig\">\n" +
"<span class=\"snarkConfigTitle\"><a href=\"configure\">" +
"<img alt=\"\" border=\"0\" src=\"" + _imgPath + "config.png\"> ");
out.write(_("Configuration"));
out.write("</a></span></span></div>\n");
}
/**
* @param url in base32 or hex
* @since 0.8.4
*/
private void addMagnet(String url) {
try {
MagnetURI magnet = new MagnetURI(_manager.util(), url);
String name = magnet.getName();
byte[] ih = magnet.getInfoHash();
String trackerURL = magnet.getTrackerURL();
_manager.addMagnet(name, ih, trackerURL, true);
} catch (IllegalArgumentException iae) {
_manager.addMessage(_("Invalid magnet URL {0}", url));
}
}
/** copied from ConfigTunnelsHelper */
private static final String HOP = "hop";
private static final String TUNNEL = "tunnel";
/** dummies for translation */
private static final String HOPS = ngettext("1 hop", "{0} hops");
private static final String TUNNELS = ngettext("1 tunnel", "{0} tunnels");
/** prevents the ngettext line below from getting tagged */
private static final String DUMMY0 = "{0} ";
private static final String DUMMY1 = "1 ";
/** modded from ConfigTunnelsHelper @since 0.7.14 */
private String renderOptions(int min, int max, String strNow, String selName, String name) {
int now = 2;
try {
now = Integer.parseInt(strNow);
} catch (Throwable t) {}
StringBuilder buf = new StringBuilder(128);
buf.append("<select name=\"").append(selName).append("\">\n");
for (int i = min; i <= max; i++) {
buf.append("<option value=\"").append(i).append("\" ");
if (i == now)
buf.append("selected=\"selected\" ");
// constants to prevent tagging
buf.append(">").append(ngettext(DUMMY1 + name, DUMMY0 + name + 's', i));
buf.append("</option>\n");
}
buf.append("</select>\n");
return buf.toString();
}
/** translate */
private String _(String s) {
return _manager.util().getString(s);
}
/** translate */
private String _(String s, Object o) {
return _manager.util().getString(s, o);
}
/** translate */
private String _(String s, Object o, Object o2) {
return _manager.util().getString(s, o, o2);
}
/** translate (ngettext) @since 0.7.14 */
private String ngettext(String s, String p, int n) {
return _manager.util().getString(n, s, p);
}
/** dummy for tagging */
private static String ngettext(String s, String p) {
return null;
}
// rounding makes us look faster :)
private static String formatSize(long bytes) {
if (bytes < 5000)
return bytes + " B";
else if (bytes < 5*1024*1024)
return ((bytes + 512)/1024) + " KB";
else if (bytes < 10*1024*1024*1024l)
return ((bytes + 512*1024)/(1024*1024)) + " MB";
else
return ((bytes + 512*1024*1024)/(1024*1024*1024)) + " GB";
}
/** @since 0.7.14 */
static String urlify(String s) {
return urlify(s, 100);
}
/** @since 0.9 */
private static String urlify(String s, int max) {
StringBuilder buf = new StringBuilder(256);
// browsers seem to work without doing this but let's be strict
String link = urlEncode(s);
String display;
if (s.length() <= max)
display = link;
else
display = urlEncode(s.substring(0, max)) + "…";
buf.append("<a href=\"").append(link).append("\">").append(display).append("</a>");
return buf.toString();
}
/** @since 0.8.13 */
private static String urlEncode(String s) {
return s.replace(";", "%3B").replace("&", "&").replace(" ", "%20")
.replace("[", "%5B").replace("]", "%5D");
}
private static final String DOCTYPE = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n";
private static final String HEADER_A = "<link href=\"";
private static final String HEADER_B = "snark.css\" rel=\"stylesheet\" type=\"text/css\" >";
private static final String TABLE_HEADER = "<table border=\"0\" class=\"snarkTorrents\" width=\"100%\" >\n" +
"<thead>\n";
private static final String FOOTER = "</div></center></body></html>";
/**
* Sort alphabetically in current locale, ignore case,
* directories first
* @since 0.9.6
*/
private static class ListingComparator implements Comparator<File> {
private final Comparator collator = Collator.getInstance();
public int compare(File l, File r) {
if (l.isDirectory() && !r.isDirectory())
return -1;
if (r.isDirectory() && !l.isDirectory())
return 1;
return collator.compare(l.getName(), r.getName());
}
}
/**
* Modded heavily from the Jetty version in Resource.java,
* pass Resource as 1st param
* All the xxxResource constructors are package local so we can't extend them.
*
* <pre>
// ========================================================================
// $Id: Resource.java,v 1.32 2009/05/16 01:53:36 gregwilkins Exp $
// Copyright 1996-2004 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.
// ========================================================================
* </pre>
*
* Get the resource list as a HTML directory listing.
* @param r The Resource
* @param base The base URL
* @param parent True if the parent directory should be included
* @param postParams map of POST parameters or null if not a POST
* @return String of HTML or null if postParams != null
* @since 0.7.14
*/
private String getListHTML(File r, String base, boolean parent, Map postParams)
throws IOException
{
File[] ls = null;
if (r.isDirectory()) {
ls = r.listFiles();
Arrays.sort(ls, new ListingComparator());
} // if r is not a directory, we are only showing torrent info section
String title = decodePath(base);
String cpath = _contextPath + '/';
if (title.startsWith(cpath))
title = title.substring(cpath.length());
// Get the snark associated with this directory
String torrentName;
int slash = title.indexOf('/');
if (slash > 0)
torrentName = title.substring(0, slash);
else
torrentName = title;
Snark snark = _manager.getTorrentByBaseName(torrentName);
if (snark != null && postParams != null) {
// caller must P-R-G
savePriorities(snark, postParams);
return null;
}
StringBuilder buf=new StringBuilder(4096);
buf.append(DOCTYPE).append("<HTML><HEAD><TITLE>");
if (title.endsWith("/"))
title = title.substring(0, title.length() - 1);
String directory = title;
title = _("Torrent") + ": " + title;
buf.append(title);
buf.append("</TITLE>").append(HEADER_A).append(_themePath).append(HEADER_B).append("<link rel=\"shortcut icon\" href=\"" + _themePath + "favicon.ico\">" +
"</HEAD><BODY>\n<center><div class=\"snarknavbar\"><a href=\"").append(_contextPath).append("/\" title=\"Torrents\"");
buf.append(" class=\"snarkRefresh\"><img alt=\"\" border=\"0\" src=\"" + _imgPath + "arrow_refresh.png\"> ");
if (_contextName.equals(DEFAULT_NAME))
buf.append(_("I2PSnark"));
else
buf.append(_contextName);
buf.append("</a></div></center>\n");
if (parent) // always true
buf.append("<div class=\"page\"><div class=\"mainsection\">");
boolean showPriority = ls != null && snark != null && snark.getStorage() != null && !snark.getStorage().complete();
if (showPriority)
buf.append("<form action=\"").append(base).append("\" method=\"POST\">\n");
if (snark != null) {
// first table - torrent info
buf.append("<table class=\"snarkTorrentInfo\">\n");
buf.append("<tr><th><b>")
.append(_("Torrent"))
.append(":</b> ")
.append(snark.getBaseName())
.append("</th></tr>\n");
String fullPath = snark.getName();
String baseName = urlEncode((new File(fullPath)).getName());
buf.append("<tr><td>")
.append("<img alt=\"\" border=\"0\" src=\"" + _imgPath + "file.png\" > <b>")
.append(_("Torrent file"))
.append(":</b> <a href=\"").append(_contextPath).append('/').append(baseName).append("\">")
.append(fullPath)
.append("</a></td></tr>\n");
MetaInfo meta = snark.getMetaInfo();
if (meta != null) {
String announce = meta.getAnnounce();
if (announce != null) {
buf.append("<tr><td>");
String trackerLink = getTrackerLink(announce, snark.getInfoHash());
if (trackerLink != null)
buf.append(trackerLink).append(' ');
buf.append("<b>").append(_("Primary Tracker")).append(":</b> ");
buf.append(getShortTrackerLink(announce, snark.getInfoHash()));
buf.append("</td></tr>");
}
List<List<String>> alist = meta.getAnnounceList();
if (alist != null) {
buf.append("<tr><td>" +
"<img alt=\"\" border=\"0\" src=\"")
.append(_imgPath).append("details.png\"> <b>");
buf.append(_("Tracker List")).append(":</b> ");
for (List<String> alist2 : alist) {
buf.append('[');
boolean more = false;
for (String s : alist2) {
if (more)
buf.append(' ');
else
more = true;
buf.append(getShortTrackerLink(s, snark.getInfoHash()));
}
buf.append("] ");
}
buf.append("</td></tr>");
}
}
if (meta != null) {
String com = meta.getComment();
if (com != null) {
if (com.length() > 1024)
com = com.substring(0, 1024);
buf.append("<tr><td><img alt=\"\" border=\"0\" src=\"")
.append(_imgPath).append("details.png\"> <b>")
.append(_("Comment")).append(":</b> ")
.append(DataHelper.stripHTML(com))
.append("</td></tr>\n");
}
long dat = meta.getCreationDate();
if (dat > 0) {
String date = (new SimpleDateFormat("yyyy-MM-dd HH:mm")).format(new Date(dat));
buf.append("<tr><td><img alt=\"\" border=\"0\" src=\"")
.append(_imgPath).append("details.png\"> <b>")
.append(_("Created")).append(":</b> ")
.append(date).append(" UTC")
.append("</td></tr>\n");
}
String cby = meta.getCreatedBy();
if (cby != null) {
if (cby.length() > 128)
cby = com.substring(0, 128);
buf.append("<tr><td><img alt=\"\" border=\"0\" src=\"")
.append(_imgPath).append("details.png\"> <b>")
.append(_("Created By")).append(":</b> ")
.append(DataHelper.stripHTML(cby))
.append("</td></tr>\n");
}
}
String hex = I2PSnarkUtil.toHex(snark.getInfoHash());
if (meta == null || !meta.isPrivate()) {
buf.append("<tr><td><a href=\"")
.append(MagnetURI.MAGNET_FULL).append(hex).append("\">")
.append(toImg("magnet", _("Magnet link")))
.append("</a> <b>Magnet:</b> <a href=\"")
.append(MagnetURI.MAGNET_FULL).append(hex).append("\">")
.append(MagnetURI.MAGNET_FULL).append(hex).append("</a>")
.append("</td></tr>\n");
} else {
buf.append("<tr><td>")
.append(_("Private torrent"))
.append("</td></tr>\n");
}
// We don't have the hash of the torrent file
//buf.append("<tr><td>").append(_("Maggot link")).append(": <a href=\"").append(MAGGOT).append(hex).append(':').append(hex).append("\">")
// .append(MAGGOT).append(hex).append(':').append(hex).append("</a></td></tr>");
buf.append("<tr><td>")
.append("<img alt=\"\" border=\"0\" src=\"" + _imgPath + "size.png\" > <b>")
.append(_("Size"))
.append(":</b> ")
.append(formatSize(snark.getTotalLength()));
int pieces = snark.getPieces();
double completion = (pieces - snark.getNeeded()) / (double) pieces;
if (completion < 1.0)
buf.append(" <img alt=\"\" border=\"0\" src=\"" + _imgPath + "head_rx.png\" > <b>")
.append(_("Completion"))
.append(":</b> ")
.append((new DecimalFormat("0.00%")).format(completion));
else
buf.append(" <img alt=\"\" border=\"0\" src=\"" + _imgPath + "head_rx.png\" > ")
.append(_("Complete"));
// else unknown
long needed = snark.getNeededLength();
if (needed > 0)
buf.append(" <img alt=\"\" border=\"0\" src=\"" + _imgPath + "head_rx.png\" > <b>")
.append(_("Remaining"))
.append(":</b> ")
.append(formatSize(needed));
if (meta != null) {
List files = meta.getFiles();
int fileCount = files != null ? files.size() : 1;
buf.append(" <img alt=\"\" border=\"0\" src=\"" + _imgPath + "file.png\" > <b>")
.append(_("Files"))
.append(":</b> ")
.append(fileCount);
}
buf.append(" <img alt=\"\" border=\"0\" src=\"" + _imgPath + "file.png\" > <b>")
.append(_("Pieces"))
.append(":</b> ")
.append(pieces);
buf.append(" <img alt=\"\" border=\"0\" src=\"" + _imgPath + "file.png\" > <b>")
.append(_("Piece size"))
.append(":</b> ")
.append(formatSize(snark.getPieceLength(0)))
.append("</td></tr>\n");
} else {
// shouldn't happen
buf.append("<tr><th>Not found<br>resource=\"").append(r.toString())
.append("\"<br>base=\"").append(base)
.append("\"<br>torrent=\"").append(torrentName)
.append("\"</th></tr>\n");
}
buf.append("</table>\n");
if (ls == null) {
// We are only showing the torrent info section
buf.append("</div></div></BODY></HTML>");
return buf.toString();
}
// second table - dir info
buf.append("<table class=\"snarkDirInfo\"><thead>\n");
buf.append("<tr>\n")
.append("<th colspan=2>")
.append("<img border=\"0\" src=\"" + _imgPath + "file.png\" title=\"")
.append(_("Directory"))
.append(": ")
.append(directory)
.append("\" alt=\"")
.append(_("Directory"))
.append("\"></th>\n");
buf.append("<th align=\"right\">")
.append("<img border=\"0\" src=\"" + _imgPath + "size.png\" title=\"")
.append(_("Size"))
.append("\" alt=\"")
.append(_("Size"))
.append("\"></th>\n");
buf.append("<th class=\"headerstatus\">")
.append("<img border=\"0\" src=\"" + _imgPath + "status.png\" title=\"")
.append(_("Status"))
.append("\" alt=\"")
.append(_("Status"))
.append("\"></th>\n");
if (showPriority)
buf.append("<th class=\"headerpriority\">")
.append("<img border=\"0\" src=\"" + _imgPath + "priority.png\" title=\"")
.append(_("Priority"))
.append("\" alt=\"")
.append(_("Priority"))
.append("\"></th>\n");
buf.append("</tr>\n</thead>\n");
buf.append("<tr><td colspan=\"" + (showPriority ? '5' : '4') + "\" class=\"ParentDir\"><A HREF=\"");
buf.append(addPaths(base,"../"));
buf.append("\"><img alt=\"\" border=\"0\" src=\"" + _imgPath + "up.png\"> ")
.append(_("Up to higher level directory"))
.append("</A></td></tr>\n");
//DateFormat dfmt=DateFormat.getDateTimeInstance(DateFormat.MEDIUM,
// DateFormat.MEDIUM);
boolean showSaveButton = false;
for (int i=0 ; i< ls.length ; i++)
{
String encoded = encodePath(ls[i].getName());
// bugfix for I2P - Backport from Jetty 6 (zero file lengths and last-modified times)
// http://jira.codehaus.org/browse/JETTY-361?page=com.atlassian.jira.plugin.system.issuetabpanels%3Achangehistory-tabpanel#issue-tabs
// See resource.diff attachment
//Resource item = addPath(encoded);
File item = ls[i];
String rowClass = (i % 2 == 0 ? "snarkTorrentEven" : "snarkTorrentOdd");
buf.append("<TR class=\"").append(rowClass).append("\">");
// Get completeness and status string
boolean complete = false;
String status = "";
long length = item.length();
if (item.isDirectory()) {
complete = true;
//status = toImg("tick") + ' ' + _("Directory");
} else {
if (snark == null || snark.getStorage() == null) {
// Assume complete, perhaps he removed a completed torrent but kept a bookmark
complete = true;
status = toImg("cancel") + ' ' + _("Torrent not found?");
} else {
Storage storage = snark.getStorage();
try {
File f = item;
if (f != null) {
long remaining = storage.remaining(f.getCanonicalPath());
if (remaining < 0) {
complete = true;
status = toImg("cancel") + ' ' + _("File not found in torrent?");
} else if (remaining == 0 || length <= 0) {
complete = true;
status = toImg("tick") + ' ' + _("Complete");
} else {
int priority = storage.getPriority(f.getCanonicalPath());
if (priority < 0)
status = toImg("cancel");
else if (priority == 0)
status = toImg("clock");
else
status = toImg("clock_red");
status += " " +
(100 * (length - remaining) / length) + "% " + _("complete") +
" (" + DataHelper.formatSize2(remaining) + "B " + _("remaining") + ")";
}
} else {
status = "Not a file?";
}
} catch (IOException ioe) {
status = "Not a file? " + ioe;
}
}
}
String path=addPaths(base,encoded);
if (item.isDirectory() && !path.endsWith("/"))
path=addPaths(path,"/");
String icon = toIcon(item);
buf.append("<TD class=\"snarkFileIcon\">");
if (complete) {
buf.append("<a href=\"").append(path).append("\">");
// thumbnail ?
String plc = item.toString().toLowerCase(Locale.US);
if (plc.endsWith(".jpg") || plc.endsWith(".jpeg") || plc.endsWith(".png") ||
plc.endsWith(".gif") || plc.endsWith(".ico")) {
buf.append("<img alt=\"\" border=\"0\" class=\"thumb\" src=\"")
.append(path).append("\"></a>");
} else {
buf.append(toImg(icon, _("Open"))).append("</a>");
}
} else {
buf.append(toImg(icon));
}
buf.append("</TD><TD class=\"snarkFileName\">");
if (complete)
buf.append("<a href=\"").append(path).append("\">");
buf.append(item.getName());
if (complete)
buf.append("</a>");
buf.append("</TD><TD ALIGN=right class=\"snarkFileSize\">");
if (!item.isDirectory())
buf.append(DataHelper.formatSize2(length)).append('B');
buf.append("</TD><TD class=\"snarkFileStatus\">");
//buf.append(dfmt.format(new Date(item.lastModified())));
buf.append(status);
buf.append("</TD>");
if (showPriority) {
buf.append("<td class=\"priority\">");
File f = item;
if ((!complete) && (!item.isDirectory()) && f != null) {
int pri = snark.getStorage().getPriority(f.getCanonicalPath());
buf.append("<input type=\"radio\" value=\"5\" name=\"pri.").append(f.getCanonicalPath()).append("\" ");
if (pri > 0)
buf.append("checked=\"true\"");
buf.append('>').append(_("High"));
buf.append("<input type=\"radio\" value=\"0\" name=\"pri.").append(f.getCanonicalPath()).append("\" ");
if (pri == 0)
buf.append("checked=\"true\"");
buf.append('>').append(_("Normal"));
buf.append("<input type=\"radio\" value=\"-9\" name=\"pri.").append(f.getCanonicalPath()).append("\" ");
if (pri < 0)
buf.append("checked=\"true\"");
buf.append('>').append(_("Skip"));
showSaveButton = true;
}
buf.append("</td>");
}
buf.append("</TR>\n");
}
if (showSaveButton) {
buf.append("<thead><tr><th colspan=\"4\"> </th><th class=\"headerpriority\"><input type=\"submit\" value=\"");
buf.append(_("Save priorities"));
buf.append("\" name=\"foo\" ></th></tr></thead>\n");
}
buf.append("</table>\n");
if (showPriority)
buf.append("</form>");
buf.append("</div></div></BODY></HTML>\n");
return buf.toString();
}
/** @since 0.7.14 */
private String toIcon(File item) {
if (item.isDirectory())
return "folder";
return toIcon(item.toString());
}
/**
* Pick an icon; try to catch the common types in an i2p environment
* @return file name not including ".png"
* @since 0.7.14
*/
private String toIcon(String path) {
String icon;
// Note that for this to work well, our custom mime.properties file must be loaded.
String plc = path.toLowerCase(Locale.US);
String mime = getMimeType(path);
if (mime == null)
mime = "";
if (mime.equals("text/html"))
icon = "html";
else if (mime.equals("text/plain") ||
mime.equals("text/x-sfv") ||
mime.equals("application/rtf") ||
mime.equals("application/epub+zip") ||
mime.equals("application/x-mobipocket-ebook"))
icon = "page";
else if (mime.equals("application/java-archive") ||
plc.endsWith(".deb"))
icon = "package";
else if (plc.endsWith(".xpi2p"))
icon = "plugin";
else if (mime.equals("application/pdf"))
icon = "page_white_acrobat";
else if (mime.startsWith("image/"))
icon = "photo";
else if (mime.startsWith("audio/") || mime.equals("application/ogg"))
icon = "music";
else if (mime.startsWith("video/"))
icon = "film";
else if (mime.equals("application/zip") || mime.equals("application/x-gtar") ||
mime.equals("application/compress") || mime.equals("application/gzip") ||
mime.equals("application/x-7z-compressed") || mime.equals("application/x-rar-compressed") ||
mime.equals("application/x-tar") || mime.equals("application/x-bzip2"))
icon = "compress";
else if (plc.endsWith(".exe"))
icon = "application";
else if (plc.endsWith(".iso"))
icon = "cd";
else
icon = "page_white";
return icon;
}
/** @since 0.7.14 */
private String toImg(String icon) {
return "<img alt=\"\" height=\"16\" width=\"16\" src=\"" + _contextPath + "/.icons/" + icon + ".png\">";
}
/** @since 0.8.2 */
private String toImg(String icon, String altText) {
return "<img alt=\"" + altText + "\" height=\"16\" width=\"16\" src=\"" + _contextPath + "/.icons/" + icon + ".png\">";
}
/** @since 0.8.1 */
private void savePriorities(Snark snark, Map postParams) {
Storage storage = snark.getStorage();
if (storage == null)
return;
Set<Map.Entry> entries = postParams.entrySet();
for (Map.Entry entry : entries) {
String key = (String)entry.getKey();
if (key.startsWith("pri.")) {
try {
String file = key.substring(4);
String val = ((String[])entry.getValue())[0]; // jetty arrays
int pri = Integer.parseInt(val);
storage.setPriority(file, pri);
//System.err.println("Priority now " + pri + " for " + file);
} catch (Throwable t) { t.printStackTrace(); }
}
}
snark.updatePiecePriorities();
_manager.saveTorrentStatus(snark.getMetaInfo(), storage.getBitField(), storage.getFilePriorities());
}
}
| false | true | private void displaySnark(PrintWriter out, Snark snark, String uri, int row, long stats[], boolean showPeers,
boolean isDegraded, boolean noThinsp, boolean showDebug, boolean statsOnly,
String stParam) throws IOException {
// stats
long uploaded = snark.getUploaded();
stats[0] += snark.getDownloaded();
stats[1] += uploaded;
long downBps = snark.getDownloadRate();
long upBps = snark.getUploadRate();
boolean isRunning = !snark.isStopped();
if (isRunning) {
stats[2] += downBps;
stats[3] += upBps;
}
int curPeers = snark.getPeerCount();
stats[4] += curPeers;
long total = snark.getTotalLength();
if (total > 0)
stats[5] += total;
if (statsOnly)
return;
String basename = snark.getBaseName();
if (basename.length() > MAX_DISPLAYED_FILENAME_LENGTH) {
String start = basename.substring(0, MAX_DISPLAYED_FILENAME_LENGTH);
if (start.indexOf(" ") < 0 && start.indexOf("-") < 0) {
// browser has nowhere to break it
basename = start + "…";
}
}
// includes skipped files, -1 for magnet mode
long remaining = snark.getRemainingLength();
if (remaining > total)
remaining = total;
// does not include skipped files, -1 for magnet mode or when not running.
long needed = snark.getNeededLength();
if (needed > total)
needed = total;
long remainingSeconds;
if (downBps > 0 && needed > 0)
remainingSeconds = needed / downBps;
else
remainingSeconds = -1;
MetaInfo meta = snark.getMetaInfo();
// isValid means isNotMagnet
boolean isValid = meta != null;
boolean isMultiFile = isValid && meta.getFiles() != null;
String err = snark.getTrackerProblems();
int knownPeers = Math.max(curPeers, snark.getTrackerSeenPeers());
String rowClass = (row % 2 == 0 ? "snarkTorrentEven" : "snarkTorrentOdd");
String statusString;
if (snark.isChecking()) {
statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "stalled.png\" title=\"" + _("Checking") + "\"></td>" +
"<td class=\"snarkTorrentStatus\">" + _("Checking");
} else if (snark.isAllocating()) {
statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "stalled.png\" title=\"" + _("Allocating") + "\"></td>" +
"<td class=\"snarkTorrentStatus\">" + _("Allocating");
} else if (err != null && curPeers == 0) {
// Also don't show if seeding... but then we won't see the not-registered error
// && remaining != 0 && needed != 0) {
// let's only show this if we have no peers, otherwise PEX and DHT should bail us out, user doesn't care
//if (isRunning && curPeers > 0 && !showPeers)
// statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "trackererror.png\" title=\"" + err + "\"></td>" +
// "<td class=\"snarkTorrentStatus " + rowClass + "\">" + _("Tracker Error") +
// ": <a href=\"" + uri + "?p=" + Base64.encode(snark.getInfoHash()) + "\">" +
// curPeers + thinsp(noThinsp) +
// ngettext("1 peer", "{0} peers", knownPeers) + "</a>";
//else if (isRunning)
if (isRunning)
statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "trackererror.png\" title=\"" + err + "\"></td>" +
"<td class=\"snarkTorrentStatus\">" + _("Tracker Error") +
": " + curPeers + thinsp(noThinsp) +
ngettext("1 peer", "{0} peers", knownPeers);
else {
if (err.length() > MAX_DISPLAYED_ERROR_LENGTH)
err = err.substring(0, MAX_DISPLAYED_ERROR_LENGTH) + "…";
statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "trackererror.png\" title=\"" + err + "\"></td>" +
"<td class=\"snarkTorrentStatus\">" + _("Tracker Error");
}
} else if (snark.isStarting()) {
statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "stalled.png\" title=\"" + _("Starting") + "\"></td>" +
"<td class=\"snarkTorrentStatus\">" + _("Starting");
} else if (remaining == 0 || needed == 0) { // < 0 means no meta size yet
// partial complete or seeding
if (isRunning) {
String img;
String txt;
if (remaining == 0) {
img = "seeding";
txt = _("Seeding");
} else {
// partial
img = "complete";
txt = _("Complete");
}
if (curPeers > 0 && !showPeers)
statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + img + ".png\" title=\"" + txt + "\"></td>" +
"<td class=\"snarkTorrentStatus\">" + txt +
": <a href=\"" + uri + "?p=" + Base64.encode(snark.getInfoHash()) + stParam + "\">" +
curPeers + thinsp(noThinsp) +
ngettext("1 peer", "{0} peers", knownPeers) + "</a>";
else
statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + img + ".png\" title=\"" + txt + "\"></td>" +
"<td class=\"snarkTorrentStatus\">" + txt +
": " + curPeers + thinsp(noThinsp) +
ngettext("1 peer", "{0} peers", knownPeers);
} else {
statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "complete.png\" title=\"" + _("Complete") + "\"></td>" +
"<td class=\"snarkTorrentStatus\">" + _("Complete");
}
} else {
if (isRunning && curPeers > 0 && downBps > 0 && !showPeers)
statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "downloading.png\" title=\"" + _("OK") + "\"></td>" +
"<td class=\"snarkTorrentStatus\">" + _("OK") +
": <a href=\"" + uri + "?p=" + Base64.encode(snark.getInfoHash()) + stParam + "\">" +
curPeers + thinsp(noThinsp) +
ngettext("1 peer", "{0} peers", knownPeers) + "</a>";
else if (isRunning && curPeers > 0 && downBps > 0)
statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "downloading.png\" title=\"" + _("OK") + "\"></td>" +
"<td class=\"snarkTorrentStatus\">" + _("OK") +
": " + curPeers + thinsp(noThinsp) +
ngettext("1 peer", "{0} peers", knownPeers);
else if (isRunning && curPeers > 0 && !showPeers)
statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "stalled.png\" title=\"" + _("Stalled") + "\"></td>" +
"<td class=\"snarkTorrentStatus\">" + _("Stalled") +
": <a href=\"" + uri + "?p=" + Base64.encode(snark.getInfoHash()) + stParam + "\">" +
curPeers + thinsp(noThinsp) +
ngettext("1 peer", "{0} peers", knownPeers) + "</a>";
else if (isRunning && curPeers > 0)
statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "stalled.png\" title=\"" + _("Stalled") + "\"></td>" +
"<td class=\"snarkTorrentStatus\">" + _("Stalled") +
": " + curPeers + thinsp(noThinsp) +
ngettext("1 peer", "{0} peers", knownPeers);
else if (isRunning && knownPeers > 0)
statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "nopeers.png\" title=\"" + _("No Peers") + "\"></td>" +
"<td class=\"snarkTorrentStatus\">" + _("No Peers") +
": 0" + thinsp(noThinsp) + knownPeers ;
else if (isRunning)
statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "nopeers.png\" title=\"" + _("No Peers") + "\"></td>" +
"<td class=\"snarkTorrentStatus\">" + _("No Peers");
else
statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "stopped.png\" title=\"" + _("Stopped") + "\"></td>" +
"<td class=\"snarkTorrentStatus\">" + _("Stopped");
}
out.write("<tr class=\"" + rowClass + "\">");
out.write("<td class=\"center\">");
out.write(statusString + "</td>\n\t");
// (i) icon column
out.write("<td>");
if (isValid && meta.getAnnounce() != null) {
// Link to local details page - note that trailing slash on a single-file torrent
// gets us to the details page instead of the file.
//StringBuilder buf = new StringBuilder(128);
//buf.append("<a href=\"").append(snark.getBaseName())
// .append("/\" title=\"").append(_("Torrent details"))
// .append("\"><img alt=\"").append(_("Info")).append("\" border=\"0\" src=\"")
// .append(_imgPath).append("details.png\"></a>");
//out.write(buf.toString());
// Link to tracker details page
String trackerLink = getTrackerLink(meta.getAnnounce(), snark.getInfoHash());
if (trackerLink != null)
out.write(trackerLink);
}
String encodedBaseName = urlEncode(basename);
// File type icon column
out.write("</td>\n<td>");
if (isValid) {
// Link to local details page - note that trailing slash on a single-file torrent
// gets us to the details page instead of the file.
StringBuilder buf = new StringBuilder(128);
buf.append("<a href=\"").append(encodedBaseName)
.append("/\" title=\"").append(_("Torrent details"))
.append("\">");
out.write(buf.toString());
}
String icon;
if (isMultiFile)
icon = "folder";
else if (isValid)
icon = toIcon(meta.getName());
else if (snark instanceof FetchAndAdd)
icon = "basket_put";
else
icon = "magnet";
if (isValid) {
out.write(toImg(icon));
out.write("</a>");
} else {
out.write(toImg(icon));
}
// Torrent name column
out.write("</td><td class=\"snarkTorrentName\">");
if (remaining == 0 || isMultiFile) {
StringBuilder buf = new StringBuilder(128);
buf.append("<a href=\"").append(encodedBaseName);
if (isMultiFile)
buf.append('/');
buf.append("\" title=\"");
if (isMultiFile)
buf.append(_("View files"));
else
buf.append(_("Open file"));
buf.append("\">");
out.write(buf.toString());
}
out.write(basename);
if (remaining == 0 || isMultiFile)
out.write("</a>");
out.write("<td align=\"right\" class=\"snarkTorrentETA\">");
if(isRunning && remainingSeconds > 0 && !snark.isChecking())
out.write(DataHelper.formatDuration2(Math.max(remainingSeconds, 10) * 1000)); // (eta 6h)
out.write("</td>\n\t");
out.write("<td align=\"right\" class=\"snarkTorrentDownloaded\">");
if (remaining > 0)
out.write(formatSize(total-remaining) + thinsp(noThinsp) + formatSize(total));
else if (remaining == 0)
out.write(formatSize(total)); // 3GB
//else
// out.write("??"); // no meta size yet
out.write("</td>\n\t");
out.write("<td align=\"right\" class=\"snarkTorrentUploaded\">");
if(isRunning && isValid)
out.write(formatSize(uploaded));
out.write("</td>\n\t");
out.write("<td align=\"right\" class=\"snarkTorrentRateDown\">");
if(isRunning && needed > 0)
out.write(formatSize(downBps) + "ps");
out.write("</td>\n\t");
out.write("<td align=\"right\" class=\"snarkTorrentRateUp\">");
if(isRunning && isValid)
out.write(formatSize(upBps) + "ps");
out.write("</td>\n\t");
out.write("<td align=\"center\" class=\"snarkTorrentAction\">");
String b64 = Base64.encode(snark.getInfoHash());
if (snark.isChecking()) {
// show no buttons
} else if (isRunning) {
// Stop Button
if (isDegraded)
out.write("<a href=\"" + _contextPath + "/?action=Stop_" + b64 + "&nonce=" + _nonce + stParam + "\"><img title=\"");
else
out.write("<input type=\"image\" name=\"action_Stop_" + b64 + "\" value=\"foo\" title=\"");
out.write(_("Stop the torrent"));
out.write("\" src=\"" + _imgPath + "stop.png\" alt=\"");
out.write(_("Stop"));
out.write("\">");
if (isDegraded)
out.write("</a>");
} else if (!snark.isStarting()) {
if (!_manager.isStopping()) {
// Start Button
// This works in Opera but it's displayed a little differently, so use noThinsp here too so all 3 icons are consistent
if (noThinsp)
out.write("<a href=\"" + _contextPath + "/?action=Start_" + b64 + "&nonce=" + _nonce + stParam + "\"><img title=\"");
else
out.write("<input type=\"image\" name=\"action_Start_" + b64 + "\" value=\"foo\" title=\"");
out.write(_("Start the torrent"));
out.write("\" src=\"" + _imgPath + "start.png\" alt=\"");
out.write(_("Start"));
out.write("\">");
if (isDegraded)
out.write("</a>");
}
if (isValid) {
// Remove Button
// Doesnt work with Opera so use noThinsp instead of isDegraded
if (noThinsp)
out.write("<a href=\"" + _contextPath + "/?action=Remove_" + b64 + "&nonce=" + _nonce + stParam + "\"><img title=\"");
else
out.write("<input type=\"image\" name=\"action_Remove_" + b64 + "\" value=\"foo\" title=\"");
out.write(_("Remove the torrent from the active list, deleting the .torrent file"));
out.write("\" onclick=\"if (!confirm('");
// Can't figure out how to escape double quotes inside the onclick string.
// Single quotes in translate strings with parameters must be doubled.
// Then the remaining single quote must be escaped
out.write(_("Are you sure you want to delete the file \\''{0}.torrent\\'' (downloaded data will not be deleted) ?", basename));
out.write("')) { return false; }\"");
out.write(" src=\"" + _imgPath + "remove.png\" alt=\"");
out.write(_("Remove"));
out.write("\">");
if (isDegraded)
out.write("</a>");
}
// Delete Button
// Doesnt work with Opera so use noThinsp instead of isDegraded
if (noThinsp)
out.write("<a href=\"" + _contextPath + "/?action=Delete_" + b64 + "&nonce=" + _nonce + stParam + "\"><img title=\"");
else
out.write("<input type=\"image\" name=\"action_Delete_" + b64 + "\" value=\"foo\" title=\"");
out.write(_("Delete the .torrent file and the associated data file(s)"));
out.write("\" onclick=\"if (!confirm('");
// Can't figure out how to escape double quotes inside the onclick string.
// Single quotes in translate strings with parameters must be doubled.
// Then the remaining single quote must be escaped
out.write(_("Are you sure you want to delete the torrent \\''{0}\\'' and all downloaded data?", basename));
out.write("')) { return false; }\"");
out.write(" src=\"" + _imgPath + "delete.png\" alt=\"");
out.write(_("Delete"));
out.write("\">");
if (isDegraded)
out.write("</a>");
}
out.write("</td>\n</tr>\n");
if(showPeers && isRunning && curPeers > 0) {
List<Peer> peers = snark.getPeerList();
if (!showDebug)
Collections.sort(peers, new PeerComparator());
for (Peer peer : peers) {
if (!peer.isConnected())
continue;
out.write("<tr class=\"" + rowClass + "\"><td></td>");
out.write("<td colspan=\"4\" align=\"right\">");
String ch = peer.toString().substring(0, 4);
String client;
if ("AwMD".equals(ch))
client = _("I2PSnark");
else if ("BFJT".equals(ch))
client = "I2PRufus";
else if ("TTMt".equals(ch))
client = "I2P-BT";
else if ("LUFa".equals(ch))
client = "Azureus";
else if ("CwsL".equals(ch))
client = "I2PSnarkXL";
else if ("ZV".equals(ch.substring(2,4)) || "VUZP".equals(ch))
client = "Robert";
else if (ch.startsWith("LV")) // LVCS 1.0.2?; LVRS 1.0.4
client = "Transmission";
else if ("LUtU".equals(ch))
client = "KTorrent";
else
client = _("Unknown") + " (" + ch + ')';
out.write(client + " <tt>" + peer.toString().substring(5, 9)+ "</tt>");
if (showDebug)
out.write(" inactive " + (peer.getInactiveTime() / 1000) + "s");
out.write("</td>\n\t");
out.write("<td class=\"snarkTorrentStatus\">");
out.write("</td>\n\t");
out.write("<td align=\"right\" class=\"snarkTorrentStatus\">");
float pct;
if (isValid) {
pct = (float) (100.0 * peer.completed() / meta.getPieces());
if (pct >= 100.0)
out.write(_("Seed"));
else {
String ps = String.valueOf(pct);
if (ps.length() > 5)
ps = ps.substring(0, 5);
out.write(ps + "%");
}
} else {
pct = (float) 101.0;
// until we get the metainfo we don't know how many pieces there are
//out.write("??");
}
out.write("</td>\n\t");
out.write("<td class=\"snarkTorrentStatus\">");
out.write("</td>\n\t");
out.write("<td align=\"right\" class=\"snarkTorrentStatus\">");
if (needed > 0) {
if (peer.isInteresting() && !peer.isChoked()) {
out.write("<span class=\"unchoked\">");
out.write(formatSize(peer.getDownloadRate()) + "ps</span>");
} else {
out.write("<span class=\"choked\"><a title=\"");
if (!peer.isInteresting())
out.write(_("Uninteresting (The peer has no pieces we need)"));
else
out.write(_("Choked (The peer is not allowing us to request pieces)"));
out.write("\">");
out.write(formatSize(peer.getDownloadRate()) + "ps</a></span>");
}
} else if (!isValid) {
//if (peer supports metadata extension) {
out.write("<span class=\"unchoked\">");
out.write(formatSize(peer.getDownloadRate()) + "ps</span>");
//} else {
//}
}
out.write("</td>\n\t");
out.write("<td align=\"right\" class=\"snarkTorrentStatus\">");
if (isValid && pct < 100.0) {
if (peer.isInterested() && !peer.isChoking()) {
out.write("<span class=\"unchoked\">");
out.write(formatSize(peer.getUploadRate()) + "ps</span>");
} else {
out.write("<span class=\"choked\"><a title=\"");
if (!peer.isInterested())
out.write(_("Uninterested (We have no pieces the peer needs)"));
else
out.write(_("Choking (We are not allowing the peer to request pieces)"));
out.write("\">");
out.write(formatSize(peer.getUploadRate()) + "ps</a></span>");
}
}
out.write("</td>\n\t");
out.write("<td class=\"snarkTorrentStatus\">");
out.write("</td></tr>\n\t");
if (showDebug)
out.write("<tr class=\"" + rowClass + "\"><td></td><td colspan=\"10\" align=\"right\">" + peer.getSocket() + "</td></tr>");
}
}
}
| private void displaySnark(PrintWriter out, Snark snark, String uri, int row, long stats[], boolean showPeers,
boolean isDegraded, boolean noThinsp, boolean showDebug, boolean statsOnly,
String stParam) throws IOException {
// stats
long uploaded = snark.getUploaded();
stats[0] += snark.getDownloaded();
stats[1] += uploaded;
long downBps = snark.getDownloadRate();
long upBps = snark.getUploadRate();
boolean isRunning = !snark.isStopped();
if (isRunning) {
stats[2] += downBps;
stats[3] += upBps;
}
int curPeers = snark.getPeerCount();
stats[4] += curPeers;
long total = snark.getTotalLength();
if (total > 0)
stats[5] += total;
if (statsOnly)
return;
String basename = snark.getBaseName();
String fullBasename = basename;
if (basename.length() > MAX_DISPLAYED_FILENAME_LENGTH) {
String start = basename.substring(0, MAX_DISPLAYED_FILENAME_LENGTH);
if (start.indexOf(" ") < 0 && start.indexOf("-") < 0) {
// browser has nowhere to break it
basename = start + "…";
}
}
// includes skipped files, -1 for magnet mode
long remaining = snark.getRemainingLength();
if (remaining > total)
remaining = total;
// does not include skipped files, -1 for magnet mode or when not running.
long needed = snark.getNeededLength();
if (needed > total)
needed = total;
long remainingSeconds;
if (downBps > 0 && needed > 0)
remainingSeconds = needed / downBps;
else
remainingSeconds = -1;
MetaInfo meta = snark.getMetaInfo();
// isValid means isNotMagnet
boolean isValid = meta != null;
boolean isMultiFile = isValid && meta.getFiles() != null;
String err = snark.getTrackerProblems();
int knownPeers = Math.max(curPeers, snark.getTrackerSeenPeers());
String rowClass = (row % 2 == 0 ? "snarkTorrentEven" : "snarkTorrentOdd");
String statusString;
if (snark.isChecking()) {
statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "stalled.png\" title=\"" + _("Checking") + "\"></td>" +
"<td class=\"snarkTorrentStatus\">" + _("Checking");
} else if (snark.isAllocating()) {
statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "stalled.png\" title=\"" + _("Allocating") + "\"></td>" +
"<td class=\"snarkTorrentStatus\">" + _("Allocating");
} else if (err != null && curPeers == 0) {
// Also don't show if seeding... but then we won't see the not-registered error
// && remaining != 0 && needed != 0) {
// let's only show this if we have no peers, otherwise PEX and DHT should bail us out, user doesn't care
//if (isRunning && curPeers > 0 && !showPeers)
// statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "trackererror.png\" title=\"" + err + "\"></td>" +
// "<td class=\"snarkTorrentStatus " + rowClass + "\">" + _("Tracker Error") +
// ": <a href=\"" + uri + "?p=" + Base64.encode(snark.getInfoHash()) + "\">" +
// curPeers + thinsp(noThinsp) +
// ngettext("1 peer", "{0} peers", knownPeers) + "</a>";
//else if (isRunning)
if (isRunning)
statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "trackererror.png\" title=\"" + err + "\"></td>" +
"<td class=\"snarkTorrentStatus\">" + _("Tracker Error") +
": " + curPeers + thinsp(noThinsp) +
ngettext("1 peer", "{0} peers", knownPeers);
else {
if (err.length() > MAX_DISPLAYED_ERROR_LENGTH)
err = err.substring(0, MAX_DISPLAYED_ERROR_LENGTH) + "…";
statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "trackererror.png\" title=\"" + err + "\"></td>" +
"<td class=\"snarkTorrentStatus\">" + _("Tracker Error");
}
} else if (snark.isStarting()) {
statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "stalled.png\" title=\"" + _("Starting") + "\"></td>" +
"<td class=\"snarkTorrentStatus\">" + _("Starting");
} else if (remaining == 0 || needed == 0) { // < 0 means no meta size yet
// partial complete or seeding
if (isRunning) {
String img;
String txt;
if (remaining == 0) {
img = "seeding";
txt = _("Seeding");
} else {
// partial
img = "complete";
txt = _("Complete");
}
if (curPeers > 0 && !showPeers)
statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + img + ".png\" title=\"" + txt + "\"></td>" +
"<td class=\"snarkTorrentStatus\">" + txt +
": <a href=\"" + uri + "?p=" + Base64.encode(snark.getInfoHash()) + stParam + "\">" +
curPeers + thinsp(noThinsp) +
ngettext("1 peer", "{0} peers", knownPeers) + "</a>";
else
statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + img + ".png\" title=\"" + txt + "\"></td>" +
"<td class=\"snarkTorrentStatus\">" + txt +
": " + curPeers + thinsp(noThinsp) +
ngettext("1 peer", "{0} peers", knownPeers);
} else {
statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "complete.png\" title=\"" + _("Complete") + "\"></td>" +
"<td class=\"snarkTorrentStatus\">" + _("Complete");
}
} else {
if (isRunning && curPeers > 0 && downBps > 0 && !showPeers)
statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "downloading.png\" title=\"" + _("OK") + "\"></td>" +
"<td class=\"snarkTorrentStatus\">" + _("OK") +
": <a href=\"" + uri + "?p=" + Base64.encode(snark.getInfoHash()) + stParam + "\">" +
curPeers + thinsp(noThinsp) +
ngettext("1 peer", "{0} peers", knownPeers) + "</a>";
else if (isRunning && curPeers > 0 && downBps > 0)
statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "downloading.png\" title=\"" + _("OK") + "\"></td>" +
"<td class=\"snarkTorrentStatus\">" + _("OK") +
": " + curPeers + thinsp(noThinsp) +
ngettext("1 peer", "{0} peers", knownPeers);
else if (isRunning && curPeers > 0 && !showPeers)
statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "stalled.png\" title=\"" + _("Stalled") + "\"></td>" +
"<td class=\"snarkTorrentStatus\">" + _("Stalled") +
": <a href=\"" + uri + "?p=" + Base64.encode(snark.getInfoHash()) + stParam + "\">" +
curPeers + thinsp(noThinsp) +
ngettext("1 peer", "{0} peers", knownPeers) + "</a>";
else if (isRunning && curPeers > 0)
statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "stalled.png\" title=\"" + _("Stalled") + "\"></td>" +
"<td class=\"snarkTorrentStatus\">" + _("Stalled") +
": " + curPeers + thinsp(noThinsp) +
ngettext("1 peer", "{0} peers", knownPeers);
else if (isRunning && knownPeers > 0)
statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "nopeers.png\" title=\"" + _("No Peers") + "\"></td>" +
"<td class=\"snarkTorrentStatus\">" + _("No Peers") +
": 0" + thinsp(noThinsp) + knownPeers ;
else if (isRunning)
statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "nopeers.png\" title=\"" + _("No Peers") + "\"></td>" +
"<td class=\"snarkTorrentStatus\">" + _("No Peers");
else
statusString = "<img alt=\"\" border=\"0\" src=\"" + _imgPath + "stopped.png\" title=\"" + _("Stopped") + "\"></td>" +
"<td class=\"snarkTorrentStatus\">" + _("Stopped");
}
out.write("<tr class=\"" + rowClass + "\">");
out.write("<td class=\"center\">");
out.write(statusString + "</td>\n\t");
// (i) icon column
out.write("<td>");
if (isValid && meta.getAnnounce() != null) {
// Link to local details page - note that trailing slash on a single-file torrent
// gets us to the details page instead of the file.
//StringBuilder buf = new StringBuilder(128);
//buf.append("<a href=\"").append(snark.getBaseName())
// .append("/\" title=\"").append(_("Torrent details"))
// .append("\"><img alt=\"").append(_("Info")).append("\" border=\"0\" src=\"")
// .append(_imgPath).append("details.png\"></a>");
//out.write(buf.toString());
// Link to tracker details page
String trackerLink = getTrackerLink(meta.getAnnounce(), snark.getInfoHash());
if (trackerLink != null)
out.write(trackerLink);
}
String encodedBaseName = urlEncode(fullBasename);
// File type icon column
out.write("</td>\n<td>");
if (isValid) {
// Link to local details page - note that trailing slash on a single-file torrent
// gets us to the details page instead of the file.
StringBuilder buf = new StringBuilder(128);
buf.append("<a href=\"").append(encodedBaseName)
.append("/\" title=\"").append(_("Torrent details"))
.append("\">");
out.write(buf.toString());
}
String icon;
if (isMultiFile)
icon = "folder";
else if (isValid)
icon = toIcon(meta.getName());
else if (snark instanceof FetchAndAdd)
icon = "basket_put";
else
icon = "magnet";
if (isValid) {
out.write(toImg(icon));
out.write("</a>");
} else {
out.write(toImg(icon));
}
// Torrent name column
out.write("</td><td class=\"snarkTorrentName\">");
if (remaining == 0 || isMultiFile) {
StringBuilder buf = new StringBuilder(128);
buf.append("<a href=\"").append(encodedBaseName);
if (isMultiFile)
buf.append('/');
buf.append("\" title=\"");
if (isMultiFile)
buf.append(_("View files"));
else
buf.append(_("Open file"));
buf.append("\">");
out.write(buf.toString());
}
out.write(basename);
if (remaining == 0 || isMultiFile)
out.write("</a>");
out.write("<td align=\"right\" class=\"snarkTorrentETA\">");
if(isRunning && remainingSeconds > 0 && !snark.isChecking())
out.write(DataHelper.formatDuration2(Math.max(remainingSeconds, 10) * 1000)); // (eta 6h)
out.write("</td>\n\t");
out.write("<td align=\"right\" class=\"snarkTorrentDownloaded\">");
if (remaining > 0)
out.write(formatSize(total-remaining) + thinsp(noThinsp) + formatSize(total));
else if (remaining == 0)
out.write(formatSize(total)); // 3GB
//else
// out.write("??"); // no meta size yet
out.write("</td>\n\t");
out.write("<td align=\"right\" class=\"snarkTorrentUploaded\">");
if(isRunning && isValid)
out.write(formatSize(uploaded));
out.write("</td>\n\t");
out.write("<td align=\"right\" class=\"snarkTorrentRateDown\">");
if(isRunning && needed > 0)
out.write(formatSize(downBps) + "ps");
out.write("</td>\n\t");
out.write("<td align=\"right\" class=\"snarkTorrentRateUp\">");
if(isRunning && isValid)
out.write(formatSize(upBps) + "ps");
out.write("</td>\n\t");
out.write("<td align=\"center\" class=\"snarkTorrentAction\">");
String b64 = Base64.encode(snark.getInfoHash());
if (snark.isChecking()) {
// show no buttons
} else if (isRunning) {
// Stop Button
if (isDegraded)
out.write("<a href=\"" + _contextPath + "/?action=Stop_" + b64 + "&nonce=" + _nonce + stParam + "\"><img title=\"");
else
out.write("<input type=\"image\" name=\"action_Stop_" + b64 + "\" value=\"foo\" title=\"");
out.write(_("Stop the torrent"));
out.write("\" src=\"" + _imgPath + "stop.png\" alt=\"");
out.write(_("Stop"));
out.write("\">");
if (isDegraded)
out.write("</a>");
} else if (!snark.isStarting()) {
if (!_manager.isStopping()) {
// Start Button
// This works in Opera but it's displayed a little differently, so use noThinsp here too so all 3 icons are consistent
if (noThinsp)
out.write("<a href=\"" + _contextPath + "/?action=Start_" + b64 + "&nonce=" + _nonce + stParam + "\"><img title=\"");
else
out.write("<input type=\"image\" name=\"action_Start_" + b64 + "\" value=\"foo\" title=\"");
out.write(_("Start the torrent"));
out.write("\" src=\"" + _imgPath + "start.png\" alt=\"");
out.write(_("Start"));
out.write("\">");
if (isDegraded)
out.write("</a>");
}
if (isValid) {
// Remove Button
// Doesnt work with Opera so use noThinsp instead of isDegraded
if (noThinsp)
out.write("<a href=\"" + _contextPath + "/?action=Remove_" + b64 + "&nonce=" + _nonce + stParam + "\"><img title=\"");
else
out.write("<input type=\"image\" name=\"action_Remove_" + b64 + "\" value=\"foo\" title=\"");
out.write(_("Remove the torrent from the active list, deleting the .torrent file"));
out.write("\" onclick=\"if (!confirm('");
// Can't figure out how to escape double quotes inside the onclick string.
// Single quotes in translate strings with parameters must be doubled.
// Then the remaining single quote must be escaped
out.write(_("Are you sure you want to delete the file \\''{0}\\'' (downloaded data will not be deleted) ?", snark.getName()));
out.write("')) { return false; }\"");
out.write(" src=\"" + _imgPath + "remove.png\" alt=\"");
out.write(_("Remove"));
out.write("\">");
if (isDegraded)
out.write("</a>");
}
// Delete Button
// Doesnt work with Opera so use noThinsp instead of isDegraded
if (noThinsp)
out.write("<a href=\"" + _contextPath + "/?action=Delete_" + b64 + "&nonce=" + _nonce + stParam + "\"><img title=\"");
else
out.write("<input type=\"image\" name=\"action_Delete_" + b64 + "\" value=\"foo\" title=\"");
out.write(_("Delete the .torrent file and the associated data file(s)"));
out.write("\" onclick=\"if (!confirm('");
// Can't figure out how to escape double quotes inside the onclick string.
// Single quotes in translate strings with parameters must be doubled.
// Then the remaining single quote must be escaped
out.write(_("Are you sure you want to delete the torrent \\''{0}\\'' and all downloaded data?", fullBasename));
out.write("')) { return false; }\"");
out.write(" src=\"" + _imgPath + "delete.png\" alt=\"");
out.write(_("Delete"));
out.write("\">");
if (isDegraded)
out.write("</a>");
}
out.write("</td>\n</tr>\n");
if(showPeers && isRunning && curPeers > 0) {
List<Peer> peers = snark.getPeerList();
if (!showDebug)
Collections.sort(peers, new PeerComparator());
for (Peer peer : peers) {
if (!peer.isConnected())
continue;
out.write("<tr class=\"" + rowClass + "\"><td></td>");
out.write("<td colspan=\"4\" align=\"right\">");
String ch = peer.toString().substring(0, 4);
String client;
if ("AwMD".equals(ch))
client = _("I2PSnark");
else if ("BFJT".equals(ch))
client = "I2PRufus";
else if ("TTMt".equals(ch))
client = "I2P-BT";
else if ("LUFa".equals(ch))
client = "Azureus";
else if ("CwsL".equals(ch))
client = "I2PSnarkXL";
else if ("ZV".equals(ch.substring(2,4)) || "VUZP".equals(ch))
client = "Robert";
else if (ch.startsWith("LV")) // LVCS 1.0.2?; LVRS 1.0.4
client = "Transmission";
else if ("LUtU".equals(ch))
client = "KTorrent";
else
client = _("Unknown") + " (" + ch + ')';
out.write(client + " <tt>" + peer.toString().substring(5, 9)+ "</tt>");
if (showDebug)
out.write(" inactive " + (peer.getInactiveTime() / 1000) + "s");
out.write("</td>\n\t");
out.write("<td class=\"snarkTorrentStatus\">");
out.write("</td>\n\t");
out.write("<td align=\"right\" class=\"snarkTorrentStatus\">");
float pct;
if (isValid) {
pct = (float) (100.0 * peer.completed() / meta.getPieces());
if (pct >= 100.0)
out.write(_("Seed"));
else {
String ps = String.valueOf(pct);
if (ps.length() > 5)
ps = ps.substring(0, 5);
out.write(ps + "%");
}
} else {
pct = (float) 101.0;
// until we get the metainfo we don't know how many pieces there are
//out.write("??");
}
out.write("</td>\n\t");
out.write("<td class=\"snarkTorrentStatus\">");
out.write("</td>\n\t");
out.write("<td align=\"right\" class=\"snarkTorrentStatus\">");
if (needed > 0) {
if (peer.isInteresting() && !peer.isChoked()) {
out.write("<span class=\"unchoked\">");
out.write(formatSize(peer.getDownloadRate()) + "ps</span>");
} else {
out.write("<span class=\"choked\"><a title=\"");
if (!peer.isInteresting())
out.write(_("Uninteresting (The peer has no pieces we need)"));
else
out.write(_("Choked (The peer is not allowing us to request pieces)"));
out.write("\">");
out.write(formatSize(peer.getDownloadRate()) + "ps</a></span>");
}
} else if (!isValid) {
//if (peer supports metadata extension) {
out.write("<span class=\"unchoked\">");
out.write(formatSize(peer.getDownloadRate()) + "ps</span>");
//} else {
//}
}
out.write("</td>\n\t");
out.write("<td align=\"right\" class=\"snarkTorrentStatus\">");
if (isValid && pct < 100.0) {
if (peer.isInterested() && !peer.isChoking()) {
out.write("<span class=\"unchoked\">");
out.write(formatSize(peer.getUploadRate()) + "ps</span>");
} else {
out.write("<span class=\"choked\"><a title=\"");
if (!peer.isInterested())
out.write(_("Uninterested (We have no pieces the peer needs)"));
else
out.write(_("Choking (We are not allowing the peer to request pieces)"));
out.write("\">");
out.write(formatSize(peer.getUploadRate()) + "ps</a></span>");
}
}
out.write("</td>\n\t");
out.write("<td class=\"snarkTorrentStatus\">");
out.write("</td></tr>\n\t");
if (showDebug)
out.write("<tr class=\"" + rowClass + "\"><td></td><td colspan=\"10\" align=\"right\">" + peer.getSocket() + "</td></tr>");
}
}
}
|
diff --git a/src/main/java/com/onarandombox/multiverseinventories/ShareHandler.java b/src/main/java/com/onarandombox/multiverseinventories/ShareHandler.java
index 62a9415..a0f20db 100644
--- a/src/main/java/com/onarandombox/multiverseinventories/ShareHandler.java
+++ b/src/main/java/com/onarandombox/multiverseinventories/ShareHandler.java
@@ -1,217 +1,228 @@
package com.onarandombox.multiverseinventories;
import com.onarandombox.multiverseinventories.api.Inventories;
import com.onarandombox.multiverseinventories.api.profile.PlayerProfile;
import com.onarandombox.multiverseinventories.api.profile.ProfileContainer;
import com.onarandombox.multiverseinventories.api.profile.WorldGroupProfile;
import com.onarandombox.multiverseinventories.api.profile.WorldProfile;
import com.onarandombox.multiverseinventories.share.Sharable;
import com.onarandombox.multiverseinventories.share.Sharables;
import com.onarandombox.multiverseinventories.share.Shares;
import com.onarandombox.multiverseinventories.util.Logging;
import com.onarandombox.multiverseinventories.util.Perm;
import org.bukkit.World;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.List;
/**
* Simple implementation of ShareHandler.
*/
final class ShareHandler {
private List<PersistingProfile> fromProfiles;
private List<PersistingProfile> toProfiles;
private Player player;
private World fromWorld;
private World toWorld;
private Inventories inventories;
private boolean hasBypass = false;
public ShareHandler(Inventories inventories, Player player,
World fromWorld, World toWorld) {
this.fromProfiles = new ArrayList<PersistingProfile>();
this.toProfiles = new ArrayList<PersistingProfile>();
this.player = player;
this.fromWorld = fromWorld;
this.toWorld = toWorld;
this.inventories = inventories;
}
/**
* @return The profiles for the world/groups the player is coming from.
*/
public List<PersistingProfile> getFromProfiles() {
return this.fromProfiles;
}
/**
* @return The profiles for the world/groups the player is going to.
*/
public List<PersistingProfile> getToProfiles() {
return this.toProfiles;
}
/**
* @return The world travelling from.
*/
public World getFromWorld() {
return this.fromWorld;
}
/**
* @return The world travelling to.
*/
public World getToWorld() {
return this.toWorld;
}
/**
* @return The player involved in this sharing transaction.
*/
public Player getPlayer() {
return this.player;
}
/**
* @param container The group/world the player's data is associated with.
* @param shares What from this group needs to be saved.
* @param profile The player player that will need data saved to.
*/
public void addFromProfile(ProfileContainer container, Shares shares, PlayerProfile profile) {
this.getFromProfiles().add(new DefaultPersistingProfile(container.getDataName(), shares, profile));
}
/**
* @param container The group/world the player's data is associated with.
* @param shares What from this group needs to be loaded.
* @param profile The player player that will need data loaded from.
*/
public void addToProfile(ProfileContainer container, Shares shares, PlayerProfile profile) {
this.getToProfiles().add(new DefaultPersistingProfile(container.getDataName(), shares, profile));
}
/**
* Finalizes the transfer from one world to another. This handles the switching
* inventories/stats for a player and persisting the changes.
*/
public void handleSharing() {
Logging.finer("=== " + this.getPlayer().getName() + " traveling from world: " + this.getFromWorld().getName()
+ " to " + "world: " + this.getToWorld().getName() + " ===");
// Grab the player from the world they're coming from to save their stuff to every time.
WorldProfile fromWorldProfile = this.inventories.getWorldManager()
.getWorldProfile(this.getFromWorld().getName());
this.addFromProfile(fromWorldProfile, Sharables.allOf(),
fromWorldProfile.getPlayerData(this.getPlayer()));
if (Perm.BYPASS_WORLD.hasBypass(this.getPlayer(), this.getToWorld().getName())) {
this.hasBypass = true;
completeSharing();
return;
}
// Get any groups we need to save stuff to.
List<WorldGroupProfile> fromWorldGroups = this.inventories.getGroupManager()
.getGroupsForWorld(this.getFromWorld().getName());
for (WorldGroupProfile fromWorldGroup : fromWorldGroups) {
PlayerProfile profile = fromWorldGroup.getPlayerData(this.getPlayer());
if (!fromWorldGroup.containsWorld(this.getToWorld().getName())) {
this.addFromProfile(fromWorldGroup,
Sharables.allOf(), profile);
} else {
if (!fromWorldGroup.getShares().isSharing(Sharables.all())) {
//Shares sharing = Sharables.complementOf(fromWorldGroup.getShares());
this.addFromProfile(fromWorldGroup, Sharables.fromShares(fromWorldGroup.getShares()), profile);
}
}
}
if (fromWorldGroups.isEmpty()) {
Logging.finer("No groups for fromWorld.");
}
Shares sharesToUpdate = Sharables.noneOf();
List<WorldGroupProfile> toWorldGroups = this.inventories.getGroupManager()
- .getGroupsForWorld(this.getToWorld().getName());
+ .getGroupsForWorld(this.getToWorld().getName());;
if (!toWorldGroups.isEmpty()) {
// Get groups we need to load from
for (WorldGroupProfile toWorldGroup : toWorldGroups) {
if (Perm.BYPASS_GROUP.hasBypass(this.getPlayer(), toWorldGroup.getName())) {
this.hasBypass = true;
} else {
PlayerProfile profile = toWorldGroup.getPlayerData(this.getPlayer());
if (!toWorldGroup.containsWorld(this.getFromWorld().getName())) {
Shares sharesToAdd = Sharables.allOf();
sharesToUpdate.addAll(sharesToAdd);
this.addToProfile(toWorldGroup,
sharesToAdd, profile);
} else {
if (!toWorldGroup.getShares().isSharing(Sharables.all())) {
Shares sharesToAdd = Sharables.fromShares(toWorldGroup.getShares());
sharesToUpdate.addAll(sharesToAdd);
this.addToProfile(toWorldGroup, sharesToAdd, profile);
+ } else {
+ sharesToUpdate = Sharables.allOf();
}
}
}
}
+ } else {
+ // Get world we need to load from.
+ Logging.finer("No groups for toWorld.");
+ WorldProfile toWorldProfile = this.inventories.getWorldManager()
+ .getWorldProfile(this.getToWorld().getName());
+ this.addToProfile(toWorldProfile, Sharables.allOf(),
+ toWorldProfile.getPlayerData(this.getPlayer()));
+ sharesToUpdate = Sharables.allOf();
}
if (!sharesToUpdate.isSharing(Sharables.all())) {
+ System.out.println(sharesToUpdate + " VS " + Sharables.all());
sharesToUpdate = Sharables.complementOf(sharesToUpdate);
// Get world we need to load from.
Logging.finer("No groups for toWorld.");
WorldProfile toWorldProfile = this.inventories.getWorldManager()
.getWorldProfile(this.getToWorld().getName());
this.addToProfile(toWorldProfile, sharesToUpdate,
toWorldProfile.getPlayerData(this.getPlayer()));
}
this.completeSharing();
}
private void completeSharing() {
Logging.finer("Travel affected by " + this.getFromProfiles().size() + " fromProfiles and "
+ this.getToProfiles().size() + " toProfiles");
// This if statement should never happen, really.
if (this.getToProfiles().isEmpty()) {
if (hasBypass) {
Logging.fine(this.getPlayer().getName() + " has bypass permission for 1 or more world/groups!");
} else {
Logging.finer("No toProfiles...");
}
if (!this.getFromProfiles().isEmpty()) {
updateProfile(this.getFromProfiles().get(0));
} else {
Logging.warning("No fromWorld to save to");
}
Logging.finer("=== " + this.getPlayer().getName() + "'s travel handling complete! ===");
return;
}
for (PersistingProfile persistingProfile : this.getFromProfiles()) {
updateProfile(persistingProfile);
}
for (PersistingProfile persistingProfile : this.getToProfiles()) {
updatePlayer(persistingProfile);
}
Logging.finer("=== " + this.getPlayer().getName() + "'s travel handling complete! ===");
}
private void updateProfile(PersistingProfile profile) {
for (Sharable sharable : profile.getShares()) {
sharable.updateProfile(profile.getProfile(), this.getPlayer());
}
Logging.finest("Persisting: " + profile.getShares().toString() + " to "
+ profile.getProfile().getType() + ":" + profile.getDataName()
+ " for player " + profile.getProfile().getPlayer().getName());
this.inventories.getData().updatePlayerData(profile.getDataName(), profile.getProfile());
}
private void updatePlayer(PersistingProfile profile) {
for (Sharable sharable : profile.getShares()) {
sharable.updatePlayer(this.getPlayer(), profile.getProfile());
}
Logging.finest("Updating " + profile.getShares().toString() + " for "
+ profile.getProfile().getPlayer().getName() + "for "
+ profile.getProfile().getType() + ":" + profile.getDataName());
}
}
| false | true | public void handleSharing() {
Logging.finer("=== " + this.getPlayer().getName() + " traveling from world: " + this.getFromWorld().getName()
+ " to " + "world: " + this.getToWorld().getName() + " ===");
// Grab the player from the world they're coming from to save their stuff to every time.
WorldProfile fromWorldProfile = this.inventories.getWorldManager()
.getWorldProfile(this.getFromWorld().getName());
this.addFromProfile(fromWorldProfile, Sharables.allOf(),
fromWorldProfile.getPlayerData(this.getPlayer()));
if (Perm.BYPASS_WORLD.hasBypass(this.getPlayer(), this.getToWorld().getName())) {
this.hasBypass = true;
completeSharing();
return;
}
// Get any groups we need to save stuff to.
List<WorldGroupProfile> fromWorldGroups = this.inventories.getGroupManager()
.getGroupsForWorld(this.getFromWorld().getName());
for (WorldGroupProfile fromWorldGroup : fromWorldGroups) {
PlayerProfile profile = fromWorldGroup.getPlayerData(this.getPlayer());
if (!fromWorldGroup.containsWorld(this.getToWorld().getName())) {
this.addFromProfile(fromWorldGroup,
Sharables.allOf(), profile);
} else {
if (!fromWorldGroup.getShares().isSharing(Sharables.all())) {
//Shares sharing = Sharables.complementOf(fromWorldGroup.getShares());
this.addFromProfile(fromWorldGroup, Sharables.fromShares(fromWorldGroup.getShares()), profile);
}
}
}
if (fromWorldGroups.isEmpty()) {
Logging.finer("No groups for fromWorld.");
}
Shares sharesToUpdate = Sharables.noneOf();
List<WorldGroupProfile> toWorldGroups = this.inventories.getGroupManager()
.getGroupsForWorld(this.getToWorld().getName());
if (!toWorldGroups.isEmpty()) {
// Get groups we need to load from
for (WorldGroupProfile toWorldGroup : toWorldGroups) {
if (Perm.BYPASS_GROUP.hasBypass(this.getPlayer(), toWorldGroup.getName())) {
this.hasBypass = true;
} else {
PlayerProfile profile = toWorldGroup.getPlayerData(this.getPlayer());
if (!toWorldGroup.containsWorld(this.getFromWorld().getName())) {
Shares sharesToAdd = Sharables.allOf();
sharesToUpdate.addAll(sharesToAdd);
this.addToProfile(toWorldGroup,
sharesToAdd, profile);
} else {
if (!toWorldGroup.getShares().isSharing(Sharables.all())) {
Shares sharesToAdd = Sharables.fromShares(toWorldGroup.getShares());
sharesToUpdate.addAll(sharesToAdd);
this.addToProfile(toWorldGroup, sharesToAdd, profile);
}
}
}
}
}
if (!sharesToUpdate.isSharing(Sharables.all())) {
sharesToUpdate = Sharables.complementOf(sharesToUpdate);
// Get world we need to load from.
Logging.finer("No groups for toWorld.");
WorldProfile toWorldProfile = this.inventories.getWorldManager()
.getWorldProfile(this.getToWorld().getName());
this.addToProfile(toWorldProfile, sharesToUpdate,
toWorldProfile.getPlayerData(this.getPlayer()));
}
this.completeSharing();
}
| public void handleSharing() {
Logging.finer("=== " + this.getPlayer().getName() + " traveling from world: " + this.getFromWorld().getName()
+ " to " + "world: " + this.getToWorld().getName() + " ===");
// Grab the player from the world they're coming from to save their stuff to every time.
WorldProfile fromWorldProfile = this.inventories.getWorldManager()
.getWorldProfile(this.getFromWorld().getName());
this.addFromProfile(fromWorldProfile, Sharables.allOf(),
fromWorldProfile.getPlayerData(this.getPlayer()));
if (Perm.BYPASS_WORLD.hasBypass(this.getPlayer(), this.getToWorld().getName())) {
this.hasBypass = true;
completeSharing();
return;
}
// Get any groups we need to save stuff to.
List<WorldGroupProfile> fromWorldGroups = this.inventories.getGroupManager()
.getGroupsForWorld(this.getFromWorld().getName());
for (WorldGroupProfile fromWorldGroup : fromWorldGroups) {
PlayerProfile profile = fromWorldGroup.getPlayerData(this.getPlayer());
if (!fromWorldGroup.containsWorld(this.getToWorld().getName())) {
this.addFromProfile(fromWorldGroup,
Sharables.allOf(), profile);
} else {
if (!fromWorldGroup.getShares().isSharing(Sharables.all())) {
//Shares sharing = Sharables.complementOf(fromWorldGroup.getShares());
this.addFromProfile(fromWorldGroup, Sharables.fromShares(fromWorldGroup.getShares()), profile);
}
}
}
if (fromWorldGroups.isEmpty()) {
Logging.finer("No groups for fromWorld.");
}
Shares sharesToUpdate = Sharables.noneOf();
List<WorldGroupProfile> toWorldGroups = this.inventories.getGroupManager()
.getGroupsForWorld(this.getToWorld().getName());;
if (!toWorldGroups.isEmpty()) {
// Get groups we need to load from
for (WorldGroupProfile toWorldGroup : toWorldGroups) {
if (Perm.BYPASS_GROUP.hasBypass(this.getPlayer(), toWorldGroup.getName())) {
this.hasBypass = true;
} else {
PlayerProfile profile = toWorldGroup.getPlayerData(this.getPlayer());
if (!toWorldGroup.containsWorld(this.getFromWorld().getName())) {
Shares sharesToAdd = Sharables.allOf();
sharesToUpdate.addAll(sharesToAdd);
this.addToProfile(toWorldGroup,
sharesToAdd, profile);
} else {
if (!toWorldGroup.getShares().isSharing(Sharables.all())) {
Shares sharesToAdd = Sharables.fromShares(toWorldGroup.getShares());
sharesToUpdate.addAll(sharesToAdd);
this.addToProfile(toWorldGroup, sharesToAdd, profile);
} else {
sharesToUpdate = Sharables.allOf();
}
}
}
}
} else {
// Get world we need to load from.
Logging.finer("No groups for toWorld.");
WorldProfile toWorldProfile = this.inventories.getWorldManager()
.getWorldProfile(this.getToWorld().getName());
this.addToProfile(toWorldProfile, Sharables.allOf(),
toWorldProfile.getPlayerData(this.getPlayer()));
sharesToUpdate = Sharables.allOf();
}
if (!sharesToUpdate.isSharing(Sharables.all())) {
System.out.println(sharesToUpdate + " VS " + Sharables.all());
sharesToUpdate = Sharables.complementOf(sharesToUpdate);
// Get world we need to load from.
Logging.finer("No groups for toWorld.");
WorldProfile toWorldProfile = this.inventories.getWorldManager()
.getWorldProfile(this.getToWorld().getName());
this.addToProfile(toWorldProfile, sharesToUpdate,
toWorldProfile.getPlayerData(this.getPlayer()));
}
this.completeSharing();
}
|
diff --git a/src/java/net/sf/kraken/protocols/xmpp/XMPPSession.java b/src/java/net/sf/kraken/protocols/xmpp/XMPPSession.java
index d056f1c..a493b8e 100644
--- a/src/java/net/sf/kraken/protocols/xmpp/XMPPSession.java
+++ b/src/java/net/sf/kraken/protocols/xmpp/XMPPSession.java
@@ -1,684 +1,684 @@
/**
* $Revision$
* $Date$
*
* Copyright 2006-2010 Daniel Henninger. All rights reserved.
*
* This software is published under the terms of the GNU Public License (GPL),
* a copy of which is included in this distribution.
*/
package net.sf.kraken.protocols.xmpp;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Timer;
import java.util.TimerTask;
import net.sf.kraken.avatars.Avatar;
import net.sf.kraken.protocols.xmpp.packet.BuzzExtension;
import net.sf.kraken.protocols.xmpp.packet.GoogleMailBoxPacket;
import net.sf.kraken.protocols.xmpp.packet.GoogleMailNotifyExtension;
import net.sf.kraken.protocols.xmpp.packet.GoogleNewMailExtension;
import net.sf.kraken.protocols.xmpp.packet.GoogleUserSettingExtension;
import net.sf.kraken.protocols.xmpp.packet.IQWithPacketExtension;
import net.sf.kraken.protocols.xmpp.packet.ProbePacket;
import net.sf.kraken.protocols.xmpp.packet.VCardUpdateExtension;
import net.sf.kraken.registration.Registration;
import net.sf.kraken.session.TransportSession;
import net.sf.kraken.type.*;
import org.apache.log4j.Logger;
import org.jivesoftware.openfire.user.UserNotFoundException;
import org.jivesoftware.smack.*;
import org.jivesoftware.smack.Roster.SubscriptionMode;
import org.jivesoftware.smack.filter.OrFilter;
import org.jivesoftware.smack.filter.PacketExtensionFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.Presence.Type;
import org.jivesoftware.smack.provider.ProviderManager;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smackx.ChatState;
import org.jivesoftware.smackx.packet.ChatStateExtension;
import org.jivesoftware.smackx.packet.VCard;
import org.jivesoftware.util.Base64;
import org.jivesoftware.util.JiveGlobals;
import org.jivesoftware.util.LocaleUtils;
import org.jivesoftware.util.NotFoundException;
import org.xmpp.packet.JID;
/**
* Handles XMPP transport session.
*
* @author Daniel Henninger
* @author Mehmet Ecevit
*/
public class XMPPSession extends TransportSession<XMPPBuddy> {
static Logger Log = Logger.getLogger(XMPPSession.class);
/**
* Create an XMPP Session instance.
*
* @param registration Registration information used for logging in.
* @param jid JID associated with this session.
* @param transport Transport instance associated with this session.
* @param priority Priority of this session.
*/
public XMPPSession(Registration registration, JID jid, XMPPTransport transport, Integer priority) {
super(registration, jid, transport, priority);
setSupportedFeature(SupportedFeature.attention);
setSupportedFeature(SupportedFeature.chatstates);
SASLAuthentication.registerSASLMechanism("DIGEST-MD5", MySASLDigestMD5Mechanism.class);
Log.debug("Creating "+getTransport().getType()+" session for " + registration.getUsername());
String connecthost;
Integer connectport;
String domain;
connecthost = JiveGlobals.getProperty("plugin.gateway."+getTransport().getType()+".connecthost", (getTransport().getType().equals(TransportType.gtalk) ? "talk.google.com" : getTransport().getType().equals(TransportType.facebook) ? "chat.facebook.com" : "jabber.org"));
connectport = JiveGlobals.getIntProperty("plugin.gateway."+getTransport().getType()+".connectport", 5222);
if (getTransport().getType().equals(TransportType.gtalk)) {
domain = "gmail.com";
}
else if (getTransport().getType().equals(TransportType.facebook)) {
//if (connecthost.equals("www.facebook.com")) {
connecthost = "chat.facebook.com";
//}
//if (connectport.equals(80)) {
connectport = 5222;
//}
domain = "chat.facebook.com";
}
else {
domain = connecthost;
}
// For different domains other than 'gmail.com', which is given with Google Application services
if (registration.getUsername().indexOf("@") > -1) {
domain = registration.getUsername().substring( registration.getUsername().indexOf("@")+1 );
}
// If administrator specified "*" for domain, allow user to connect to anything.
if (connecthost.equals("*")) {
connecthost = domain;
}
config = new ConnectionConfiguration(connecthost, connectport, domain);
config.setCompressionEnabled(JiveGlobals.getBooleanProperty("plugin.gateway."+getTransport().getType()+".usecompression", false));
if (getTransport().getType().equals(TransportType.facebook)) {
//SASLAuthentication.supportSASLMechanism("PLAIN", 0);
//config.setSASLAuthenticationEnabled(false);
//config.setSecurityMode(ConnectionConfiguration.SecurityMode.enabled);
}
// instead, send the initial presence right after logging in. This
// allows us to use a different presence mode than the plain old
// 'available' as initial presence.
config.setSendPresence(false);
if (getTransport().getType().equals(TransportType.gtalk) && JiveGlobals.getBooleanProperty("plugin.gateway.gtalk.mailnotifications", true)) {
ProviderManager.getInstance().addIQProvider(GoogleMailBoxPacket.MAILBOX_ELEMENT, GoogleMailBoxPacket.MAILBOX_NAMESPACE, new GoogleMailBoxPacket.Provider());
ProviderManager.getInstance().addExtensionProvider(GoogleNewMailExtension.ELEMENT_NAME, GoogleNewMailExtension.NAMESPACE, new GoogleNewMailExtension.Provider());
}
}
/*
* XMPP connection
*/
public XMPPConnection conn = null;
/**
* XMPP listener
*/
private XMPPListener listener = null;
/**
* Run thread.
*/
private Thread runThread = null;
/**
* Instance that will handle all presence stanzas sent from the legacy
* domain
*/
private XMPPPresenceHandler presenceHandler = null;
/*
* XMPP connection configuration
*/
private final ConnectionConfiguration config;
/**
* Timer to check for online status.
*/
public Timer timer = new Timer();
/**
* Interval at which status is checked.
*/
private int timerInterval = 60000; // 1 minute
/**
* Mail checker
*/
MailCheck mailCheck;
/**
* XMPP Resource - the resource we are using (randomly generated)
*/
public String xmppResource = StringUtils.randomString(10);
/**
* Returns a full JID based off of a username passed in.
*
* If it already looks like a JID, returns what was passed in.
*
* @param username Username to turn into a JID.
* @return Converted username.
*/
public String generateFullJID(String username) {
if (username.indexOf("@") > -1) {
return username;
}
if (getTransport().getType().equals(TransportType.gtalk)) {
return username+"@"+"gmail.com";
}
else if (getTransport().getType().equals(TransportType.facebook)) {
return username+"@"+"chat.facebook.com";
}
else {
String connecthost = JiveGlobals.getProperty("plugin.gateway."+getTransport().getType()+".connecthost", (getTransport().getType().equals(TransportType.gtalk) ? "talk.google.com" : getTransport().getType().equals(TransportType.facebook) ? "chat.facebook.com" : "jabber.org"));
return username+"@"+connecthost;
}
}
/**
* Returns a username based off of a registered name (possible JID) passed in.
*
* If it already looks like a username, returns what was passed in.
*
* @param regName Registered name to turn into a username.
* @return Converted registered name.
*/
public String generateUsername(String regName) {
if (regName.indexOf("@") > -1) {
if (getTransport().getType().equals(TransportType.gtalk)) {
return regName;
}
else {
return regName.substring(0, regName.indexOf("@"));
}
}
else {
if (getTransport().getType().equals(TransportType.gtalk)) {
return regName+"@gmail.com";
}
else {
return regName;
}
}
}
/**
* @see net.sf.kraken.session.TransportSession#logIn(net.sf.kraken.type.PresenceType, String)
*/
@Override
public void logIn(PresenceType presenceType, String verboseStatus) {
final org.jivesoftware.smack.packet.Presence presence = new org.jivesoftware.smack.packet.Presence(org.jivesoftware.smack.packet.Presence.Type.available);
if (JiveGlobals.getBooleanProperty("plugin.gateway."+getTransport().getType()+".avatars", true) && getAvatar() != null) {
Avatar avatar = getAvatar();
// Same thing in this case, so lets go ahead and set them.
avatar.setLegacyIdentifier(avatar.getXmppHash());
VCardUpdateExtension ext = new VCardUpdateExtension();
ext.setPhotoHash(avatar.getLegacyIdentifier());
presence.addExtension(ext);
}
final Presence.Mode pMode = ((XMPPTransport) getTransport())
.convertGatewayStatusToXMPP(presenceType);
if (pMode != null) {
presence.setMode(pMode);
}
if (verboseStatus != null && verboseStatus.trim().length() > 0) {
presence.setStatus(verboseStatus);
}
setPendingPresenceAndStatus(presenceType, verboseStatus);
if (!this.isLoggedIn()) {
listener = new XMPPListener(this);
presenceHandler = new XMPPPresenceHandler(this);
runThread = new Thread() {
@Override
public void run() {
String userName = generateUsername(registration.getUsername());
conn = new XMPPConnection(config);
try {
Roster.setDefaultSubscriptionMode(SubscriptionMode.manual);
conn.connect();
conn.addConnectionListener(listener);
try {
- conn.login(userName, registration.getPassword(), xmppResource);
- conn.sendPacket(presence); // send initial presence.
- conn.getChatManager().addChatListener(listener);
- conn.getRoster().addRosterListener(listener);
conn.addPacketListener(presenceHandler, new PacketTypeFilter(org.jivesoftware.smack.packet.Presence.class));
// Use this to filter out anything we don't care about
conn.addPacketListener(listener, new OrFilter(
new PacketTypeFilter(GoogleMailBoxPacket.class),
new PacketExtensionFilter(GoogleNewMailExtension.ELEMENT_NAME, GoogleNewMailExtension.NAMESPACE)
));
+ conn.login(userName, registration.getPassword(), xmppResource);
+ conn.sendPacket(presence); // send initial presence.
+ conn.getChatManager().addChatListener(listener);
+ conn.getRoster().addRosterListener(listener);
if (JiveGlobals.getBooleanProperty("plugin.gateway."+getTransport().getType()+".avatars", true) && getAvatar() != null) {
new Thread() {
@Override
public void run() {
Avatar avatar = getAvatar();
VCard vCard = new VCard();
try {
vCard.load(conn);
vCard.setAvatar(Base64.decode(avatar.getImageData()), avatar.getMimeType());
vCard.save(conn);
}
catch (XMPPException e) {
Log.debug("XMPP: Error while updating vcard for avatar change.", e);
}
catch (NotFoundException e) {
Log.debug("XMPP: Unable to find avatar while setting initial.", e);
}
}
}.start();
}
setLoginStatus(TransportLoginStatus.LOGGED_IN);
syncUsers();
if (getTransport().getType().equals(TransportType.gtalk) && JiveGlobals.getBooleanProperty("plugin.gateway.gtalk.mailnotifications", true)) {
conn.sendPacket(new IQWithPacketExtension(generateFullJID(getRegistration().getUsername()), new GoogleUserSettingExtension(false, true, false), IQ.Type.SET));
conn.sendPacket(new IQWithPacketExtension(generateFullJID(getRegistration().getUsername()), new GoogleMailNotifyExtension()));
mailCheck = new MailCheck();
timer.schedule(mailCheck, timerInterval, timerInterval);
}
}
catch (XMPPException e) {
Log.debug(getTransport().getType()+" user's login/password does not appear to be correct: "+getRegistration().getUsername(), e);
sessionDisconnectedNoReconnect(LocaleUtils.getLocalizedString("gateway.xmpp.passwordincorrect", "kraken"));
setFailureStatus(ConnectionFailureReason.USERNAME_OR_PASSWORD_INCORRECT);
}
}
catch (XMPPException e) {
Log.debug(getTransport().getType()+" user is not able to connect: "+getRegistration().getUsername(), e);
sessionDisconnected(LocaleUtils.getLocalizedString("gateway.xmpp.connectionfailed", "kraken"));
setFailureStatus(ConnectionFailureReason.CAN_NOT_CONNECT);
}
}
};
runThread.start();
}
}
/**
* @see net.sf.kraken.session.TransportSession#logOut()
*/
@Override
public void logOut() {
cleanUp();
sessionDisconnectedNoReconnect(null);
}
/**
* @see net.sf.kraken.session.TransportSession#cleanUp()
*/
@Override
public void cleanUp() {
if (timer != null) {
try {
timer.cancel();
}
catch (Exception e) {
// Ignore
}
timer = null;
}
if (mailCheck != null) {
try {
mailCheck.cancel();
}
catch (Exception e) {
// Ignore
}
mailCheck = null;
}
if (conn != null) {
try {
conn.removeConnectionListener(listener);
}
catch (Exception e) {
// Ignore
}
try {
conn.removePacketListener(listener);
}
catch (Exception e) {
// Ignore
}
try {
conn.removePacketListener(presenceHandler);
} catch (Exception e) {
// Ignore
}
try {
conn.getChatManager().removeChatListener(listener);
}
catch (Exception e) {
// Ignore
}
try {
conn.getRoster().removeRosterListener(listener);
}
catch (Exception e) {
// Ignore
}
try {
conn.disconnect();
}
catch (Exception e) {
// Ignore
}
}
conn = null;
listener = null;
presenceHandler = null;
if (runThread != null) {
try {
runThread.interrupt();
}
catch (Exception e) {
// Ignore
}
runThread = null;
}
}
/**
* @see net.sf.kraken.session.TransportSession#updateStatus(net.sf.kraken.type.PresenceType, String)
*/
@Override
public void updateStatus(PresenceType presenceType, String verboseStatus) {
setPresenceAndStatus(presenceType, verboseStatus);
final org.jivesoftware.smack.packet.Presence presence = constructCurrentLegacyPresencePacket();
try {
conn.sendPacket(presence);
}
catch (IllegalStateException e) {
Log.debug("XMPP: Not connected while trying to change status.");
}
}
/**
* @see net.sf.kraken.session.TransportSession#addContact(org.xmpp.packet.JID, String, java.util.ArrayList)
*/
@Override
public void addContact(JID jid, String nickname, ArrayList<String> groups) {
String mail = getTransport().convertJIDToID(jid);
try {
conn.getRoster().createEntry(mail, nickname, groups.toArray(new String[groups.size()]));
RosterEntry entry = conn.getRoster().getEntry(mail);
getBuddyManager().storeBuddy(new XMPPBuddy(getBuddyManager(), mail, nickname, entry.getGroups(), entry));
}
catch (XMPPException ex) {
Log.debug("XMPP: unable to add:"+ mail);
}
}
/**
* @see net.sf.kraken.session.TransportSession#removeContact(net.sf.kraken.roster.TransportBuddy)
*/
@Override
public void removeContact(XMPPBuddy contact) {
RosterEntry user2remove;
String mail = getTransport().convertJIDToID(contact.getJID());
user2remove = conn.getRoster().getEntry(mail);
try {
conn.getRoster().removeEntry(user2remove);
}
catch (XMPPException ex) {
Log.debug("XMPP: unable to remove:"+ mail);
}
}
/**
* @see net.sf.kraken.session.TransportSession#updateContact(net.sf.kraken.roster.TransportBuddy)
*/
@Override
public void updateContact(XMPPBuddy contact) {
RosterEntry user2Update;
String mail = getTransport().convertJIDToID(contact.getJID());
user2Update = conn.getRoster().getEntry(mail);
user2Update.setName(contact.getNickname());
Collection<String> newgroups = contact.getGroups();
if (newgroups == null) {
newgroups = new ArrayList<String>();
}
for (RosterGroup group : conn.getRoster().getGroups()) {
if (newgroups.contains(group.getName())) {
if (!group.contains(user2Update)) {
try {
group.addEntry(user2Update);
}
catch (XMPPException e) {
Log.debug("XMPP: Unable to add roster item to group.");
}
}
newgroups.remove(group.getName());
}
else {
if (group.contains(user2Update)) {
try {
group.removeEntry(user2Update);
}
catch (XMPPException e) {
Log.debug("XMPP: Unable to delete roster item from group.");
}
}
}
}
for (String group : newgroups) {
RosterGroup newgroup = conn.getRoster().createGroup(group);
try {
newgroup.addEntry(user2Update);
}
catch (XMPPException e) {
Log.debug("XMPP: Unable to add roster item to new group.");
}
}
}
/**
* @see net.sf.kraken.session.TransportSession#acceptAddContact(JID)
*/
@Override
public void acceptAddContact(JID jid) {
final String userID = getTransport().convertJIDToID(jid);
Log.debug("XMPP: accept-add contact: " + userID);
final Presence accept = new Presence(Type.subscribed);
accept.setTo(userID);
conn.sendPacket(accept);
}
/**
* @see net.sf.kraken.session.TransportSession#sendMessage(org.xmpp.packet.JID, String)
*/
@Override
public void sendMessage(JID jid, String message) {
Chat chat = conn.getChatManager().createChat(getTransport().convertJIDToID(jid), listener);
try {
chat.sendMessage(message);
}
catch (XMPPException e) {
// Ignore
}
}
/**
* @see net.sf.kraken.session.TransportSession#sendChatState(org.xmpp.packet.JID, net.sf.kraken.type.ChatStateType)
*/
@Override
public void sendChatState(JID jid, ChatStateType chatState) {
final Presence presence = conn.getRoster().getPresence(jid.toString());
if (presence == null || presence.getType().equals(Presence.Type.unavailable)) {
// don't send chat state to contacts that are offline.
return;
}
Chat chat = conn.getChatManager().createChat(getTransport().convertJIDToID(jid), listener);
try {
ChatState state = ChatState.active;
switch (chatState) {
case active: state = ChatState.active; break;
case composing: state = ChatState.composing; break;
case paused: state = ChatState.paused; break;
case inactive: state = ChatState.inactive; break;
case gone: state = ChatState.gone; break;
}
Message message = new Message();
message.addExtension(new ChatStateExtension(state));
chat.sendMessage(message);
}
catch (XMPPException e) {
// Ignore
}
}
/**
* @see net.sf.kraken.session.TransportSession#sendBuzzNotification(org.xmpp.packet.JID, String)
*/
@Override
public void sendBuzzNotification(JID jid, String message) {
Chat chat = conn.getChatManager().createChat(getTransport().convertJIDToID(jid), listener);
try {
Message m = new Message();
m.setTo(getTransport().convertJIDToID(jid));
m.addExtension(new BuzzExtension());
chat.sendMessage(m);
}
catch (XMPPException e) {
// Ignore
}
}
/**
* Returns a (legacy/Smack-based) Presence stanza that represents the
* current presence of this session. The Presence includes relevant Mode,
* Status and VCardUpdate information.
*
* This method uses the fields {@link TransportSession#presence} and
* {@link TransportSession#verboseStatus} to generate the result.
*
* @return A Presence packet representing the current presence state of this
* session.
*/
public Presence constructCurrentLegacyPresencePacket() {
final org.jivesoftware.smack.packet.Presence presence = new org.jivesoftware.smack.packet.Presence(
org.jivesoftware.smack.packet.Presence.Type.available);
final Presence.Mode pMode = ((XMPPTransport) getTransport())
.convertGatewayStatusToXMPP(this.presence);
if (pMode != null) {
presence.setMode(pMode);
}
if (verboseStatus != null && verboseStatus.trim().length() > 0) {
presence.setStatus(verboseStatus);
}
final Avatar avatar = getAvatar();
if (avatar != null) {
final VCardUpdateExtension ext = new VCardUpdateExtension();
ext.setPhotoHash(avatar.getLegacyIdentifier());
presence.addExtension(ext);
}
return presence;
}
/**
* @see net.sf.kraken.session.TransportSession#updateLegacyAvatar(String, byte[])
*/
@Override
public void updateLegacyAvatar(String type, final byte[] data) {
new Thread() {
@Override
public void run() {
Avatar avatar = getAvatar();
VCard vCard = new VCard();
try {
vCard.load(conn);
vCard.setAvatar(data, avatar.getMimeType());
vCard.save(conn);
avatar.setLegacyIdentifier(avatar.getXmppHash());
// Same thing in this case, so lets go ahead and set them.
final org.jivesoftware.smack.packet.Presence presence = constructCurrentLegacyPresencePacket();
conn.sendPacket(presence);
}
catch (XMPPException e) {
Log.debug("XMPP: Error while updating vcard for avatar change.", e);
}
}
}.start();
}
public void syncUsers() {
for (RosterEntry entry : conn.getRoster().getEntries()) {
getBuddyManager().storeBuddy(new XMPPBuddy(getBuddyManager(), entry.getUser(), entry.getName(), entry.getGroups(), entry));
//ProbePacket probe = new ProbePacket(this.getJID()+"/"+xmppResource, entry.getUser());
ProbePacket probe = new ProbePacket(null, entry.getUser());
Log.debug("XMPP: Sending the following probe packet: "+probe.toXML());
try {
conn.sendPacket(probe);
}
catch (IllegalStateException e) {
Log.debug("XMPP: Not connected while trying to send probe.");
}
}
try {
getTransport().syncLegacyRoster(getJID(), getBuddyManager().getBuddies());
}
catch (UserNotFoundException ex) {
Log.error("XMPP: User not found while syncing legacy roster: ", ex);
}
getBuddyManager().activate();
// lets repoll the roster since smack seems to get out of sync...
// we'll let the roster listener take care of this though.
conn.getRoster().reload();
}
private class MailCheck extends TimerTask {
/**
* Check GMail for new mail.
*/
@Override
public void run() {
if (getTransport().getType().equals(TransportType.gtalk) && JiveGlobals.getBooleanProperty("plugin.gateway.gtalk.mailnotifications", true)) {
GoogleMailNotifyExtension gmne = new GoogleMailNotifyExtension();
gmne.setNewerThanTime(listener.getLastGMailThreadDate());
gmne.setNewerThanTid(listener.getLastGMailThreadId());
conn.sendPacket(new IQWithPacketExtension(generateFullJID(getRegistration().getUsername()), gmne));
}
}
}
}
| false | true | public void logIn(PresenceType presenceType, String verboseStatus) {
final org.jivesoftware.smack.packet.Presence presence = new org.jivesoftware.smack.packet.Presence(org.jivesoftware.smack.packet.Presence.Type.available);
if (JiveGlobals.getBooleanProperty("plugin.gateway."+getTransport().getType()+".avatars", true) && getAvatar() != null) {
Avatar avatar = getAvatar();
// Same thing in this case, so lets go ahead and set them.
avatar.setLegacyIdentifier(avatar.getXmppHash());
VCardUpdateExtension ext = new VCardUpdateExtension();
ext.setPhotoHash(avatar.getLegacyIdentifier());
presence.addExtension(ext);
}
final Presence.Mode pMode = ((XMPPTransport) getTransport())
.convertGatewayStatusToXMPP(presenceType);
if (pMode != null) {
presence.setMode(pMode);
}
if (verboseStatus != null && verboseStatus.trim().length() > 0) {
presence.setStatus(verboseStatus);
}
setPendingPresenceAndStatus(presenceType, verboseStatus);
if (!this.isLoggedIn()) {
listener = new XMPPListener(this);
presenceHandler = new XMPPPresenceHandler(this);
runThread = new Thread() {
@Override
public void run() {
String userName = generateUsername(registration.getUsername());
conn = new XMPPConnection(config);
try {
Roster.setDefaultSubscriptionMode(SubscriptionMode.manual);
conn.connect();
conn.addConnectionListener(listener);
try {
conn.login(userName, registration.getPassword(), xmppResource);
conn.sendPacket(presence); // send initial presence.
conn.getChatManager().addChatListener(listener);
conn.getRoster().addRosterListener(listener);
conn.addPacketListener(presenceHandler, new PacketTypeFilter(org.jivesoftware.smack.packet.Presence.class));
// Use this to filter out anything we don't care about
conn.addPacketListener(listener, new OrFilter(
new PacketTypeFilter(GoogleMailBoxPacket.class),
new PacketExtensionFilter(GoogleNewMailExtension.ELEMENT_NAME, GoogleNewMailExtension.NAMESPACE)
));
if (JiveGlobals.getBooleanProperty("plugin.gateway."+getTransport().getType()+".avatars", true) && getAvatar() != null) {
new Thread() {
@Override
public void run() {
Avatar avatar = getAvatar();
VCard vCard = new VCard();
try {
vCard.load(conn);
vCard.setAvatar(Base64.decode(avatar.getImageData()), avatar.getMimeType());
vCard.save(conn);
}
catch (XMPPException e) {
Log.debug("XMPP: Error while updating vcard for avatar change.", e);
}
catch (NotFoundException e) {
Log.debug("XMPP: Unable to find avatar while setting initial.", e);
}
}
}.start();
}
setLoginStatus(TransportLoginStatus.LOGGED_IN);
syncUsers();
if (getTransport().getType().equals(TransportType.gtalk) && JiveGlobals.getBooleanProperty("plugin.gateway.gtalk.mailnotifications", true)) {
conn.sendPacket(new IQWithPacketExtension(generateFullJID(getRegistration().getUsername()), new GoogleUserSettingExtension(false, true, false), IQ.Type.SET));
conn.sendPacket(new IQWithPacketExtension(generateFullJID(getRegistration().getUsername()), new GoogleMailNotifyExtension()));
mailCheck = new MailCheck();
timer.schedule(mailCheck, timerInterval, timerInterval);
}
}
catch (XMPPException e) {
Log.debug(getTransport().getType()+" user's login/password does not appear to be correct: "+getRegistration().getUsername(), e);
sessionDisconnectedNoReconnect(LocaleUtils.getLocalizedString("gateway.xmpp.passwordincorrect", "kraken"));
setFailureStatus(ConnectionFailureReason.USERNAME_OR_PASSWORD_INCORRECT);
}
}
catch (XMPPException e) {
Log.debug(getTransport().getType()+" user is not able to connect: "+getRegistration().getUsername(), e);
sessionDisconnected(LocaleUtils.getLocalizedString("gateway.xmpp.connectionfailed", "kraken"));
setFailureStatus(ConnectionFailureReason.CAN_NOT_CONNECT);
}
}
};
runThread.start();
}
}
| public void logIn(PresenceType presenceType, String verboseStatus) {
final org.jivesoftware.smack.packet.Presence presence = new org.jivesoftware.smack.packet.Presence(org.jivesoftware.smack.packet.Presence.Type.available);
if (JiveGlobals.getBooleanProperty("plugin.gateway."+getTransport().getType()+".avatars", true) && getAvatar() != null) {
Avatar avatar = getAvatar();
// Same thing in this case, so lets go ahead and set them.
avatar.setLegacyIdentifier(avatar.getXmppHash());
VCardUpdateExtension ext = new VCardUpdateExtension();
ext.setPhotoHash(avatar.getLegacyIdentifier());
presence.addExtension(ext);
}
final Presence.Mode pMode = ((XMPPTransport) getTransport())
.convertGatewayStatusToXMPP(presenceType);
if (pMode != null) {
presence.setMode(pMode);
}
if (verboseStatus != null && verboseStatus.trim().length() > 0) {
presence.setStatus(verboseStatus);
}
setPendingPresenceAndStatus(presenceType, verboseStatus);
if (!this.isLoggedIn()) {
listener = new XMPPListener(this);
presenceHandler = new XMPPPresenceHandler(this);
runThread = new Thread() {
@Override
public void run() {
String userName = generateUsername(registration.getUsername());
conn = new XMPPConnection(config);
try {
Roster.setDefaultSubscriptionMode(SubscriptionMode.manual);
conn.connect();
conn.addConnectionListener(listener);
try {
conn.addPacketListener(presenceHandler, new PacketTypeFilter(org.jivesoftware.smack.packet.Presence.class));
// Use this to filter out anything we don't care about
conn.addPacketListener(listener, new OrFilter(
new PacketTypeFilter(GoogleMailBoxPacket.class),
new PacketExtensionFilter(GoogleNewMailExtension.ELEMENT_NAME, GoogleNewMailExtension.NAMESPACE)
));
conn.login(userName, registration.getPassword(), xmppResource);
conn.sendPacket(presence); // send initial presence.
conn.getChatManager().addChatListener(listener);
conn.getRoster().addRosterListener(listener);
if (JiveGlobals.getBooleanProperty("plugin.gateway."+getTransport().getType()+".avatars", true) && getAvatar() != null) {
new Thread() {
@Override
public void run() {
Avatar avatar = getAvatar();
VCard vCard = new VCard();
try {
vCard.load(conn);
vCard.setAvatar(Base64.decode(avatar.getImageData()), avatar.getMimeType());
vCard.save(conn);
}
catch (XMPPException e) {
Log.debug("XMPP: Error while updating vcard for avatar change.", e);
}
catch (NotFoundException e) {
Log.debug("XMPP: Unable to find avatar while setting initial.", e);
}
}
}.start();
}
setLoginStatus(TransportLoginStatus.LOGGED_IN);
syncUsers();
if (getTransport().getType().equals(TransportType.gtalk) && JiveGlobals.getBooleanProperty("plugin.gateway.gtalk.mailnotifications", true)) {
conn.sendPacket(new IQWithPacketExtension(generateFullJID(getRegistration().getUsername()), new GoogleUserSettingExtension(false, true, false), IQ.Type.SET));
conn.sendPacket(new IQWithPacketExtension(generateFullJID(getRegistration().getUsername()), new GoogleMailNotifyExtension()));
mailCheck = new MailCheck();
timer.schedule(mailCheck, timerInterval, timerInterval);
}
}
catch (XMPPException e) {
Log.debug(getTransport().getType()+" user's login/password does not appear to be correct: "+getRegistration().getUsername(), e);
sessionDisconnectedNoReconnect(LocaleUtils.getLocalizedString("gateway.xmpp.passwordincorrect", "kraken"));
setFailureStatus(ConnectionFailureReason.USERNAME_OR_PASSWORD_INCORRECT);
}
}
catch (XMPPException e) {
Log.debug(getTransport().getType()+" user is not able to connect: "+getRegistration().getUsername(), e);
sessionDisconnected(LocaleUtils.getLocalizedString("gateway.xmpp.connectionfailed", "kraken"));
setFailureStatus(ConnectionFailureReason.CAN_NOT_CONNECT);
}
}
};
runThread.start();
}
}
|
diff --git a/src/test/java/mork/gui/GuiTest.java b/src/test/java/mork/gui/GuiTest.java
index d1f0aeb..9349411 100644
--- a/src/test/java/mork/gui/GuiTest.java
+++ b/src/test/java/mork/gui/GuiTest.java
@@ -1,16 +1,22 @@
package mork.gui;
import junit.framework.TestCase;
public class GuiTest extends TestCase {
public void testFindThunderbirdProfile() throws Exception {
ProfileLocator locator = new ProfileLocator();
String result = locator.locateFirstThunderbirdAddressbookPath();
assertNotNull(result);
- //TODO this test does not pass on linux; result is similar to /home/user/.mozilla-thunderbird/abc1234.default
- assertTrue(result.contains("Thunderbird"));
- assertTrue(result.contains("Profiles"));
+ // TODO this test does not pass on linux; result is similar to
+ // /home/user/.mozilla-thunderbird/abc1234.default
+ if (result.contains("Thunderbird") && result.contains("Profiles")) {
+ return;
+ }
+ if (result.contains(".mozilla-thunderbird")) {
+ return;
+ }
+ fail("Unknown Thunderbird location: " + result);
}
}
| true | true | public void testFindThunderbirdProfile() throws Exception {
ProfileLocator locator = new ProfileLocator();
String result = locator.locateFirstThunderbirdAddressbookPath();
assertNotNull(result);
//TODO this test does not pass on linux; result is similar to /home/user/.mozilla-thunderbird/abc1234.default
assertTrue(result.contains("Thunderbird"));
assertTrue(result.contains("Profiles"));
}
| public void testFindThunderbirdProfile() throws Exception {
ProfileLocator locator = new ProfileLocator();
String result = locator.locateFirstThunderbirdAddressbookPath();
assertNotNull(result);
// TODO this test does not pass on linux; result is similar to
// /home/user/.mozilla-thunderbird/abc1234.default
if (result.contains("Thunderbird") && result.contains("Profiles")) {
return;
}
if (result.contains(".mozilla-thunderbird")) {
return;
}
fail("Unknown Thunderbird location: " + result);
}
|
diff --git a/src/org/eclipse/core/internal/localstore/SafeChunkyInputStream.java b/src/org/eclipse/core/internal/localstore/SafeChunkyInputStream.java
index f0e5c811..d96c7143 100644
--- a/src/org/eclipse/core/internal/localstore/SafeChunkyInputStream.java
+++ b/src/org/eclipse/core/internal/localstore/SafeChunkyInputStream.java
@@ -1,179 +1,181 @@
/*******************************************************************************
* Copyright (c) 2000, 2004 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.core.internal.localstore;
import java.io.*;
/**
* @see SafeChunkyOutputStream
*/
public class SafeChunkyInputStream extends InputStream {
protected static final int BUFFER_SIZE = 8192;
protected byte[] buffer;
protected int bufferLength = 0;
protected byte[] chunk;
protected int chunkLength = 0;
protected boolean endOfFile = false;
protected InputStream input;
protected int nextByteInBuffer = 0;
protected int nextByteInChunk = 0;
public SafeChunkyInputStream(File target) throws IOException {
this(target, BUFFER_SIZE);
}
public SafeChunkyInputStream(File target, int bufferSize) throws IOException {
input = new FileInputStream(target);
buffer = new byte[bufferSize];
}
protected void accumulate(byte[] data, int start, int end) {
byte[] result = new byte[chunk.length + end - start];
System.arraycopy(chunk, 0, result, 0, chunk.length);
System.arraycopy(data, start, result, chunk.length, end - start);
chunk = result;
chunkLength = chunkLength + end - start;
}
public int available() throws IOException {
return chunkLength - nextByteInChunk;
}
protected void buildChunk() throws IOException {
- if (nextByteInBuffer + ILocalStoreConstants.CHUNK_DELIMITER_SIZE > bufferLength)
- shiftAndFillBuffer();
- int end = find(ILocalStoreConstants.END_CHUNK, nextByteInBuffer, bufferLength, true);
- if (end != -1) {
- accumulate(buffer, nextByteInBuffer, end);
- nextByteInBuffer = end + ILocalStoreConstants.CHUNK_DELIMITER_SIZE;
- return;
- }
- accumulate(buffer, nextByteInBuffer, bufferLength);
- bufferLength = input.read(buffer);
- nextByteInBuffer = 0;
- if (bufferLength == -1) {
- endOfFile = true;
- return;
+ //read buffer loads of data until an entire chunk is accumulated
+ while (true) {
+ if (nextByteInBuffer + ILocalStoreConstants.CHUNK_DELIMITER_SIZE > bufferLength)
+ shiftAndFillBuffer();
+ int end = find(ILocalStoreConstants.END_CHUNK, nextByteInBuffer, bufferLength, true);
+ if (end != -1) {
+ accumulate(buffer, nextByteInBuffer, end);
+ nextByteInBuffer = end + ILocalStoreConstants.CHUNK_DELIMITER_SIZE;
+ return;
+ }
+ accumulate(buffer, nextByteInBuffer, bufferLength);
+ bufferLength = input.read(buffer);
+ nextByteInBuffer = 0;
+ if (bufferLength == -1) {
+ endOfFile = true;
+ return;
+ }
}
- buildChunk();
}
public void close() throws IOException {
input.close();
}
protected boolean compare(byte[] source, byte[] target, int startIndex) {
for (int i = 0; i < target.length; i++) {
if (source[startIndex] != target[i])
return false;
startIndex++;
}
return true;
}
protected int find(byte[] pattern, int startIndex, int endIndex, boolean accumulate) throws IOException {
int pos = findByte(pattern[0], startIndex, endIndex);
if (pos == -1)
return -1;
if (pos + ILocalStoreConstants.CHUNK_DELIMITER_SIZE > bufferLength) {
if (accumulate)
accumulate(buffer, nextByteInBuffer, pos);
nextByteInBuffer = pos;
pos = 0;
shiftAndFillBuffer();
}
if (compare(buffer, pattern, pos))
return pos;
return find(pattern, pos + 1, endIndex, accumulate);
}
protected int findByte(byte target, int startIndex, int endIndex) {
while (startIndex < endIndex) {
if (buffer[startIndex] == target)
return startIndex;
startIndex++;
}
return -1;
}
protected void findChunkStart() throws IOException {
if (nextByteInBuffer + ILocalStoreConstants.CHUNK_DELIMITER_SIZE > bufferLength)
shiftAndFillBuffer();
int begin = find(ILocalStoreConstants.BEGIN_CHUNK, nextByteInBuffer, bufferLength, false);
if (begin != -1) {
nextByteInBuffer = begin + ILocalStoreConstants.CHUNK_DELIMITER_SIZE;
return;
}
bufferLength = input.read(buffer);
nextByteInBuffer = 0;
if (bufferLength == -1) {
resetChunk();
endOfFile = true;
return;
}
findChunkStart();
}
public int read() throws IOException {
if (endOfFile)
return -1;
// if there are bytes left in the chunk, return the first available
if (nextByteInChunk < chunkLength)
return chunk[nextByteInChunk++] & 0xFF;
// Otherwise the chunk is empty so clear the current one, get the next
// one and recursively call read. Need to recur as the chunk may be
// real but empty.
resetChunk();
findChunkStart();
if (endOfFile)
return -1;
buildChunk();
refineChunk();
return read();
}
/**
* Skip over any begin chunks in the current chunk. This could be optimized
* to skip at the same time as we are scanning the buffer.
*/
protected void refineChunk() {
int start = chunkLength - ILocalStoreConstants.CHUNK_DELIMITER_SIZE;
if (start < 0)
return;
for (int i = start; i >= 0; i--) {
if (compare(chunk, ILocalStoreConstants.BEGIN_CHUNK, i)) {
nextByteInChunk = i + ILocalStoreConstants.CHUNK_DELIMITER_SIZE;
return;
}
}
}
protected void resetChunk() {
chunk = new byte[0];
chunkLength = 0;
nextByteInChunk = 0;
}
protected void shiftAndFillBuffer() throws IOException {
int length = bufferLength - nextByteInBuffer;
System.arraycopy(buffer, nextByteInBuffer, buffer, 0, length);
nextByteInBuffer = 0;
bufferLength = length;
int read = input.read(buffer, bufferLength, buffer.length - bufferLength);
if (read != -1)
bufferLength += read;
else {
resetChunk();
endOfFile = true;
}
}
}
| false | true | protected void buildChunk() throws IOException {
if (nextByteInBuffer + ILocalStoreConstants.CHUNK_DELIMITER_SIZE > bufferLength)
shiftAndFillBuffer();
int end = find(ILocalStoreConstants.END_CHUNK, nextByteInBuffer, bufferLength, true);
if (end != -1) {
accumulate(buffer, nextByteInBuffer, end);
nextByteInBuffer = end + ILocalStoreConstants.CHUNK_DELIMITER_SIZE;
return;
}
accumulate(buffer, nextByteInBuffer, bufferLength);
bufferLength = input.read(buffer);
nextByteInBuffer = 0;
if (bufferLength == -1) {
endOfFile = true;
return;
}
buildChunk();
}
| protected void buildChunk() throws IOException {
//read buffer loads of data until an entire chunk is accumulated
while (true) {
if (nextByteInBuffer + ILocalStoreConstants.CHUNK_DELIMITER_SIZE > bufferLength)
shiftAndFillBuffer();
int end = find(ILocalStoreConstants.END_CHUNK, nextByteInBuffer, bufferLength, true);
if (end != -1) {
accumulate(buffer, nextByteInBuffer, end);
nextByteInBuffer = end + ILocalStoreConstants.CHUNK_DELIMITER_SIZE;
return;
}
accumulate(buffer, nextByteInBuffer, bufferLength);
bufferLength = input.read(buffer);
nextByteInBuffer = 0;
if (bufferLength == -1) {
endOfFile = true;
return;
}
}
}
|
diff --git a/core/src/main/java/com/zaubersoftware/gnip4j/api/support/http/AbstractRemoteResourceProvider.java b/core/src/main/java/com/zaubersoftware/gnip4j/api/support/http/AbstractRemoteResourceProvider.java
index 4cac93b..ab1a21b 100644
--- a/core/src/main/java/com/zaubersoftware/gnip4j/api/support/http/AbstractRemoteResourceProvider.java
+++ b/core/src/main/java/com/zaubersoftware/gnip4j/api/support/http/AbstractRemoteResourceProvider.java
@@ -1,45 +1,45 @@
/**
* Copyright (c) 2011-2012 Zauber S.A. <http://www.zaubersoftware.com/>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.zaubersoftware.gnip4j.api.support.http;
import java.net.URI;
import com.zaubersoftware.gnip4j.api.RemoteResourceProvider;
import com.zaubersoftware.gnip4j.api.exception.AuthenticationGnipException;
import com.zaubersoftware.gnip4j.api.exception.TransportGnipException;
/**
* Abstract {@link RemoteResourceProvider}.
*
* @author Juan F. Codagnone
* @since May 23, 2011
*/
public abstract class AbstractRemoteResourceProvider implements RemoteResourceProvider {
protected static final String USER_AGENT = "Gnip4j (https://github.com/zaubersoftware/gnip4j/)";
/** validate responses */
public final void validateStatusLine(final URI uri, final int statusCode, final String reason) {
- if (statusCode >= 200 || statusCode <= 299) {
+ if (statusCode >= 200 && statusCode <= 299) {
// nothing to do
} else if (statusCode == 401) {
throw new AuthenticationGnipException(reason);
} else {
throw new TransportGnipException(
String.format("Connection to %s: Unexpected status code: %s %s",
uri, statusCode, reason));
}
}
}
| true | true | public final void validateStatusLine(final URI uri, final int statusCode, final String reason) {
if (statusCode >= 200 || statusCode <= 299) {
// nothing to do
} else if (statusCode == 401) {
throw new AuthenticationGnipException(reason);
} else {
throw new TransportGnipException(
String.format("Connection to %s: Unexpected status code: %s %s",
uri, statusCode, reason));
}
}
| public final void validateStatusLine(final URI uri, final int statusCode, final String reason) {
if (statusCode >= 200 && statusCode <= 299) {
// nothing to do
} else if (statusCode == 401) {
throw new AuthenticationGnipException(reason);
} else {
throw new TransportGnipException(
String.format("Connection to %s: Unexpected status code: %s %s",
uri, statusCode, reason));
}
}
|
diff --git a/servlet/src/test/java/io/undertow/servlet/test/streams/ContentLengthCloseFlushServlet.java b/servlet/src/test/java/io/undertow/servlet/test/streams/ContentLengthCloseFlushServlet.java
index ce852feb9..2ed3bc546 100644
--- a/servlet/src/test/java/io/undertow/servlet/test/streams/ContentLengthCloseFlushServlet.java
+++ b/servlet/src/test/java/io/undertow/servlet/test/streams/ContentLengthCloseFlushServlet.java
@@ -1,31 +1,31 @@
package io.undertow.servlet.test.streams;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* @author Stuart Douglas
*/
public class ContentLengthCloseFlushServlet extends HttpServlet {
private boolean completed = false;
@Override
- protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
+ protected synchronized void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
if (completed) {
resp.getWriter().write("OK");
} else {
resp.setContentLength(1);
ServletOutputStream stream = resp.getOutputStream();
stream.write('a'); //the stream should automatically close here, because it is the content length, but flush should still work
stream.flush();
stream.close();
completed = true;
}
}
}
| true | true | protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
if (completed) {
resp.getWriter().write("OK");
} else {
resp.setContentLength(1);
ServletOutputStream stream = resp.getOutputStream();
stream.write('a'); //the stream should automatically close here, because it is the content length, but flush should still work
stream.flush();
stream.close();
completed = true;
}
}
| protected synchronized void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
if (completed) {
resp.getWriter().write("OK");
} else {
resp.setContentLength(1);
ServletOutputStream stream = resp.getOutputStream();
stream.write('a'); //the stream should automatically close here, because it is the content length, but flush should still work
stream.flush();
stream.close();
completed = true;
}
}
|
diff --git a/webmacro/src/org/webmacro/resource/CachingProvider.java b/webmacro/src/org/webmacro/resource/CachingProvider.java
index 5415b37c..1f165251 100755
--- a/webmacro/src/org/webmacro/resource/CachingProvider.java
+++ b/webmacro/src/org/webmacro/resource/CachingProvider.java
@@ -1,125 +1,125 @@
package org.webmacro.resource;
import org.webmacro.*;
import org.webmacro.util.*;
import java.util.Properties;
import org.webmacro.util.ScalableMap;
import java.lang.ref.Reference;
import org.webmacro.util.TimeLoop;
import org.webmacro.Log;
abstract public class CachingProvider implements Provider
{
private ScalableMap _cache;
private Object[] _writeLocks = new Object[101];
private static final TimeLoop _tl;
private Log _log;
private static final long DURATION = 1000;
private static int PERIODS = 600;
static {
_tl = new TimeLoop(DURATION, PERIODS); // 10min max, 1sec intervals
_tl.setDaemon(true);
_tl.start();
}
public CachingProvider() {
for (int i=0; i<_writeLocks.length; i++) {
_writeLocks[i] = new Object();
}
}
/**
* You must implement this, loading an object from permanent
* storage (or constructing it) on demand.
*/
abstract public TimedReference load(String query)
throws NotFoundException;
/**
* If you over-ride this method be sure and call super.init(...)
*/
public void init(Broker b, Properties config) throws InitException
{
_log = b.getLog("resource");
_cache = new ScalableMap(1001);
}
/**
* Clear the cache. If you over-ride this method be sure
* and call super.flush().
*/
public void flush() {
_cache.clear();
}
/**
* Close down the provider. If you over-ride this method be
* sure and call super.destroy().
*/
public void destroy() {
_cache = null;
}
/**
* Get the object associated with the specific query, first
* trying to look it up in a cache. If it's not there, then
* call load(String) to load it into the cache.
*/
public Object get(final String query) throws NotFoundException
{
TimedReference r;
try {
r = (TimedReference) _cache.get(query);
} catch (NullPointerException e) {
throw new NotFoundException(this + " is not initialized", e);
}
Object o = null;
if (r != null) {
o = r.get();
}
if (o == null) {
// DOUBLE CHECKED LOCKING IS DANGEROUS IN JAVA:
// this looks like double-checked locking but it isn't, we
- // synchrnoized on a less expensive lock inside r.get().
+ // synchrnoized on a less expensive lock inside _cache.get()
// the following ilne lets us simultaneously load up to
// writeLocks.length resources.
int lockIndex = Math.abs(query.hashCode()) % _writeLocks.length;
synchronized(_writeLocks[lockIndex])
{
if (r != null){
o = r.get();
}
if (o == null) {
r = load(query);
if (r != null) {
_cache.put(query,r);
}
o = r.get();
try {
_log.debug("cached: " + query + " for " + r.getTimeout());
_tl.scheduleTime(
new Runnable() {
public void run() {
_cache.remove(query);
_log.debug("cache expired: " + query);
}
}, r.getTimeout());
} catch (Exception e) {
_log.error("CachingProvider caught an exception", e);
}
}
}
}
return o;
}
public String toString() {
return "CachingProvider(type = " + getType() + ")";
}
}
| true | true | public Object get(final String query) throws NotFoundException
{
TimedReference r;
try {
r = (TimedReference) _cache.get(query);
} catch (NullPointerException e) {
throw new NotFoundException(this + " is not initialized", e);
}
Object o = null;
if (r != null) {
o = r.get();
}
if (o == null) {
// DOUBLE CHECKED LOCKING IS DANGEROUS IN JAVA:
// this looks like double-checked locking but it isn't, we
// synchrnoized on a less expensive lock inside r.get().
// the following ilne lets us simultaneously load up to
// writeLocks.length resources.
int lockIndex = Math.abs(query.hashCode()) % _writeLocks.length;
synchronized(_writeLocks[lockIndex])
{
if (r != null){
o = r.get();
}
if (o == null) {
r = load(query);
if (r != null) {
_cache.put(query,r);
}
o = r.get();
try {
_log.debug("cached: " + query + " for " + r.getTimeout());
_tl.scheduleTime(
new Runnable() {
public void run() {
_cache.remove(query);
_log.debug("cache expired: " + query);
}
}, r.getTimeout());
} catch (Exception e) {
_log.error("CachingProvider caught an exception", e);
}
}
}
}
return o;
}
| public Object get(final String query) throws NotFoundException
{
TimedReference r;
try {
r = (TimedReference) _cache.get(query);
} catch (NullPointerException e) {
throw new NotFoundException(this + " is not initialized", e);
}
Object o = null;
if (r != null) {
o = r.get();
}
if (o == null) {
// DOUBLE CHECKED LOCKING IS DANGEROUS IN JAVA:
// this looks like double-checked locking but it isn't, we
// synchrnoized on a less expensive lock inside _cache.get()
// the following ilne lets us simultaneously load up to
// writeLocks.length resources.
int lockIndex = Math.abs(query.hashCode()) % _writeLocks.length;
synchronized(_writeLocks[lockIndex])
{
if (r != null){
o = r.get();
}
if (o == null) {
r = load(query);
if (r != null) {
_cache.put(query,r);
}
o = r.get();
try {
_log.debug("cached: " + query + " for " + r.getTimeout());
_tl.scheduleTime(
new Runnable() {
public void run() {
_cache.remove(query);
_log.debug("cache expired: " + query);
}
}, r.getTimeout());
} catch (Exception e) {
_log.error("CachingProvider caught an exception", e);
}
}
}
}
return o;
}
|
diff --git a/tool/src/java/org/sakaiproject/profile2/tool/pages/MyPreferences.java b/tool/src/java/org/sakaiproject/profile2/tool/pages/MyPreferences.java
index ce57c3e0..3e57573d 100644
--- a/tool/src/java/org/sakaiproject/profile2/tool/pages/MyPreferences.java
+++ b/tool/src/java/org/sakaiproject/profile2/tool/pages/MyPreferences.java
@@ -1,361 +1,361 @@
/**
* Copyright (c) 2008-2010 The Sakai Foundation
*
* Licensed under the Educational Community 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.osedu.org/licenses/ECL-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.sakaiproject.profile2.tool.pages;
import org.apache.log4j.Logger;
import org.apache.wicket.AttributeModifier;
import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.AjaxFormChoiceComponentUpdatingBehavior;
import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior;
import org.apache.wicket.ajax.markup.html.form.AjaxCheckBox;
import org.apache.wicket.extensions.ajax.markup.html.AjaxLazyLoadPanel;
import org.apache.wicket.extensions.ajax.markup.html.IndicatingAjaxButton;
import org.apache.wicket.markup.html.WebMarkupContainer;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.CheckBox;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.Radio;
import org.apache.wicket.markup.html.form.RadioGroup;
import org.apache.wicket.markup.html.panel.EmptyPanel;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.model.Model;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.model.ResourceModel;
import org.apache.wicket.model.StringResourceModel;
import org.sakaiproject.profile2.exception.ProfilePreferencesNotDefinedException;
import org.sakaiproject.profile2.model.ProfilePreferences;
import org.sakaiproject.profile2.tool.components.EnablingCheckBox;
import org.sakaiproject.profile2.tool.components.IconWithClueTip;
import org.sakaiproject.profile2.tool.pages.panels.TwitterPrefsPane;
import org.sakaiproject.profile2.util.ProfileConstants;
public class MyPreferences extends BasePage{
private static final Logger log = Logger.getLogger(MyPreferences.class);
private transient ProfilePreferences profilePreferences;
private CheckBox officialImage;
private CheckBox gravatarImage;
public MyPreferences() {
log.debug("MyPreferences()");
disableLink(preferencesLink);
//get current user
final String userUuid = sakaiProxy.getCurrentUserId();
//get the prefs record for this user from the database, or a default if none exists yet
profilePreferences = preferencesLogic.getPreferencesRecordForUser(userUuid, false);
//if null, throw exception
if(profilePreferences == null) {
- throw new ProfilePreferencesNotDefinedException("Couldn't create default preferences record for " + userUuid);
+ throw new ProfilePreferencesNotDefinedException("Couldn't retrieve preferences record for " + userUuid);
}
//get email address for this user
String emailAddress = sakaiProxy.getUserEmail(userUuid);
//if no email, set a message into it fo display
if(emailAddress == null || emailAddress.length() == 0) {
emailAddress = new ResourceModel("preferences.email.none").getObject();
}
Label heading = new Label("heading", new ResourceModel("heading.preferences"));
add(heading);
//feedback for form submit action
final Label formFeedback = new Label("formFeedback");
formFeedback.setOutputMarkupPlaceholderTag(true);
final String formFeedbackId = formFeedback.getMarkupId();
add(formFeedback);
//create model
CompoundPropertyModel<ProfilePreferences> preferencesModel = new CompoundPropertyModel<ProfilePreferences>(profilePreferences);
//setup form
Form<ProfilePreferences> form = new Form<ProfilePreferences>("form", preferencesModel);
form.setOutputMarkupId(true);
//EMAIL SECTION
//email settings
form.add(new Label("emailSectionHeading", new ResourceModel("heading.section.email")));
form.add(new Label("emailSectionText", new StringResourceModel("preferences.email.message", null, new Object[] { emailAddress })).setEscapeModelStrings(false));
//on/off labels
form.add(new Label("prefOn", new ResourceModel("preference.option.on")));
form.add(new Label("prefOff", new ResourceModel("preference.option.off")));
//request emails
final RadioGroup<Boolean> emailRequests = new RadioGroup<Boolean>("requestEmailEnabled", new PropertyModel<Boolean>(preferencesModel, "requestEmailEnabled"));
emailRequests.add(new Radio<Boolean>("requestsOn", new Model<Boolean>(Boolean.valueOf(true))));
emailRequests.add(new Radio<Boolean>("requestsOff", new Model<Boolean>(Boolean.valueOf(false))));
emailRequests.add(new Label("requestsLabel", new ResourceModel("preferences.email.requests")));
form.add(emailRequests);
//updater
emailRequests.add(new AjaxFormChoiceComponentUpdatingBehavior() {
private static final long serialVersionUID = 1L;
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
//confirm emails
final RadioGroup<Boolean> emailConfirms = new RadioGroup<Boolean>("confirmEmailEnabled", new PropertyModel<Boolean>(preferencesModel, "confirmEmailEnabled"));
emailConfirms.add(new Radio<Boolean>("confirmsOn", new Model<Boolean>(Boolean.valueOf(true))));
emailConfirms.add(new Radio<Boolean>("confirmsOff", new Model<Boolean>(Boolean.valueOf(false))));
emailConfirms.add(new Label("confirmsLabel", new ResourceModel("preferences.email.confirms")));
form.add(emailConfirms);
//updater
emailConfirms.add(new AjaxFormChoiceComponentUpdatingBehavior() {
private static final long serialVersionUID = 1L;
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
//new message emails
final RadioGroup<Boolean> emailNewMessage = new RadioGroup<Boolean>("messageNewEmailEnabled", new PropertyModel<Boolean>(preferencesModel, "messageNewEmailEnabled"));
emailNewMessage.add(new Radio<Boolean>("messageNewOn", new Model<Boolean>(Boolean.valueOf(true))));
emailNewMessage.add(new Radio<Boolean>("messageNewOff", new Model<Boolean>(Boolean.valueOf(false))));
emailNewMessage.add(new Label("messageNewLabel", new ResourceModel("preferences.email.message.new")));
form.add(emailNewMessage);
//updater
emailNewMessage.add(new AjaxFormChoiceComponentUpdatingBehavior() {
private static final long serialVersionUID = 1L;
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
//message reply emails
final RadioGroup<Boolean> emailReplyMessage = new RadioGroup<Boolean>("messageReplyEmailEnabled", new PropertyModel<Boolean>(preferencesModel, "messageReplyEmailEnabled"));
emailReplyMessage.add(new Radio<Boolean>("messageReplyOn", new Model<Boolean>(Boolean.valueOf(true))));
emailReplyMessage.add(new Radio<Boolean>("messageReplyOff", new Model<Boolean>(Boolean.valueOf(false))));
emailReplyMessage.add(new Label("messageReplyLabel", new ResourceModel("preferences.email.message.reply")));
form.add(emailReplyMessage);
//updater
emailReplyMessage.add(new AjaxFormChoiceComponentUpdatingBehavior() {
private static final long serialVersionUID = 1L;
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
// TWITTER SECTION
//headings
WebMarkupContainer twitterSectionHeadingContainer = new WebMarkupContainer("twitterSectionHeadingContainer");
twitterSectionHeadingContainer.add(new Label("twitterSectionHeading", new ResourceModel("heading.section.twitter")));
twitterSectionHeadingContainer.add(new Label("twitterSectionText", new ResourceModel("preferences.twitter.message")));
form.add(twitterSectionHeadingContainer);
//panel
if(sakaiProxy.isTwitterIntegrationEnabledGlobally()) {
form.add(new AjaxLazyLoadPanel("twitterPanel"){
private static final long serialVersionUID = 1L;
@Override
public Component getLazyLoadComponent(String markupId) {
return new TwitterPrefsPane(markupId, userUuid);
}
});
} else {
form.add(new EmptyPanel("twitterPanel"));
twitterSectionHeadingContainer.setVisible(false);
}
// IMAGE SECTION
//only one of these can be selected at a time
WebMarkupContainer is = new WebMarkupContainer("imageSettingsContainer");
is.setOutputMarkupId(true);
// headings
is.add(new Label("imageSettingsHeading", new ResourceModel("heading.section.image")));
is.add(new Label("imageSettingsText", new ResourceModel("preferences.image.message")));
//official image
//checkbox
WebMarkupContainer officialImageContainer = new WebMarkupContainer("officialImageContainer");
officialImageContainer.add(new Label("officialImageLabel", new ResourceModel("preferences.image.official")));
officialImage = new CheckBox("officialImage", new PropertyModel<Boolean>(preferencesModel, "useOfficialImage"));
officialImage.setOutputMarkupId(true);
officialImageContainer.add(officialImage);
//updater
officialImage.add(new AjaxFormComponentUpdatingBehavior("onchange") {
private static final long serialVersionUID = 1L;
protected void onUpdate(AjaxRequestTarget target) {
//set gravatar to false
gravatarImage.setModelObject(false);
target.addComponent(gravatarImage);
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
is.add(officialImageContainer);
//if using official images but alternate choice isn't allowed, hide this section
boolean officialImageEnabled = sakaiProxy.isUsingOfficialImageButAlternateSelectionEnabled();
if(!officialImageEnabled) {
profilePreferences.setUseOfficialImage(false); //set the model false to clear data as well (doesnt really need to do this but we do it to keep things in sync)
officialImageContainer.setVisible(false);
}
//gravatar
//checkbox
WebMarkupContainer gravatarContainer = new WebMarkupContainer("gravatarContainer");
gravatarContainer.add(new Label("gravatarLabel", new ResourceModel("preferences.image.gravatar")));
gravatarImage = new CheckBox("gravatarImage", new PropertyModel<Boolean>(preferencesModel, "useGravatar"));
gravatarContainer.add(gravatarImage);
//updater
gravatarImage.add(new AjaxFormComponentUpdatingBehavior("onchange") {
private static final long serialVersionUID = 1L;
protected void onUpdate(AjaxRequestTarget target) {
//set official to false
officialImage.setModelObject(false);
target.addComponent(officialImage);
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
is.add(gravatarContainer);
//if gravatar's are disabled, hide this section
boolean gravatarEnabled = sakaiProxy.isGravatarImageEnabledGlobally();
if(!gravatarEnabled) {
profilePreferences.setUseGravatar(false); //set the model false to clear data as well (doesnt really need to do this but we do it to keep things in sync)
gravatarContainer.setVisible(false);
}
//if official image disabled and gravatar disabled, hide the entire container
if(!officialImageEnabled && !gravatarEnabled) {
is.setVisible(false);
}
form.add(is);
// WIDGET SECTION
WebMarkupContainer ws = new WebMarkupContainer("widgetSettingsContainer");
ws.setOutputMarkupId(true);
//widget settings
ws.add(new Label("widgetSettingsHeading", new ResourceModel("heading.section.widget")));
ws.add(new Label("widgetSettingsText", new ResourceModel("preferences.widget.message")));
//kudos
WebMarkupContainer kudosContainer = new WebMarkupContainer("kudosContainer");
kudosContainer.add(new Label("kudosLabel", new ResourceModel("preferences.widget.kudos")));
CheckBox kudosSetting = new CheckBox("kudosSetting", new PropertyModel<Boolean>(preferencesModel, "showKudos"));
kudosContainer.add(kudosSetting);
//tooltip
kudosContainer.add(new IconWithClueTip("kudosToolTip", ProfileConstants.INFO_IMAGE, new ResourceModel("preferences.widget.kudos.tooltip")));
//updater
kudosSetting.add(new AjaxFormComponentUpdatingBehavior("onchange") {
private static final long serialVersionUID = 1L;
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
ws.add(kudosContainer);
//gallery feed
WebMarkupContainer galleryFeedContainer = new WebMarkupContainer("galleryFeedContainer");
galleryFeedContainer.add(new Label("galleryFeedLabel", new ResourceModel("preferences.widget.gallery")));
CheckBox galleryFeedSetting = new CheckBox("galleryFeedSetting", new PropertyModel<Boolean>(preferencesModel, "showGalleryFeed"));
galleryFeedContainer.add(galleryFeedSetting);
//tooltip
galleryFeedContainer.add(new IconWithClueTip("galleryFeedToolTip", ProfileConstants.INFO_IMAGE, new ResourceModel("preferences.widget.gallery.tooltip")));
//updater
galleryFeedSetting.add(new AjaxFormComponentUpdatingBehavior("onchange") {
private static final long serialVersionUID = 1L;
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
ws.add(galleryFeedContainer);
galleryFeedContainer.setVisible(sakaiProxy.isProfileGalleryEnabledGlobally());
form.add(ws);
//submit button
IndicatingAjaxButton submitButton = new IndicatingAjaxButton("submit", form) {
private static final long serialVersionUID = 1L;
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
//get the backing model
ProfilePreferences profilePreferences = (ProfilePreferences) form.getModelObject();
formFeedback.setDefaultModel(new ResourceModel("success.preferences.save.ok"));
formFeedback.add(new AttributeModifier("class", true, new Model<String>("success")));
//save
if(preferencesLogic.savePreferencesRecord(profilePreferences)) {
formFeedback.setDefaultModel(new ResourceModel("success.preferences.save.ok"));
formFeedback.add(new AttributeModifier("class", true, new Model<String>("success")));
//post update event
sakaiProxy.postEvent(ProfileConstants.EVENT_PREFERENCES_UPDATE, "/profile/"+userUuid, true);
} else {
formFeedback.setDefaultModel(new ResourceModel("error.preferences.save.failed"));
formFeedback.add(new AttributeModifier("class", true, new Model<String>("alertMessage")));
}
//resize iframe
target.appendJavascript("setMainFrameHeight(window.name);");
target.addComponent(formFeedback);
}
};
submitButton.setModel(new ResourceModel("button.save.settings"));
submitButton.setDefaultFormProcessing(false);
form.add(submitButton);
add(form);
}
}
| true | true | public MyPreferences() {
log.debug("MyPreferences()");
disableLink(preferencesLink);
//get current user
final String userUuid = sakaiProxy.getCurrentUserId();
//get the prefs record for this user from the database, or a default if none exists yet
profilePreferences = preferencesLogic.getPreferencesRecordForUser(userUuid, false);
//if null, throw exception
if(profilePreferences == null) {
throw new ProfilePreferencesNotDefinedException("Couldn't create default preferences record for " + userUuid);
}
//get email address for this user
String emailAddress = sakaiProxy.getUserEmail(userUuid);
//if no email, set a message into it fo display
if(emailAddress == null || emailAddress.length() == 0) {
emailAddress = new ResourceModel("preferences.email.none").getObject();
}
Label heading = new Label("heading", new ResourceModel("heading.preferences"));
add(heading);
//feedback for form submit action
final Label formFeedback = new Label("formFeedback");
formFeedback.setOutputMarkupPlaceholderTag(true);
final String formFeedbackId = formFeedback.getMarkupId();
add(formFeedback);
//create model
CompoundPropertyModel<ProfilePreferences> preferencesModel = new CompoundPropertyModel<ProfilePreferences>(profilePreferences);
//setup form
Form<ProfilePreferences> form = new Form<ProfilePreferences>("form", preferencesModel);
form.setOutputMarkupId(true);
//EMAIL SECTION
//email settings
form.add(new Label("emailSectionHeading", new ResourceModel("heading.section.email")));
form.add(new Label("emailSectionText", new StringResourceModel("preferences.email.message", null, new Object[] { emailAddress })).setEscapeModelStrings(false));
//on/off labels
form.add(new Label("prefOn", new ResourceModel("preference.option.on")));
form.add(new Label("prefOff", new ResourceModel("preference.option.off")));
//request emails
final RadioGroup<Boolean> emailRequests = new RadioGroup<Boolean>("requestEmailEnabled", new PropertyModel<Boolean>(preferencesModel, "requestEmailEnabled"));
emailRequests.add(new Radio<Boolean>("requestsOn", new Model<Boolean>(Boolean.valueOf(true))));
emailRequests.add(new Radio<Boolean>("requestsOff", new Model<Boolean>(Boolean.valueOf(false))));
emailRequests.add(new Label("requestsLabel", new ResourceModel("preferences.email.requests")));
form.add(emailRequests);
//updater
emailRequests.add(new AjaxFormChoiceComponentUpdatingBehavior() {
private static final long serialVersionUID = 1L;
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
//confirm emails
final RadioGroup<Boolean> emailConfirms = new RadioGroup<Boolean>("confirmEmailEnabled", new PropertyModel<Boolean>(preferencesModel, "confirmEmailEnabled"));
emailConfirms.add(new Radio<Boolean>("confirmsOn", new Model<Boolean>(Boolean.valueOf(true))));
emailConfirms.add(new Radio<Boolean>("confirmsOff", new Model<Boolean>(Boolean.valueOf(false))));
emailConfirms.add(new Label("confirmsLabel", new ResourceModel("preferences.email.confirms")));
form.add(emailConfirms);
//updater
emailConfirms.add(new AjaxFormChoiceComponentUpdatingBehavior() {
private static final long serialVersionUID = 1L;
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
//new message emails
final RadioGroup<Boolean> emailNewMessage = new RadioGroup<Boolean>("messageNewEmailEnabled", new PropertyModel<Boolean>(preferencesModel, "messageNewEmailEnabled"));
emailNewMessage.add(new Radio<Boolean>("messageNewOn", new Model<Boolean>(Boolean.valueOf(true))));
emailNewMessage.add(new Radio<Boolean>("messageNewOff", new Model<Boolean>(Boolean.valueOf(false))));
emailNewMessage.add(new Label("messageNewLabel", new ResourceModel("preferences.email.message.new")));
form.add(emailNewMessage);
//updater
emailNewMessage.add(new AjaxFormChoiceComponentUpdatingBehavior() {
private static final long serialVersionUID = 1L;
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
//message reply emails
final RadioGroup<Boolean> emailReplyMessage = new RadioGroup<Boolean>("messageReplyEmailEnabled", new PropertyModel<Boolean>(preferencesModel, "messageReplyEmailEnabled"));
emailReplyMessage.add(new Radio<Boolean>("messageReplyOn", new Model<Boolean>(Boolean.valueOf(true))));
emailReplyMessage.add(new Radio<Boolean>("messageReplyOff", new Model<Boolean>(Boolean.valueOf(false))));
emailReplyMessage.add(new Label("messageReplyLabel", new ResourceModel("preferences.email.message.reply")));
form.add(emailReplyMessage);
//updater
emailReplyMessage.add(new AjaxFormChoiceComponentUpdatingBehavior() {
private static final long serialVersionUID = 1L;
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
// TWITTER SECTION
//headings
WebMarkupContainer twitterSectionHeadingContainer = new WebMarkupContainer("twitterSectionHeadingContainer");
twitterSectionHeadingContainer.add(new Label("twitterSectionHeading", new ResourceModel("heading.section.twitter")));
twitterSectionHeadingContainer.add(new Label("twitterSectionText", new ResourceModel("preferences.twitter.message")));
form.add(twitterSectionHeadingContainer);
//panel
if(sakaiProxy.isTwitterIntegrationEnabledGlobally()) {
form.add(new AjaxLazyLoadPanel("twitterPanel"){
private static final long serialVersionUID = 1L;
@Override
public Component getLazyLoadComponent(String markupId) {
return new TwitterPrefsPane(markupId, userUuid);
}
});
} else {
form.add(new EmptyPanel("twitterPanel"));
twitterSectionHeadingContainer.setVisible(false);
}
// IMAGE SECTION
//only one of these can be selected at a time
WebMarkupContainer is = new WebMarkupContainer("imageSettingsContainer");
is.setOutputMarkupId(true);
// headings
is.add(new Label("imageSettingsHeading", new ResourceModel("heading.section.image")));
is.add(new Label("imageSettingsText", new ResourceModel("preferences.image.message")));
//official image
//checkbox
WebMarkupContainer officialImageContainer = new WebMarkupContainer("officialImageContainer");
officialImageContainer.add(new Label("officialImageLabel", new ResourceModel("preferences.image.official")));
officialImage = new CheckBox("officialImage", new PropertyModel<Boolean>(preferencesModel, "useOfficialImage"));
officialImage.setOutputMarkupId(true);
officialImageContainer.add(officialImage);
//updater
officialImage.add(new AjaxFormComponentUpdatingBehavior("onchange") {
private static final long serialVersionUID = 1L;
protected void onUpdate(AjaxRequestTarget target) {
//set gravatar to false
gravatarImage.setModelObject(false);
target.addComponent(gravatarImage);
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
is.add(officialImageContainer);
//if using official images but alternate choice isn't allowed, hide this section
boolean officialImageEnabled = sakaiProxy.isUsingOfficialImageButAlternateSelectionEnabled();
if(!officialImageEnabled) {
profilePreferences.setUseOfficialImage(false); //set the model false to clear data as well (doesnt really need to do this but we do it to keep things in sync)
officialImageContainer.setVisible(false);
}
//gravatar
//checkbox
WebMarkupContainer gravatarContainer = new WebMarkupContainer("gravatarContainer");
gravatarContainer.add(new Label("gravatarLabel", new ResourceModel("preferences.image.gravatar")));
gravatarImage = new CheckBox("gravatarImage", new PropertyModel<Boolean>(preferencesModel, "useGravatar"));
gravatarContainer.add(gravatarImage);
//updater
gravatarImage.add(new AjaxFormComponentUpdatingBehavior("onchange") {
private static final long serialVersionUID = 1L;
protected void onUpdate(AjaxRequestTarget target) {
//set official to false
officialImage.setModelObject(false);
target.addComponent(officialImage);
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
is.add(gravatarContainer);
//if gravatar's are disabled, hide this section
boolean gravatarEnabled = sakaiProxy.isGravatarImageEnabledGlobally();
if(!gravatarEnabled) {
profilePreferences.setUseGravatar(false); //set the model false to clear data as well (doesnt really need to do this but we do it to keep things in sync)
gravatarContainer.setVisible(false);
}
//if official image disabled and gravatar disabled, hide the entire container
if(!officialImageEnabled && !gravatarEnabled) {
is.setVisible(false);
}
form.add(is);
// WIDGET SECTION
WebMarkupContainer ws = new WebMarkupContainer("widgetSettingsContainer");
ws.setOutputMarkupId(true);
//widget settings
ws.add(new Label("widgetSettingsHeading", new ResourceModel("heading.section.widget")));
ws.add(new Label("widgetSettingsText", new ResourceModel("preferences.widget.message")));
//kudos
WebMarkupContainer kudosContainer = new WebMarkupContainer("kudosContainer");
kudosContainer.add(new Label("kudosLabel", new ResourceModel("preferences.widget.kudos")));
CheckBox kudosSetting = new CheckBox("kudosSetting", new PropertyModel<Boolean>(preferencesModel, "showKudos"));
kudosContainer.add(kudosSetting);
//tooltip
kudosContainer.add(new IconWithClueTip("kudosToolTip", ProfileConstants.INFO_IMAGE, new ResourceModel("preferences.widget.kudos.tooltip")));
//updater
kudosSetting.add(new AjaxFormComponentUpdatingBehavior("onchange") {
private static final long serialVersionUID = 1L;
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
ws.add(kudosContainer);
//gallery feed
WebMarkupContainer galleryFeedContainer = new WebMarkupContainer("galleryFeedContainer");
galleryFeedContainer.add(new Label("galleryFeedLabel", new ResourceModel("preferences.widget.gallery")));
CheckBox galleryFeedSetting = new CheckBox("galleryFeedSetting", new PropertyModel<Boolean>(preferencesModel, "showGalleryFeed"));
galleryFeedContainer.add(galleryFeedSetting);
//tooltip
galleryFeedContainer.add(new IconWithClueTip("galleryFeedToolTip", ProfileConstants.INFO_IMAGE, new ResourceModel("preferences.widget.gallery.tooltip")));
//updater
galleryFeedSetting.add(new AjaxFormComponentUpdatingBehavior("onchange") {
private static final long serialVersionUID = 1L;
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
ws.add(galleryFeedContainer);
galleryFeedContainer.setVisible(sakaiProxy.isProfileGalleryEnabledGlobally());
form.add(ws);
//submit button
IndicatingAjaxButton submitButton = new IndicatingAjaxButton("submit", form) {
private static final long serialVersionUID = 1L;
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
//get the backing model
ProfilePreferences profilePreferences = (ProfilePreferences) form.getModelObject();
formFeedback.setDefaultModel(new ResourceModel("success.preferences.save.ok"));
formFeedback.add(new AttributeModifier("class", true, new Model<String>("success")));
//save
if(preferencesLogic.savePreferencesRecord(profilePreferences)) {
formFeedback.setDefaultModel(new ResourceModel("success.preferences.save.ok"));
formFeedback.add(new AttributeModifier("class", true, new Model<String>("success")));
//post update event
sakaiProxy.postEvent(ProfileConstants.EVENT_PREFERENCES_UPDATE, "/profile/"+userUuid, true);
} else {
formFeedback.setDefaultModel(new ResourceModel("error.preferences.save.failed"));
formFeedback.add(new AttributeModifier("class", true, new Model<String>("alertMessage")));
}
//resize iframe
target.appendJavascript("setMainFrameHeight(window.name);");
target.addComponent(formFeedback);
}
};
submitButton.setModel(new ResourceModel("button.save.settings"));
submitButton.setDefaultFormProcessing(false);
form.add(submitButton);
add(form);
}
| public MyPreferences() {
log.debug("MyPreferences()");
disableLink(preferencesLink);
//get current user
final String userUuid = sakaiProxy.getCurrentUserId();
//get the prefs record for this user from the database, or a default if none exists yet
profilePreferences = preferencesLogic.getPreferencesRecordForUser(userUuid, false);
//if null, throw exception
if(profilePreferences == null) {
throw new ProfilePreferencesNotDefinedException("Couldn't retrieve preferences record for " + userUuid);
}
//get email address for this user
String emailAddress = sakaiProxy.getUserEmail(userUuid);
//if no email, set a message into it fo display
if(emailAddress == null || emailAddress.length() == 0) {
emailAddress = new ResourceModel("preferences.email.none").getObject();
}
Label heading = new Label("heading", new ResourceModel("heading.preferences"));
add(heading);
//feedback for form submit action
final Label formFeedback = new Label("formFeedback");
formFeedback.setOutputMarkupPlaceholderTag(true);
final String formFeedbackId = formFeedback.getMarkupId();
add(formFeedback);
//create model
CompoundPropertyModel<ProfilePreferences> preferencesModel = new CompoundPropertyModel<ProfilePreferences>(profilePreferences);
//setup form
Form<ProfilePreferences> form = new Form<ProfilePreferences>("form", preferencesModel);
form.setOutputMarkupId(true);
//EMAIL SECTION
//email settings
form.add(new Label("emailSectionHeading", new ResourceModel("heading.section.email")));
form.add(new Label("emailSectionText", new StringResourceModel("preferences.email.message", null, new Object[] { emailAddress })).setEscapeModelStrings(false));
//on/off labels
form.add(new Label("prefOn", new ResourceModel("preference.option.on")));
form.add(new Label("prefOff", new ResourceModel("preference.option.off")));
//request emails
final RadioGroup<Boolean> emailRequests = new RadioGroup<Boolean>("requestEmailEnabled", new PropertyModel<Boolean>(preferencesModel, "requestEmailEnabled"));
emailRequests.add(new Radio<Boolean>("requestsOn", new Model<Boolean>(Boolean.valueOf(true))));
emailRequests.add(new Radio<Boolean>("requestsOff", new Model<Boolean>(Boolean.valueOf(false))));
emailRequests.add(new Label("requestsLabel", new ResourceModel("preferences.email.requests")));
form.add(emailRequests);
//updater
emailRequests.add(new AjaxFormChoiceComponentUpdatingBehavior() {
private static final long serialVersionUID = 1L;
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
//confirm emails
final RadioGroup<Boolean> emailConfirms = new RadioGroup<Boolean>("confirmEmailEnabled", new PropertyModel<Boolean>(preferencesModel, "confirmEmailEnabled"));
emailConfirms.add(new Radio<Boolean>("confirmsOn", new Model<Boolean>(Boolean.valueOf(true))));
emailConfirms.add(new Radio<Boolean>("confirmsOff", new Model<Boolean>(Boolean.valueOf(false))));
emailConfirms.add(new Label("confirmsLabel", new ResourceModel("preferences.email.confirms")));
form.add(emailConfirms);
//updater
emailConfirms.add(new AjaxFormChoiceComponentUpdatingBehavior() {
private static final long serialVersionUID = 1L;
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
//new message emails
final RadioGroup<Boolean> emailNewMessage = new RadioGroup<Boolean>("messageNewEmailEnabled", new PropertyModel<Boolean>(preferencesModel, "messageNewEmailEnabled"));
emailNewMessage.add(new Radio<Boolean>("messageNewOn", new Model<Boolean>(Boolean.valueOf(true))));
emailNewMessage.add(new Radio<Boolean>("messageNewOff", new Model<Boolean>(Boolean.valueOf(false))));
emailNewMessage.add(new Label("messageNewLabel", new ResourceModel("preferences.email.message.new")));
form.add(emailNewMessage);
//updater
emailNewMessage.add(new AjaxFormChoiceComponentUpdatingBehavior() {
private static final long serialVersionUID = 1L;
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
//message reply emails
final RadioGroup<Boolean> emailReplyMessage = new RadioGroup<Boolean>("messageReplyEmailEnabled", new PropertyModel<Boolean>(preferencesModel, "messageReplyEmailEnabled"));
emailReplyMessage.add(new Radio<Boolean>("messageReplyOn", new Model<Boolean>(Boolean.valueOf(true))));
emailReplyMessage.add(new Radio<Boolean>("messageReplyOff", new Model<Boolean>(Boolean.valueOf(false))));
emailReplyMessage.add(new Label("messageReplyLabel", new ResourceModel("preferences.email.message.reply")));
form.add(emailReplyMessage);
//updater
emailReplyMessage.add(new AjaxFormChoiceComponentUpdatingBehavior() {
private static final long serialVersionUID = 1L;
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
// TWITTER SECTION
//headings
WebMarkupContainer twitterSectionHeadingContainer = new WebMarkupContainer("twitterSectionHeadingContainer");
twitterSectionHeadingContainer.add(new Label("twitterSectionHeading", new ResourceModel("heading.section.twitter")));
twitterSectionHeadingContainer.add(new Label("twitterSectionText", new ResourceModel("preferences.twitter.message")));
form.add(twitterSectionHeadingContainer);
//panel
if(sakaiProxy.isTwitterIntegrationEnabledGlobally()) {
form.add(new AjaxLazyLoadPanel("twitterPanel"){
private static final long serialVersionUID = 1L;
@Override
public Component getLazyLoadComponent(String markupId) {
return new TwitterPrefsPane(markupId, userUuid);
}
});
} else {
form.add(new EmptyPanel("twitterPanel"));
twitterSectionHeadingContainer.setVisible(false);
}
// IMAGE SECTION
//only one of these can be selected at a time
WebMarkupContainer is = new WebMarkupContainer("imageSettingsContainer");
is.setOutputMarkupId(true);
// headings
is.add(new Label("imageSettingsHeading", new ResourceModel("heading.section.image")));
is.add(new Label("imageSettingsText", new ResourceModel("preferences.image.message")));
//official image
//checkbox
WebMarkupContainer officialImageContainer = new WebMarkupContainer("officialImageContainer");
officialImageContainer.add(new Label("officialImageLabel", new ResourceModel("preferences.image.official")));
officialImage = new CheckBox("officialImage", new PropertyModel<Boolean>(preferencesModel, "useOfficialImage"));
officialImage.setOutputMarkupId(true);
officialImageContainer.add(officialImage);
//updater
officialImage.add(new AjaxFormComponentUpdatingBehavior("onchange") {
private static final long serialVersionUID = 1L;
protected void onUpdate(AjaxRequestTarget target) {
//set gravatar to false
gravatarImage.setModelObject(false);
target.addComponent(gravatarImage);
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
is.add(officialImageContainer);
//if using official images but alternate choice isn't allowed, hide this section
boolean officialImageEnabled = sakaiProxy.isUsingOfficialImageButAlternateSelectionEnabled();
if(!officialImageEnabled) {
profilePreferences.setUseOfficialImage(false); //set the model false to clear data as well (doesnt really need to do this but we do it to keep things in sync)
officialImageContainer.setVisible(false);
}
//gravatar
//checkbox
WebMarkupContainer gravatarContainer = new WebMarkupContainer("gravatarContainer");
gravatarContainer.add(new Label("gravatarLabel", new ResourceModel("preferences.image.gravatar")));
gravatarImage = new CheckBox("gravatarImage", new PropertyModel<Boolean>(preferencesModel, "useGravatar"));
gravatarContainer.add(gravatarImage);
//updater
gravatarImage.add(new AjaxFormComponentUpdatingBehavior("onchange") {
private static final long serialVersionUID = 1L;
protected void onUpdate(AjaxRequestTarget target) {
//set official to false
officialImage.setModelObject(false);
target.addComponent(officialImage);
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
is.add(gravatarContainer);
//if gravatar's are disabled, hide this section
boolean gravatarEnabled = sakaiProxy.isGravatarImageEnabledGlobally();
if(!gravatarEnabled) {
profilePreferences.setUseGravatar(false); //set the model false to clear data as well (doesnt really need to do this but we do it to keep things in sync)
gravatarContainer.setVisible(false);
}
//if official image disabled and gravatar disabled, hide the entire container
if(!officialImageEnabled && !gravatarEnabled) {
is.setVisible(false);
}
form.add(is);
// WIDGET SECTION
WebMarkupContainer ws = new WebMarkupContainer("widgetSettingsContainer");
ws.setOutputMarkupId(true);
//widget settings
ws.add(new Label("widgetSettingsHeading", new ResourceModel("heading.section.widget")));
ws.add(new Label("widgetSettingsText", new ResourceModel("preferences.widget.message")));
//kudos
WebMarkupContainer kudosContainer = new WebMarkupContainer("kudosContainer");
kudosContainer.add(new Label("kudosLabel", new ResourceModel("preferences.widget.kudos")));
CheckBox kudosSetting = new CheckBox("kudosSetting", new PropertyModel<Boolean>(preferencesModel, "showKudos"));
kudosContainer.add(kudosSetting);
//tooltip
kudosContainer.add(new IconWithClueTip("kudosToolTip", ProfileConstants.INFO_IMAGE, new ResourceModel("preferences.widget.kudos.tooltip")));
//updater
kudosSetting.add(new AjaxFormComponentUpdatingBehavior("onchange") {
private static final long serialVersionUID = 1L;
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
ws.add(kudosContainer);
//gallery feed
WebMarkupContainer galleryFeedContainer = new WebMarkupContainer("galleryFeedContainer");
galleryFeedContainer.add(new Label("galleryFeedLabel", new ResourceModel("preferences.widget.gallery")));
CheckBox galleryFeedSetting = new CheckBox("galleryFeedSetting", new PropertyModel<Boolean>(preferencesModel, "showGalleryFeed"));
galleryFeedContainer.add(galleryFeedSetting);
//tooltip
galleryFeedContainer.add(new IconWithClueTip("galleryFeedToolTip", ProfileConstants.INFO_IMAGE, new ResourceModel("preferences.widget.gallery.tooltip")));
//updater
galleryFeedSetting.add(new AjaxFormComponentUpdatingBehavior("onchange") {
private static final long serialVersionUID = 1L;
protected void onUpdate(AjaxRequestTarget target) {
target.appendJavascript("$('#" + formFeedbackId + "').fadeOut();");
}
});
ws.add(galleryFeedContainer);
galleryFeedContainer.setVisible(sakaiProxy.isProfileGalleryEnabledGlobally());
form.add(ws);
//submit button
IndicatingAjaxButton submitButton = new IndicatingAjaxButton("submit", form) {
private static final long serialVersionUID = 1L;
protected void onSubmit(AjaxRequestTarget target, Form<?> form) {
//get the backing model
ProfilePreferences profilePreferences = (ProfilePreferences) form.getModelObject();
formFeedback.setDefaultModel(new ResourceModel("success.preferences.save.ok"));
formFeedback.add(new AttributeModifier("class", true, new Model<String>("success")));
//save
if(preferencesLogic.savePreferencesRecord(profilePreferences)) {
formFeedback.setDefaultModel(new ResourceModel("success.preferences.save.ok"));
formFeedback.add(new AttributeModifier("class", true, new Model<String>("success")));
//post update event
sakaiProxy.postEvent(ProfileConstants.EVENT_PREFERENCES_UPDATE, "/profile/"+userUuid, true);
} else {
formFeedback.setDefaultModel(new ResourceModel("error.preferences.save.failed"));
formFeedback.add(new AttributeModifier("class", true, new Model<String>("alertMessage")));
}
//resize iframe
target.appendJavascript("setMainFrameHeight(window.name);");
target.addComponent(formFeedback);
}
};
submitButton.setModel(new ResourceModel("button.save.settings"));
submitButton.setDefaultFormProcessing(false);
form.add(submitButton);
add(form);
}
|
diff --git a/cosmo/src/test/unit/java/org/osaf/cosmo/service/impl/StandardFreeBusyQueryProcessorTest.java b/cosmo/src/test/unit/java/org/osaf/cosmo/service/impl/StandardFreeBusyQueryProcessorTest.java
index 856fcf5ae..2f49c409b 100644
--- a/cosmo/src/test/unit/java/org/osaf/cosmo/service/impl/StandardFreeBusyQueryProcessorTest.java
+++ b/cosmo/src/test/unit/java/org/osaf/cosmo/service/impl/StandardFreeBusyQueryProcessorTest.java
@@ -1,182 +1,182 @@
/*
* Copyright 2007 Open Source Applications 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.osaf.cosmo.service.impl;
import java.util.Iterator;
import junit.framework.Assert;
import net.fortuna.ical4j.model.DateTime;
import net.fortuna.ical4j.model.Parameter;
import net.fortuna.ical4j.model.Period;
import net.fortuna.ical4j.model.Property;
import net.fortuna.ical4j.model.PropertyList;
import net.fortuna.ical4j.model.component.VFreeBusy;
import net.fortuna.ical4j.model.parameter.FbType;
import net.fortuna.ical4j.model.property.FreeBusy;
import org.osaf.cosmo.calendar.util.CalendarUtils;
import org.osaf.cosmo.dao.UserDao;
import org.osaf.cosmo.dao.hibernate.AbstractHibernateDaoTestCase;
import org.osaf.cosmo.dao.hibernate.CalendarDaoImpl;
import org.osaf.cosmo.dao.hibernate.ContentDaoImpl;
import org.osaf.cosmo.dao.hibernate.UserDaoImpl;
import org.osaf.cosmo.model.CalendarCollectionStamp;
import org.osaf.cosmo.model.CollectionItem;
import org.osaf.cosmo.model.ContentItem;
import org.osaf.cosmo.model.EventStamp;
import org.osaf.cosmo.model.FreeBusyItem;
import org.osaf.cosmo.model.NoteItem;
import org.osaf.cosmo.model.User;
/**
* Test StandardFreeBusyQueryProcessorTest
*
*/
public class StandardFreeBusyQueryProcessorTest extends AbstractHibernateDaoTestCase {
protected ContentDaoImpl contentDao = null;
protected CalendarDaoImpl calendarDao = null;
protected UserDaoImpl userDao = null;
protected StandardFreeBusyQueryProcessor queryProcessor = null;
protected final String CALENDAR_UID = "calendaruid";
public StandardFreeBusyQueryProcessorTest() {
super();
}
@Override
protected void onSetUpInTransaction() throws Exception {
// TODO Auto-generated method stub
super.onSetUpInTransaction();
queryProcessor = new StandardFreeBusyQueryProcessor();
queryProcessor.setCalendarDao(calendarDao);
CollectionItem calendar = generateCalendar("testcalendar", "testuser");
calendar.setUid(CALENDAR_UID);
CollectionItem root = (CollectionItem) contentDao.getRootItem(getUser(userDao, "testuser"));
contentDao.createCollection(root, calendar);
for (int i = 1; i <= 3; i++) {
ContentItem event = generateEvent("test" + i + ".ics", "eventwithtimezone"
+ i + ".ics", "testuser");
event.setUid(CALENDAR_UID + i);
contentDao.createContent(calendar, event);
}
- FreeBusyItem fb = generateFreeBusy("test4.ics", "Vfreebusy.ics", "testuser");
+ FreeBusyItem fb = generateFreeBusy("test4.ics", "vfreebusy.ics", "testuser");
fb.setUid(CALENDAR_UID + "4");
contentDao.createContent(calendar, fb);
clearSession();
}
public void testFreeBusyQuery() throws Exception {
DateTime start = new DateTime("20070507T051500Z");
DateTime end = new DateTime("200705016T051500Z");
Period period = new Period(start, end);
CollectionItem calendar = contentDao.findCollectionByUid(CALENDAR_UID);
// verify we get resuts from VEVENTS in collection
VFreeBusy vfb = queryProcessor.generateFreeBusy(calendar, period);
verifyPeriods(vfb, null, "20070508T081500Z/20070508T091500Z,20070509T081500Z/20070509T091500Z,20070510T081500Z/20070510T091500Z,20070511T081500Z/20070511T091500Z,20070512T081500Z/20070512T091500Z,20070513T081500Z/20070513T091500Z,20070514T081500Z/20070514T091500Z,20070515T081500Z/20070515T091500Z");
verifyPeriods(vfb, FbType.BUSY_TENTATIVE, "20070508T101500Z/20070508T111500Z,20070515T101500Z/20070515T111500Z");
// verify we get resuts from VFREEBUSY in collection
start = new DateTime("20060101T051500Z");
end = new DateTime("20060105T051500Z");
period = new Period(start, end);
vfb = queryProcessor.generateFreeBusy(calendar, period);
verifyPeriods(vfb, null, "20060103T100000Z/20060103T120000Z,20060104T100000Z/20060104T120000Z");
verifyPeriods(vfb, FbType.BUSY_TENTATIVE, "20060102T100000Z/20060102T120000Z");
verifyPeriods(vfb, FbType.BUSY_UNAVAILABLE, "20060105T010000Z/20060105T020000Z");
}
private User getUser(UserDao userDao, String username) {
return helper.getUser(userDao, contentDao, username);
}
private CollectionItem generateCalendar(String name, String owner) {
CollectionItem calendar = new CollectionItem();
calendar.setName(name);
calendar.setOwner(getUser(userDao, owner));
CalendarCollectionStamp ccs = new CalendarCollectionStamp();
calendar.addStamp(ccs);
ccs.setDescription("test description");
ccs.setLanguage("en");
return calendar;
}
private NoteItem generateEvent(String name, String file,
String owner) throws Exception {
NoteItem event = new NoteItem();
event.setName(name);
event.setDisplayName(name);
event.setOwner(getUser(userDao, owner));
EventStamp evs = new EventStamp();
event.addStamp(evs);
evs.setCalendar(CalendarUtils.parseCalendar(helper.getBytes(baseDir + "/" + file)));
return event;
}
private FreeBusyItem generateFreeBusy(String name, String file,
String owner) throws Exception {
FreeBusyItem fb = new FreeBusyItem();
fb.setName(name);
fb.setDisplayName(name);
fb.setOwner(getUser(userDao, owner));
fb.setFreeBusyCalendar(CalendarUtils.parseCalendar(helper.getBytes(baseDir + "/" + file)));
return fb;
}
private void verifyPeriods(VFreeBusy vfb, FbType fbtype, String periods) {
PropertyList props = vfb.getProperties(Property.FREEBUSY);
FreeBusy fb = null;
for(Iterator it = props.iterator();it.hasNext();) {
FreeBusy next = (FreeBusy) it.next();
FbType type = (FbType) next.getParameter(Parameter.FBTYPE);
if(type==null && fbtype==null) {
fb = next;
}
else if(type != null && type.equals(fbtype)) {
fb = next;
}
}
if(fb==null)
Assert.fail("periods " + periods + " not in " + vfb.toString());
Assert.assertEquals(periods, fb.getPeriods().toString());
}
}
| true | true | protected void onSetUpInTransaction() throws Exception {
// TODO Auto-generated method stub
super.onSetUpInTransaction();
queryProcessor = new StandardFreeBusyQueryProcessor();
queryProcessor.setCalendarDao(calendarDao);
CollectionItem calendar = generateCalendar("testcalendar", "testuser");
calendar.setUid(CALENDAR_UID);
CollectionItem root = (CollectionItem) contentDao.getRootItem(getUser(userDao, "testuser"));
contentDao.createCollection(root, calendar);
for (int i = 1; i <= 3; i++) {
ContentItem event = generateEvent("test" + i + ".ics", "eventwithtimezone"
+ i + ".ics", "testuser");
event.setUid(CALENDAR_UID + i);
contentDao.createContent(calendar, event);
}
FreeBusyItem fb = generateFreeBusy("test4.ics", "Vfreebusy.ics", "testuser");
fb.setUid(CALENDAR_UID + "4");
contentDao.createContent(calendar, fb);
clearSession();
}
| protected void onSetUpInTransaction() throws Exception {
// TODO Auto-generated method stub
super.onSetUpInTransaction();
queryProcessor = new StandardFreeBusyQueryProcessor();
queryProcessor.setCalendarDao(calendarDao);
CollectionItem calendar = generateCalendar("testcalendar", "testuser");
calendar.setUid(CALENDAR_UID);
CollectionItem root = (CollectionItem) contentDao.getRootItem(getUser(userDao, "testuser"));
contentDao.createCollection(root, calendar);
for (int i = 1; i <= 3; i++) {
ContentItem event = generateEvent("test" + i + ".ics", "eventwithtimezone"
+ i + ".ics", "testuser");
event.setUid(CALENDAR_UID + i);
contentDao.createContent(calendar, event);
}
FreeBusyItem fb = generateFreeBusy("test4.ics", "vfreebusy.ics", "testuser");
fb.setUid(CALENDAR_UID + "4");
contentDao.createContent(calendar, fb);
clearSession();
}
|
diff --git a/pgtest3/source-impl/de/unisiegen/tpml/graphics/outline/binding/OutlineUnbound.java b/pgtest3/source-impl/de/unisiegen/tpml/graphics/outline/binding/OutlineUnbound.java
index 509665c7..64c64a11 100644
--- a/pgtest3/source-impl/de/unisiegen/tpml/graphics/outline/binding/OutlineUnbound.java
+++ b/pgtest3/source-impl/de/unisiegen/tpml/graphics/outline/binding/OutlineUnbound.java
@@ -1,373 +1,379 @@
package de.unisiegen.tpml.graphics.outline.binding ;
import java.lang.reflect.InvocationTargetException ;
import java.lang.reflect.Method ;
import java.util.ArrayList ;
import java.util.Enumeration ;
import de.unisiegen.tpml.core.expressions.Attr ;
import de.unisiegen.tpml.core.expressions.CurriedLet ;
import de.unisiegen.tpml.core.expressions.CurriedLetRec ;
import de.unisiegen.tpml.core.expressions.CurriedMeth ;
import de.unisiegen.tpml.core.expressions.Expression ;
import de.unisiegen.tpml.core.expressions.Identifier ;
import de.unisiegen.tpml.core.expressions.Lambda ;
import de.unisiegen.tpml.core.expressions.Let ;
import de.unisiegen.tpml.core.expressions.LetRec ;
import de.unisiegen.tpml.core.expressions.Meth ;
import de.unisiegen.tpml.core.expressions.MultiLambda ;
import de.unisiegen.tpml.core.expressions.MultiLet ;
import de.unisiegen.tpml.core.expressions.ObjectExpr ;
import de.unisiegen.tpml.core.expressions.Recursion ;
import de.unisiegen.tpml.core.expressions.Row ;
/**
* Finds the unbound {@link Identifier}s in a given {@link Expression}.
*
* @author Christian Fehler
* @version $Rev: 995 $
*/
public final class OutlineUnbound
{
/**
* The <code>String</code> for the beginning of the find methods.
*/
private static final String FIND = "find" ; //$NON-NLS-1$
/**
* The list of unbound {@link Identifier}s in the {@link Expression}.
*/
private ArrayList < Identifier > list ;
/**
* Initilizes the list and finds the unbound {@link Identifier}s.
*
* @param pExpression The input {@link Expression}.
*/
public OutlineUnbound ( Expression pExpression )
{
this.list = new ArrayList < Identifier > ( ) ;
find ( new ArrayList < String > ( ) , pExpression ) ;
}
/**
* Finds the unbounded {@link Identifier}s in the given {@link Expression}.
*
* @param pBounded The list of bounded {@link Identifier}s.
* @param pExpression The input {@link Expression}.
*/
private final void find ( ArrayList < String > pBounded ,
Expression pExpression )
{
for ( Method method : this.getClass ( ).getDeclaredMethods ( ) )
{
if ( method.getName ( ).equals (
FIND + pExpression.getClass ( ).getSimpleName ( ) ) )
{
try
{
Object [ ] argument = new Object [ 2 ] ;
argument [ 0 ] = pBounded ;
argument [ 1 ] = pExpression ;
method.invoke ( this , argument ) ;
}
catch ( IllegalArgumentException e )
{
- // Do nothing
+ System.err.println ( "IllegalArgumentException: " //$NON-NLS-1$
+ + this.getClass ( ).getCanonicalName ( ) + "." + FIND //$NON-NLS-1$
+ + pExpression.getClass ( ).getSimpleName ( ) ) ;
}
catch ( IllegalAccessException e )
{
- // Do nothing
+ System.err.println ( "IllegalAccessException: " //$NON-NLS-1$
+ + this.getClass ( ).getCanonicalName ( ) + "." + FIND //$NON-NLS-1$
+ + pExpression.getClass ( ).getSimpleName ( ) ) ;
}
catch ( InvocationTargetException e )
{
- // Do nothing
+ System.err.println ( "InvocationTargetException: " //$NON-NLS-1$
+ + this.getClass ( ).getCanonicalName ( ) + "." + FIND //$NON-NLS-1$
+ + pExpression.getClass ( ).getSimpleName ( ) ) ;
}
return ;
}
}
Enumeration < Expression > children = pExpression.children ( ) ;
while ( children.hasMoreElements ( ) )
{
find ( pBounded , children.nextElement ( ) ) ;
}
}
/**
* Finds the unbounded {@link Identifier}s in the given {@link CurriedLet}.
*
* @param pBounded The list of bounded {@link Identifier}s.
* @param pExpression The input {@link CurriedLet}.
*/
@ SuppressWarnings ( "unused" )
private final void findCurriedLet ( ArrayList < String > pBounded ,
CurriedLet pExpression )
{
ArrayList < String > bounded1 = new ArrayList < String > ( pBounded ) ;
ArrayList < String > bounded2 = new ArrayList < String > ( pBounded ) ;
// New bindings in E1, Identifier 1 to n
for ( int i = 1 ; i < pExpression.getIdentifiers ( ).length ; i ++ )
{
bounded1.add ( pExpression.getIdentifiers ( i ) ) ;
}
find ( bounded1 , pExpression.getE1 ( ) ) ;
// New bindings in E2, Identifier 0
bounded2.add ( pExpression.getIdentifiers ( 0 ) ) ;
find ( bounded2 , pExpression.getE2 ( ) ) ;
}
/**
* Finds the unbounded {@link Identifier}s in the given {@link CurriedLetRec}.
*
* @param pBounded The list of bounded {@link Identifier}s.
* @param pExpression The input {@link CurriedLetRec}.
*/
@ SuppressWarnings ( "unused" )
private final void findCurriedLetRec ( ArrayList < String > pBounded ,
CurriedLetRec pExpression )
{
ArrayList < String > bounded1 = new ArrayList < String > ( pBounded ) ;
ArrayList < String > bounded2 = new ArrayList < String > ( pBounded ) ;
// New bindings in E1, Identifier 0 to n
for ( int i = 0 ; i < pExpression.getIdentifiers ( ).length ; i ++ )
{
bounded1.add ( pExpression.getIdentifiers ( i ) ) ;
}
find ( bounded1 , pExpression.getE1 ( ) ) ;
// New bindings in E2, Identifier 0
bounded2.add ( pExpression.getIdentifiers ( 0 ) ) ;
find ( bounded2 , pExpression.getE2 ( ) ) ;
}
/**
* Finds the unbounded {@link Identifier}s in the given {@link CurriedMeth}.
*
* @param pBounded The list of bounded {@link Identifier}s.
* @param pExpression The input {@link CurriedMeth}.
*/
@ SuppressWarnings ( "unused" )
private final void findCurriedMeth ( ArrayList < String > pBounded ,
CurriedMeth pExpression )
{
ArrayList < String > bounded = new ArrayList < String > ( pBounded ) ;
// New bindings in E, Identifier 1 to n
for ( int i = 1 ; i < pExpression.getIdentifiers ( ).length ; i ++ )
{
bounded.add ( pExpression.getIdentifiers ( i ) ) ;
}
find ( bounded , pExpression.getE ( ) ) ;
}
/**
* Finds the unbounded {@link Identifier}s in the given {@link Identifier}.
*
* @param pBounded The list of bounded {@link Identifier}s.
* @param pExpression The input {@link Identifier}.
*/
@ SuppressWarnings ( "unused" )
private final void findIdentifier ( ArrayList < String > pBounded ,
Identifier pExpression )
{
if ( ! pBounded.contains ( pExpression.getName ( ) ) )
{
this.list.add ( pExpression ) ;
}
}
/**
* Finds the unbounded {@link Identifier}s in the given {@link Lambda}.
*
* @param pBounded The list of bounded {@link Identifier}s.
* @param pExpression The input {@link Lambda}.
*/
@ SuppressWarnings ( "unused" )
private final void findLambda ( ArrayList < String > pBounded ,
Lambda pExpression )
{
ArrayList < String > bounded = new ArrayList < String > ( pBounded ) ;
// New binding in E
bounded.add ( pExpression.getId ( ) ) ;
find ( bounded , pExpression.getE ( ) ) ;
}
/**
* Finds the unbounded {@link Identifier}s in the given {@link Let}.
*
* @param pBounded The list of bounded {@link Identifier}s.
* @param pExpression The input {@link Let}.
*/
@ SuppressWarnings ( "unused" )
private final void findLet ( ArrayList < String > pBounded , Let pExpression )
{
ArrayList < String > bounded1 = new ArrayList < String > ( pBounded ) ;
ArrayList < String > bounded2 = new ArrayList < String > ( pBounded ) ;
// No new binding in E1
find ( bounded1 , pExpression.getE1 ( ) ) ;
// New binding in E2
bounded2.add ( pExpression.getId ( ) ) ;
find ( bounded2 , pExpression.getE2 ( ) ) ;
}
/**
* Finds the unbounded {@link Identifier}s in the given {@link LetRec}.
*
* @param pBounded The list of bounded {@link Identifier}s.
* @param pExpression The input {@link LetRec}.
*/
@ SuppressWarnings ( "unused" )
private final void findLetRec ( ArrayList < String > pBounded ,
LetRec pExpression )
{
ArrayList < String > bounded1 = new ArrayList < String > ( pBounded ) ;
ArrayList < String > bounded2 = new ArrayList < String > ( pBounded ) ;
// New binding in E1
bounded1.add ( pExpression.getId ( ) ) ;
find ( bounded1 , pExpression.getE1 ( ) ) ;
// New binding in E2
bounded2.add ( pExpression.getId ( ) ) ;
find ( bounded2 , pExpression.getE2 ( ) ) ;
}
/**
* Finds the unbounded {@link Identifier}s in the given {@link MultiLambda}.
*
* @param pBounded The list of bounded {@link Identifier}s.
* @param pExpression The input {@link MultiLambda}.
*/
@ SuppressWarnings ( "unused" )
private final void findMultiLambda ( ArrayList < String > pBounded ,
MultiLambda pExpression )
{
ArrayList < String > bounded = new ArrayList < String > ( pBounded ) ;
// New bindings in E
for ( int i = 0 ; i < pExpression.getIdentifiers ( ).length ; i ++ )
{
bounded.add ( pExpression.getIdentifiers ( i ) ) ;
}
find ( bounded , pExpression.getE ( ) ) ;
}
/**
* Finds the unbounded {@link Identifier}s in the given {@link MultiLet}.
*
* @param pBounded The list of bounded {@link Identifier}s.
* @param pExpression The input {@link MultiLet}.
*/
@ SuppressWarnings ( "unused" )
private final void findMultiLet ( ArrayList < String > pBounded ,
MultiLet pExpression )
{
ArrayList < String > bounded1 = new ArrayList < String > ( pBounded ) ;
ArrayList < String > bounded2 = new ArrayList < String > ( pBounded ) ;
// No new binding in E1
find ( bounded1 , pExpression.getE1 ( ) ) ;
// New bindings in E2
for ( int i = 0 ; i < pExpression.getIdentifiers ( ).length ; i ++ )
{
bounded2.add ( pExpression.getIdentifiers ( i ) ) ;
}
find ( bounded2 , pExpression.getE2 ( ) ) ;
}
/**
* Finds the unbounded {@link Identifier}s in the given {@link ObjectExpr}.
*
* @param pBounded The list of bounded {@link Identifier}s.
* @param pExpression The input {@link ObjectExpr}.
*/
@ SuppressWarnings ( "unused" )
private final void findObjectExpr ( ArrayList < String > pBounded ,
ObjectExpr pExpression )
{
ArrayList < String > bounded = new ArrayList < String > ( pBounded ) ;
// New binding in E
bounded.add ( pExpression.getId ( ) ) ;
find ( bounded , pExpression.getE ( ) ) ;
}
/**
* Finds the unbounded {@link Identifier}s in the given {@link Recursion}.
*
* @param pBounded The list of bounded {@link Identifier}s.
* @param pExpression The input {@link Recursion}.
*/
@ SuppressWarnings ( "unused" )
private final void findRecursion ( ArrayList < String > pBounded ,
Recursion pExpression )
{
ArrayList < String > bounded = new ArrayList < String > ( pBounded ) ;
// New binding in E
bounded.add ( pExpression.getId ( ) ) ;
find ( bounded , pExpression.getE ( ) ) ;
}
/**
* Finds the unbounded {@link Identifier}s in the given {@link Row}.
*
* @param pBounded The list of bounded {@link Identifier}s.
* @param pExpression The input {@link Row}.
*/
@ SuppressWarnings ( "unused" )
private final void findRow ( ArrayList < String > pBounded , Row pExpression )
{
ArrayList < String > bounded = new ArrayList < String > ( pBounded ) ;
for ( int i = 0 ; i < pExpression.getExpressions ( ).length ; i ++ )
{
if ( pExpression.getExpressions ( i ) instanceof Attr )
{
Attr attr = ( Attr ) pExpression.getExpressions ( i ) ;
find ( bounded , attr ) ;
// New binding in the rest of the row
bounded.add ( attr.getId ( ) ) ;
}
else if ( pExpression.getExpressions ( i ) instanceof Meth )
{
find ( bounded , pExpression.getExpressions ( i ) ) ;
}
else if ( pExpression.getExpressions ( i ) instanceof CurriedMeth )
{
find ( bounded , pExpression.getExpressions ( i ) ) ;
}
}
}
/**
* Returns the unbound {@link Identifier} in the {@link Expression}.
*
* @param pIndex The index of the unbound {@link Identifier}.
* @return The unbound {@link Identifier} in the {@link Expression}.
*/
public final Identifier get ( int pIndex )
{
return this.list.get ( pIndex ) ;
}
/**
* Returns the size of the list. The size is equal to the number of unbound
* {@link Identifier}s.
*
* @return The number of unbound {@link Identifier}s.
*/
public final int size ( )
{
return this.list.size ( ) ;
}
}
| false | true | private final void find ( ArrayList < String > pBounded ,
Expression pExpression )
{
for ( Method method : this.getClass ( ).getDeclaredMethods ( ) )
{
if ( method.getName ( ).equals (
FIND + pExpression.getClass ( ).getSimpleName ( ) ) )
{
try
{
Object [ ] argument = new Object [ 2 ] ;
argument [ 0 ] = pBounded ;
argument [ 1 ] = pExpression ;
method.invoke ( this , argument ) ;
}
catch ( IllegalArgumentException e )
{
// Do nothing
}
catch ( IllegalAccessException e )
{
// Do nothing
}
catch ( InvocationTargetException e )
{
// Do nothing
}
return ;
}
}
Enumeration < Expression > children = pExpression.children ( ) ;
while ( children.hasMoreElements ( ) )
{
find ( pBounded , children.nextElement ( ) ) ;
}
}
| private final void find ( ArrayList < String > pBounded ,
Expression pExpression )
{
for ( Method method : this.getClass ( ).getDeclaredMethods ( ) )
{
if ( method.getName ( ).equals (
FIND + pExpression.getClass ( ).getSimpleName ( ) ) )
{
try
{
Object [ ] argument = new Object [ 2 ] ;
argument [ 0 ] = pBounded ;
argument [ 1 ] = pExpression ;
method.invoke ( this , argument ) ;
}
catch ( IllegalArgumentException e )
{
System.err.println ( "IllegalArgumentException: " //$NON-NLS-1$
+ this.getClass ( ).getCanonicalName ( ) + "." + FIND //$NON-NLS-1$
+ pExpression.getClass ( ).getSimpleName ( ) ) ;
}
catch ( IllegalAccessException e )
{
System.err.println ( "IllegalAccessException: " //$NON-NLS-1$
+ this.getClass ( ).getCanonicalName ( ) + "." + FIND //$NON-NLS-1$
+ pExpression.getClass ( ).getSimpleName ( ) ) ;
}
catch ( InvocationTargetException e )
{
System.err.println ( "InvocationTargetException: " //$NON-NLS-1$
+ this.getClass ( ).getCanonicalName ( ) + "." + FIND //$NON-NLS-1$
+ pExpression.getClass ( ).getSimpleName ( ) ) ;
}
return ;
}
}
Enumeration < Expression > children = pExpression.children ( ) ;
while ( children.hasMoreElements ( ) )
{
find ( pBounded , children.nextElement ( ) ) ;
}
}
|
diff --git a/lenskit-eval/src/main/java/org/grouplens/lenskit/eval/graph/DumpGraphTask.java b/lenskit-eval/src/main/java/org/grouplens/lenskit/eval/graph/DumpGraphTask.java
index f3240c5c5..de7594ce9 100644
--- a/lenskit-eval/src/main/java/org/grouplens/lenskit/eval/graph/DumpGraphTask.java
+++ b/lenskit-eval/src/main/java/org/grouplens/lenskit/eval/graph/DumpGraphTask.java
@@ -1,198 +1,198 @@
/*
* LensKit, an open source recommender systems toolkit.
* Copyright 2010-2013 Regents of the University of Minnesota and contributors
* Work on LensKit has been funded by the National Science Foundation under
* grants IIS 05-34939, 08-08692, 08-12148, and 10-17697.
*
* 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 program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.grouplens.lenskit.eval.graph;
import com.google.common.io.Closer;
import com.google.common.io.Files;
import org.grouplens.grapht.graph.Edge;
import org.grouplens.grapht.graph.Graph;
import org.grouplens.grapht.graph.Node;
import org.grouplens.grapht.spi.AbstractSatisfactionVisitor;
import org.grouplens.grapht.spi.CachedSatisfaction;
import org.grouplens.grapht.spi.Satisfaction;
import org.grouplens.grapht.util.Providers;
import org.grouplens.lenskit.core.LenskitConfiguration;
import org.grouplens.lenskit.core.RecommenderConfigurationException;
import org.grouplens.lenskit.core.RecommenderInstantiator;
import org.grouplens.lenskit.data.dao.EventCollectionDAO;
import org.grouplens.lenskit.data.dao.EventDAO;
import org.grouplens.lenskit.data.pref.PreferenceDomain;
import org.grouplens.lenskit.eval.AbstractTask;
import org.grouplens.lenskit.eval.TaskExecutionException;
import org.grouplens.lenskit.eval.algorithm.LenskitAlgorithmInstance;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nonnull;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Set;
/**
* Command to dump a graph.
*
* @author <a href="http://www.grouplens.org">GroupLens Research</a>
*/
@SuppressWarnings("unused")
public class DumpGraphTask extends AbstractTask<File> {
private static final Logger logger = LoggerFactory.getLogger(DumpGraphTask.class);
private LenskitAlgorithmInstance algorithm;
private File output;
private PreferenceDomain domain = null;
public DumpGraphTask() {
this(null);
}
public DumpGraphTask(String name) {
super(name);
}
@Nonnull
@Override
public String getName() {
String name = super.getName();
if (name == null) {
name = algorithm.getName();
if (name == null) {
name = "algorithm";
}
}
return name;
}
public LenskitAlgorithmInstance getAlgorithm() {
return algorithm;
}
public DumpGraphTask setAlgorithm(LenskitAlgorithmInstance algorithm) {
this.algorithm = algorithm;
return this;
}
public File getOutput() {
return output;
}
public DumpGraphTask setOutput(File f) {
output = f;
return this;
}
public DumpGraphTask setOutput(String fn) {
return setOutput(new File(fn));
}
public PreferenceDomain getDomain() {
return domain;
}
public DumpGraphTask setDomain(PreferenceDomain dom) {
domain = dom;
return this;
}
@Override
public File perform() throws TaskExecutionException {
if (output == null) {
logger.error("no output file specified");
throw new IllegalStateException("no graph output file specified");
}
LenskitConfiguration config = algorithm.getConfig().copy();
// FIXME This is an ugly DAO-type kludge
- config.bind(EventDAO.class).toProvider(Providers.<EventDAO>of(null));
+ config.bind(EventDAO.class).toProvider(Providers.<EventDAO>of(null, EventDAO.class));
if (domain != null) {
config.bind(PreferenceDomain.class).to(domain);
}
logger.info("dumping graph {}", getName());
RecommenderInstantiator instantiator;
try {
instantiator = RecommenderInstantiator.forConfig(config);
} catch (RecommenderConfigurationException e) {
throw new TaskExecutionException("error resolving algorithm configuration", e);
}
Graph initial = instantiator.getGraph();
logger.debug("graph has {} nodes", initial.getNodes().size());
Graph unshared = instantiator.simulate();
logger.debug("unshared graph has {} nodes", unshared.getNodes().size());
try {
writeGraph(initial, unshared.getNodes(), output);
} catch (IOException e) {
throw new TaskExecutionException("error writing graph", e);
}
// TODO Support dumping the instantiated graph again
return output;
}
@SuppressWarnings("PMD.AvoidCatchingThrowable")
private void writeGraph(Graph g, Set<Node> unshared, File file) throws IOException, TaskExecutionException {
Files.createParentDirs(output);
Closer close = Closer.create();
try {
FileWriter writer = close.register(new FileWriter(file));
GraphWriter gw = close.register(new GraphWriter(writer));
renderGraph(g, unshared, gw);
} catch (Throwable th) {
throw close.rethrow(th, TaskExecutionException.class);
} finally {
close.close();
}
}
private void renderGraph(final Graph g, Set<Node> unshared, final GraphWriter gw) throws TaskExecutionException {
// Handle the root node
Node root = g.getNode(null);
if (root == null) {
throw new TaskExecutionException("no root node for graph");
}
GraphDumper dumper = new GraphDumper(g, unshared, gw);
try {
String rid = dumper.setRoot(root);
for (Edge e: g.getOutgoingEdges(root)) {
Node target = e.getTail();
CachedSatisfaction csat = target.getLabel();
assert csat != null;
if (!satIsNull(csat.getSatisfaction())) {
String id = dumper.process(target);
gw.putEdge(EdgeBuilder.create(rid, id)
.set("arrowhead", "vee")
.build());
}
}
dumper.finish();
} catch (IOException e) {
throw new TaskExecutionException("error writing graph", e);
}
}
private boolean satIsNull(Satisfaction sat) {
return sat.visit(new AbstractSatisfactionVisitor<Boolean>(false) {
@Override
public Boolean visitNull() {
return true;
}
});
}
}
| true | true | public File perform() throws TaskExecutionException {
if (output == null) {
logger.error("no output file specified");
throw new IllegalStateException("no graph output file specified");
}
LenskitConfiguration config = algorithm.getConfig().copy();
// FIXME This is an ugly DAO-type kludge
config.bind(EventDAO.class).toProvider(Providers.<EventDAO>of(null));
if (domain != null) {
config.bind(PreferenceDomain.class).to(domain);
}
logger.info("dumping graph {}", getName());
RecommenderInstantiator instantiator;
try {
instantiator = RecommenderInstantiator.forConfig(config);
} catch (RecommenderConfigurationException e) {
throw new TaskExecutionException("error resolving algorithm configuration", e);
}
Graph initial = instantiator.getGraph();
logger.debug("graph has {} nodes", initial.getNodes().size());
Graph unshared = instantiator.simulate();
logger.debug("unshared graph has {} nodes", unshared.getNodes().size());
try {
writeGraph(initial, unshared.getNodes(), output);
} catch (IOException e) {
throw new TaskExecutionException("error writing graph", e);
}
// TODO Support dumping the instantiated graph again
return output;
}
| public File perform() throws TaskExecutionException {
if (output == null) {
logger.error("no output file specified");
throw new IllegalStateException("no graph output file specified");
}
LenskitConfiguration config = algorithm.getConfig().copy();
// FIXME This is an ugly DAO-type kludge
config.bind(EventDAO.class).toProvider(Providers.<EventDAO>of(null, EventDAO.class));
if (domain != null) {
config.bind(PreferenceDomain.class).to(domain);
}
logger.info("dumping graph {}", getName());
RecommenderInstantiator instantiator;
try {
instantiator = RecommenderInstantiator.forConfig(config);
} catch (RecommenderConfigurationException e) {
throw new TaskExecutionException("error resolving algorithm configuration", e);
}
Graph initial = instantiator.getGraph();
logger.debug("graph has {} nodes", initial.getNodes().size());
Graph unshared = instantiator.simulate();
logger.debug("unshared graph has {} nodes", unshared.getNodes().size());
try {
writeGraph(initial, unshared.getNodes(), output);
} catch (IOException e) {
throw new TaskExecutionException("error writing graph", e);
}
// TODO Support dumping the instantiated graph again
return output;
}
|
diff --git a/tools/org/newdawn/slick/tools/peditor/ParticleGame.java b/tools/org/newdawn/slick/tools/peditor/ParticleGame.java
index a580d35..8ad2857 100644
--- a/tools/org/newdawn/slick/tools/peditor/ParticleGame.java
+++ b/tools/org/newdawn/slick/tools/peditor/ParticleGame.java
@@ -1,306 +1,306 @@
package org.newdawn.slick.tools.peditor;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import org.lwjgl.LWJGLException;
import org.lwjgl.opengl.Display;
import org.lwjgl.opengl.GL11;
import org.newdawn.slick.BasicGame;
import org.newdawn.slick.Color;
import org.newdawn.slick.Font;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.Image;
import org.newdawn.slick.InputListener;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.particles.ConfigurableEmitter;
import org.newdawn.slick.particles.ParticleEmitter;
import org.newdawn.slick.particles.ParticleSystem;
import org.newdawn.slick.util.Log;
/**
* A LWJGL canvas displaying a particle system
*
* @author kevin
*/
public class ParticleGame extends BasicGame {
/** Emitters waiting to be added once the system is created */
private ArrayList waiting = new ArrayList();
/** The particle system being displayed on the panel */
private ParticleSystem system;
/** The font used to display info on the canvas */
private Font defaultFont;
/** The list of emitters being displayed in the system */
private ArrayList emitters = new ArrayList();
/** The maximum number of particles in use */
private int max;
/** True if the hud should be displayed */
private boolean hudOn = true;
/** True if the rendering is paused */
private boolean paused;
/** The amount the system moves */
private int systemMove;
/** The y position of the system */
private float ypos;
/** The background image file to load */
private File backgroundImage;
/** The background image being rendered */
private Image background;
/** An input listener to be added on init */
private InputListener listener;
/**
* Create a new canvas
*
* @param editor
* The editor which this canvas is part of
* @throws LWJGLException
* Indicates a failure to create the OpenGL context
*/
public ParticleGame(ParticleEditor editor) throws LWJGLException {
super("Particle Game");
}
/**
* Set the input listener to be added on init
*
* @param listener The listener to be added on init
*/
public void setListener(InputListener listener) {
this.listener = listener;
}
/**
* Set the image to display behind the particle system
*
* @param file
* The file to load for the background image
*/
public void setBackgroundImage(File file) {
backgroundImage = file;
background = null;
}
/**
* Set how much the system should move
*
* @param move
* The amount of the system should move
* @param reset
* True if the position should be reset
*/
public void setSystemMove(int move, boolean reset) {
this.systemMove = move;
if (reset) {
ypos = 0;
}
}
/**
* Indicate if this canvas should pause
*
* @param paused
* True if the rendering should pause
*/
public void setPaused(boolean paused) {
this.paused = paused;
}
/**
* Check if the canvas is paused
*
* @return True if the canvas is paused
*/
public boolean isPaused() {
return paused;
}
/**
* Check if this hud is being displayed
*
* @return True if this hud is being displayed
*/
public boolean isHudOn() {
return hudOn;
}
/**
* Indicate if the HUD should be drawn
*
* @param hud
* True if the HUD should be drawn
*/
public void setHud(boolean hud) {
this.hudOn = hud;
}
/**
* Add an emitter to the particle system held here
*
* @param emitter
* The emitter to add
*/
public void addEmitter(ConfigurableEmitter emitter) {
emitters.add(emitter);
if (system == null) {
waiting.add(emitter);
} else {
system.addEmitter(emitter);
}
}
/**
* Remove an emitter from the system held here
*
* @param emitter
* The emitter to be removed
*/
public void removeEmitter(ConfigurableEmitter emitter) {
emitters.remove(emitter);
system.removeEmitter(emitter);
}
/**
* Clear the particle system held in this canvas
*
* @param additive
* True if the particle system should be set to additive
*/
public void clearSystem(boolean additive) {
system = new ParticleSystem("org/newdawn/slick/data/particle.tga", 2000);
if (additive) {
system.setBlendingMode(ParticleSystem.BLEND_ADDITIVE);
}
system.setRemoveCompletedEmitters(false);
}
/**
* Set the particle system to be displayed
*
* @param system
* The system to be displayed
*/
public void setSystem(ParticleSystem system) {
this.system = system;
emitters.clear();
system.setRemoveCompletedEmitters(false);
for (int i = 0; i < system.getEmitterCount(); i++) {
emitters.add(system.getEmitter(i));
}
}
/**
* Reset the counts held in this canvas (maximum particles for instance)
*/
public void resetCounts() {
max = 0;
}
/**
* Get the particle system being displayed
*
* @return The system being displayed
*/
public ParticleSystem getSystem() {
return system;
}
public void init(GameContainer container) throws SlickException {
container.getInput().addListener(listener);
container.setShowFPS(false);
system = new ParticleSystem("org/newdawn/slick/data/particle.tga", 2000);
system.setBlendingMode(ParticleSystem.BLEND_ADDITIVE);
system.setRemoveCompletedEmitters(false);
for (int i = 0; i < waiting.size(); i++) {
system.addEmitter((ParticleEmitter) waiting.get(i));
}
waiting.clear();
}
public void update(GameContainer container, int delta)
throws SlickException {
if (!paused) {
ypos += delta * 0.002 * systemMove;
if (ypos > 300) {
ypos = -300;
}
if (ypos < -300) {
ypos = 300;
}
for (int i = 0; i < emitters.size(); i++) {
((ConfigurableEmitter) emitters.get(i)).replayCheck();
}
for (int i = 0; i < delta; i++) {
system.update(1);
}
}
Display.sync(100);
}
public void render(GameContainer container, Graphics g)
throws SlickException {
try {
if (backgroundImage != null) {
if (background == null) {
background = new Image(
new FileInputStream(backgroundImage),
backgroundImage.getAbsolutePath(), false);
}
}
} catch (Exception e) {
Log.error("Failed to load backgroundImage: " + backgroundImage);
Log.error(e);
backgroundImage = null;
background = null;
}
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT);
GL11.glLoadIdentity();
if (background != null) {
g.fillRect(0, 0, container.getWidth(), container.getHeight(), background, 0, 0);
}
max = Math.max(max, system.getParticleCount());
if (hudOn) {
g.setColor(Color.white);
g.drawString("FPS: " + container.getFPS(), 10, 10);
g.drawString("Particles: " + system.getParticleCount(), 10,
25);
g.drawString("Max: " + max, 10, 40);
g.drawString(
- "LMB: Position Emitter RMB: Default Position", 90,
+ "LMB: Position Emitter RMB: Default Position", 20,
527);
}
GL11.glTranslatef(250, 300, 0);
for (int i = 0; i < emitters.size(); i++) {
((ConfigurableEmitter) emitters.get(i)).setPosition(0, ypos);
}
system.render();
g.setColor(new Color(0, 0, 0, 0.5f));
g.fillRect(-1, -5, 2, 10);
g.fillRect(-5, -1, 10, 2);
}
}
| true | true | public void render(GameContainer container, Graphics g)
throws SlickException {
try {
if (backgroundImage != null) {
if (background == null) {
background = new Image(
new FileInputStream(backgroundImage),
backgroundImage.getAbsolutePath(), false);
}
}
} catch (Exception e) {
Log.error("Failed to load backgroundImage: " + backgroundImage);
Log.error(e);
backgroundImage = null;
background = null;
}
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT);
GL11.glLoadIdentity();
if (background != null) {
g.fillRect(0, 0, container.getWidth(), container.getHeight(), background, 0, 0);
}
max = Math.max(max, system.getParticleCount());
if (hudOn) {
g.setColor(Color.white);
g.drawString("FPS: " + container.getFPS(), 10, 10);
g.drawString("Particles: " + system.getParticleCount(), 10,
25);
g.drawString("Max: " + max, 10, 40);
g.drawString(
"LMB: Position Emitter RMB: Default Position", 90,
527);
}
GL11.glTranslatef(250, 300, 0);
for (int i = 0; i < emitters.size(); i++) {
((ConfigurableEmitter) emitters.get(i)).setPosition(0, ypos);
}
system.render();
g.setColor(new Color(0, 0, 0, 0.5f));
g.fillRect(-1, -5, 2, 10);
g.fillRect(-5, -1, 10, 2);
}
| public void render(GameContainer container, Graphics g)
throws SlickException {
try {
if (backgroundImage != null) {
if (background == null) {
background = new Image(
new FileInputStream(backgroundImage),
backgroundImage.getAbsolutePath(), false);
}
}
} catch (Exception e) {
Log.error("Failed to load backgroundImage: " + backgroundImage);
Log.error(e);
backgroundImage = null;
background = null;
}
GL11.glClear(GL11.GL_COLOR_BUFFER_BIT);
GL11.glLoadIdentity();
if (background != null) {
g.fillRect(0, 0, container.getWidth(), container.getHeight(), background, 0, 0);
}
max = Math.max(max, system.getParticleCount());
if (hudOn) {
g.setColor(Color.white);
g.drawString("FPS: " + container.getFPS(), 10, 10);
g.drawString("Particles: " + system.getParticleCount(), 10,
25);
g.drawString("Max: " + max, 10, 40);
g.drawString(
"LMB: Position Emitter RMB: Default Position", 20,
527);
}
GL11.glTranslatef(250, 300, 0);
for (int i = 0; i < emitters.size(); i++) {
((ConfigurableEmitter) emitters.get(i)).setPosition(0, ypos);
}
system.render();
g.setColor(new Color(0, 0, 0, 0.5f));
g.fillRect(-1, -5, 2, 10);
g.fillRect(-5, -1, 10, 2);
}
|
diff --git a/javasrc/src/org/ccnx/ccn/impl/repo/RepositoryInterestHandler.java b/javasrc/src/org/ccnx/ccn/impl/repo/RepositoryInterestHandler.java
index a3919cfad..96f633f10 100644
--- a/javasrc/src/org/ccnx/ccn/impl/repo/RepositoryInterestHandler.java
+++ b/javasrc/src/org/ccnx/ccn/impl/repo/RepositoryInterestHandler.java
@@ -1,354 +1,351 @@
/*
* Part of the CCNx Java Library.
*
* Copyright (C) 2008, 2009, 2010, 2011 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 java.util.logging.Level;
import org.ccnx.ccn.CCNFilterListener;
import org.ccnx.ccn.CCNHandle;
import org.ccnx.ccn.impl.repo.RepositoryInfo.RepositoryInfoObject;
import org.ccnx.ccn.impl.support.Log;
import org.ccnx.ccn.io.content.ContentEncodingException;
import org.ccnx.ccn.profiles.CommandMarker;
import org.ccnx.ccn.profiles.nameenum.NameEnumerationResponse;
import org.ccnx.ccn.profiles.repo.RepositoryOperations;
import org.ccnx.ccn.protocol.ContentName;
import org.ccnx.ccn.protocol.ContentObject;
import org.ccnx.ccn.protocol.Interest;
/**
* Handles interests matching the repository's namespace.
*
* @see RepositoryServer
* @see RepositoryFlowControl
* @see RepositoryDataListener
*/
public class RepositoryInterestHandler implements CCNFilterListener {
private RepositoryServer _server;
private CCNHandle _handle;
public RepositoryInterestHandler(RepositoryServer server) {
_server = server;
_handle = server.getHandle();
}
/**
* Parse incoming interests for type and dispatch those dedicated to some special purpose.
* Interests can be to start a write or a name enumeration request.
* If the interest has no special purpose, its assumed that it's to actually read data from
* the repository and the request is sent to the RepositoryStore to be processed.
*/
public boolean handleInterest(Interest interest) {
_server._stats.increment(RepositoryServer.StatsEnum.HandleInterest);
if (Log.isLoggable(Log.FAC_REPO, Level.FINER))
Log.finer(Log.FAC_REPO, "Saw interest: {0}", interest.name());
try {
if (interest.name().startsWith(CommandMarker.COMMAND_PREFIX)) {
if (RepositoryOperations.isStartWriteOperation(interest)) {
_server._stats.increment(RepositoryServer.StatsEnum.HandleInterestCommands);
_server._stats.increment(RepositoryServer.StatsEnum.HandleInterestStartWriteReceived);
if (allowGenerated(interest)) {
startWrite(interest);
_server._stats.increment(RepositoryServer.StatsEnum.HandleInterestStartWriteProcessed);
} else
_server._stats.increment(RepositoryServer.StatsEnum.HandleInterestStartWriteIgnored);
return true;
} else if (RepositoryOperations.isNameEnumerationOperation(interest)) {
_server._stats.increment(RepositoryServer.StatsEnum.HandleInterestCommands);
_server._stats.increment(RepositoryServer.StatsEnum.HandleInterestNameEnumReceived);
// Note - we are purposely allowing requests with allowGenerated turned off
// for NE for now. Disallowing it potentially causes problems.
nameEnumeratorResponse(interest);
_server._stats.increment(RepositoryServer.StatsEnum.HandleInterestNameEnumProcessed);
return true;
} else if (RepositoryOperations.isCheckedWriteOperation(interest)) {
_server._stats.increment(RepositoryServer.StatsEnum.HandleInterestCommands);
_server._stats.increment(RepositoryServer.StatsEnum.HandleInterestCheckedWriteReceived);
if (allowGenerated(interest)) {
startWriteChecked(interest);
_server._stats.increment(RepositoryServer.StatsEnum.HandleInterestCheckedWriteProcessed);
} else
_server._stats.increment(RepositoryServer.StatsEnum.HandleInterestCheckedWriteIgnored);
return true;
} else if (RepositoryOperations.isBulkImportOperation(interest)) {
_server._stats.increment(RepositoryServer.StatsEnum.HandleInterestCommands);
_server._stats.increment(RepositoryServer.StatsEnum.HandleInterestBulkImportReceived);
if (allowGenerated(interest)) {
addBulkDataToRepo(interest);
_server._stats.increment(RepositoryServer.StatsEnum.HandleInterestBulkImportReceived);
} else
_server._stats.increment(RepositoryServer.StatsEnum.HandleInterestBulkImportIgnored);
return true;
}
}
_server._stats.increment(RepositoryServer.StatsEnum.HandleInterestUncategorized);
ContentObject content = _server.getRepository().getContent(interest);
if (content != null) {
if (Log.isLoggable(Log.FAC_REPO, Level.FINEST))
Log.finest(Log.FAC_REPO, "Satisfying interest: {0} with content {1}", interest, content.name());
_handle.put(content);
} else {
if (Log.isLoggable(Log.FAC_REPO, Level.FINE))
Log.fine(Log.FAC_REPO, "Unsatisfied interest: {0}", interest);
}
} catch (Exception e) {
_server._stats.increment(RepositoryServer.StatsEnum.HandleInterestErrors);
Log.logStackTrace(Level.WARNING, e);
e.printStackTrace();
}
return true;
}
protected boolean allowGenerated(Interest interest) {
if (null != interest.answerOriginKind() && (interest.answerOriginKind() & Interest.ANSWER_GENERATED) == 0)
return false; // Request to not answer
else
return true;
}
/**
* Check for duplicate request, i.e. request already in process
* Logs the request if found to be a duplicate.
* @param interest the incoming interest containing the request command
* @return true if request is duplicate
*/
protected boolean isDuplicateRequest(Interest interest) {
synchronized (_server.getDataListeners()) {
for (RepositoryDataListener listener : _server.getDataListeners()) {
if (listener.getOrigInterest().equals(interest)) {
_server._stats.increment(RepositoryServer.StatsEnum.HandleInterestDuplicateRequests);
if (Log.isLoggable(Log.FAC_REPO, Level.INFO))
Log.info(Log.FAC_REPO, "Request {0} is a duplicate, ignoring", interest.name());
return true;
}
}
}
return false;
}
/**
* Check whether new writes are allowed now
* Logs the discarded request if it cannot be processed
* @param interest the incoming interest containing the command
* @return true if writes are presently suspended
*/
protected boolean isWriteSuspended(Interest interest) {
// For now we need to wait until all current sessions are complete before a namespace
// change which will reset the filters is allowed. So for now, we just don't allow any
// new sessions to start until a pending namespace change is complete to allow there to
// be space for this to actually happen. In theory we should probably figure out a way
// to allow new sessions that are within the new namespace to start but figuring out all
// the locking/startup issues surrounding this is complex so for now we just don't allow it.
if (_server.getPendingNameSpaceState()) {
_server._stats.increment(RepositoryServer.StatsEnum.HandleInterestWriteSuspended);
if (Log.isLoggable(Log.FAC_REPO, Level.INFO))
Log.info(Log.FAC_REPO, "Discarding write request {0} due to pending namespace change", interest.name());
return true;
}
return false;
}
/**
* Handle start write requests
*
* @param interest
*/
private void startWrite(Interest interest) {
if (isDuplicateRequest(interest)) return;
if (isWriteSuspended(interest)) return;
// Create the name for the initial interest to retrieve content from the client that it desires to
// write. Strip from the write request name (in the incoming Interest) the start write command component
// and the nonce component to get the prefix for the content to be written.
ContentName listeningName = new ContentName(interest.name().count() - 2, interest.name().components());
try {
if (Log.isLoggable(Log.FAC_REPO, Level.INFO))
Log.info(Log.FAC_REPO, "Processing write request for {0}", listeningName);
// Create the initial read interest. Set maxSuffixComponents = 2 to get only content with one
// component past the prefix, plus the implicit digest. This is designed to retrieve segments
// of a stream and avoid other content more levels below in the name space. We do not ask for
// a specific segment initially so as to support arbitrary starting segment numbers.
// TODO use better exclude filters to ensure we're only getting segments.
Interest readInterest = Interest.constructInterest(listeningName, _server.getExcludes(), null, 2, null, null);
RepositoryDataListener listener;
RepositoryInfoObject rio = _server.getRepository().getRepoInfo(interest.name(), null, null);
if (null == rio)
return; // Should have logged an error in getRepoInfo
// Hand the object the outstanding interest, so it can put its first block immediately.
rio.save(interest);
// Check for special case file written to repo
ContentName globalPrefix = _server.getRepository().getGlobalPrefix();
String localName = _server.getRepository().getLocalName();
if (BasicPolicy.getPolicyName(globalPrefix, localName).isPrefixOf(listeningName)) {
_server._stats.increment(RepositoryServer.StatsEnum.HandleInterestStartWritePolicyHandlers);
new RepositoryPolicyHandler(interest, readInterest, _server);
return;
}
listener = new RepositoryDataListener(interest, readInterest, _server);
_server.addListener(listener);
listener.getInterests().add(readInterest, null);
_handle.expressInterest(readInterest, listener);
_server._stats.increment(RepositoryServer.StatsEnum.HandleInterestStartWriteExpressInterest);
} catch (Exception e) {
_server._stats.increment(RepositoryServer.StatsEnum.HandleInterestStartWriteErrors);
Log.logStackTrace(Level.WARNING, e);
e.printStackTrace();
}
}
/**
* Handle requests to check for specific stream content and read and store it if not
* already present.
* @param interest the interest containing the request
* @throws RepositoryException
* @throws ContentEncodingException
* @throws IOException
*/
private void startWriteChecked(Interest interest) {
if (isDuplicateRequest(interest)) return;
if (isWriteSuspended(interest)) return;
try {
if (Log.isLoggable(Log.FAC_REPO, Level.FINER))
Log.finer(Log.FAC_REPO, "Repo checked write request: {0}", interest.name());
if (!RepositoryOperations.verifyCheckedWrite(interest)) {
Log.warning(Log.FAC_REPO, "Repo checked write malformed request {0}", interest.name());
return;
}
ContentName target = RepositoryOperations.getCheckedWriteTarget(interest);
boolean verified = false;
RepositoryInfoObject rio = null;
ContentName unverifiedKeyLocator = null;
ContentName digestFreeTarget = new ContentName(target.count()-1, target.components());
if (_server.getRepository().hasContent(target)) {
unverifiedKeyLocator = _server.getKeyTarget(digestFreeTarget);
if (null == unverifiedKeyLocator) {
// First impl, no further checks, if we have first segment, assume we have (or are fetching)
// the whole thing
// TODO: add better verification:
// find highest segment in the store (probably a new internal interest seeking rightmost)
// getContent(): need full object in this case, verify that last segment matches segment name => verified = true
verified = true;
}
}
if (verified) {
// Send back a RepositoryInfoObject that contains a confirmation that content is already in repo
if (Log.isLoggable(Log.FAC_REPO, Level.FINER))
Log.finer(Log.FAC_REPO, "Checked write confirmed");
ArrayList<ContentName> target_names = new ArrayList<ContentName>();
target_names.add(target);
rio = _server.getRepository().getRepoInfo(interest.name(), null, target_names);
} else {
// Send back response that does not confirm content
if (Log.isLoggable(Log.FAC_REPO, Level.FINER))
Log.finer(Log.FAC_REPO, "Checked write not confirmed");
rio = _server.getRepository().getRepoInfo(interest.name(), null, null);
}
if (null == rio)
return; // Should have logged an error in getRepoInfo
// Hand the object the outstanding interest, so it can put its first block immediately.
rio.save(interest);
if (!verified) {
Interest readInterest;
+ // If we have an unverifiedKeyLocator here, we need to sync a key, but not the file itself
+ // Otherwise we have to start by syncing the file and we will check the keys later (in the
+ // DataHandler).
if (null != unverifiedKeyLocator) {
interest = Interest.constructInterest(target, _server.getExcludes(), null, 2, null, null);
readInterest = interest;
} else {
- // Create the initial read interest. Set maxSuffixComponents = minSuffixComponents = 0
+ // Create the initial read interest. Set maxSuffixComponents = minSuffixComponents = 1
// because in this SPECIAL CASE we have the complete name of the first segment.
- readInterest = Interest.constructInterest(target, _server.getExcludes(), null, 0, 0, null);
- // SPECIAL CASE: this initial interest is more specific than the standard reading interests, so
- // it will not be recognized as requesting a specific segment (segment is not final component).
- // However, until this initial interest is satisfied, there is no processing requiring standard
- // segment format, and when the first (satisfying) data arrives this interest will be immediately
- // discarded. The returned data (ContentObject) explicit name will never include the implicit
- // digest and so is processed correctly regardless of the interest that retrieved it.
+ readInterest = Interest.constructInterest(digestFreeTarget, _server.getExcludes(), null, 1, 1, null);
}
_server.getDataHandler().addSync(digestFreeTarget);
_server.doSync(interest, readInterest);
} else {
if (Log.isLoggable(Log.FAC_REPO, Level.FINER))
Log.finer(Log.FAC_REPO, "Repo checked write content verified for {0}", interest.name());
}
} catch (Exception e) {
Log.logStackTrace(Level.WARNING, e);
e.printStackTrace();
}
}
/**
* Add to the repository via file based on interest request
* @param interest
* @throws IOException
* @throws ContentEncodingException
* @throws RepositoryException
* @throws IOException
* @throws ContentEncodingException
*/
private void addBulkDataToRepo(Interest interest) throws ContentEncodingException, IOException {
int i = CommandMarker.COMMAND_MARKER_REPO_ADD_FILE.findMarker(interest.name());
if (i >= 0) {
String[] args = CommandMarker.getArguments(interest.name().component(i));
String result = "OK";
if (null != args && args.length > 0) {
try {
if (!_server.getRepository().bulkImport(args[0]))
return; // reexpression - ignore
} catch (RepositoryException e) {
Log.warning(Log.FAC_REPO, "Bulk import error : " + e.getMessage());
result = e.getMessage();
}
RepositoryInfoObject rio = _server.getRepository().getRepoInfo(interest.name(), result, null);
rio.save(interest);
}
}
}
/**
* Handle name enumeration requests
*
* @param interest
*/
public void nameEnumeratorResponse(Interest interest) {
NameEnumerationResponse ner = _server.getRepository().getNamesWithPrefix(interest, _server.getResponseName());
if (ner!=null && ner.hasNames()) {
_server.sendEnumerationResponse(ner);
_server._stats.increment(RepositoryServer.StatsEnum.HandleInterestNameEnumResponses);
if (Log.isLoggable(Log.FAC_REPO, Level.FINE))
Log.fine(Log.FAC_REPO, "sending back name enumeration response {0}", ner.getPrefix());
} else {
if (Log.isLoggable(Log.FAC_REPO, Level.FINE))
Log.fine(Log.FAC_REPO, "we are not sending back a response to the name enumeration interest (interest.name() = {0})", interest.name());
}
}
}
| false | true | private void startWriteChecked(Interest interest) {
if (isDuplicateRequest(interest)) return;
if (isWriteSuspended(interest)) return;
try {
if (Log.isLoggable(Log.FAC_REPO, Level.FINER))
Log.finer(Log.FAC_REPO, "Repo checked write request: {0}", interest.name());
if (!RepositoryOperations.verifyCheckedWrite(interest)) {
Log.warning(Log.FAC_REPO, "Repo checked write malformed request {0}", interest.name());
return;
}
ContentName target = RepositoryOperations.getCheckedWriteTarget(interest);
boolean verified = false;
RepositoryInfoObject rio = null;
ContentName unverifiedKeyLocator = null;
ContentName digestFreeTarget = new ContentName(target.count()-1, target.components());
if (_server.getRepository().hasContent(target)) {
unverifiedKeyLocator = _server.getKeyTarget(digestFreeTarget);
if (null == unverifiedKeyLocator) {
// First impl, no further checks, if we have first segment, assume we have (or are fetching)
// the whole thing
// TODO: add better verification:
// find highest segment in the store (probably a new internal interest seeking rightmost)
// getContent(): need full object in this case, verify that last segment matches segment name => verified = true
verified = true;
}
}
if (verified) {
// Send back a RepositoryInfoObject that contains a confirmation that content is already in repo
if (Log.isLoggable(Log.FAC_REPO, Level.FINER))
Log.finer(Log.FAC_REPO, "Checked write confirmed");
ArrayList<ContentName> target_names = new ArrayList<ContentName>();
target_names.add(target);
rio = _server.getRepository().getRepoInfo(interest.name(), null, target_names);
} else {
// Send back response that does not confirm content
if (Log.isLoggable(Log.FAC_REPO, Level.FINER))
Log.finer(Log.FAC_REPO, "Checked write not confirmed");
rio = _server.getRepository().getRepoInfo(interest.name(), null, null);
}
if (null == rio)
return; // Should have logged an error in getRepoInfo
// Hand the object the outstanding interest, so it can put its first block immediately.
rio.save(interest);
if (!verified) {
Interest readInterest;
if (null != unverifiedKeyLocator) {
interest = Interest.constructInterest(target, _server.getExcludes(), null, 2, null, null);
readInterest = interest;
} else {
// Create the initial read interest. Set maxSuffixComponents = minSuffixComponents = 0
// because in this SPECIAL CASE we have the complete name of the first segment.
readInterest = Interest.constructInterest(target, _server.getExcludes(), null, 0, 0, null);
// SPECIAL CASE: this initial interest is more specific than the standard reading interests, so
// it will not be recognized as requesting a specific segment (segment is not final component).
// However, until this initial interest is satisfied, there is no processing requiring standard
// segment format, and when the first (satisfying) data arrives this interest will be immediately
// discarded. The returned data (ContentObject) explicit name will never include the implicit
// digest and so is processed correctly regardless of the interest that retrieved it.
}
_server.getDataHandler().addSync(digestFreeTarget);
_server.doSync(interest, readInterest);
} else {
if (Log.isLoggable(Log.FAC_REPO, Level.FINER))
Log.finer(Log.FAC_REPO, "Repo checked write content verified for {0}", interest.name());
}
} catch (Exception e) {
Log.logStackTrace(Level.WARNING, e);
e.printStackTrace();
}
}
| private void startWriteChecked(Interest interest) {
if (isDuplicateRequest(interest)) return;
if (isWriteSuspended(interest)) return;
try {
if (Log.isLoggable(Log.FAC_REPO, Level.FINER))
Log.finer(Log.FAC_REPO, "Repo checked write request: {0}", interest.name());
if (!RepositoryOperations.verifyCheckedWrite(interest)) {
Log.warning(Log.FAC_REPO, "Repo checked write malformed request {0}", interest.name());
return;
}
ContentName target = RepositoryOperations.getCheckedWriteTarget(interest);
boolean verified = false;
RepositoryInfoObject rio = null;
ContentName unverifiedKeyLocator = null;
ContentName digestFreeTarget = new ContentName(target.count()-1, target.components());
if (_server.getRepository().hasContent(target)) {
unverifiedKeyLocator = _server.getKeyTarget(digestFreeTarget);
if (null == unverifiedKeyLocator) {
// First impl, no further checks, if we have first segment, assume we have (or are fetching)
// the whole thing
// TODO: add better verification:
// find highest segment in the store (probably a new internal interest seeking rightmost)
// getContent(): need full object in this case, verify that last segment matches segment name => verified = true
verified = true;
}
}
if (verified) {
// Send back a RepositoryInfoObject that contains a confirmation that content is already in repo
if (Log.isLoggable(Log.FAC_REPO, Level.FINER))
Log.finer(Log.FAC_REPO, "Checked write confirmed");
ArrayList<ContentName> target_names = new ArrayList<ContentName>();
target_names.add(target);
rio = _server.getRepository().getRepoInfo(interest.name(), null, target_names);
} else {
// Send back response that does not confirm content
if (Log.isLoggable(Log.FAC_REPO, Level.FINER))
Log.finer(Log.FAC_REPO, "Checked write not confirmed");
rio = _server.getRepository().getRepoInfo(interest.name(), null, null);
}
if (null == rio)
return; // Should have logged an error in getRepoInfo
// Hand the object the outstanding interest, so it can put its first block immediately.
rio.save(interest);
if (!verified) {
Interest readInterest;
// If we have an unverifiedKeyLocator here, we need to sync a key, but not the file itself
// Otherwise we have to start by syncing the file and we will check the keys later (in the
// DataHandler).
if (null != unverifiedKeyLocator) {
interest = Interest.constructInterest(target, _server.getExcludes(), null, 2, null, null);
readInterest = interest;
} else {
// Create the initial read interest. Set maxSuffixComponents = minSuffixComponents = 1
// because in this SPECIAL CASE we have the complete name of the first segment.
readInterest = Interest.constructInterest(digestFreeTarget, _server.getExcludes(), null, 1, 1, null);
}
_server.getDataHandler().addSync(digestFreeTarget);
_server.doSync(interest, readInterest);
} else {
if (Log.isLoggable(Log.FAC_REPO, Level.FINER))
Log.finer(Log.FAC_REPO, "Repo checked write content verified for {0}", interest.name());
}
} catch (Exception e) {
Log.logStackTrace(Level.WARNING, e);
e.printStackTrace();
}
}
|
diff --git a/client/gui/MapRadar.java b/client/gui/MapRadar.java
index f26ec34..6b7f9e4 100644
--- a/client/gui/MapRadar.java
+++ b/client/gui/MapRadar.java
@@ -1,150 +1,150 @@
package client.gui;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.geom.Rectangle2D;
import common.*;
import client.*;
public class MapRadar extends Widget implements MapChangeListener, Constants
{
public static final Color RADAR_COLOR = new Color(180, 180, 180, 127);
public static final Color RADAR_BACKGROUND_COLOR = new Color(200, 200, 200, 60);
protected float scale;
protected boolean showName;
protected Map map;
protected GameEngine engine;
public MapRadar(int x, int y, GameEngine engine, Map map)
{
super(x, y, 10, 10);
setMap(map);
setup();
this.engine = engine;
}
public MapRadar(int x, int y, GameEngine engine, Map map, Color c)
{
super(x, y, 10, 10, c);
setMap(map);
setup();
this.engine = engine;
}
private void setup()
{
scale = 1.0f;
showName = true;
}
public void setShowName(boolean flag)
{
showName = flag;
}
public boolean getShowName()
{
return showName;
}
public void setMap(Map map)
{
if (map == null)
return;
this.map = map;
scale = 8;
width = Math.round(scale * map.getWidth());
height = Math.round(scale * map.getHeight());
}
public Map getMap()
{
return map;
}
public void draw(Graphics2D g, int windowWidth, int windowHeight)
{
if (map == null)
return;
// Draw background
g.setColor(RADAR_BACKGROUND_COLOR);
g.fill(getFixedBounds(windowWidth, windowHeight));
// Draw walls
g.setColor(RADAR_COLOR);
final int offsetX = getFixedX(windowWidth), offsetY = getFixedY(windowHeight);
for (int x=0; x < map.getWidth(); x++)
for (int y=0; y < map.getHeight(); y++)
{
if (map.isWall(x, y))
g.fillRect(Math.round(scale * x) + offsetX,
Math.round(scale * y) + offsetY,
Math.round(scale),
Math.round(scale));
}
// TODO: Draw players:
final LocalPlayer localPlayer = engine.getLocalPlayer();
final int localID = localPlayer.getPlayerID();
float time;
int px, py;
for (Player p : engine.playerList)
{
if (p.getPlayerID() == localID || p.equals(localPlayer))
{
g.setColor(Color.green);
}
else if (p.getTeam() != TEAM_A && p.getTeam() != TEAM_B)
{
time = p.getTimeSinceLastSound();
if (time > BLIP_TIME)
continue;
g.setColor(GuiUtils.modulateColor(TEAMLESS_COLOR, 1 - (float)time/BLIP_TIME));
}
else if (p.getTeam() == localPlayer.getTeam())
{
g.setColor(Color.blue);
}
else
{
time = p.getTimeSinceLastSound();
if (time > BLIP_TIME)
continue;
g.setColor(GuiUtils.modulateColor(Color.red, 1 - (float)time/BLIP_TIME));
}
px = Math.round(p.getPosition().getX() * scale) + offsetX;
py = Math.round(p.getPosition().getY() * scale) + offsetY;
- px = Math.min(x + width, Math.max(x, px));
- py = Math.min(y + height, Math.max(y, py));
+ px = Math.min(getFixedX(windowWidth) + width, Math.max(getFixedX(windowWidth), px));
+ py = Math.min(getFixedY(windowHeight) + height, Math.max(getFixedY(windowHeight), py));
g.fillRect(px - 1, py - 1, 3, 3);
} // end if draw players
if (showName)
{
String name = map.getName();
Rectangle2D bounds = g.getFontMetrics().getStringBounds(name, g);
int xpos = x, ypos = y + height;
if (x < 0)
xpos = (int)Math.round(windowWidth - bounds.getWidth() + x - width - bounds.getX());
if (y < 0)
ypos = (int)Math.round(windowHeight - bounds.getHeight() + y - height - bounds.getY());
g.setColor(Color.yellow);
g.drawString(name, xpos, ypos);
}
} // end draw()
public void mapChanged(Map newMap)
{
setMap(newMap);
}
}
| true | true | public void draw(Graphics2D g, int windowWidth, int windowHeight)
{
if (map == null)
return;
// Draw background
g.setColor(RADAR_BACKGROUND_COLOR);
g.fill(getFixedBounds(windowWidth, windowHeight));
// Draw walls
g.setColor(RADAR_COLOR);
final int offsetX = getFixedX(windowWidth), offsetY = getFixedY(windowHeight);
for (int x=0; x < map.getWidth(); x++)
for (int y=0; y < map.getHeight(); y++)
{
if (map.isWall(x, y))
g.fillRect(Math.round(scale * x) + offsetX,
Math.round(scale * y) + offsetY,
Math.round(scale),
Math.round(scale));
}
// TODO: Draw players:
final LocalPlayer localPlayer = engine.getLocalPlayer();
final int localID = localPlayer.getPlayerID();
float time;
int px, py;
for (Player p : engine.playerList)
{
if (p.getPlayerID() == localID || p.equals(localPlayer))
{
g.setColor(Color.green);
}
else if (p.getTeam() != TEAM_A && p.getTeam() != TEAM_B)
{
time = p.getTimeSinceLastSound();
if (time > BLIP_TIME)
continue;
g.setColor(GuiUtils.modulateColor(TEAMLESS_COLOR, 1 - (float)time/BLIP_TIME));
}
else if (p.getTeam() == localPlayer.getTeam())
{
g.setColor(Color.blue);
}
else
{
time = p.getTimeSinceLastSound();
if (time > BLIP_TIME)
continue;
g.setColor(GuiUtils.modulateColor(Color.red, 1 - (float)time/BLIP_TIME));
}
px = Math.round(p.getPosition().getX() * scale) + offsetX;
py = Math.round(p.getPosition().getY() * scale) + offsetY;
px = Math.min(x + width, Math.max(x, px));
py = Math.min(y + height, Math.max(y, py));
g.fillRect(px - 1, py - 1, 3, 3);
} // end if draw players
if (showName)
{
String name = map.getName();
Rectangle2D bounds = g.getFontMetrics().getStringBounds(name, g);
int xpos = x, ypos = y + height;
if (x < 0)
xpos = (int)Math.round(windowWidth - bounds.getWidth() + x - width - bounds.getX());
if (y < 0)
ypos = (int)Math.round(windowHeight - bounds.getHeight() + y - height - bounds.getY());
g.setColor(Color.yellow);
g.drawString(name, xpos, ypos);
}
} // end draw()
| public void draw(Graphics2D g, int windowWidth, int windowHeight)
{
if (map == null)
return;
// Draw background
g.setColor(RADAR_BACKGROUND_COLOR);
g.fill(getFixedBounds(windowWidth, windowHeight));
// Draw walls
g.setColor(RADAR_COLOR);
final int offsetX = getFixedX(windowWidth), offsetY = getFixedY(windowHeight);
for (int x=0; x < map.getWidth(); x++)
for (int y=0; y < map.getHeight(); y++)
{
if (map.isWall(x, y))
g.fillRect(Math.round(scale * x) + offsetX,
Math.round(scale * y) + offsetY,
Math.round(scale),
Math.round(scale));
}
// TODO: Draw players:
final LocalPlayer localPlayer = engine.getLocalPlayer();
final int localID = localPlayer.getPlayerID();
float time;
int px, py;
for (Player p : engine.playerList)
{
if (p.getPlayerID() == localID || p.equals(localPlayer))
{
g.setColor(Color.green);
}
else if (p.getTeam() != TEAM_A && p.getTeam() != TEAM_B)
{
time = p.getTimeSinceLastSound();
if (time > BLIP_TIME)
continue;
g.setColor(GuiUtils.modulateColor(TEAMLESS_COLOR, 1 - (float)time/BLIP_TIME));
}
else if (p.getTeam() == localPlayer.getTeam())
{
g.setColor(Color.blue);
}
else
{
time = p.getTimeSinceLastSound();
if (time > BLIP_TIME)
continue;
g.setColor(GuiUtils.modulateColor(Color.red, 1 - (float)time/BLIP_TIME));
}
px = Math.round(p.getPosition().getX() * scale) + offsetX;
py = Math.round(p.getPosition().getY() * scale) + offsetY;
px = Math.min(getFixedX(windowWidth) + width, Math.max(getFixedX(windowWidth), px));
py = Math.min(getFixedY(windowHeight) + height, Math.max(getFixedY(windowHeight), py));
g.fillRect(px - 1, py - 1, 3, 3);
} // end if draw players
if (showName)
{
String name = map.getName();
Rectangle2D bounds = g.getFontMetrics().getStringBounds(name, g);
int xpos = x, ypos = y + height;
if (x < 0)
xpos = (int)Math.round(windowWidth - bounds.getWidth() + x - width - bounds.getX());
if (y < 0)
ypos = (int)Math.round(windowHeight - bounds.getHeight() + y - height - bounds.getY());
g.setColor(Color.yellow);
g.drawString(name, xpos, ypos);
}
} // end draw()
|
diff --git a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/BasicErrorController.java b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/BasicErrorController.java
index 0c64466d06..4cda5f4d77 100644
--- a/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/BasicErrorController.java
+++ b/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/web/BasicErrorController.java
@@ -1,115 +1,115 @@
/*
* Copyright 2012-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.actuate.web;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.embedded.AbstractEmbeddedServletContainerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
/**
* Basic global error {@link Controller}, rendering servlet container error codes and
* messages where available. More specific errors can be handled either using Spring MVC
* abstractions (e.g. {@code @ExceptionHandler}) or by adding servlet
* {@link AbstractEmbeddedServletContainerFactory#setErrorPages(java.util.Set) container
* error pages}.
*
* @author Dave Syer
*/
@Controller
public class BasicErrorController implements ErrorController {
private static final String ERROR_KEY = "error";
private Log logger = LogFactory.getLog(BasicErrorController.class);
@Value("${error.path:/error}")
private String errorPath;
@Override
public String getErrorPath() {
return this.errorPath;
}
@RequestMapping(value = "${error.path:/error}", produces = "text/html")
public ModelAndView errorHtml(HttpServletRequest request) {
Map<String, Object> map = error(request);
return new ModelAndView(ERROR_KEY, map);
}
@RequestMapping(value = "${error.path:/error}")
@ResponseBody
public Map<String, Object> error(HttpServletRequest request) {
Map<String, Object> map = new LinkedHashMap<String, Object>();
map.put("timestamp", new Date());
try {
Throwable error = (Throwable) request
.getAttribute("javax.servlet.error.exception");
Object obj = request.getAttribute("javax.servlet.error.status_code");
int status = 999;
if (obj != null) {
status = (Integer) obj;
map.put(ERROR_KEY, HttpStatus.valueOf(status).getReasonPhrase());
}
else {
map.put(ERROR_KEY, "None");
}
map.put("status", status);
if (error != null) {
- while (error instanceof ServletException) {
+ while (error instanceof ServletException && error.getCause() != null) {
error = ((ServletException) error).getCause();
}
map.put("exception", error.getClass().getName());
map.put("message", error.getMessage());
String trace = request.getParameter("trace");
if (trace != null && !"false".equals(trace.toLowerCase())) {
StringWriter stackTrace = new StringWriter();
error.printStackTrace(new PrintWriter(stackTrace));
stackTrace.flush();
map.put("trace", stackTrace.toString());
}
this.logger.error(error);
}
else {
Object message = request.getAttribute("javax.servlet.error.message");
map.put("message", message == null ? "No message available" : message);
}
return map;
}
catch (Exception ex) {
map.put(ERROR_KEY, ex.getClass().getName());
map.put("message", ex.getMessage());
this.logger.error(ex);
return map;
}
}
}
| true | true | public Map<String, Object> error(HttpServletRequest request) {
Map<String, Object> map = new LinkedHashMap<String, Object>();
map.put("timestamp", new Date());
try {
Throwable error = (Throwable) request
.getAttribute("javax.servlet.error.exception");
Object obj = request.getAttribute("javax.servlet.error.status_code");
int status = 999;
if (obj != null) {
status = (Integer) obj;
map.put(ERROR_KEY, HttpStatus.valueOf(status).getReasonPhrase());
}
else {
map.put(ERROR_KEY, "None");
}
map.put("status", status);
if (error != null) {
while (error instanceof ServletException) {
error = ((ServletException) error).getCause();
}
map.put("exception", error.getClass().getName());
map.put("message", error.getMessage());
String trace = request.getParameter("trace");
if (trace != null && !"false".equals(trace.toLowerCase())) {
StringWriter stackTrace = new StringWriter();
error.printStackTrace(new PrintWriter(stackTrace));
stackTrace.flush();
map.put("trace", stackTrace.toString());
}
this.logger.error(error);
}
else {
Object message = request.getAttribute("javax.servlet.error.message");
map.put("message", message == null ? "No message available" : message);
}
return map;
}
catch (Exception ex) {
map.put(ERROR_KEY, ex.getClass().getName());
map.put("message", ex.getMessage());
this.logger.error(ex);
return map;
}
}
| public Map<String, Object> error(HttpServletRequest request) {
Map<String, Object> map = new LinkedHashMap<String, Object>();
map.put("timestamp", new Date());
try {
Throwable error = (Throwable) request
.getAttribute("javax.servlet.error.exception");
Object obj = request.getAttribute("javax.servlet.error.status_code");
int status = 999;
if (obj != null) {
status = (Integer) obj;
map.put(ERROR_KEY, HttpStatus.valueOf(status).getReasonPhrase());
}
else {
map.put(ERROR_KEY, "None");
}
map.put("status", status);
if (error != null) {
while (error instanceof ServletException && error.getCause() != null) {
error = ((ServletException) error).getCause();
}
map.put("exception", error.getClass().getName());
map.put("message", error.getMessage());
String trace = request.getParameter("trace");
if (trace != null && !"false".equals(trace.toLowerCase())) {
StringWriter stackTrace = new StringWriter();
error.printStackTrace(new PrintWriter(stackTrace));
stackTrace.flush();
map.put("trace", stackTrace.toString());
}
this.logger.error(error);
}
else {
Object message = request.getAttribute("javax.servlet.error.message");
map.put("message", message == null ? "No message available" : message);
}
return map;
}
catch (Exception ex) {
map.put(ERROR_KEY, ex.getClass().getName());
map.put("message", ex.getMessage());
this.logger.error(ex);
return map;
}
}
|
diff --git a/cloud/cloud-utils/src/main/java/org/openinfinity/cloud/util/credentials/ProviderCredentialsImpl.java b/cloud/cloud-utils/src/main/java/org/openinfinity/cloud/util/credentials/ProviderCredentialsImpl.java
index 2588b1a0..a90b3c27 100644
--- a/cloud/cloud-utils/src/main/java/org/openinfinity/cloud/util/credentials/ProviderCredentialsImpl.java
+++ b/cloud/cloud-utils/src/main/java/org/openinfinity/cloud/util/credentials/ProviderCredentialsImpl.java
@@ -1,52 +1,52 @@
/*
* Copyright (c) 2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openinfinity.cloud.util.credentials;
import org.jets3t.service.security.ProviderCredentials;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.Profile;
/**
* Provider credentials extension for accessing infrastructure services.
*
* @author Ilkka Leinonen
* @version 1.0.0
* @since 1.0.0
*/
@Configuration
@Profile("jets3t")
@ImportResource("classpath:/META-INF/spring/cloud-infrastructure-configuration.xml")
public class ProviderCredentialsImpl extends ProviderCredentials {
- public ProviderCredentialsImpl(@Value("${accesskeyid}") String accessKey, @Value("${secretkey}") String secretKey) {
+ public ProviderCredentialsImpl(@Value("${eucaaccesskeyid}") String accessKey, @Value("${eucasecretkey}") String secretKey) {
super(accessKey, secretKey);
}
@Override
protected String getTypeName() {
return "";
}
@Override
protected String getVersionPrefix() {
return V3_KEYS_DELIMITER;
}
}
| true | true | public ProviderCredentialsImpl(@Value("${accesskeyid}") String accessKey, @Value("${secretkey}") String secretKey) {
super(accessKey, secretKey);
}
| public ProviderCredentialsImpl(@Value("${eucaaccesskeyid}") String accessKey, @Value("${eucasecretkey}") String secretKey) {
super(accessKey, secretKey);
}
|
diff --git a/main/Board.java b/main/Board.java
index 89f5108..e13378e 100644
--- a/main/Board.java
+++ b/main/Board.java
@@ -1,92 +1,92 @@
package main;
/**
* @author boaz, September 2010
* @version 1.0
*/
public class Board {
/**
* Board game - private array of chars
*/
private char[] locate;
/**
* Constructor for class Board - only initialize locate array
*/
public Board()
{
locate = new char[9];
locate[0]='1';
locate[1]='2';
locate[2]='3';
locate[3]='4';
locate[4]='5';
locate[5]='6';
locate[6]='7';
locate[7]='8';
locate[8]='9';
}
/**
* This function just print the board to standard output.
*
*/
public void PrintBoard()
{
System.out.println(locate[0] + "|" + locate[1] + "|" + locate[2]);
System.out.println("-----");
System.out.println(locate[3] + "|" + locate[4] + "|" + locate[5]);
System.out.println("-----");
System.out.println(locate[6] + "|" + locate[7] + "|" + locate[8]);
}
/**
*
* @param i - The locate that we want to get.
* @return The value in locate i.
*/
public char getLocateValue(int i)
{
return locate[i];
}
/**
*
* @param i - The locate that we want to change
* @param value - Value to set to locate i
*/
public void setLocateValue(int i, char value)
{
locate[i] = value;
}
/**
*
* @return true if have a winner in this board, false otherwise.
*/
public boolean isWin()
{
if ( (locate[0] == locate[1] && locate[1] == locate[2]) || //0-1-2 (first row)
(locate[3] == locate[4] && locate[4] == locate[5]) || //3-4-5 (second row)
(locate[6] == locate[7] && locate[7] == locate[8]) || //6-7-8 (third row)
(locate[0] == locate[3] && locate[3] == locate[6]) || //0-3-6 (left column)
(locate[1] == locate[4] && locate[4] == locate[7]) || //1-4-7 (center column)
(locate[2] == locate[5] && locate[5] == locate[8]) || //2-5-8 (right column)
- (locate[0] == locate[1] && locate[1] == locate[2]) || //0-4-8 (left-up diagonal)
- (locate[0] == locate[1] && locate[1] == locate[2]) ) //2-4-6 (left-down diagonal)
+ (locate[0] == locate[4] && locate[4] == locate[8]) || //0-4-8 (left-up diagonal)
+ (locate[2] == locate[4] && locate[4] == locate[6]) ) //2-4-6 (left-down diagonal)
return true;
else
return false;
}
/**
*
* @return
*/
public int[] getEmpty() {
// TODO Auto-generated method stub
return null;
}
}
| true | true | public boolean isWin()
{
if ( (locate[0] == locate[1] && locate[1] == locate[2]) || //0-1-2 (first row)
(locate[3] == locate[4] && locate[4] == locate[5]) || //3-4-5 (second row)
(locate[6] == locate[7] && locate[7] == locate[8]) || //6-7-8 (third row)
(locate[0] == locate[3] && locate[3] == locate[6]) || //0-3-6 (left column)
(locate[1] == locate[4] && locate[4] == locate[7]) || //1-4-7 (center column)
(locate[2] == locate[5] && locate[5] == locate[8]) || //2-5-8 (right column)
(locate[0] == locate[1] && locate[1] == locate[2]) || //0-4-8 (left-up diagonal)
(locate[0] == locate[1] && locate[1] == locate[2]) ) //2-4-6 (left-down diagonal)
return true;
else
return false;
}
| public boolean isWin()
{
if ( (locate[0] == locate[1] && locate[1] == locate[2]) || //0-1-2 (first row)
(locate[3] == locate[4] && locate[4] == locate[5]) || //3-4-5 (second row)
(locate[6] == locate[7] && locate[7] == locate[8]) || //6-7-8 (third row)
(locate[0] == locate[3] && locate[3] == locate[6]) || //0-3-6 (left column)
(locate[1] == locate[4] && locate[4] == locate[7]) || //1-4-7 (center column)
(locate[2] == locate[5] && locate[5] == locate[8]) || //2-5-8 (right column)
(locate[0] == locate[4] && locate[4] == locate[8]) || //0-4-8 (left-up diagonal)
(locate[2] == locate[4] && locate[4] == locate[6]) ) //2-4-6 (left-down diagonal)
return true;
else
return false;
}
|
diff --git a/src/test/java/org/atlasapi/remotesite/channel4/C4AtoZAtomAdapterTest.java b/src/test/java/org/atlasapi/remotesite/channel4/C4AtoZAtomAdapterTest.java
index 3b8cb20f1..608c261d4 100644
--- a/src/test/java/org/atlasapi/remotesite/channel4/C4AtoZAtomAdapterTest.java
+++ b/src/test/java/org/atlasapi/remotesite/channel4/C4AtoZAtomAdapterTest.java
@@ -1,78 +1,78 @@
/* Copyright 2009 Meta Broadcast 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.atlasapi.remotesite.channel4;
import org.atlasapi.media.entity.Brand;
import org.atlasapi.media.entity.Playlist;
import org.atlasapi.media.entity.Publisher;
import org.atlasapi.persistence.content.ContentWriter;
import org.atlasapi.persistence.logging.NullAdapterLog;
import org.atlasapi.persistence.system.RemoteSiteClient;
import org.atlasapi.remotesite.SiteSpecificAdapter;
import org.jmock.Expectations;
import org.jmock.integration.junit3.MockObjectTestCase;
import com.google.common.io.Resources;
import com.sun.syndication.feed.atom.Feed;
/**
* Unit test for {@link C4AtoZAtomContentLoader}.
*
* @author Robert Chatley ([email protected])
*/
public class C4AtoZAtomAdapterTest extends MockObjectTestCase {
String uri = "http://www.channel4.com/programmes/atoz/a";
private SiteSpecificAdapter<Brand> brandAdapter;
private RemoteSiteClient<Feed> itemClient;
private C4AtoZAtomContentLoader adapter;
private ContentWriter writer;
Brand brand101 = new Brand("http://www.channel4.com/programmes/a-bipolar-expedition", "curie:101", Publisher.C4);
Brand brand202 = new Brand("http://www.channel4.com/programmes/a-bipolar-expedition-part-2", "curie:202", Publisher.C4);
private final AtomFeedBuilder atoza = new AtomFeedBuilder(Resources.getResource(getClass(), "a.atom"));
private final AtomFeedBuilder atoza2 = new AtomFeedBuilder(Resources.getResource(getClass(), "a2.atom"));
@SuppressWarnings("unchecked")
@Override
protected void setUp() throws Exception {
super.setUp();
brandAdapter = mock(SiteSpecificAdapter.class);
itemClient = mock(RemoteSiteClient.class);
writer = mock(ContentWriter.class);
adapter = new C4AtoZAtomContentLoader(itemClient, brandAdapter, writer, null, new NullAdapterLog());
}
public void testPerformsGetCorrespondingGivenUriAndPassesResultToExtractor() throws Exception {
checking(new Expectations() {{
one(itemClient).get("http://api.channel4.com/programmes/atoz/a.atom"); will(returnValue(atoza.build()));
one(itemClient).get("http://api.channel4.com/programmes/atoz/a/page-2.atom"); will(returnValue(atoza2.build()));
one(writer).createOrUpdatePlaylist(brand101, true);
one(writer).createOrUpdatePlaylist(brand202, true);
- one(writer).createOrUpdatePlaylist(new Playlist(uri, null), true);
+ one(writer).createOrUpdatePlaylistSkeleton(new Playlist(uri, null));
allowing(brandAdapter).fetch("http://www.channel4.com/programmes/a-bipolar-expedition"); will(returnValue(brand101));
allowing(brandAdapter).fetch("http://www.channel4.com/programmes/a-bipolar-expedition-part-2"); will(returnValue(brand202));
allowing(brandAdapter).canFetch("http://www.channel4.com/programmes/a-bipolar-expedition"); will(returnValue(true));
allowing(brandAdapter).canFetch("http://www.channel4.com/programmes/a-bipolar-expedition-part-2"); will(returnValue(true));
}});
adapter.loadAndSaveByLetter("a");
}
}
| true | true | public void testPerformsGetCorrespondingGivenUriAndPassesResultToExtractor() throws Exception {
checking(new Expectations() {{
one(itemClient).get("http://api.channel4.com/programmes/atoz/a.atom"); will(returnValue(atoza.build()));
one(itemClient).get("http://api.channel4.com/programmes/atoz/a/page-2.atom"); will(returnValue(atoza2.build()));
one(writer).createOrUpdatePlaylist(brand101, true);
one(writer).createOrUpdatePlaylist(brand202, true);
one(writer).createOrUpdatePlaylist(new Playlist(uri, null), true);
allowing(brandAdapter).fetch("http://www.channel4.com/programmes/a-bipolar-expedition"); will(returnValue(brand101));
allowing(brandAdapter).fetch("http://www.channel4.com/programmes/a-bipolar-expedition-part-2"); will(returnValue(brand202));
allowing(brandAdapter).canFetch("http://www.channel4.com/programmes/a-bipolar-expedition"); will(returnValue(true));
allowing(brandAdapter).canFetch("http://www.channel4.com/programmes/a-bipolar-expedition-part-2"); will(returnValue(true));
}});
adapter.loadAndSaveByLetter("a");
}
| public void testPerformsGetCorrespondingGivenUriAndPassesResultToExtractor() throws Exception {
checking(new Expectations() {{
one(itemClient).get("http://api.channel4.com/programmes/atoz/a.atom"); will(returnValue(atoza.build()));
one(itemClient).get("http://api.channel4.com/programmes/atoz/a/page-2.atom"); will(returnValue(atoza2.build()));
one(writer).createOrUpdatePlaylist(brand101, true);
one(writer).createOrUpdatePlaylist(brand202, true);
one(writer).createOrUpdatePlaylistSkeleton(new Playlist(uri, null));
allowing(brandAdapter).fetch("http://www.channel4.com/programmes/a-bipolar-expedition"); will(returnValue(brand101));
allowing(brandAdapter).fetch("http://www.channel4.com/programmes/a-bipolar-expedition-part-2"); will(returnValue(brand202));
allowing(brandAdapter).canFetch("http://www.channel4.com/programmes/a-bipolar-expedition"); will(returnValue(true));
allowing(brandAdapter).canFetch("http://www.channel4.com/programmes/a-bipolar-expedition-part-2"); will(returnValue(true));
}});
adapter.loadAndSaveByLetter("a");
}
|
diff --git a/src/com/arantius/tivocommander/Upcoming.java b/src/com/arantius/tivocommander/Upcoming.java
index 3fcc642..1d930dc 100644
--- a/src/com/arantius/tivocommander/Upcoming.java
+++ b/src/com/arantius/tivocommander/Upcoming.java
@@ -1,178 +1,178 @@
/*
TiVo Commander allows control of a TiVo Premiere device.
Copyright (C) 2011 Anthony Lieuallen ([email protected])
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
package com.arantius.tivocommander;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.TimeZone;
import org.codehaus.jackson.JsonNode;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import com.arantius.tivocommander.rpc.MindRpc;
import com.arantius.tivocommander.rpc.request.UpcomingSearch;
import com.arantius.tivocommander.rpc.response.MindRpcResponse;
import com.arantius.tivocommander.rpc.response.MindRpcResponseListener;
public class Upcoming extends ListActivity {
private class DateInPast extends Throwable {
private static final long serialVersionUID = -4184008452910054505L;
}
private final OnItemClickListener mOnClickListener =
new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
JsonNode show = mShows.path(position);
Intent intent = new Intent(Upcoming.this, ExploreTabs.class);
intent.putExtra("contentId", show.path("contentId").getTextValue());
intent.putExtra("collectionId", show.path("collectionId")
.getTextValue());
intent.putExtra("offerId", show.path("offerId").getTextValue());
startActivity(intent);
}
};
private final MindRpcResponseListener mUpcomingListener =
new MindRpcResponseListener() {
public void onResponse(MindRpcResponse response) {
setProgressBarIndeterminateVisibility(false);
findViewById(android.R.id.empty).setVisibility(View.VISIBLE);
mShows = response.getBody().path("offer");
List<HashMap<String, Object>> listItems =
new ArrayList<HashMap<String, Object>>();
for (int i = 0; i < mShows.size(); i++) {
final JsonNode item = mShows.path(i);
try {
HashMap<String, Object> listItem = new HashMap<String, Object>();
String channelNum =
item.path("channel").path("channelNumber").getTextValue();
String callSign =
item.path("channel").path("callSign").getTextValue();
String details =
String.format("%s %s %s", formatTime(item), channelNum,
callSign);
if (item.path("episodic").getBooleanValue()
- && item.path("episodeNumber").path(0).getIntValue() > 0
+ && item.path("episodeNum").path(0).getIntValue() > 0
&& item.path("seasonNumber").getIntValue() > 0) {
details =
String.format("(Sea %d Ep %d) ", item.path("seasonNumber")
.getIntValue(), item.path("episodeNum").path(0)
.getIntValue())
+ details;
}
listItem.put("icon", R.drawable.blank);
if (item.has("recordingForOfferId")) {
listItem.put("icon", R.drawable.check);
}
listItem.put("details", details);
listItem.put("title", item.has("subtitle") ? item
.path("subtitle").getTextValue() : item.path("title")
.getTextValue());
listItems.add(listItem);
} catch (DateInPast e) {
// No-op. Just don't show past items.
}
}
final ListView lv = getListView();
lv.setAdapter(new SimpleAdapter(Upcoming.this, listItems,
R.layout.item_upcoming,
new String[] { "details", "icon", "title" }, new int[] {
R.id.upcoming_details, R.id.upcoming_icon,
R.id.upcoming_title }));
lv.setOnItemClickListener(mOnClickListener);
}
};
protected JsonNode mShows;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MindRpc.init(this);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.list_empty);
findViewById(android.R.id.empty).setVisibility(View.GONE);
Bundle bundle = getIntent().getExtras();
String collectionId = null;
if (bundle != null) {
collectionId = bundle.getString("collectionId");
if (collectionId == null) {
Toast.makeText(getApplicationContext(), "Oops; missing collection ID",
Toast.LENGTH_SHORT).show();
} else {
setProgressBarIndeterminateVisibility(true);
UpcomingSearch request = new UpcomingSearch(collectionId);
MindRpc.addRequest(request, mUpcomingListener);
}
}
Utils.log(String.format("Upcoming: collectionId:%s", collectionId));
}
@Override
protected void onResume() {
super.onResume();
Utils.log("Activity:Resume:Upcoming");
MindRpc.init(this);
}
protected String formatTime(JsonNode item) throws DateInPast {
String timeIn = item.path("startTime").getTextValue();
if (timeIn == null) {
return null;
}
Date playTime = Utils.parseDateTimeStr(timeIn);
if (playTime.before(new Date())) {
throw new DateInPast();
}
SimpleDateFormat dateFormatter = new SimpleDateFormat("EEE M/d hh:mm a");
dateFormatter.setTimeZone(TimeZone.getDefault());
return dateFormatter.format(playTime);
}
@Override
protected void onPause() {
super.onPause();
Utils.log("Activity:Pause:Upcoming");
}
}
| true | true | public void onResponse(MindRpcResponse response) {
setProgressBarIndeterminateVisibility(false);
findViewById(android.R.id.empty).setVisibility(View.VISIBLE);
mShows = response.getBody().path("offer");
List<HashMap<String, Object>> listItems =
new ArrayList<HashMap<String, Object>>();
for (int i = 0; i < mShows.size(); i++) {
final JsonNode item = mShows.path(i);
try {
HashMap<String, Object> listItem = new HashMap<String, Object>();
String channelNum =
item.path("channel").path("channelNumber").getTextValue();
String callSign =
item.path("channel").path("callSign").getTextValue();
String details =
String.format("%s %s %s", formatTime(item), channelNum,
callSign);
if (item.path("episodic").getBooleanValue()
&& item.path("episodeNumber").path(0).getIntValue() > 0
&& item.path("seasonNumber").getIntValue() > 0) {
details =
String.format("(Sea %d Ep %d) ", item.path("seasonNumber")
.getIntValue(), item.path("episodeNum").path(0)
.getIntValue())
+ details;
}
listItem.put("icon", R.drawable.blank);
if (item.has("recordingForOfferId")) {
listItem.put("icon", R.drawable.check);
}
listItem.put("details", details);
listItem.put("title", item.has("subtitle") ? item
.path("subtitle").getTextValue() : item.path("title")
.getTextValue());
listItems.add(listItem);
} catch (DateInPast e) {
// No-op. Just don't show past items.
}
}
final ListView lv = getListView();
lv.setAdapter(new SimpleAdapter(Upcoming.this, listItems,
R.layout.item_upcoming,
new String[] { "details", "icon", "title" }, new int[] {
R.id.upcoming_details, R.id.upcoming_icon,
R.id.upcoming_title }));
lv.setOnItemClickListener(mOnClickListener);
}
| public void onResponse(MindRpcResponse response) {
setProgressBarIndeterminateVisibility(false);
findViewById(android.R.id.empty).setVisibility(View.VISIBLE);
mShows = response.getBody().path("offer");
List<HashMap<String, Object>> listItems =
new ArrayList<HashMap<String, Object>>();
for (int i = 0; i < mShows.size(); i++) {
final JsonNode item = mShows.path(i);
try {
HashMap<String, Object> listItem = new HashMap<String, Object>();
String channelNum =
item.path("channel").path("channelNumber").getTextValue();
String callSign =
item.path("channel").path("callSign").getTextValue();
String details =
String.format("%s %s %s", formatTime(item), channelNum,
callSign);
if (item.path("episodic").getBooleanValue()
&& item.path("episodeNum").path(0).getIntValue() > 0
&& item.path("seasonNumber").getIntValue() > 0) {
details =
String.format("(Sea %d Ep %d) ", item.path("seasonNumber")
.getIntValue(), item.path("episodeNum").path(0)
.getIntValue())
+ details;
}
listItem.put("icon", R.drawable.blank);
if (item.has("recordingForOfferId")) {
listItem.put("icon", R.drawable.check);
}
listItem.put("details", details);
listItem.put("title", item.has("subtitle") ? item
.path("subtitle").getTextValue() : item.path("title")
.getTextValue());
listItems.add(listItem);
} catch (DateInPast e) {
// No-op. Just don't show past items.
}
}
final ListView lv = getListView();
lv.setAdapter(new SimpleAdapter(Upcoming.this, listItems,
R.layout.item_upcoming,
new String[] { "details", "icon", "title" }, new int[] {
R.id.upcoming_details, R.id.upcoming_icon,
R.id.upcoming_title }));
lv.setOnItemClickListener(mOnClickListener);
}
|
diff --git a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/BreakpointMarkerUpdater.java b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/BreakpointMarkerUpdater.java
index 61f98efd7..1d027badc 100644
--- a/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/BreakpointMarkerUpdater.java
+++ b/org.eclipse.jdt.debug.ui/ui/org/eclipse/jdt/internal/debug/ui/BreakpointMarkerUpdater.java
@@ -1,89 +1,93 @@
/*******************************************************************************
* Copyright (c) 2006 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.jdt.internal.debug.ui;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jdt.core.dom.AST;
import org.eclipse.jdt.core.dom.ASTParser;
import org.eclipse.jdt.core.dom.CompilationUnit;
import org.eclipse.jdt.internal.debug.ui.actions.ValidBreakpointLocationLocator;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.Position;
import org.eclipse.ui.texteditor.IMarkerUpdater;
/**
* This class provides a mechanism to correct the placement of a
* breakpoint marker when the related document is edited.
*
* This updater is used to cover the line number discrepency cases that <code>BasicMarkerUpdater</code> does not:
* <ul>
* <li>If you insert a blank line at the start of the line of code, the breakpoint
* is moved from the blank line to the next viable line down,
* following the same breakpoint placement rules as creating a breakpoint</li>
*
* <li>If you select the contents of an entire line and delete them
* (leaving the line blank), the breakpoint is moved to the next viable line down,
* following the same breakpoint placement rules as creating a breakpoint</li>
*
* <li>If the breakpoint is on the last viable line of a class file and the line is removed via either of
* the aforementioned deletion cases, the breakpoint is removed</li>
*
* <li>In the general deletion case if a valid breakpoint location can not be determined, it is removed</li>
* </ul>
*
* @since 3.3
*/
public class BreakpointMarkerUpdater implements IMarkerUpdater {
public BreakpointMarkerUpdater() {}
/* (non-Javadoc)
* @see org.eclipse.ui.texteditor.IMarkerUpdater#getAttribute()
*/
public String[] getAttribute() {
return new String[] {IMarker.LINE_NUMBER};
}
/* (non-Javadoc)
* @see org.eclipse.ui.texteditor.IMarkerUpdater#getMarkerType()
*/
public String getMarkerType() {
return "org.eclipse.debug.core.breakpointMarker"; //$NON-NLS-1$
}
/* (non-Javadoc)
* @see org.eclipse.ui.texteditor.IMarkerUpdater#updateMarker(org.eclipse.core.resources.IMarker, org.eclipse.jface.text.IDocument, org.eclipse.jface.text.Position)
*/
public boolean updateMarker(IMarker marker, IDocument document, Position position) {
if(position.isDeleted()) {
return false;
}
ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setSource(document.get().toCharArray());
CompilationUnit unit = (CompilationUnit) parser.createAST(null);
if(unit != null) {
try {
ValidBreakpointLocationLocator loc = new ValidBreakpointLocationLocator(unit, document.getLineOfOffset(position.getOffset())+1, true, true);
unit.accept(loc);
if(loc.getLocationType() == ValidBreakpointLocationLocator.LOCATION_NOT_FOUND) {
return false;
}
+ //if the line number is already good, perform no resource updating
+ if(marker.getAttribute(IMarker.LINE_NUMBER, -1) == loc.getLineLocation()) {
+ return true;
+ }
marker.setAttribute(IMarker.LINE_NUMBER, loc.getLineLocation());
return true;
}
catch (BadLocationException e) {JDIDebugUIPlugin.log(e);}
catch (CoreException e) {JDIDebugUIPlugin.log(e);}
}
return false;
}
}
| true | true | public boolean updateMarker(IMarker marker, IDocument document, Position position) {
if(position.isDeleted()) {
return false;
}
ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setSource(document.get().toCharArray());
CompilationUnit unit = (CompilationUnit) parser.createAST(null);
if(unit != null) {
try {
ValidBreakpointLocationLocator loc = new ValidBreakpointLocationLocator(unit, document.getLineOfOffset(position.getOffset())+1, true, true);
unit.accept(loc);
if(loc.getLocationType() == ValidBreakpointLocationLocator.LOCATION_NOT_FOUND) {
return false;
}
marker.setAttribute(IMarker.LINE_NUMBER, loc.getLineLocation());
return true;
}
catch (BadLocationException e) {JDIDebugUIPlugin.log(e);}
catch (CoreException e) {JDIDebugUIPlugin.log(e);}
}
return false;
}
| public boolean updateMarker(IMarker marker, IDocument document, Position position) {
if(position.isDeleted()) {
return false;
}
ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setSource(document.get().toCharArray());
CompilationUnit unit = (CompilationUnit) parser.createAST(null);
if(unit != null) {
try {
ValidBreakpointLocationLocator loc = new ValidBreakpointLocationLocator(unit, document.getLineOfOffset(position.getOffset())+1, true, true);
unit.accept(loc);
if(loc.getLocationType() == ValidBreakpointLocationLocator.LOCATION_NOT_FOUND) {
return false;
}
//if the line number is already good, perform no resource updating
if(marker.getAttribute(IMarker.LINE_NUMBER, -1) == loc.getLineLocation()) {
return true;
}
marker.setAttribute(IMarker.LINE_NUMBER, loc.getLineLocation());
return true;
}
catch (BadLocationException e) {JDIDebugUIPlugin.log(e);}
catch (CoreException e) {JDIDebugUIPlugin.log(e);}
}
return false;
}
|
diff --git a/net/sourceforge/frcsimulator/Client.java b/net/sourceforge/frcsimulator/Client.java
index 13080e9..f7f7adc 100644
--- a/net/sourceforge/frcsimulator/Client.java
+++ b/net/sourceforge/frcsimulator/Client.java
@@ -1,119 +1,119 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package net.sourceforge.frcsimulator;
import java.awt.GraphicsEnvironment;
import java.util.logging.SimpleFormatter;
import java.util.logging.StreamHandler;
import javax.swing.SwingUtilities;
import net.sourceforge.frcsimulator.Arguments;
import net.sourceforge.frcsimulator.gui.SimulatorControlFrame;
import net.sourceforge.frcsimulator.gui.SimulatorDriverStation;
import net.sourceforge.frcsimulator.internals.CRIO;
import net.sourceforge.frcsimulator.internals.CRIOModule;
import net.sourceforge.frcsimulator.internals.ModuleException;
import net.sourceforge.frcsimulator.mistware.Simulator;
/**
*
* @author wolf
*/
public class Client {
public static final int E_NONE = 0, E_BADARGS = 2, E_SIMFAIL = 5;
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Arguments arguments = new Arguments(args);
boolean gui = !GraphicsEnvironment.isHeadless();
// Process arguments
if(arguments.get("gui") != null || arguments.get("g") != null) gui=true;
if(arguments.get("cli") != null || arguments.get("c") != null) gui=false;
String testCase = arguments.get("simulate") != null ? arguments.get("simulate")[0] : (arguments.get("s") != null ? arguments.get("s")[0] : "net.sourceforge.frcsimulator.test.FRCBotRobotBase");
try {
if(arguments.get("analog") !=null){
for(int i = 0; i < arguments.get("analog").length;i++){
CRIO.getInstance().addModule(new CRIOModule(0x01), Integer.parseInt(arguments.get("analog")[i])-1);
}
}
if(arguments.get("digital") !=null){
for(int i = 0; i < arguments.get("digital").length;i++){
CRIO.getInstance().addModule(new CRIOModule(0x02), Integer.parseInt(arguments.get("digital")[i])-1);
}
}
if(arguments.get("solenoid") !=null){
for(int i = 0; i < arguments.get("solenoid").length;i++){
CRIO.getInstance().addModule(new CRIOModule(0x03), Integer.parseInt(arguments.get("solenoid")[i])-1);
}
}
- CRIO.getInstance().addModule(new CRIOModule(0x01), 1);
+ CRIO.getInstance().addModule(new CRIOModule(0x01), 0);
} catch (ModuleException ex) {
ex.printStackTrace();
}
if (gui) {
simulatorGui(testCase);
} else {
simulatorCli(testCase);
}
}
public static void simulatorCli(String testCase) {
Simulator simulator;
try {
simulator = new Simulator(testCase);
} catch (ClassNotFoundException ex) {
System.err.println("The simulator couldn't find the given class!");
ex.printStackTrace();
System.exit(E_BADARGS); // Bad arguments
return; // Needed so NetBeans won't complain about simulator being unitinitalized.
}
simulator.getLogger().addHandler(new StreamHandler(System.out, new SimpleFormatter()));
try {
simulator.onStatusChange(Client.class.getMethod("simStateChangeCli", Simulator.Status.class, Simulator.Status.class));
} catch (Exception e) {
System.err.println("Oops, couldn't add a status change hook to the simulator.");
e.printStackTrace();
}
simulator.start();
try {
simulator.join();
} catch (InterruptedException e) {
System.err.println("Interrupted while join()ing simulator:");
e.printStackTrace();
}
if (simulator.getStatus() == Simulator.Status.ERROR) {
System.exit(E_SIMFAIL); // Abnormal simulator failure
}
System.exit(E_NONE);
}
public static void simStateChangeCli(Simulator.Status status, Simulator.Status oldStatus) {
System.out.println("Simulator status: " + status.toString());
}
private static void simulatorGui(final String testCase) {
final Object lock = new Object();
synchronized (lock) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
SimulatorControlFrame simulatorControlFrame = new SimulatorControlFrame(testCase);
SimulatorDriverStation simulatorDriverStation = new SimulatorDriverStation(testCase);
synchronized (lock) {
lock.notify();
}
}
});
try {
lock.wait();
} catch (InterruptedException ex) {
System.exit(2);
}
}
}
}
| true | true | public static void main(String[] args) {
Arguments arguments = new Arguments(args);
boolean gui = !GraphicsEnvironment.isHeadless();
// Process arguments
if(arguments.get("gui") != null || arguments.get("g") != null) gui=true;
if(arguments.get("cli") != null || arguments.get("c") != null) gui=false;
String testCase = arguments.get("simulate") != null ? arguments.get("simulate")[0] : (arguments.get("s") != null ? arguments.get("s")[0] : "net.sourceforge.frcsimulator.test.FRCBotRobotBase");
try {
if(arguments.get("analog") !=null){
for(int i = 0; i < arguments.get("analog").length;i++){
CRIO.getInstance().addModule(new CRIOModule(0x01), Integer.parseInt(arguments.get("analog")[i])-1);
}
}
if(arguments.get("digital") !=null){
for(int i = 0; i < arguments.get("digital").length;i++){
CRIO.getInstance().addModule(new CRIOModule(0x02), Integer.parseInt(arguments.get("digital")[i])-1);
}
}
if(arguments.get("solenoid") !=null){
for(int i = 0; i < arguments.get("solenoid").length;i++){
CRIO.getInstance().addModule(new CRIOModule(0x03), Integer.parseInt(arguments.get("solenoid")[i])-1);
}
}
CRIO.getInstance().addModule(new CRIOModule(0x01), 1);
} catch (ModuleException ex) {
ex.printStackTrace();
}
if (gui) {
simulatorGui(testCase);
} else {
simulatorCli(testCase);
}
}
| public static void main(String[] args) {
Arguments arguments = new Arguments(args);
boolean gui = !GraphicsEnvironment.isHeadless();
// Process arguments
if(arguments.get("gui") != null || arguments.get("g") != null) gui=true;
if(arguments.get("cli") != null || arguments.get("c") != null) gui=false;
String testCase = arguments.get("simulate") != null ? arguments.get("simulate")[0] : (arguments.get("s") != null ? arguments.get("s")[0] : "net.sourceforge.frcsimulator.test.FRCBotRobotBase");
try {
if(arguments.get("analog") !=null){
for(int i = 0; i < arguments.get("analog").length;i++){
CRIO.getInstance().addModule(new CRIOModule(0x01), Integer.parseInt(arguments.get("analog")[i])-1);
}
}
if(arguments.get("digital") !=null){
for(int i = 0; i < arguments.get("digital").length;i++){
CRIO.getInstance().addModule(new CRIOModule(0x02), Integer.parseInt(arguments.get("digital")[i])-1);
}
}
if(arguments.get("solenoid") !=null){
for(int i = 0; i < arguments.get("solenoid").length;i++){
CRIO.getInstance().addModule(new CRIOModule(0x03), Integer.parseInt(arguments.get("solenoid")[i])-1);
}
}
CRIO.getInstance().addModule(new CRIOModule(0x01), 0);
} catch (ModuleException ex) {
ex.printStackTrace();
}
if (gui) {
simulatorGui(testCase);
} else {
simulatorCli(testCase);
}
}
|
diff --git a/PortParser/thcsw002Parser.java b/PortParser/thcsw002Parser.java
index 9ee13f4..67c3194 100644
--- a/PortParser/thcsw002Parser.java
+++ b/PortParser/thcsw002Parser.java
@@ -1,335 +1,346 @@
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import javax.swing.BoxLayout;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollBar;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
public class thcsw002Parser implements ActionListener {
/* Main file IO */
private BufferedReader diskFile;
private String regex = ";"; // Query delimeter
/* Main File Opener GUI */
private JFrame serverWindow = new JFrame("FileParser for Switches");
private JPanel mainPanel = new JPanel();
private JPanel btnPanel = new JPanel();
private JTextArea outTextArea = new JTextArea(21,36);
// private JButton closeButton = new JButton("Close");
// private JButton saveButton = new JButton("Save...");
private String newLine = System.getProperty("line.separator");
private JScrollPane outScrollPane = new JScrollPane(outTextArea);
private JScrollBar vsb = outScrollPane.getVerticalScrollBar();
private String commaDelimeter = ",";
/* Menu Bar */
private JMenu fileOptions; // file
private JMenuItem openNewFileItem;
private JMenuItem saveExisitingFileItem;
private JMenuItem exitProgramItem;
private JMenu viewOptions; // view
private JMenuItem viewFileItem;
@SuppressWarnings("unused")
public static void main (String[] args) throws Exception {
String filename = null;
String identifiers = null;
boolean cmdLineArgs = false;
thcsw002Parser fileParser = null;
/* Process cmdlineArgs */
switch (args.length) {
case 2: identifiers = args[1];
case 1: filename = args[0];
cmdLineArgs = true; // we have cmd line params
case 0: // fall thru for default cases
default:
fileParser = new thcsw002Parser(cmdLineArgs);
break;
}
}
public thcsw002Parser(boolean cmdLineArgs) {
if (!cmdLineArgs) {
buildMainGUI();
}
}
public void parser(String fileName, String identifiers) {
// Open the file in question
if (fileName == null || identifiers == null) throw new IllegalArgumentException("Can't have null args.");
ArrayList <IdTagObjs> idTags = new ArrayList<IdTagObjs>();
idTags.add(new IdTagObjs("Port")); // add the port identifiers
try {
diskFile = new BufferedReader(new FileReader(fileName));
String[] inputid = identifiers.split(regex);
ArrayList<String> intermediateids = new ArrayList<String>();
// add the identifiers in the identifier data structure
for (String id : inputid) {
idTags.add(new IdTagObjs(id.trim()));
intermediateids.add(id.trim());
}
Object[] idobjArray = intermediateids.toArray();
// ids only contain what was input from the command line
String[] ids = Arrays.copyOf(idobjArray, idobjArray.length, String[].class);
boolean gotFirstPortTag = false;
// boolean gotNextPortTag = false;
String line = null;
// TODO Rem this for csv printout
serverWindow.setTitle("Looking for the contents of: " + fileName);
// Print header
String header = null;
for (IdTagObjs a : idTags) {
if (header == null) header = a.getIdentifierTag();
else header += commaDelimeter + a.getIdentifierTag();
}
printToConsole(header);
// Parsing loop
while (!gotFirstPortTag) {
line = diskFile.readLine().trim();
// Get the opening port tag
if (!gotFirstPortTag && line.contains("Port") || line.contains("port")) {
line = line.substring(line.indexOf(" "), line.length());
idTags.get(0).setIdVal(line);
gotFirstPortTag = true;
}
}
while (true) {
line = diskFile.readLine().trim();
// Check to see if we have the requisite identifiers
// while the line doesn't contain a reference to a port
while(!(line.contains("Port ") || line.contains("port "))) {
// Compare the identifiers to the line
String searchTerm = null;
for (int index = 0; index < ids.length; index++) {
searchTerm = ids[index];
if (line.contains(searchTerm)) {
line = line.substring(line.indexOf("=")+1, line.length());
// find the searchTerm
idTags.get(index+1).setIdVal(line);
//printToConsole(searchTerm + " "+ line);
break; // move on to the next line
}
}
line = diskFile.readLine().trim();
}
// Print out the port
if (line.contains("Port ") || line.contains("port ")) {
+ boolean debugger = false;
+ if (line.contains("6/47")) debugger = true;
String output = null;
for (IdTagObjs a : idTags) {
if (output == null) output = a.getIdVal();
else output += commaDelimeter + a.getIdVal();
}
printToConsole(output);
// Set up for the next port
line = line.substring(line.indexOf(" "), line.length());
idTags.get(0).setIdVal(line);
}
}
}
- catch (NullPointerException npe) {}
+ // Flush all the stuff to screen if EOF is reached
+ catch (NullPointerException npe) {
+ String output = null;
+ for (IdTagObjs a : idTags) {
+ if (output == null) output = a.getIdVal();
+ else output += commaDelimeter + a.getIdVal();
+ }
+ printToConsole(output);
+ // Be done with the parsing
+ }
catch (IOException fnfe) {
printToConsole("Can't open the file, make sure it's there.");
}
}
public void printFile(String fileName) throws IOException {
BufferedReader diskFile = new BufferedReader(
new FileReader(fileName));
serverWindow.setTitle("The contents of " + fileName + " is:");
while(true) {
try {
printToConsole(diskFile.readLine().trim());
}
catch(IOException ioe) {
//System.out.println("Listing complete.");
diskFile.close();
break;
}
}
}
private void buildMainGUI() {
/* Output gui */
serverWindow.setSize(450, 450);
serverWindow.setLocation(250, 250);
mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.X_AXIS));
serverWindow.getContentPane().add(mainPanel, "Center");
serverWindow.getContentPane().add(btnPanel, "South");
mainPanel.add(outScrollPane);
outTextArea.setEditable(true); // Just make this a display text area
// btnPanel.add(closeButton);
// closeButton.addActionListener(this); // make sure button closes gui
// btnPanel.add(saveButton);
// saveButton.addActionListener(this);
/* Create the menuBar */
createFileMenu();
createViewMenu();
JMenuBar menuBar = new JMenuBar();
serverWindow.setJMenuBar(menuBar);
menuBar.add(fileOptions);
menuBar.add(viewOptions);
printToConsole("Open a file to parse by clicking File > Open File...");
serverWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
serverWindow.setVisible(true);
}
private void createFileMenu() {
fileOptions = new JMenu("File");
openNewFileItem = new JMenuItem("Open File...");
saveExisitingFileItem = new JMenuItem("Save");
exitProgramItem = new JMenuItem("Close Program");
openNewFileItem.addActionListener(this);
saveExisitingFileItem.addActionListener(this);
exitProgramItem.addActionListener(this);
fileOptions.add(openNewFileItem);
fileOptions.add(saveExisitingFileItem);
fileOptions.addSeparator();
fileOptions.add(exitProgramItem);
}
private void createViewMenu() {
viewOptions = new JMenu("View");
viewFileItem = new JMenuItem("View File");
viewFileItem.addActionListener(this);
viewOptions.add(viewFileItem);
}
@Override
public void actionPerformed(ActionEvent ae) {
if (ae.getSource() == openNewFileItem) {
String filename = null;
String identifiers = null;
JFileChooser jfc = new JFileChooser();
int retval = jfc.showOpenDialog(jfc);
if (retval == JFileChooser.APPROVE_OPTION) {
filename = jfc.getSelectedFile().getAbsolutePath();
}
else {
JOptionPane.showMessageDialog(null, "You must choose a file name.");
}
while (identifiers == null || identifiers.length() == 0 ) {
identifiers = JOptionPane.showInputDialog(null,
"Input tokens separated by semicolons, type \"Exit\" without a semicolon "
+ "to exit program, or \"Cancel\" to cancel the process.",
"rxByteCount;txByteCount;rxHCOctets;txHCOctets");
}
/* figure out what tokens we have */
if (identifiers.compareToIgnoreCase("exit") == 0) {
JOptionPane.showMessageDialog(null, "Exiting the program.");
System.exit(0);
}
else if (identifiers.compareToIgnoreCase("cancel") == 0); // just don't do anything
else { /* parse the file */
outTextArea.setText("");
parser(filename, identifiers);
}
}
if (ae.getSource() == exitProgramItem) {
int retVal = JOptionPane.showConfirmDialog(serverWindow, "Do you want to save file before exiting?", "Closing program", JOptionPane.YES_NO_CANCEL_OPTION);
try {
switch (retVal) {
case JOptionPane.YES_OPTION:
printToFile(); // Fall thru to close out
case JOptionPane.NO_OPTION:
System.exit(0); // terminate app
break;
default: // if they closed out or cancelled
break;
}
} catch (IOException e) {
// TODO Auto-generated catch block
JOptionPane.showMessageDialog(serverWindow, "Couldn't save to file, try again...");
} // print to file
}
if (ae.getSource() == saveExisitingFileItem) {
try {
printToFile();
} catch (IOException e) {
// TODO Auto-generated catch block
JOptionPane.showMessageDialog(serverWindow, "Couldn't save to file, try again...");
} // print to file
}
if (ae.getSource() == viewFileItem) {
try {
String filename = null;
JFileChooser jfc = new JFileChooser();
int retval = jfc.showOpenDialog(jfc);
if (retval == JFileChooser.APPROVE_OPTION) {
filename = jfc.getSelectedFile().getAbsolutePath();
}
else {
JOptionPane.showMessageDialog(null, "You must choose a file name.");
}
outTextArea.setText(""); // clear screen
printFile(filename);
} catch (NullPointerException npe) {} // reached eof
catch (IOException ioe) {
JOptionPane.showMessageDialog(serverWindow, "Couldn't open the file, try again...");
}
}
}
private void printToConsole (String msg) {
outTextArea.append(msg + newLine);
vsb.setValue(vsb.getMaximum());
outTextArea.setCaretPosition(outTextArea.getDocument().getLength());
}
private void printToFile() throws IOException {
JFileChooser saveFile = new JFileChooser();
int retval = saveFile.showSaveDialog(saveFile);
String fileToSave = null;
String fileData = null;
if (retval == JFileChooser.APPROVE_OPTION) {
fileToSave = saveFile.getSelectedFile().getAbsolutePath();
fileData = outTextArea.getText();
BufferedWriter diskFile = new BufferedWriter(new FileWriter(fileToSave));
diskFile.write(fileData);
diskFile.close();
JOptionPane.showMessageDialog(serverWindow, "Done Saving to " + fileToSave);
}
else {
JOptionPane.showMessageDialog(null, "Data not saved to file.");
}
}
}
| false | true | public void parser(String fileName, String identifiers) {
// Open the file in question
if (fileName == null || identifiers == null) throw new IllegalArgumentException("Can't have null args.");
ArrayList <IdTagObjs> idTags = new ArrayList<IdTagObjs>();
idTags.add(new IdTagObjs("Port")); // add the port identifiers
try {
diskFile = new BufferedReader(new FileReader(fileName));
String[] inputid = identifiers.split(regex);
ArrayList<String> intermediateids = new ArrayList<String>();
// add the identifiers in the identifier data structure
for (String id : inputid) {
idTags.add(new IdTagObjs(id.trim()));
intermediateids.add(id.trim());
}
Object[] idobjArray = intermediateids.toArray();
// ids only contain what was input from the command line
String[] ids = Arrays.copyOf(idobjArray, idobjArray.length, String[].class);
boolean gotFirstPortTag = false;
// boolean gotNextPortTag = false;
String line = null;
// TODO Rem this for csv printout
serverWindow.setTitle("Looking for the contents of: " + fileName);
// Print header
String header = null;
for (IdTagObjs a : idTags) {
if (header == null) header = a.getIdentifierTag();
else header += commaDelimeter + a.getIdentifierTag();
}
printToConsole(header);
// Parsing loop
while (!gotFirstPortTag) {
line = diskFile.readLine().trim();
// Get the opening port tag
if (!gotFirstPortTag && line.contains("Port") || line.contains("port")) {
line = line.substring(line.indexOf(" "), line.length());
idTags.get(0).setIdVal(line);
gotFirstPortTag = true;
}
}
while (true) {
line = diskFile.readLine().trim();
// Check to see if we have the requisite identifiers
// while the line doesn't contain a reference to a port
while(!(line.contains("Port ") || line.contains("port "))) {
// Compare the identifiers to the line
String searchTerm = null;
for (int index = 0; index < ids.length; index++) {
searchTerm = ids[index];
if (line.contains(searchTerm)) {
line = line.substring(line.indexOf("=")+1, line.length());
// find the searchTerm
idTags.get(index+1).setIdVal(line);
//printToConsole(searchTerm + " "+ line);
break; // move on to the next line
}
}
line = diskFile.readLine().trim();
}
// Print out the port
if (line.contains("Port ") || line.contains("port ")) {
String output = null;
for (IdTagObjs a : idTags) {
if (output == null) output = a.getIdVal();
else output += commaDelimeter + a.getIdVal();
}
printToConsole(output);
// Set up for the next port
line = line.substring(line.indexOf(" "), line.length());
idTags.get(0).setIdVal(line);
}
}
}
catch (NullPointerException npe) {}
catch (IOException fnfe) {
printToConsole("Can't open the file, make sure it's there.");
}
}
| public void parser(String fileName, String identifiers) {
// Open the file in question
if (fileName == null || identifiers == null) throw new IllegalArgumentException("Can't have null args.");
ArrayList <IdTagObjs> idTags = new ArrayList<IdTagObjs>();
idTags.add(new IdTagObjs("Port")); // add the port identifiers
try {
diskFile = new BufferedReader(new FileReader(fileName));
String[] inputid = identifiers.split(regex);
ArrayList<String> intermediateids = new ArrayList<String>();
// add the identifiers in the identifier data structure
for (String id : inputid) {
idTags.add(new IdTagObjs(id.trim()));
intermediateids.add(id.trim());
}
Object[] idobjArray = intermediateids.toArray();
// ids only contain what was input from the command line
String[] ids = Arrays.copyOf(idobjArray, idobjArray.length, String[].class);
boolean gotFirstPortTag = false;
// boolean gotNextPortTag = false;
String line = null;
// TODO Rem this for csv printout
serverWindow.setTitle("Looking for the contents of: " + fileName);
// Print header
String header = null;
for (IdTagObjs a : idTags) {
if (header == null) header = a.getIdentifierTag();
else header += commaDelimeter + a.getIdentifierTag();
}
printToConsole(header);
// Parsing loop
while (!gotFirstPortTag) {
line = diskFile.readLine().trim();
// Get the opening port tag
if (!gotFirstPortTag && line.contains("Port") || line.contains("port")) {
line = line.substring(line.indexOf(" "), line.length());
idTags.get(0).setIdVal(line);
gotFirstPortTag = true;
}
}
while (true) {
line = diskFile.readLine().trim();
// Check to see if we have the requisite identifiers
// while the line doesn't contain a reference to a port
while(!(line.contains("Port ") || line.contains("port "))) {
// Compare the identifiers to the line
String searchTerm = null;
for (int index = 0; index < ids.length; index++) {
searchTerm = ids[index];
if (line.contains(searchTerm)) {
line = line.substring(line.indexOf("=")+1, line.length());
// find the searchTerm
idTags.get(index+1).setIdVal(line);
//printToConsole(searchTerm + " "+ line);
break; // move on to the next line
}
}
line = diskFile.readLine().trim();
}
// Print out the port
if (line.contains("Port ") || line.contains("port ")) {
boolean debugger = false;
if (line.contains("6/47")) debugger = true;
String output = null;
for (IdTagObjs a : idTags) {
if (output == null) output = a.getIdVal();
else output += commaDelimeter + a.getIdVal();
}
printToConsole(output);
// Set up for the next port
line = line.substring(line.indexOf(" "), line.length());
idTags.get(0).setIdVal(line);
}
}
}
// Flush all the stuff to screen if EOF is reached
catch (NullPointerException npe) {
String output = null;
for (IdTagObjs a : idTags) {
if (output == null) output = a.getIdVal();
else output += commaDelimeter + a.getIdVal();
}
printToConsole(output);
// Be done with the parsing
}
catch (IOException fnfe) {
printToConsole("Can't open the file, make sure it's there.");
}
}
|
diff --git a/measurement-point/measurement-scheduler/src/main/java/net/es/mp/scheduler/jobs/OWAMPJob.java b/measurement-point/measurement-scheduler/src/main/java/net/es/mp/scheduler/jobs/OWAMPJob.java
index 36c08df..17ed50b 100644
--- a/measurement-point/measurement-scheduler/src/main/java/net/es/mp/scheduler/jobs/OWAMPJob.java
+++ b/measurement-point/measurement-scheduler/src/main/java/net/es/mp/scheduler/jobs/OWAMPJob.java
@@ -1,398 +1,398 @@
package net.es.mp.scheduler.jobs;
import java.io.BufferedReader;
import java.io.IOException;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.es.mp.authz.AuthzConditions;
import net.es.mp.measurement.types.Measurement;
import net.es.mp.measurement.types.MeasurementResult;
import net.es.mp.measurement.types.OWAMPMeasurement;
import net.es.mp.measurement.types.OWAMPResult;
import net.es.mp.scheduler.MPSchedulingService;
import net.es.mp.scheduler.types.OWAMPSchedule;
import net.es.mp.scheduler.types.Schedule;
import net.es.mp.types.parameters.OWAMPParams;
import net.es.mp.util.archivers.Archiver;
import net.es.mp.util.archivers.LocalArchiver;
import net.es.mp.util.publishers.LocalStreamPublisher;
import net.es.mp.util.publishers.Publisher;
import org.apache.log4j.Logger;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.ISODateTimeFormat;
import com.mongodb.BasicDBObject;
public class OWAMPJob extends ExecCommandJob{
private Logger log = Logger.getLogger(OWAMPJob.class);
private Logger netlogger = Logger.getLogger("netlogger");
private long timeout;
private String controller;
private String commandPath;
final private static String PROP_CONTROLLER_HOST = "controllerHost";
final private static String PROP_COMMAND = "command";
final private static String PROP_TIMEOUT = "timeout";
final private static String DEFAULT_COMMAND = "owping";
final private static String DEFAULT_ERROR_MSG = "The owping command returned an unknown error";
public void init(Schedule schedule, AuthzConditions authzConditions){
//read config
MPSchedulingService globals = MPSchedulingService.getInstance();
Map config = MPSchedulingService.getInstance().getToolConfig(OWAMPParams.TYPE_VALUE);
if(config.containsKey(PROP_CONTROLLER_HOST) &&
config.get(PROP_CONTROLLER_HOST) != null){
this.controller = (String) config.get(PROP_CONTROLLER_HOST);
}else{
//default to this host
this.controller = globals.getContainer().getWebServer().getHostname();
}
if(config.containsKey(PROP_COMMAND) &&
config.get(PROP_COMMAND) != null){
this.commandPath = (String) config.get(PROP_COMMAND);
}else{
//default to this host
this.commandPath = DEFAULT_COMMAND;
}
if(config.containsKey(PROP_TIMEOUT) &&
config.get(PROP_TIMEOUT) != null){
this.timeout = (Integer) config.get(PROP_TIMEOUT);
}else{
//default based on duration
Integer count = ((OWAMPSchedule) schedule).getPacketCount();
if(count == null){
count = OWAMPParams.DEFAULT_PACKET_COUNT;
}
Double wait = ((OWAMPSchedule) schedule).getPacketWait();
if(wait == null){
wait = OWAMPParams.DEFAULT_PACKET_WAIT;
}
this.timeout = 3*((int)(count*wait)) + 30L ;
}
//user provided command arguments
this.commandArgs.add(((OWAMPSchedule) schedule).getDestination());
//user provided options
this.userCommandOpts.add(new ExecCommandOpt(OWAMPParams.SOURCE, "-S"));
this.userCommandOpts.add(new ExecCommandOpt(OWAMPParams.PACKET_COUNT, "-c",
OWAMPParams.DEFAULT_PACKET_COUNT+""));
this.userCommandOpts.add(new ExecCommandOpt(OWAMPParams.PACKET_WAIT, "-i",
OWAMPParams.DEFAULT_PACKET_WAIT+""));
this.userCommandOpts.add(new ExecCommandOpt(OWAMPParams.PACKET_TIMEOUT, "-L"));
this.userCommandOpts.add(new ExecCommandOpt(OWAMPParams.PACKET_PADDING, "-s"));
this.userCommandOpts.add(new ExecCommandOpt(OWAMPParams.DSCP, "-D"));
this.userCommandOpts.add(new ExecCommandOpt(OWAMPParams.TEST_PORTS, "-P"));
//user provided flags
this.userCommandOpts.add(new ExecCommandOpt(OWAMPParams.IP_VERSION, "-4", true,
OWAMPParams.IPV_V4_ONLY));
this.userCommandOpts.add(new ExecCommandOpt(OWAMPParams.IP_VERSION, "-6", true,
OWAMPParams.IPV_V6_ONLY));
//TODO: server set options and flags
//make sure it only returns one-way
this.providerCommandOpts.add("-t");
//machine readbale output
//this.providerCommandOpts.add("-M");
//populate known errors
this.knownErrors.add(new ExecCommandError(
Pattern.compile("owping:.*,\\s+(Unable to open control connection to .*)"),
OWAMPResult.STATUS_CTRL_CONNECT_FAILED));
this.knownErrors.add(new ExecCommandError(
Pattern.compile("owping:.*,\\s+getaddrinfo.*"),
OWAMPResult.STATUS_CTRL_CONNECT_FAILED,
"Invalid hostname provided"));
this.knownErrors.add(new ExecCommandError(
Pattern.compile("owping:.*,\\s+(Server denied test.*)"),
OWAMPResult.STATUS_DENIED));
}
protected long getTimeout() {
return this.timeout;
}
protected String getToolName() {
return this.commandPath;
}
protected void handleOutput(BufferedReader stdout, BufferedReader stderr,
Schedule schedule) throws IOException {
OWAMPSchedule owampSchedule = (OWAMPSchedule) schedule;
//Init measurement
OWAMPMeasurement measurement = this.buildMeasurement(owampSchedule);
//Build result
MeasurementResult result = new OWAMPResult(new BasicDBObject());
result.setStatus(MeasurementResult.STATUS_OK);
Pattern ipLinePattern = Pattern.compile("---\\s*owping\\s+statistics\\s+from\\s+\\[(.+)\\]:\\d+\\s+to\\s+\\[(.+)\\]:\\d+\\s*---");
Pattern startPattern = Pattern.compile("first:\\s+(.+)");
Pattern endPattern = Pattern.compile("last:\\s+(.+)");
Pattern lossPattern = Pattern.compile("\\d+\\s+sent,\\s+(\\d+)\\s+lost\\s+\\(\\d+(\\.\\d+)?%\\),\\s+(\\d+)\\s+duplicates");
- Pattern delayPattern = Pattern.compile("one-way\\s+delay\\s+min/median/max\\s+=\\s+(.+)/(.+)/(.+)\\s+ms,\\s+\\((err=)?(\\d+)?.+\\)");
+ Pattern delayPattern = Pattern.compile("one-way\\s+delay\\s+min/median/max\\s+=\\s+(.+)/(.+)/(.+)\\s+ms,\\s+\\((err=)?(\\-?[0-9\\.]+)?.+?$\\)");
Pattern ttlPattern1 = Pattern.compile("Hops\\s+=\\s+(\\d+)\\s+\\(consistently\\)");
Pattern ttlPattern2 = Pattern.compile("TTL\\s+not\\s+reported");
Pattern ttlPattern3 = Pattern.compile("Hops\\s+takes\\s+(\\d+)\\s+values;\\s+Min\\s+Hops\\s+=\\s+(\\d+),\\s+Max\\s+Hops\\s+=\\s+(\\d+)");
DateTimeFormatter dateParser = ISODateTimeFormat.localDateOptionalTimeParser().withZone(DateTimeZone.getDefault());
String outputLine = null;
boolean ipsFound = false;
boolean startFound = false;
boolean endFound = false;
boolean lossFound = false;
boolean delayFound = false;
boolean ttlFound = false;
String returnedSource = "";
String returnedDest = "";
while((outputLine = stdout.readLine()) != null){
log.debug(outputLine.trim());
Matcher ipLineMatcher = ipLinePattern.matcher(outputLine.trim());
Matcher startMatcher = startPattern.matcher(outputLine.trim());
Matcher endMatcher = endPattern.matcher(outputLine.trim());
Matcher lossMatcher = lossPattern.matcher(outputLine.trim());
Matcher delayMatcher = delayPattern.matcher(outputLine.trim());
Matcher ttlMatcher1 = ttlPattern1.matcher(outputLine.trim());
Matcher ttlMatcher2 = ttlPattern2.matcher(outputLine.trim());
Matcher ttlMatcher3 = ttlPattern3.matcher(outputLine.trim());
if(ipLineMatcher.matches()){
returnedSource = ipLineMatcher.group(1);
returnedDest = ipLineMatcher.group(2);
ipsFound = true;
}else if(startMatcher.matches()){
result.setStartTime(dateParser.parseDateTime(startMatcher.group(1)).toDate());
//result.setStartTime(new Date());
startFound = true;
}else if(endMatcher.matches()){
result.setEndTime(dateParser.parseDateTime(endMatcher.group(1)).toDate());
//result.setEndTime(new Date());
endFound = true;
}else if(lossMatcher.matches()){
((OWAMPResult)result).setLoss(Integer.parseInt(lossMatcher.group(1)));
((OWAMPResult)result).setDuplicates(Integer.parseInt(lossMatcher.group(3)));
lossFound = true;
}else if(delayMatcher.matches()){
try{
((OWAMPResult)result).setMinDelay(Double.parseDouble(delayMatcher.group(1)));
((OWAMPResult)result).setMedianDelay(Double.parseDouble(delayMatcher.group(2)));
((OWAMPResult)result).setMaxDelay(Double.parseDouble(delayMatcher.group(3)));
if(delayMatcher.groupCount() >= 5 && delayMatcher.group(5) != null){
((OWAMPResult)result).setMaxError(Double.parseDouble(delayMatcher.group(5)));
}else{
((OWAMPResult)result).setMaxError(null);
}
delayFound = true;
}catch(Exception e){
//handle NaN issues, treat this like an error condition for now
continue;
}
}else if(ttlMatcher1.matches()){
((OWAMPResult)result).setMinTTL(Integer.parseInt(ttlMatcher1.group(1)));
((OWAMPResult)result).setMaxTTL(Integer.parseInt(ttlMatcher1.group(1)));
ttlFound = true;
}else if(ttlMatcher2.matches()){
//same host
((OWAMPResult)result).setMinTTL(0);
((OWAMPResult)result).setMaxTTL(0);
ttlFound = true;
}else if(ttlMatcher3.matches()){
((OWAMPResult)result).setMinTTL(Integer.parseInt(ttlMatcher3.group(2)));
((OWAMPResult)result).setMaxTTL(Integer.parseInt(ttlMatcher3.group(3)));
ttlFound = true;
}
}
System.out.println(ipsFound + " " + startFound + " " + endFound + " " +
lossFound + " " + delayFound + " " + ttlFound);
//check for errors
log.debug("STDERROR:");
String[] errArr = this.parseErrorMsg(stderr, DEFAULT_ERROR_MSG);
if(errArr != null){
result = this.buildErrorResult(errArr[0], errArr[1], result.getStartTime(), result.getEndTime());
}else if(!ipsFound){
result = this.buildErrorResult(MeasurementResult.STATUS_ERROR,
"Unable to parse IP addresses in owping output",
result.getStartTime(),
result.getEndTime());
}else if(!startFound){
result = this.buildErrorResult(MeasurementResult.STATUS_ERROR,
"Unable to parse start time in owping output",
result.getStartTime(),
result.getEndTime());
}else if(!endFound){
result = this.buildErrorResult(MeasurementResult.STATUS_ERROR,
"Unable to parse end time in owping output",
result.getStartTime(),
result.getEndTime());
}else if(!lossFound){
result = this.buildErrorResult(MeasurementResult.STATUS_ERROR,
"Unable to parse loss in owping output",
result.getStartTime(),
result.getEndTime());
}else if(!delayFound){
result = this.buildErrorResult(MeasurementResult.STATUS_ERROR,
"Unable to parse delay in owping output",
result.getStartTime(),
result.getEndTime());
}else if(!ttlFound){
result = this.buildErrorResult(MeasurementResult.STATUS_ERROR,
"Unable to parse TTL values in owping output",
result.getStartTime(),
result.getEndTime());
}
measurement.setResult(result);
//figure out hostname of source and destination
try{
InetAddress inet = InetAddress.getByName(returnedSource);
String hostname = inet.getCanonicalHostName();
String ip = inet.getHostAddress();
measurement.setSourceIP(ip);
//if get back textual representation of IP then se to null
if(!ip.equals(hostname)){
measurement.setSourceHostname(hostname);
}else if(!measurement.getSource().equals(hostname)){
//this only happens if for some reason can't get hostname but source was specified as host
measurement.setSourceHostname(measurement.getSource());
}
}catch(Exception e){
//can't resolve so set to null
log.debug("Unable to set sourceHostname: " + e.getMessage());
measurement.setSourceHostname(null);
}
try{
InetAddress inet = InetAddress.getByName(returnedDest);
String hostname = inet.getCanonicalHostName();
String ip = inet.getHostAddress();
measurement.setDestinationIP(ip);
//if get back textual representation of IP then se to null
if(!ip.equals(hostname)){
measurement.setDestinationHostname(hostname);
}else if(!measurement.getDestination().equals(hostname)){
//this only happens if for some reason can't get hostname but dest was specified as host
measurement.setDestinationHostname(measurement.getDestination());
}
}catch(Exception e){
//can't resolve so set to null
log.debug("Unable to set destinationHostname: " + e.getMessage());
measurement.setDestinationHostname(null);
}
//archive and publish measurement
this.archiveAndPublish(measurement, schedule.getStreamURI());
System.out.println(measurement.toJSONString());
}
protected void handleError(int resultCode, BufferedReader stdout,
BufferedReader stderr, Schedule schedule) throws IOException {
OWAMPSchedule owamSchedule = (OWAMPSchedule) schedule;
//Init measurement
OWAMPMeasurement measurement = this.buildMeasurement(owamSchedule);
//build result
MeasurementResult result = null;
String[] errArr = this.parseErrorMsg(stderr, DEFAULT_ERROR_MSG);
if(errArr != null){
result = this.buildErrorResult(errArr[0], errArr[1], null, null);
}else{
result = this.buildErrorResult(MeasurementResult.STATUS_ERROR, DEFAULT_ERROR_MSG, null, null);
}
measurement.setResult(result);
//archive and publish
this.archiveAndPublish(measurement, schedule.getStreamURI());
}
protected void handleTimeout(Schedule schedule) {
OWAMPSchedule owampSchedule = (OWAMPSchedule) schedule;
OWAMPMeasurement measurement = this.buildMeasurement(owampSchedule);
MeasurementResult result = this.buildErrorResult(
MeasurementResult.STATUS_ERROR,
"A timeout occurred because the owping command did not return after " + this.timeout + " seconds.",
null, null);
measurement.setResult(result);
this.archiveAndPublish(measurement, schedule.getStreamURI());
}
private OWAMPMeasurement buildMeasurement(OWAMPSchedule owampSchedule){
OWAMPMeasurement measurement = new OWAMPMeasurement(new BasicDBObject());
// required by measurement and schedule
measurement.setType(owampSchedule.getType());
measurement.setScheduleURI(owampSchedule.getURI());
measurement.setSource(owampSchedule.getSource());
measurement.setDestination(owampSchedule.getDestination());
// required by measurement but not schedule
if(owampSchedule.getController() == null){
measurement.setController(this.controller);
}else{
measurement.setController(owampSchedule.getController());
}
if(owampSchedule.getIPVersion() == null){
measurement.setIPVersion(OWAMPParams.IPV_PREFER_V6);
}else{
measurement.setIPVersion(owampSchedule.getIPVersion());
}
if(owampSchedule.getPacketCount() == null){
measurement.setPacketCount(OWAMPParams.DEFAULT_PACKET_COUNT);
}else{
measurement.setPacketCount(owampSchedule.getPacketCount());
}
if(owampSchedule.getPacketWait() == null){
measurement.setPacketWait(OWAMPParams.DEFAULT_PACKET_WAIT);
}else{
measurement.setPacketWait(owampSchedule.getPacketWait());
}
// optional parameters
if(owampSchedule.getPacketTimeout() != null){
measurement.setPacketTimeout(owampSchedule.getPacketTimeout());
}
if(owampSchedule.getPacketPadding() != null){
measurement.setPacketPadding(owampSchedule.getPacketPadding());
}
if(owampSchedule.getDSCP() != null){
measurement.setDSCP(owampSchedule.getDSCP());
}
if(owampSchedule.getTestPorts() != null){
measurement.setTestPorts(owampSchedule.getTestPorts());
}
//init these fields
measurement.setSourceHostname(null);
measurement.setDestinationHostname(null);
measurement.setSourceIP(null);
measurement.setDestinationIP(null);
return measurement;
}
private void archiveAndPublish(OWAMPMeasurement measurement, String streamUri) {
//archive the measurement
Archiver archiver = new LocalArchiver();
archiver.archive(measurement);
//publish to stream
Publisher localPublisher = new LocalStreamPublisher();
List<Measurement> measList = (new ArrayList<Measurement>());
measList.add(measurement);
localPublisher.publish(measList, streamUri);
}
}
| true | true | protected void handleOutput(BufferedReader stdout, BufferedReader stderr,
Schedule schedule) throws IOException {
OWAMPSchedule owampSchedule = (OWAMPSchedule) schedule;
//Init measurement
OWAMPMeasurement measurement = this.buildMeasurement(owampSchedule);
//Build result
MeasurementResult result = new OWAMPResult(new BasicDBObject());
result.setStatus(MeasurementResult.STATUS_OK);
Pattern ipLinePattern = Pattern.compile("---\\s*owping\\s+statistics\\s+from\\s+\\[(.+)\\]:\\d+\\s+to\\s+\\[(.+)\\]:\\d+\\s*---");
Pattern startPattern = Pattern.compile("first:\\s+(.+)");
Pattern endPattern = Pattern.compile("last:\\s+(.+)");
Pattern lossPattern = Pattern.compile("\\d+\\s+sent,\\s+(\\d+)\\s+lost\\s+\\(\\d+(\\.\\d+)?%\\),\\s+(\\d+)\\s+duplicates");
Pattern delayPattern = Pattern.compile("one-way\\s+delay\\s+min/median/max\\s+=\\s+(.+)/(.+)/(.+)\\s+ms,\\s+\\((err=)?(\\d+)?.+\\)");
Pattern ttlPattern1 = Pattern.compile("Hops\\s+=\\s+(\\d+)\\s+\\(consistently\\)");
Pattern ttlPattern2 = Pattern.compile("TTL\\s+not\\s+reported");
Pattern ttlPattern3 = Pattern.compile("Hops\\s+takes\\s+(\\d+)\\s+values;\\s+Min\\s+Hops\\s+=\\s+(\\d+),\\s+Max\\s+Hops\\s+=\\s+(\\d+)");
DateTimeFormatter dateParser = ISODateTimeFormat.localDateOptionalTimeParser().withZone(DateTimeZone.getDefault());
String outputLine = null;
boolean ipsFound = false;
boolean startFound = false;
boolean endFound = false;
boolean lossFound = false;
boolean delayFound = false;
boolean ttlFound = false;
String returnedSource = "";
String returnedDest = "";
while((outputLine = stdout.readLine()) != null){
log.debug(outputLine.trim());
Matcher ipLineMatcher = ipLinePattern.matcher(outputLine.trim());
Matcher startMatcher = startPattern.matcher(outputLine.trim());
Matcher endMatcher = endPattern.matcher(outputLine.trim());
Matcher lossMatcher = lossPattern.matcher(outputLine.trim());
Matcher delayMatcher = delayPattern.matcher(outputLine.trim());
Matcher ttlMatcher1 = ttlPattern1.matcher(outputLine.trim());
Matcher ttlMatcher2 = ttlPattern2.matcher(outputLine.trim());
Matcher ttlMatcher3 = ttlPattern3.matcher(outputLine.trim());
if(ipLineMatcher.matches()){
returnedSource = ipLineMatcher.group(1);
returnedDest = ipLineMatcher.group(2);
ipsFound = true;
}else if(startMatcher.matches()){
result.setStartTime(dateParser.parseDateTime(startMatcher.group(1)).toDate());
//result.setStartTime(new Date());
startFound = true;
}else if(endMatcher.matches()){
result.setEndTime(dateParser.parseDateTime(endMatcher.group(1)).toDate());
//result.setEndTime(new Date());
endFound = true;
}else if(lossMatcher.matches()){
((OWAMPResult)result).setLoss(Integer.parseInt(lossMatcher.group(1)));
((OWAMPResult)result).setDuplicates(Integer.parseInt(lossMatcher.group(3)));
lossFound = true;
}else if(delayMatcher.matches()){
try{
((OWAMPResult)result).setMinDelay(Double.parseDouble(delayMatcher.group(1)));
((OWAMPResult)result).setMedianDelay(Double.parseDouble(delayMatcher.group(2)));
((OWAMPResult)result).setMaxDelay(Double.parseDouble(delayMatcher.group(3)));
if(delayMatcher.groupCount() >= 5 && delayMatcher.group(5) != null){
((OWAMPResult)result).setMaxError(Double.parseDouble(delayMatcher.group(5)));
}else{
((OWAMPResult)result).setMaxError(null);
}
delayFound = true;
}catch(Exception e){
//handle NaN issues, treat this like an error condition for now
continue;
}
}else if(ttlMatcher1.matches()){
((OWAMPResult)result).setMinTTL(Integer.parseInt(ttlMatcher1.group(1)));
((OWAMPResult)result).setMaxTTL(Integer.parseInt(ttlMatcher1.group(1)));
ttlFound = true;
}else if(ttlMatcher2.matches()){
//same host
((OWAMPResult)result).setMinTTL(0);
((OWAMPResult)result).setMaxTTL(0);
ttlFound = true;
}else if(ttlMatcher3.matches()){
((OWAMPResult)result).setMinTTL(Integer.parseInt(ttlMatcher3.group(2)));
((OWAMPResult)result).setMaxTTL(Integer.parseInt(ttlMatcher3.group(3)));
ttlFound = true;
}
}
System.out.println(ipsFound + " " + startFound + " " + endFound + " " +
lossFound + " " + delayFound + " " + ttlFound);
//check for errors
log.debug("STDERROR:");
String[] errArr = this.parseErrorMsg(stderr, DEFAULT_ERROR_MSG);
if(errArr != null){
result = this.buildErrorResult(errArr[0], errArr[1], result.getStartTime(), result.getEndTime());
}else if(!ipsFound){
result = this.buildErrorResult(MeasurementResult.STATUS_ERROR,
"Unable to parse IP addresses in owping output",
result.getStartTime(),
result.getEndTime());
}else if(!startFound){
result = this.buildErrorResult(MeasurementResult.STATUS_ERROR,
"Unable to parse start time in owping output",
result.getStartTime(),
result.getEndTime());
}else if(!endFound){
result = this.buildErrorResult(MeasurementResult.STATUS_ERROR,
"Unable to parse end time in owping output",
result.getStartTime(),
result.getEndTime());
}else if(!lossFound){
result = this.buildErrorResult(MeasurementResult.STATUS_ERROR,
"Unable to parse loss in owping output",
result.getStartTime(),
result.getEndTime());
}else if(!delayFound){
result = this.buildErrorResult(MeasurementResult.STATUS_ERROR,
"Unable to parse delay in owping output",
result.getStartTime(),
result.getEndTime());
}else if(!ttlFound){
result = this.buildErrorResult(MeasurementResult.STATUS_ERROR,
"Unable to parse TTL values in owping output",
result.getStartTime(),
result.getEndTime());
}
measurement.setResult(result);
//figure out hostname of source and destination
try{
InetAddress inet = InetAddress.getByName(returnedSource);
String hostname = inet.getCanonicalHostName();
String ip = inet.getHostAddress();
measurement.setSourceIP(ip);
//if get back textual representation of IP then se to null
if(!ip.equals(hostname)){
measurement.setSourceHostname(hostname);
}else if(!measurement.getSource().equals(hostname)){
//this only happens if for some reason can't get hostname but source was specified as host
measurement.setSourceHostname(measurement.getSource());
}
}catch(Exception e){
//can't resolve so set to null
log.debug("Unable to set sourceHostname: " + e.getMessage());
measurement.setSourceHostname(null);
}
try{
InetAddress inet = InetAddress.getByName(returnedDest);
String hostname = inet.getCanonicalHostName();
String ip = inet.getHostAddress();
measurement.setDestinationIP(ip);
//if get back textual representation of IP then se to null
if(!ip.equals(hostname)){
measurement.setDestinationHostname(hostname);
}else if(!measurement.getDestination().equals(hostname)){
//this only happens if for some reason can't get hostname but dest was specified as host
measurement.setDestinationHostname(measurement.getDestination());
}
}catch(Exception e){
//can't resolve so set to null
log.debug("Unable to set destinationHostname: " + e.getMessage());
measurement.setDestinationHostname(null);
}
//archive and publish measurement
this.archiveAndPublish(measurement, schedule.getStreamURI());
System.out.println(measurement.toJSONString());
}
| protected void handleOutput(BufferedReader stdout, BufferedReader stderr,
Schedule schedule) throws IOException {
OWAMPSchedule owampSchedule = (OWAMPSchedule) schedule;
//Init measurement
OWAMPMeasurement measurement = this.buildMeasurement(owampSchedule);
//Build result
MeasurementResult result = new OWAMPResult(new BasicDBObject());
result.setStatus(MeasurementResult.STATUS_OK);
Pattern ipLinePattern = Pattern.compile("---\\s*owping\\s+statistics\\s+from\\s+\\[(.+)\\]:\\d+\\s+to\\s+\\[(.+)\\]:\\d+\\s*---");
Pattern startPattern = Pattern.compile("first:\\s+(.+)");
Pattern endPattern = Pattern.compile("last:\\s+(.+)");
Pattern lossPattern = Pattern.compile("\\d+\\s+sent,\\s+(\\d+)\\s+lost\\s+\\(\\d+(\\.\\d+)?%\\),\\s+(\\d+)\\s+duplicates");
Pattern delayPattern = Pattern.compile("one-way\\s+delay\\s+min/median/max\\s+=\\s+(.+)/(.+)/(.+)\\s+ms,\\s+\\((err=)?(\\-?[0-9\\.]+)?.+?$\\)");
Pattern ttlPattern1 = Pattern.compile("Hops\\s+=\\s+(\\d+)\\s+\\(consistently\\)");
Pattern ttlPattern2 = Pattern.compile("TTL\\s+not\\s+reported");
Pattern ttlPattern3 = Pattern.compile("Hops\\s+takes\\s+(\\d+)\\s+values;\\s+Min\\s+Hops\\s+=\\s+(\\d+),\\s+Max\\s+Hops\\s+=\\s+(\\d+)");
DateTimeFormatter dateParser = ISODateTimeFormat.localDateOptionalTimeParser().withZone(DateTimeZone.getDefault());
String outputLine = null;
boolean ipsFound = false;
boolean startFound = false;
boolean endFound = false;
boolean lossFound = false;
boolean delayFound = false;
boolean ttlFound = false;
String returnedSource = "";
String returnedDest = "";
while((outputLine = stdout.readLine()) != null){
log.debug(outputLine.trim());
Matcher ipLineMatcher = ipLinePattern.matcher(outputLine.trim());
Matcher startMatcher = startPattern.matcher(outputLine.trim());
Matcher endMatcher = endPattern.matcher(outputLine.trim());
Matcher lossMatcher = lossPattern.matcher(outputLine.trim());
Matcher delayMatcher = delayPattern.matcher(outputLine.trim());
Matcher ttlMatcher1 = ttlPattern1.matcher(outputLine.trim());
Matcher ttlMatcher2 = ttlPattern2.matcher(outputLine.trim());
Matcher ttlMatcher3 = ttlPattern3.matcher(outputLine.trim());
if(ipLineMatcher.matches()){
returnedSource = ipLineMatcher.group(1);
returnedDest = ipLineMatcher.group(2);
ipsFound = true;
}else if(startMatcher.matches()){
result.setStartTime(dateParser.parseDateTime(startMatcher.group(1)).toDate());
//result.setStartTime(new Date());
startFound = true;
}else if(endMatcher.matches()){
result.setEndTime(dateParser.parseDateTime(endMatcher.group(1)).toDate());
//result.setEndTime(new Date());
endFound = true;
}else if(lossMatcher.matches()){
((OWAMPResult)result).setLoss(Integer.parseInt(lossMatcher.group(1)));
((OWAMPResult)result).setDuplicates(Integer.parseInt(lossMatcher.group(3)));
lossFound = true;
}else if(delayMatcher.matches()){
try{
((OWAMPResult)result).setMinDelay(Double.parseDouble(delayMatcher.group(1)));
((OWAMPResult)result).setMedianDelay(Double.parseDouble(delayMatcher.group(2)));
((OWAMPResult)result).setMaxDelay(Double.parseDouble(delayMatcher.group(3)));
if(delayMatcher.groupCount() >= 5 && delayMatcher.group(5) != null){
((OWAMPResult)result).setMaxError(Double.parseDouble(delayMatcher.group(5)));
}else{
((OWAMPResult)result).setMaxError(null);
}
delayFound = true;
}catch(Exception e){
//handle NaN issues, treat this like an error condition for now
continue;
}
}else if(ttlMatcher1.matches()){
((OWAMPResult)result).setMinTTL(Integer.parseInt(ttlMatcher1.group(1)));
((OWAMPResult)result).setMaxTTL(Integer.parseInt(ttlMatcher1.group(1)));
ttlFound = true;
}else if(ttlMatcher2.matches()){
//same host
((OWAMPResult)result).setMinTTL(0);
((OWAMPResult)result).setMaxTTL(0);
ttlFound = true;
}else if(ttlMatcher3.matches()){
((OWAMPResult)result).setMinTTL(Integer.parseInt(ttlMatcher3.group(2)));
((OWAMPResult)result).setMaxTTL(Integer.parseInt(ttlMatcher3.group(3)));
ttlFound = true;
}
}
System.out.println(ipsFound + " " + startFound + " " + endFound + " " +
lossFound + " " + delayFound + " " + ttlFound);
//check for errors
log.debug("STDERROR:");
String[] errArr = this.parseErrorMsg(stderr, DEFAULT_ERROR_MSG);
if(errArr != null){
result = this.buildErrorResult(errArr[0], errArr[1], result.getStartTime(), result.getEndTime());
}else if(!ipsFound){
result = this.buildErrorResult(MeasurementResult.STATUS_ERROR,
"Unable to parse IP addresses in owping output",
result.getStartTime(),
result.getEndTime());
}else if(!startFound){
result = this.buildErrorResult(MeasurementResult.STATUS_ERROR,
"Unable to parse start time in owping output",
result.getStartTime(),
result.getEndTime());
}else if(!endFound){
result = this.buildErrorResult(MeasurementResult.STATUS_ERROR,
"Unable to parse end time in owping output",
result.getStartTime(),
result.getEndTime());
}else if(!lossFound){
result = this.buildErrorResult(MeasurementResult.STATUS_ERROR,
"Unable to parse loss in owping output",
result.getStartTime(),
result.getEndTime());
}else if(!delayFound){
result = this.buildErrorResult(MeasurementResult.STATUS_ERROR,
"Unable to parse delay in owping output",
result.getStartTime(),
result.getEndTime());
}else if(!ttlFound){
result = this.buildErrorResult(MeasurementResult.STATUS_ERROR,
"Unable to parse TTL values in owping output",
result.getStartTime(),
result.getEndTime());
}
measurement.setResult(result);
//figure out hostname of source and destination
try{
InetAddress inet = InetAddress.getByName(returnedSource);
String hostname = inet.getCanonicalHostName();
String ip = inet.getHostAddress();
measurement.setSourceIP(ip);
//if get back textual representation of IP then se to null
if(!ip.equals(hostname)){
measurement.setSourceHostname(hostname);
}else if(!measurement.getSource().equals(hostname)){
//this only happens if for some reason can't get hostname but source was specified as host
measurement.setSourceHostname(measurement.getSource());
}
}catch(Exception e){
//can't resolve so set to null
log.debug("Unable to set sourceHostname: " + e.getMessage());
measurement.setSourceHostname(null);
}
try{
InetAddress inet = InetAddress.getByName(returnedDest);
String hostname = inet.getCanonicalHostName();
String ip = inet.getHostAddress();
measurement.setDestinationIP(ip);
//if get back textual representation of IP then se to null
if(!ip.equals(hostname)){
measurement.setDestinationHostname(hostname);
}else if(!measurement.getDestination().equals(hostname)){
//this only happens if for some reason can't get hostname but dest was specified as host
measurement.setDestinationHostname(measurement.getDestination());
}
}catch(Exception e){
//can't resolve so set to null
log.debug("Unable to set destinationHostname: " + e.getMessage());
measurement.setDestinationHostname(null);
}
//archive and publish measurement
this.archiveAndPublish(measurement, schedule.getStreamURI());
System.out.println(measurement.toJSONString());
}
|
diff --git a/edu/wisc/ssec/mcidasv/data/GeoLatLonSelection.java b/edu/wisc/ssec/mcidasv/data/GeoLatLonSelection.java
index 86e01e00e..be3671a62 100644
--- a/edu/wisc/ssec/mcidasv/data/GeoLatLonSelection.java
+++ b/edu/wisc/ssec/mcidasv/data/GeoLatLonSelection.java
@@ -1,1580 +1,1581 @@
/*
* $Id$
*
* This file is part of McIDAS-V
*
* Copyright 2007-2009
* Space Science and Engineering Center (SSEC)
* University of Wisconsin - Madison
* 1225 W. Dayton Street, Madison, WI 53706, USA
* http://www.ssec.wisc.edu/mcidas
*
* All Rights Reserved
*
* McIDAS-V is built on Unidata's IDV and SSEC's VisAD libraries, and
* some McIDAS-V source code is based on IDV and VisAD source code.
*
* McIDAS-V is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* McIDAS-V 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 Public License for more details.
*
* You should have received a copy of the GNU Lesser Public License
* along with this program. If not, see http://www.gnu.org/licenses.
*/
package edu.wisc.ssec.mcidasv.data;
import edu.wisc.ssec.mcidas.AreaDirectory;
import edu.wisc.ssec.mcidas.AREAnav;
import edu.wisc.ssec.mcidas.adde.AddeTextReader;
import edu.wisc.ssec.mcidasv.Constants;
import edu.wisc.ssec.mcidasv.data.hydra.HydraRGBDisplayable;
import edu.wisc.ssec.mcidasv.data.hydra.SubsetRubberBandBox;
import edu.wisc.ssec.mcidasv.data.hydra.MultiSpectralData;
import edu.wisc.ssec.mcidasv.data.hydra.MultiDimensionSubset;
import edu.wisc.ssec.mcidasv.data.hydra.HydraContext;
import edu.wisc.ssec.mcidasv.control.LambertAEA;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import ucar.unidata.data.DataCategory;
import ucar.unidata.data.DataChoice;
import ucar.unidata.data.DataSelection;
import ucar.unidata.data.DataSourceDescriptor;
import ucar.unidata.data.DataSourceImpl;
import ucar.unidata.data.DataSelectionComponent;
import ucar.unidata.data.DirectDataChoice;
import ucar.unidata.data.GeoLocationInfo;
import ucar.unidata.data.GeoSelection;
import ucar.unidata.data.GeoSelectionPanel;
import ucar.unidata.data.grid.GridUtil;
import ucar.unidata.geoloc.*;
import ucar.unidata.idv.ui.IdvUIManager;
import ucar.unidata.ui.LatLonWidget;
import ucar.unidata.util.GuiUtils;
import ucar.unidata.util.LayoutUtil;
import ucar.unidata.util.Msg;
import ucar.unidata.util.Range;
import ucar.unidata.util.Misc;
import ucar.unidata.util.StringUtil;
import ucar.unidata.util.TwoFacedObject;
import visad.Data;
import visad.FlatField;
import visad.GriddedSet;
import visad.Gridded2DSet;
import visad.SampledSet;
import visad.VisADException;
import visad.data.mcidas.AREACoordinateSystem;
import visad.georef.EarthLocationTuple;
import visad.georef.MapProjection;
import visad.data.mcidas.BaseMapAdapter;
import java.io.File;
import java.net.URL;
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
//import java.awt.event.ActionEvent;
//import java.awt.event.ActionListener;
//import java.awt.event.FocusListener;
import java.awt.Insets;
//import java.awt.event.KeyAdapter;
//import java.awt.event.KeyListener;
import java.awt.geom.Rectangle2D;
import visad.*;
import visad.bom.RubberBandBoxRendererJ3D;
import visad.java3d.DisplayImplJ3D;
import visad.java3d.TwoDDisplayRendererJ3D;
import ucar.unidata.idv.ViewManager;
import ucar.unidata.idv.ViewDescriptor;
import ucar.unidata.idv.MapViewManager;
import ucar.unidata.idv.control.DisplayControlBase;
import ucar.unidata.view.geoloc.MapProjectionDisplayJ3D;
import ucar.unidata.view.geoloc.MapProjectionDisplay;
import java.awt.Component;
import java.awt.BorderLayout;
import java.awt.Color;
import ucar.visad.display.XYDisplay;
import ucar.visad.display.MapLines;
import ucar.visad.display.DisplayMaster;
import ucar.visad.display.LineDrawing;
import ucar.visad.display.RubberBandBox;
import ucar.visad.ProjectionCoordinateSystem;
import ucar.unidata.geoloc.projection.LatLonProjection;
public class GeoLatLonSelection extends DataSelectionComponent implements Constants {
private static GeoLocationInfo geoLocInfo;
/** The spacing used in the grid layout */
protected static final int GRID_SPACING = 3;
/** Used by derived classes when they do a GuiUtils.doLayout */
protected static final Insets GRID_INSETS = new Insets(GRID_SPACING,
GRID_SPACING,
GRID_SPACING,
GRID_SPACING);
DataChoice dataChoice;
FlatField image;
boolean isLL;
MapProjection sampleProjection;
boolean hasSubset = true;
MapProjectionDisplayJ3D mapProjDsp;
DisplayMaster dspMaster;
/** ADDE request string for text */
protected static final String REQ_TEXT = "text";
/** earth coordinates */
protected static final String TYPE_LATLON = "Latitude/Longitude";
/** image */
protected static final String TYPE_IMAGE = "Image Coordinates";
/** area */
protected static final String TYPE_AREA = "Area Coordinates";
/** flag for center */
protected static final String PLACE_CENTER = "CENTER";
/** flag for upper left */
protected static final String PLACE_ULEFT = "ULEFT";
/** flag for lower left */
private static final String PLACE_LLEFT = "LLEFT";
/** flag for upper right */
private static final String PLACE_URIGHT = "URIGHT";
/** flag for lower right */
private static final String PLACE_LRIGHT = "LRIGHT";
/** Property for image default value band */
protected static final String PROP_BAND = "BAND";
/** Property for image default value id */
protected static final String PROP_ID = "ID";
/** Property for image default value key */
protected static final String PROP_KEY = "key";
/** Property for image default value lat/lon */
protected static final String PROP_LATLON = "LATLON";
/** Property for image default value line/ele */
protected static final String PROP_LINEELE = "LINELE";
/** Property for image default value loc */
protected static final String PROP_LOC = "LOC";
/** Property for image default value mag */
protected static final String PROP_MAG = "MAG";
protected static final String PROP_LMAG = "LMAG";
protected static final String PROP_EMAG = "EMAG";
/** Property for num */
protected static final String PROP_NUM = "NUM";
/** Property for image default value place */
protected static final String PROP_PLACE = "PLACE";
/** Property for image default value size */
protected static final String PROP_SIZE = "SIZE";
/** Property for image default value spac */
protected static final String PROP_SPAC = "SPAC";
/** Property for image default value unit */
protected static final String PROP_TYPE = "TYPE";
/** Property for line resolution */
protected static final String PROP_LRES = "LRES";
protected static final String PROP_PLRES = "PLRES";
/** Property for element resolution */
protected static final String PROP_ERES = "ERES";
protected static final String PROP_PERES = "PERES";
/** This is the list of properties that are used in the advanced gui */
private static final String[] ADVANCED_PROPS = {
PROP_TYPE, PROP_BAND, PROP_PLACE, PROP_LOC, PROP_SIZE, PROP_MAG,
PROP_LMAG, PROP_EMAG
};
/** This is the list of labels used for the advanced gui */
private static final String[] ADVANCED_LABELS = {
"Coordinate Type:", "Channel:", "Placement:", "Location:", " Image Size:",
"Magnification:", " Line:", " Element:"
};
private String kmLbl = " km";
/** Input for lat/lon center point */
protected LatLonWidget latLonWidget = new LatLonWidget();
/** Widget to hold the number of elements in the advanced */
JTextField numElementsFld = new JTextField();
/** Widget to hold the number of lines in the advanced */
JTextField numLinesFld = new JTextField();
/** Widget for the line center point in the advanced section */
JTextField centerLineFld = new JTextField();
/** Widget for the element center point in the advanced section */
JTextField centerElementFld = new JTextField();
/** Label used for the line center */
private JLabel centerLineLbl = new JLabel();
/** Label used for the element center */
private JLabel centerElementLbl = new JLabel();
/** Label used for the center latitude */
private JLabel centerLatLbl = new JLabel();
/** Label used for the center longitude */
private JLabel centerLonLbl = new JLabel();
/** _more_ */
private JToggleButton lockBtn;
private JButton fullResBtn;
private JPanel lMagPanel;
private JPanel eMagPanel;
/** Widget for the line magnfication in the advanced section */
protected JSlider lineMagSlider;
/** Label for the line mag. in the advanced section */
JLabel lineMagLbl = new JLabel();
JLabel lineResLbl = new JLabel();
/** Widget for the element magnfication in the advanced section */
protected JSlider elementMagSlider;
/** Label for the element mag. in the advanced section */
JLabel elementMagLbl = new JLabel();
JLabel elementResLbl = new JLabel();
/** location panel */
protected GuiUtils.CardLayoutPanel locationPanel;
/** flag for setting properties */
private boolean amSettingProperties = false;
JComboBox coordinateTypeComboBox;
JComboBox locationComboBox;
String[] coordinateTypes = { TYPE_LATLON, TYPE_IMAGE, TYPE_AREA };
String[] locations = {"Center", "Upper Left"};
/** the place string */
private static String defaultType = TYPE_LATLON;
private static String place;
private String defaultPlace = PLACE_CENTER;
private static int numLines = 0;
private int defaultNumLines = 1000;
private static int numEles = 0;
private int defaultNumEles = 1000;
private static double latitude;
private double defaultLat = 999.0;
private static double longitude;
private double defaultLon = 999.0;
private static boolean resetLatLon = true;
private static int line;
private int defaultLine = -1;
private static int element;
private int defaultElement = -1;
private static int lineMag;
private int defaultLineMag;
private static int elementMag;
private int defaultElementMag;
private static boolean isLineEle = false;
private static double lRes;
protected static double baseLRes;
private static double eRes;
protected static double baseERes;
private Hashtable properties;
private int uLLine;
private int uLEle;
private int centerLine;
private int centerEle;
/** Maps the PROP_ property name to the gui component */
private Hashtable propToComps = new Hashtable();
private JButton locPosButton;
/** size label */ JLabel sizeLbl;
/** base number of lines */
private double baseNumLines = 0.0;
/** base number of elements */
private double baseNumElements = 0.0;
private DataSourceImpl dataSource;
private static DataSourceImpl lastDataSource;
private AreaDirectory previewDir;
private static AREAnav previewNav;
private AREAnav areaNav;
private static int flipFlag = 0;
private JPanel latLonPanel;
private JPanel lineElementPanel;
protected JButton locTypeButton;
/**
* limit of slider
*/
private static final int SLIDER_MAX = 1;
private static final int SLIDER_MIN = -29;
private static final int SLIDER_WIDTH = 150;
private static final int SLIDER_HEIGHT = 16;
/**
* Keep track of the lines to element ratio
*/
private double linesToElements = 1.0;
double[][] imageEL = new double[2][5];
double[][] areaEL = new double[2][5];
double[][] displayEL = new double[2][5];
double[][] latLon = new double[2][5];
private int[] previewDirBlk;
private int previewLineRes = 1;
private int previewEleRes = 1;
public GeoLatLonSelection(DataSourceImpl dataSource,
DataChoice dataChoice, Hashtable initProps, MapProjection sample,
AreaDirectory dir, AREAnav nav)
throws VisADException, RemoteException {
super("Lat/Lon");
if (dataSource != lastDataSource) this.resetLatLon = true;
lastDataSource = dataSource;
this.properties = initProps;
this.dataSource = dataSource;
this.dataChoice = dataChoice;
this.sampleProjection = sample;
this.baseNumLines = dir.getLines();
this.baseNumElements = dir.getElements();
this.previewDir = dir;
this.previewNav = nav;
previewDirBlk = this.previewDir.getDirectoryBlock();
int areaLinRes = previewDirBlk[11];
int areaEleRes = previewDirBlk[12];
areaNav = previewNav;
areaNav.setRes(areaLinRes, areaEleRes);
int numberOfLines;
int numberOfElements;
this.baseNumLines = previewDir.getLines();
this.baseNumElements = previewDir.getElements();
if (properties.containsKey(PROP_SIZE)) {
String str = (String)properties.get(PROP_SIZE);
String[] strs = StringUtil.split(str, " ", 2);
numberOfLines = new Integer(strs[0]).intValue();
numberOfElements = new Integer(strs[1]).intValue();
} else {
try {
numberOfLines = this.previewDir.getLines();
numberOfElements = this.previewDir.getElements();
if (numberOfLines < defaultNumLines)
defaultNumLines = numberOfLines;
if (numberOfElements < defaultNumEles)
defaultNumEles = numberOfElements;
numberOfLines = defaultNumLines;
numberOfElements = defaultNumEles;
} catch (Exception e) {
System.out.println("GeoLatLonSelection: no directory e=" + e);
return;
}
}
setNumLines(new Integer(numberOfLines));
setNumEles(new Integer(numberOfElements));
if (properties.containsKey(PROP_MAG)) {
String str = (String)properties.get(PROP_MAG);
String[] strs = StringUtil.split(str, " ", 2);
defaultLineMag = new Integer(strs[0]).intValue();
defaultElementMag = new Integer(strs[1]).intValue();
} else {
defaultLineMag = -(int)((double)this.previewDir.getLines()/(double)numberOfLines + 0.5);
defaultElementMag = -(int)((double)this.previewDir.getElements()/(double)numberOfElements + 0.5);
}
setLineMag(defaultLineMag);
setElementMag(defaultElementMag);
try {
if (properties.containsKey(PROP_LRES)) {
double bRes = new Double((String)properties.get(PROP_LRES)).doubleValue();
baseLRes = bRes * this.previewDir.getCenterLatitudeResolution();
setLRes(baseLRes * Math.abs(defaultLineMag));
}
if (properties.containsKey(PROP_ERES)) {
double bRes = new Double((String)properties.get(PROP_ERES)).doubleValue();
baseERes = bRes * this.previewDir.getCenterLongitudeResolution();
setERes(baseERes * Math.abs(defaultElementMag));
}
} catch (Exception e) {
System.out.println("GeoLatLonSelection unable to get resolution: e=" + e);
return;
}
this.place = getPlace();
if (properties.containsKey(PROP_PLACE)) {
setPlace((String)properties.get(PROP_PLACE));
}
if (properties.containsKey(PROP_PLRES)) {
this.previewLineRes = new Integer((String)properties.get(PROP_PLRES)).intValue();
}
if (properties.containsKey(PROP_PERES)) {
this.previewEleRes = new Integer((String)properties.get(PROP_PERES)).intValue();
}
if (this.resetLatLon) {
if (previewDir != null) {
setLatitude(new Double(previewDir.getCenterLatitude()));
setLongitude(new Double(previewDir.getCenterLongitude()));
}
} else {
setLatitude(this.latitude);
setLongitude(this.longitude);
}
if (properties.containsKey(PROP_LATLON)) {
String str = (String)properties.get(PROP_LATLON);
String[] strs = StringUtil.split(str, " ", 2);
setLatitude(new Double(strs[0]).doubleValue());
setLongitude(new Double(strs[1]).doubleValue());
this.isLineEle = false;
} else if (properties.containsKey(PROP_LINEELE)) {
String str = (String)properties.get(PROP_LINEELE);
String[] strs = StringUtil.split(str, " ", 3);
setLine(new Integer(strs[0]).intValue());
setElement(new Integer(strs[1]).intValue());
this.isLineEle = true;
}
if (defaultLineMag > 1) {
numberOfLines = numberOfLines * defaultLineMag;
setNumLines(new Integer(numberOfLines));
setLRes(lRes/defaultLineMag);
defaultLineMag = 1;
setLineMag(defaultLineMag);
}
if (defaultElementMag > 1) {
numberOfElements = numberOfElements * defaultElementMag;
setNumEles(new Integer(numberOfElements));
setERes(lRes/defaultElementMag);
defaultElementMag = 1;
setElementMag(defaultElementMag);
}
getGeoLocationInfo();
}
protected JComponent doMakeContents() {
String[] propArray = getAdvancedProps();
String[] labelArray = getAdvancedLabels();
Insets dfltGridSpacing = new Insets(4, 0, 4, 0);
String dfltLblSpacing = " ";
List allComps = new ArrayList();
for (int propIdx = 0; propIdx < propArray.length; propIdx++) {
JComponent propComp = null;
String prop = propArray[propIdx];
if (prop.equals(PROP_TYPE)) {
coordinateTypeComboBox = new JComboBox(coordinateTypes);
coordinateTypeComboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
int selectedIndex = coordinateTypeComboBox.getSelectedIndex();
flipLocationPanel(selectedIndex);
}
});
propComp = (JComponent)coordinateTypeComboBox;
}
else if (prop.equals(PROP_LOC)) {
locationComboBox = new JComboBox(locations);
setPlace(this.place);
locationComboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String selected =
translatePlace((String)locationComboBox.getSelectedItem());
setPlace(selected);
cyclePlace();
}
});
propComp = (JComponent)locationComboBox;
addPropComp(PROP_LOC, propComp);
ActionListener latLonChange =new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String type = getCoordinateType();
if (type.equals(TYPE_LATLON)) {
setLatitude();
setLongitude();
} else {
setLine();
setElement();
}
}
};
FocusListener linEleFocusChange = new FocusListener() {
public void focusGained(FocusEvent fe) {
}
public void focusLost(FocusEvent fe) {
setLine();
setElement();
}
};
latLonWidget = new LatLonWidget(latLonChange);
FocusListener latLonFocusChange = new FocusListener() {
public void focusGained(FocusEvent fe) {
}
public void focusLost(FocusEvent fe) {
setLatitude();
setLongitude();
}
};
if (!this.isLineEle) {
latLonWidget.setLatLon((Double.toString(this.latitude)),
(Double.toString(this.longitude)));
}
String lineStr = "";
String eleStr = "";
setLine(this.line);
setElement(this.element);
if ((this.line > 0) && (this.element > 0)) {
lineStr =Integer.toString(this.line);
eleStr =Integer.toString(this.element);
}
centerLineFld = new JTextField(lineStr, 3);
centerLineFld.addFocusListener(linEleFocusChange);
final String lineField = "";
centerElementFld = new JTextField(eleStr, 3);
centerElementFld.addFocusListener(linEleFocusChange);
final JButton centerPopupBtn =
GuiUtils.getImageButton(
"/auxdata/ui/icons/MapIcon16.png", getClass());
centerPopupBtn.setToolTipText("Center on current displays");
centerPopupBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
- popupCenterMenu( centerPopupBtn, latLonWidget);
+ dataSource.getDataContext().getIdv().getIdvUIManager().popupCenterMenu(
+ centerPopupBtn, latLonWidget);
}
});
JComponent centerPopup = GuiUtils.inset(centerPopupBtn,
new Insets(0, 0, 0, 4));
GuiUtils.tmpInsets = dfltGridSpacing;
JTextField latFld = latLonWidget.getLatField();
JTextField lonFld = latLonWidget.getLonField();
latFld.addFocusListener(latLonFocusChange);
lonFld.addFocusListener(latLonFocusChange);
latLonPanel = GuiUtils.hbox(new Component[] {
centerLatLbl = GuiUtils.rLabel(" Lat:" + dfltLblSpacing),
latFld,
centerLonLbl = GuiUtils.rLabel(" Lon:" + dfltLblSpacing),
lonFld,
new JLabel(" "), centerPopup
});
lineElementPanel =
GuiUtils.hbox(new Component[] {
centerLineLbl =
GuiUtils.rLabel(" Line:" + dfltLblSpacing),
centerLineFld,
centerElementLbl = GuiUtils.rLabel(" Element:"
+ dfltLblSpacing),
centerElementFld });
locationPanel = new GuiUtils.CardLayoutPanel();
locationPanel.addCard(latLonPanel);
locationPanel.addCard(lineElementPanel);
if (propComp != null) {
allComps.add(GuiUtils.rLabel(labelArray[propIdx]));
allComps.add(GuiUtils.left(propComp));
}
propComp = GuiUtils.hbox(new Component[] { locationPanel }, 1);
if (propComp != null) {
allComps.add(GuiUtils.rLabel(" "));
allComps.add(GuiUtils.left(propComp));
}
propComp = null;
} else if (prop.equals(PROP_SIZE)) {
ActionListener sizeChange =new ActionListener() {
public void actionPerformed(ActionEvent ae) {
getGeoLocationInfo();
}
};
FocusListener sizeFocusChange = new FocusListener() {
public void focusGained(FocusEvent fe) {
}
public void focusLost(FocusEvent fe) {
getGeoLocationInfo();
}
};
setNumLines(this.numLines);
numLinesFld = new JTextField(Integer.toString(this.numLines), 4);
numLinesFld.addActionListener(sizeChange);
numLinesFld.addFocusListener(sizeFocusChange);
setNumEles(this.numEles);
numElementsFld = new JTextField(Integer.toString(this.numEles), 4);
numElementsFld.addActionListener(sizeChange);
numElementsFld.addFocusListener(sizeFocusChange);
numLinesFld.setToolTipText("Number of lines");
numElementsFld.setToolTipText("Number of elements");
GuiUtils.tmpInsets = dfltGridSpacing;
sizeLbl = GuiUtils.lLabel("");
fullResBtn = GuiUtils.makeImageButton(
"/auxdata/ui/icons/arrow_out.png", this,
"setToFullResolution");
fullResBtn.setContentAreaFilled(false);
fullResBtn.setToolTipText("Set to full resolution");
lockBtn =
GuiUtils.getToggleImageButton(IdvUIManager.ICON_UNLOCK,
IdvUIManager.ICON_LOCK, 0, 0, true);
lockBtn.setContentAreaFilled(false);
lockBtn.setSelected(true);
lockBtn.setToolTipText(
"Unlock to automatically change size when changing magnification");
JLabel rawSizeLbl = new JLabel(" Raw size: " + previewDirBlk[8]
+ " X " + previewDirBlk[9]);
JPanel sizePanel =
GuiUtils.left(GuiUtils.doLayout(new Component[] {
numLinesFld,
new JLabel(" X "), numElementsFld, sizeLbl, fullResBtn, lockBtn,
rawSizeLbl }, 7, GuiUtils.WT_N, GuiUtils.WT_N));
addPropComp(PROP_SIZE, propComp = sizePanel);
} else if (prop.equals(PROP_MAG)) {
propComp = GuiUtils.hbox(new Component[] { new JLabel("") }, 1);
addPropComp(PROP_MAG, propComp);
} else if (prop.equals(PROP_LMAG)) {
boolean oldAmSettingProperties = amSettingProperties;
amSettingProperties = true;
ChangeListener lineListener =
new javax.swing.event.ChangeListener() {
public void stateChanged(ChangeEvent evt) {
if (amSettingProperties) {
return;
}
lineMagSliderChanged(!lockBtn.isSelected());
getGeoLocationInfo();
}
};
JComponent[] lineMagComps =
GuiUtils.makeSliderPopup(SLIDER_MIN, SLIDER_MAX, 0,
lineListener);
lineMagSlider = (JSlider) lineMagComps[1];
lineMagSlider.setPreferredSize(new Dimension(SLIDER_WIDTH,SLIDER_HEIGHT));
lineMagSlider.setMajorTickSpacing(1);
lineMagSlider.setSnapToTicks(true);
lineMagSlider.setExtent(1);
setLineMag(this.lineMag);
lineMagSlider.setValue(this.lineMag);
lineMagComps[0].setToolTipText(
"Change the line magnification");
lineMagSlider.setToolTipText(
"Slide to set line magnification factor");
String str = "Mag=" + Integer.toString(getLineMag());
lineMagLbl =
GuiUtils.getFixedWidthLabel(StringUtil.padLeft(str, 4));
str = truncateNumericString(Double.toString(baseLRes*Math.abs(getLineMag())), 1);
str = " Res=" + str + kmLbl;
lineResLbl =
GuiUtils.getFixedWidthLabel(StringUtil.padLeft(str, 4));
amSettingProperties = oldAmSettingProperties;
GuiUtils.tmpInsets = dfltGridSpacing;
lMagPanel = GuiUtils.doLayout(new Component[] {
lineMagLbl,
GuiUtils.inset(lineMagComps[1],
new Insets(0, 4, 0, 0)), lineResLbl, }, 4,
GuiUtils.WT_N, GuiUtils.WT_N);
propComp = GuiUtils.hbox(new Component[] { new JLabel(" "), lMagPanel }, 2);
addPropComp(PROP_LMAG, propComp = lMagPanel);
} else if (prop.equals(PROP_EMAG)) {
boolean oldAmSettingProperties = amSettingProperties;
amSettingProperties = true;
ChangeListener elementListener = new ChangeListener() {
public void stateChanged(
javax.swing.event.ChangeEvent evt) {
if (amSettingProperties) {
return;
}
elementMagSliderChanged(true);
getGeoLocationInfo();
}
};
JComponent[] elementMagComps =
GuiUtils.makeSliderPopup(SLIDER_MIN, SLIDER_MAX, 0,
elementListener);
elementMagSlider = (JSlider) elementMagComps[1];
elementMagSlider.setPreferredSize(new Dimension(SLIDER_WIDTH,SLIDER_HEIGHT));
elementMagSlider.setExtent(1);
elementMagSlider.setMajorTickSpacing(1);
elementMagSlider.setSnapToTicks(true);
setElementMag(this.elementMag);
elementMagSlider.setValue(this.elementMag);
elementMagComps[0].setToolTipText(
"Change the element magnification");
elementMagSlider.setToolTipText(
"Slide to set element magnification factor");
String str = "Mag=" + Integer.toString(getElementMag());
elementMagLbl =
GuiUtils.getFixedWidthLabel(StringUtil.padLeft(str, 4));
str = truncateNumericString(Double.toString(baseERes*Math.abs(getElementMag())), 1);
str = " Res=" + str + kmLbl;
elementResLbl =
GuiUtils.getFixedWidthLabel(StringUtil.padLeft(str, 4));
amSettingProperties = oldAmSettingProperties;
GuiUtils.tmpInsets = dfltGridSpacing;
eMagPanel = GuiUtils.doLayout(new Component[] {
elementMagLbl,
GuiUtils.inset(elementMagComps[1],
new Insets(0, 4, 0, 0)), elementResLbl, }, 4,
GuiUtils.WT_N, GuiUtils.WT_N);
propComp = GuiUtils.hbox(new Component[] { new JLabel(" "), eMagPanel }, 2);
addPropComp(PROP_EMAG, propComp = eMagPanel);
}
if (propComp != null) {
allComps.add(GuiUtils.rLabel(labelArray[propIdx]));
allComps.add(GuiUtils.left(propComp));
}
}
GuiUtils.tmpInsets = GRID_INSETS;
JPanel imagePanel = GuiUtils.doLayout(allComps, 2, GuiUtils.WT_NY,
GuiUtils.WT_N);
getGeoLocationInfo();
return GuiUtils.top(imagePanel);
}
/**
* Change coordinate type panel
*/
protected void flipLocationPanel(int locPanel) {
int nowPlaying = locationPanel.getVisibleIndex();
if (locPanel > 0) {
if (nowPlaying == 0) {
locationPanel.flip();
}
setIsLineEle(true);
String type = getCoordinateType();
String loc = getPlace();
int indx = 0;
if (loc.equals(PLACE_ULEFT)) indx = 1;
int ele = 0;
int lin = 0;
if (type.equals(TYPE_IMAGE)) {
ele = (int)Math.floor(imageEL[0][indx] + 0.5);
lin = (int)Math.floor(imageEL[1][indx] + 0.5);
} else if (type.equals(TYPE_AREA)) {
ele = (int)Math.floor(areaEL[0][indx] + 0.5);
lin = (int)Math.floor(areaEL[1][indx] + 0.5);
}
setElement(ele);
setLine(lin);
} else {
if (nowPlaying > 0) locationPanel.flip();
setIsLineEle(false);
}
}
/**
* Set to full resolution
*/
public void setToFullResolution() {
amSettingProperties = true;
if (!getIsLineEle()) {
setIsLineEle(true);
coordinateTypeComboBox.setSelectedItem(TYPE_IMAGE);
}
setPlace(PLACE_CENTER);
setLatitude(new Double(previewDir.getCenterLatitude()));
setLongitude(new Double(previewDir.getCenterLongitude()));
convertToLinEle();
setNumLines(previewDirBlk[8]);
setNumEles(previewDirBlk[9]);
setLineMag(1);
setElementMag(1);
lineMagSlider.setValue(1);
setLRes(-1.0);
lineMagSliderChanged(false);
elementMagSlider.setValue(1);
setERes(-1.0);
elementMagSliderChanged(false);
getGeoLocationInfo();
amSettingProperties = false;
}
public void applyToDataSelection(DataSelection dataSelection) {
if (dataSelection == null) {
dataSelection = new DataSelection(true);
}
GeoLocationInfo geoInfo = getGeoLocationInfo();
if (geoInfo == null) {
dataSelection = null;
return;
}
if (!isLineEle) {
double lat = getLatitude();
double lon = getLongitude();
if (lat > 90.0 && lon> 360.0) {
convertToLatLon();
lat = getLatitude();
lon = getLongitude();
}
String latString = Double.toString(lat);
if (latString.length()>8)
latString = latString.substring(0,7);
String lonString = Double.toString(lon);
if (lonString.length()>9)
lonString = lonString.substring(0,8);
dataSelection.putProperty(PROP_LATLON, (latString + " " + lonString));
} else {
String coordType = (String)coordinateTypeComboBox.getSelectedItem();
String typeStr = " I";
int lin = getLine();
int ele = getElement();
if (coordType.equals(TYPE_AREA)) {
typeStr = " F";
}
String linString = Integer.toString(lin);
String eleString = Integer.toString(ele);
dataSelection.putProperty(PROP_LINEELE, (linString + " " + eleString + typeStr));
}
dataSelection.putProperty(PROP_PLACE, getPlace());
dataSelection.putProperty(PROP_MAG, (getLineMag() + " " + getElementMag()));
GeoSelection geoSelection = new GeoSelection(geoInfo);
dataSelection.setGeoSelection(geoSelection);
int nlins = getNumLines();
int neles = getNumEles();
if (nlins > 0 && neles > 0) {
dataSelection.putProperty(PROP_SIZE, (nlins + " " + neles));
}
dataChoice.setDataSelection(dataSelection);
}
public GeoLocationInfo getGeoLocationInfo() {
geoLocInfo = null;
double[][] el = convertToDisplayCoords();
int ele = (int)Math.floor(el[0][0] + 0.5);
if (ele > 0) {
int lin = (int)Math.floor(el[1][0] + 0.5);
if (lin > 0) {
int nLin = getNumLines();
if (nLin > 0) {
int nEle = getNumEles();
if (nEle > 0) {
int lMag = getLineMag();
if (lMag > 1) return geoLocInfo;
int eMag = getElementMag();
if (eMag > 1) return geoLocInfo;
geoLocInfo = makeGeoLocationInfo(lin, ele, nLin, nEle,
lMag, eMag);
if (geoLocInfo != null) {
int indx = 0;
if (getPlace().equals(PLACE_ULEFT)) indx = 1;
String type = getCoordinateType();
if (type.equals(TYPE_LATLON)) {
setLatitude(latLon[0][indx]);
setLongitude(latLon[1][indx]);
} else if (type.equals(TYPE_IMAGE)) {
setElement((int)Math.floor(imageEL[0][indx]+0.5));
setLine((int)Math.floor(imageEL[1][indx]+0.5));
} else if (type.equals(TYPE_AREA)) {
setElement((int)Math.floor(areaEL[0][indx]+0.5));
setLine((int)Math.floor(areaEL[1][indx]+0.5));
}
}
}
}
}
}
return geoLocInfo;
}
private GeoLocationInfo makeGeoLocationInfo(int lin, int ele, int nlins, int neles,
int linMag, int eleMag) {
geoLocInfo = null;
String plc = getPlace();
double lat = 9999.0;
double lon = 9999.0;
try {
lat = getLatitude();
lon = getLongitude();
} catch (Exception e) {
}
if (lin < 0 && ele < 0) {
if (lat <= 90.0 && lon < 999.0) {
convertToLinEle();
ele = getElement();
lin = getLine();
} else {
return geoLocInfo;
}
} else if (lat > 90.0 && lon > 360.0) {
convertToLatLon();
lat = getLatitude();
lon = getLongitude();
}
if ((lat > 90.0) || (lat < -90.0)) {
return geoLocInfo;
}
AREACoordinateSystem macs = (AREACoordinateSystem)sampleProjection;
double dLine = (double)nlins/(2.0*this.previewLineRes)*Math.abs(linMag);
double dEle = (double)neles/(2.0*this.previewEleRes)*Math.abs(eleMag);
if (plc.equals(PLACE_CENTER)) {
displayEL[0][0] = ele;
displayEL[1][0] = lin;
displayEL[0][1] = ele - dEle;
if (displayEL[0][1] < 1) displayEL[0][1] = 1.0;
displayEL[1][1] = lin + dLine;
if (displayEL[1][1] > 500) displayEL[1][1] = 500.0;
} else if (plc.equals(PLACE_ULEFT)) {
displayEL[0][0] = ele + dEle;
if (displayEL[0][0] > 525) displayEL[0][0] = 525.0;
displayEL[1][0] = lin - dLine;
if (displayEL[1][0] < 1) displayEL[1][0] = 1.0;
displayEL[0][1] = ele;
displayEL[1][1] = lin;
}
int cEle = (int)Math.ceil(displayEL[0][0]);
int cLin = (int)Math.ceil(displayEL[1][0]);
displayEL[0][2] = cEle + dEle;
if (displayEL[0][2] > 525) displayEL[0][2] = 525.0;
displayEL[1][2] = cLin + dLine;
if (displayEL[1][2] > 500) displayEL[1][2] = 500.0;
displayEL[0][3] = cEle - dEle;
if (displayEL[0][3] < 1) displayEL[0][3] = 1.0;
displayEL[1][3] = cLin - dLine;
if (displayEL[1][3] < 1) displayEL[1][3] = 1.0;
displayEL[0][4] = cEle + dEle;
if (displayEL[0][4] > 525) displayEL[0][4] = 525.0;
displayEL[1][4] = cLin - dLine;
if (displayEL[1][4] < 1) displayEL[1][4] = 1.0;
try {
latLon = macs.toReference(displayEL);
} catch (Exception e) {
System.out.println("Error converting input lat/lon e=" + e);
}
double maxLat = latLon[0][1];
if (latLon[0][2] > maxLat) maxLat = latLon[0][2];
double minLat = latLon[0][3];
if (latLon[0][4] < minLat) minLat = latLon[0][4];
double maxLon = latLon[1][4];
if (latLon[1][2] > maxLon) maxLon = latLon[1][2];
double minLon = latLon[1][1];
if (latLon[1][3] < minLon) minLon = latLon[1][3];
areaEL = previewNav.toLinEle(latLon);
imageEL = previewNav.areaCoordToImageCoord(areaEL);
areaEL = areaNav.imageCoordToAreaCoord(imageEL);
geoLocInfo = new GeoLocationInfo(maxLat, minLon, minLat, maxLon);
return geoLocInfo;
}
/**
* Get the list of advanced property names
*
* @return array of advanced property names
*/
protected String[] getAdvancedProps() {
return ADVANCED_PROPS;
}
/**
* Get the list of advanced property labels
*
* @return list of advanced property labels
*/
protected String[] getAdvancedLabels() {
return ADVANCED_LABELS;
}
/**
* Cycle the place
*/
public void cyclePlace() {
if (this.place.equals(PLACE_CENTER)) {
double finagle = 0.5;
setLine((int)(imageEL[1][0] + finagle));
setElement((int)(imageEL[0][0] + finagle));
setLatitude(latLon[0][0]);
setLongitude(latLon[1][0]);
} else {
double finagle = 0.5;
setLine((int)(imageEL[1][1] + finagle));
setElement((int)(imageEL[0][1] + finagle));
setLatitude(latLon[0][1]);
setLongitude(latLon[1][1]);
}
}
/**
* Associates the goven JComponent with the PROP_ property
* identified by the given propId
*
* @param propId The property
* @param comp The gui component that allows the user to set the property
*
* @return Just returns the given comp
*/
protected JComponent addPropComp(String propId, JComponent comp) {
Object oldComp = propToComps.get(propId);
if (oldComp != null) {
throw new IllegalStateException(
"Already have a component defined:" + propId);
}
propToComps.put(propId, comp);
return comp;
}
/**
* Translate a place name into a human readable form
*
* @param place raw name
*
* @return human readable name
*/
protected String translatePlace(String thisPlace) {
if (thisPlace.equals("Upper Left")) {
return PLACE_ULEFT;
}
if (thisPlace.equals("Center")) {
return PLACE_CENTER;
}
return thisPlace;
}
public String getPlace() {
try {
this.place = translatePlace((String)locationComboBox.getSelectedItem());
} catch (Exception e) {
this.place = defaultPlace;
}
return this.place;
}
public void setPlace(String str) {
if (str.equals("")) str = defaultPlace;
this.place = str;
}
public int getNumLines() {
int val = -1;
try {
val = new Integer(numLinesFld.getText().trim()).intValue();
} catch (Exception e) {
if (val < 1) val = defaultNumLines;
}
setNumLines(val);
return this.numLines;
}
public void setNumLines(int val) {
if (val < 1) val = defaultNumLines;
numLinesFld.setText(new Integer(val).toString());
this.numLines = val;
}
public int getNumEles() {
int val = -1;
try {
val = new Integer(numElementsFld.getText().trim()).intValue();
} catch (Exception e) {
if (val < 1) val = defaultNumEles;
}
setNumEles(val);
return this.numEles;
}
public void setNumEles(int val) {
if (val < 1) val = defaultNumEles;
val = (int)((double)val/4.0 + 0.5)*4;
numElementsFld.setText(new Integer(val).toString());
this.numEles = val;
}
public int getLine() {
int val = -1;
try {
val = new Integer(centerLineFld.getText().trim()).intValue();
} catch (Exception e) {
}
if (val < 1) val = defaultLine;
setLine(val);
return this.line;
}
private void setLine() {
this.line = getLine();
}
public void setLine(int val) {
if (val < 0) val = defaultLine;
centerLineFld.setText(new Integer(val).toString());
this.line = val;
}
private void setElement() {
this.element = getElement();
}
public int getElement() {
int val =-1;
try {
val = new Integer(centerElementFld.getText().trim()).intValue();
} catch (Exception e) {
}
if (val < 1) val = defaultElement;
setElement(val);
return this.element;
}
public void setElement(int val) {
if (val < 0) val = defaultElement;
centerElementFld.setText(new Integer(val).toString());
this.element = val;
}
public int getLineMag() {
return this.lineMag;
}
public void setLineMag(int val) {
if (val > 1) val = defaultLineMag;
if (val == -1) val = 1;
this.lineMag = val;
}
public int getElementMag() {
return this.elementMag;
}
public void setElementMag(int val) {
if (val > 1) val = defaultElementMag;
if (val == -1) val = 1;
this.elementMag = val;
}
public double getLatitude() {
double val = latLonWidget.getLat();
Double dbl = new Double(val);
if (dbl.isNaN()) val = defaultLat;
if (val < -90.0 || val > 90.0) val = defaultLat;
setLatitude(val);
return this.latitude;
}
private void setLatitude() {
this.latitude = latLonWidget.getLat();
}
public void setLatitude(double val) {
if (val < -90.0 || val > 90.0) val = defaultLat;
latLonWidget.setLat(val);
this.latitude = val;
this.resetLatLon = false;
}
private void setLongitude() {
this.longitude = latLonWidget.getLon();
}
public double getLongitude() {
double val = latLonWidget.getLon();
Double dbl = new Double(val);
if (dbl.isNaN()) val = defaultLon;
if (val < -180.0 || val > 180.0) val = defaultLon;
setLongitude(val);
return this.longitude;
}
public void setLongitude(double val) {
if (val < -180.0 || val > 180.0) val = defaultLon;
latLonWidget.setLon(val);
this.longitude = val;
this.resetLatLon = false;
}
protected void convertToLatLon() {
double[][] el = new double[2][1];
el[0][0] = getElement();
el[1][0] = getLine();
double[][] ll = new double[2][1];
String coordType = (String)coordinateTypeComboBox.getSelectedItem();
if (coordType.equals(TYPE_IMAGE))
el = previewNav.imageCoordToAreaCoord(el);
try {
AREACoordinateSystem macs = (AREACoordinateSystem)sampleProjection;
ll = macs.toReference(el);
setLatitude(ll[0][0]);
setLongitude(ll[1][0]);
getGeoLocationInfo();
} catch (Exception e) {
System.out.println("convertToLatLon e=" + e);
}
}
protected void convertToLatLon(int ele, int lin) {
try {
double[][] el = new double[2][1];
double[][] ll = new double[2][1];
AREACoordinateSystem macs = (AREACoordinateSystem)sampleProjection;
el[0][0] = (double)ele;
el[1][0] = (double)lin;
ll = macs.toReference(el);
setLatitude(ll[0][0]);
setLongitude(ll[1][0]);
double[][] imageLE = new double[2][1];
double[][] areaLE = new double[2][1];
areaLE = previewNav.toLinEle(ll);
imageLE = previewNav.areaCoordToImageCoord(areaLE);
setCenterCoords((int)imageLE[0][0], (int)imageLE[1][0]);
getGeoLocationInfo();
} catch (Exception e) {
System.out.println("convertToLatLon e=" + e);
}
}
protected double[][] convertToDisplayCoords() {
double[][] el = new double[2][1];
try {
double[][] ll = new double[2][1];
AREACoordinateSystem macs = (AREACoordinateSystem)sampleProjection;
String type = getCoordinateType();
if (type.equals(TYPE_LATLON)) {
ll[0][0] = getLatitude();
ll[1][0] = getLongitude();
} else {
el[0][0] = (double)getElement();
el[1][0] = (double)getLine();
if (type.equals(TYPE_IMAGE)) {
el = areaNav.imageCoordToAreaCoord(el);
}
ll = previewNav.toLatLon(el);
}
el = macs.fromReference(ll);
} catch (Exception e) {
System.out.println("convertToDisplayCoords e=" + e);
}
return el;
}
protected void convertToLinEle() {
try {
double[][] el = new double[2][1];
double[][] ll = new double[2][1];
AREACoordinateSystem macs = (AREACoordinateSystem)sampleProjection;
ll[0][0] = getLatitude();
ll[1][0] = getLongitude();
String coordType = getCoordinateType();
el = previewNav.toLinEle(ll);
if (coordType.equals(TYPE_IMAGE))
el = previewNav.areaCoordToImageCoord(el);
setLine((int)el[1][0]);
setElement((int)el[0][0]);
getGeoLocationInfo();
} catch (Exception e) {
System.out.println("convertToLinEle e=" + e);
}
}
private String getCoordinateType() {
String ret = defaultType;
try {
ret = (String)coordinateTypeComboBox.getSelectedItem();
} catch (Exception e) {
}
return ret;
}
protected void setCoordinateType(String type) {
if (!type.equals(TYPE_IMAGE)) {
if (!type.equals(TYPE_AREA)) {
type = TYPE_LATLON;
}
}
coordinateTypeComboBox.setSelectedItem(type);
}
protected void setULCoords(double x, double y) {
uLLine = (int)y;
uLEle = (int)x;
}
protected void setCenterCoords(int x, int y) {
centerLine = y;
setLine(y);
centerEle = x;
setElement(x);
}
protected void elementMagSliderChanged(boolean recomputeLineEleRatio) {
int value = getElementMagValue();
setElementMag(value);
double eVal = this.eRes;
if (value < 0) eVal *= Math.abs(value);
if ((Math.abs(value) < SLIDER_MAX)) {
int lineMag = getLineMagValue();
if (lineMag > value) {
linesToElements = Math.abs(lineMag
/ (double) value);
} else {
linesToElements = Math.abs((double) value
/ lineMag);
}
}
elementMagLbl.setText(StringUtil.padLeft("Mag=" + value, 4));
String str = " Res=" +
truncateNumericString(Double.toString(baseERes*Math.abs(value)), 1);
elementResLbl.setText(StringUtil.padLeft(str, 4) + kmLbl);
if (!lockBtn.isSelected()) {
if (value > 0) {
numElementsFld.setText(""
+ (int) (this.baseNumElements * value));
} else {
numElementsFld.setText(""
+ (int) (this.baseNumElements
/ (double) -value));
}
}
}
/**
* Handle the line mag slider changed event
*
* @param evt the event
*/
protected void lineMagSliderChanged(boolean autoSetSize) {
try {
int value = getLineMagValue();
setLineMag(value);
double lVal = this.lRes;
if (value < 0) lVal *= Math.abs(value);
lineMagLbl.setText(StringUtil.padLeft("Mag=" + value, 4));
String str = " Res=" +
truncateNumericString(Double.toString(baseLRes*Math.abs(value)), 1);
lineResLbl.setText(StringUtil.padLeft(str, 4) + kmLbl);
if (autoSetSize) {
if (value > 0) {
numLinesFld.setText("" + (int) (baseNumLines * value));
} else {
numLinesFld.setText("" + (int) (baseNumLines
/ (double) -value));
}
}
if (value == 1) { // special case
if (linesToElements < 1.0) {
value = (int) (-value / linesToElements);
} else {
value = (int) (value * linesToElements);
}
} else if (value > 1) {
value = (int) (value * linesToElements);
} else {
value = (int) (value / linesToElements);
}
value = (value > 0)
? value - 1
: value + 1; // since slider is one off
amSettingProperties = true;
elementMagSlider.setValue(value);
amSettingProperties = false;
elementMagSliderChanged(false);
} catch (Exception exc) {
System.out.println("Setting line magnification" + exc);
}
}
/**
* Get the value of the line magnification slider.
*
* @return The magnification value for the line
*/
protected int getLineMagValue() {
return getMagValue(lineMagSlider);
}
/**
* Get the value of the element magnification slider.
*
* @return The magnification value for the element
*/
protected int getElementMagValue() {
return getMagValue(elementMagSlider);
}
/**
* Get the value of the given magnification slider.
*
* @param slider The slider to get the value from
* @return The magnification value
*/
private int getMagValue(JSlider slider) {
//Value is [-SLIDER_MAX,SLIDER_MAX]. We change 0 and -1 to 1
int value = slider.getValue();
if (value >= 0) {
return value + 1;
}
return value - 1;
}
/**
* Popup a centering menu
*
* @param near component to popup near
* @param latLonWidget _more_
*/
public void popupCenterMenu(JComponent near,
final LatLonWidget latLonWidget) {
List menuItems = new ArrayList();
List menus = new ArrayList();
LatLonPoint center = new LatLonPointImpl(latLon[0][0], latLon[1][0]);
menuItems.add(makeLocationMenuItem(center, "Center"));
LatLonPoint upperLeft = new LatLonPointImpl(latLon[0][1], latLon[1][1]);
menuItems.add(makeLocationMenuItem(upperLeft, "Upper Left"));
LatLonPoint upperRight =new LatLonPointImpl(latLon[0][2], latLon[1][2]);
menuItems.add(makeLocationMenuItem(upperRight, "Upper Right"));
LatLonPoint lowerLeft =new LatLonPointImpl(latLon[0][3], latLon[1][3]);
menuItems.add(makeLocationMenuItem(lowerLeft, "Lower Left"));
LatLonPoint lowerRight =new LatLonPointImpl(latLon[0][4], latLon[1][4]);
menuItems.add(makeLocationMenuItem(lowerRight, "Lower Right"));
menus.add(GuiUtils.makeMenu("Corner Points", menuItems));
GuiUtils.showPopupMenu(menuItems, near);
}
/**
* _more_
*
* @param el _more_
* @param name _more_
* @param listener _more_
*
* @return _more_
*/
private JMenuItem makeLocationMenuItem(final LatLonPoint llp,
final String name) {
JMenuItem mi = null;
try {
double alt = 0.0;
EarthLocationTuple elt =
new EarthLocationTuple(llp.getLatitude(), llp.getLongitude(), alt);
mi =
new JMenuItem(
StringUtil.padRight(name + ": ", 15, " ")
+ dataSource.getDataContext().getIdv().getDisplayConventions()
.formatLatLonPoint(elt.getLatLonPoint()));
GuiUtils.setFixedWidthFont(mi);
} catch (Exception e) {
System.out.println("makeLocationMenuItem e=" + e);
}
return mi;
}
public boolean getIsLineEle() {
return this.isLineEle;
}
public void setIsLineEle(boolean val) {
this.isLineEle = val;
}
public double getLRes() {
return this.lRes;
}
public void setLRes(double val) {
if (val < 1) val = baseLRes;
this.lRes = val;
}
public double getERes() {
return this.eRes;
}
public void setERes(double val) {
if (val < 1) val = baseERes;
this.eRes = val;
}
public int getPreviewLineRes() {
return this.previewLineRes;
}
public int getPreviewEleRes() {
return this.previewEleRes;
}
private String truncateNumericString(String str, int numDec) {
int indx = str.indexOf(".") + numDec + 1;
return str.substring(0,indx);
}
}
| true | true | protected JComponent doMakeContents() {
String[] propArray = getAdvancedProps();
String[] labelArray = getAdvancedLabels();
Insets dfltGridSpacing = new Insets(4, 0, 4, 0);
String dfltLblSpacing = " ";
List allComps = new ArrayList();
for (int propIdx = 0; propIdx < propArray.length; propIdx++) {
JComponent propComp = null;
String prop = propArray[propIdx];
if (prop.equals(PROP_TYPE)) {
coordinateTypeComboBox = new JComboBox(coordinateTypes);
coordinateTypeComboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
int selectedIndex = coordinateTypeComboBox.getSelectedIndex();
flipLocationPanel(selectedIndex);
}
});
propComp = (JComponent)coordinateTypeComboBox;
}
else if (prop.equals(PROP_LOC)) {
locationComboBox = new JComboBox(locations);
setPlace(this.place);
locationComboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String selected =
translatePlace((String)locationComboBox.getSelectedItem());
setPlace(selected);
cyclePlace();
}
});
propComp = (JComponent)locationComboBox;
addPropComp(PROP_LOC, propComp);
ActionListener latLonChange =new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String type = getCoordinateType();
if (type.equals(TYPE_LATLON)) {
setLatitude();
setLongitude();
} else {
setLine();
setElement();
}
}
};
FocusListener linEleFocusChange = new FocusListener() {
public void focusGained(FocusEvent fe) {
}
public void focusLost(FocusEvent fe) {
setLine();
setElement();
}
};
latLonWidget = new LatLonWidget(latLonChange);
FocusListener latLonFocusChange = new FocusListener() {
public void focusGained(FocusEvent fe) {
}
public void focusLost(FocusEvent fe) {
setLatitude();
setLongitude();
}
};
if (!this.isLineEle) {
latLonWidget.setLatLon((Double.toString(this.latitude)),
(Double.toString(this.longitude)));
}
String lineStr = "";
String eleStr = "";
setLine(this.line);
setElement(this.element);
if ((this.line > 0) && (this.element > 0)) {
lineStr =Integer.toString(this.line);
eleStr =Integer.toString(this.element);
}
centerLineFld = new JTextField(lineStr, 3);
centerLineFld.addFocusListener(linEleFocusChange);
final String lineField = "";
centerElementFld = new JTextField(eleStr, 3);
centerElementFld.addFocusListener(linEleFocusChange);
final JButton centerPopupBtn =
GuiUtils.getImageButton(
"/auxdata/ui/icons/MapIcon16.png", getClass());
centerPopupBtn.setToolTipText("Center on current displays");
centerPopupBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
popupCenterMenu( centerPopupBtn, latLonWidget);
}
});
JComponent centerPopup = GuiUtils.inset(centerPopupBtn,
new Insets(0, 0, 0, 4));
GuiUtils.tmpInsets = dfltGridSpacing;
JTextField latFld = latLonWidget.getLatField();
JTextField lonFld = latLonWidget.getLonField();
latFld.addFocusListener(latLonFocusChange);
lonFld.addFocusListener(latLonFocusChange);
latLonPanel = GuiUtils.hbox(new Component[] {
centerLatLbl = GuiUtils.rLabel(" Lat:" + dfltLblSpacing),
latFld,
centerLonLbl = GuiUtils.rLabel(" Lon:" + dfltLblSpacing),
lonFld,
new JLabel(" "), centerPopup
});
lineElementPanel =
GuiUtils.hbox(new Component[] {
centerLineLbl =
GuiUtils.rLabel(" Line:" + dfltLblSpacing),
centerLineFld,
centerElementLbl = GuiUtils.rLabel(" Element:"
+ dfltLblSpacing),
centerElementFld });
locationPanel = new GuiUtils.CardLayoutPanel();
locationPanel.addCard(latLonPanel);
locationPanel.addCard(lineElementPanel);
if (propComp != null) {
allComps.add(GuiUtils.rLabel(labelArray[propIdx]));
allComps.add(GuiUtils.left(propComp));
}
propComp = GuiUtils.hbox(new Component[] { locationPanel }, 1);
if (propComp != null) {
allComps.add(GuiUtils.rLabel(" "));
allComps.add(GuiUtils.left(propComp));
}
propComp = null;
} else if (prop.equals(PROP_SIZE)) {
ActionListener sizeChange =new ActionListener() {
public void actionPerformed(ActionEvent ae) {
getGeoLocationInfo();
}
};
FocusListener sizeFocusChange = new FocusListener() {
public void focusGained(FocusEvent fe) {
}
public void focusLost(FocusEvent fe) {
getGeoLocationInfo();
}
};
setNumLines(this.numLines);
numLinesFld = new JTextField(Integer.toString(this.numLines), 4);
numLinesFld.addActionListener(sizeChange);
numLinesFld.addFocusListener(sizeFocusChange);
setNumEles(this.numEles);
numElementsFld = new JTextField(Integer.toString(this.numEles), 4);
numElementsFld.addActionListener(sizeChange);
numElementsFld.addFocusListener(sizeFocusChange);
numLinesFld.setToolTipText("Number of lines");
numElementsFld.setToolTipText("Number of elements");
GuiUtils.tmpInsets = dfltGridSpacing;
sizeLbl = GuiUtils.lLabel("");
fullResBtn = GuiUtils.makeImageButton(
"/auxdata/ui/icons/arrow_out.png", this,
"setToFullResolution");
fullResBtn.setContentAreaFilled(false);
fullResBtn.setToolTipText("Set to full resolution");
lockBtn =
GuiUtils.getToggleImageButton(IdvUIManager.ICON_UNLOCK,
IdvUIManager.ICON_LOCK, 0, 0, true);
lockBtn.setContentAreaFilled(false);
lockBtn.setSelected(true);
lockBtn.setToolTipText(
"Unlock to automatically change size when changing magnification");
JLabel rawSizeLbl = new JLabel(" Raw size: " + previewDirBlk[8]
+ " X " + previewDirBlk[9]);
JPanel sizePanel =
GuiUtils.left(GuiUtils.doLayout(new Component[] {
numLinesFld,
new JLabel(" X "), numElementsFld, sizeLbl, fullResBtn, lockBtn,
rawSizeLbl }, 7, GuiUtils.WT_N, GuiUtils.WT_N));
addPropComp(PROP_SIZE, propComp = sizePanel);
} else if (prop.equals(PROP_MAG)) {
propComp = GuiUtils.hbox(new Component[] { new JLabel("") }, 1);
addPropComp(PROP_MAG, propComp);
} else if (prop.equals(PROP_LMAG)) {
boolean oldAmSettingProperties = amSettingProperties;
amSettingProperties = true;
ChangeListener lineListener =
new javax.swing.event.ChangeListener() {
public void stateChanged(ChangeEvent evt) {
if (amSettingProperties) {
return;
}
lineMagSliderChanged(!lockBtn.isSelected());
getGeoLocationInfo();
}
};
JComponent[] lineMagComps =
GuiUtils.makeSliderPopup(SLIDER_MIN, SLIDER_MAX, 0,
lineListener);
lineMagSlider = (JSlider) lineMagComps[1];
lineMagSlider.setPreferredSize(new Dimension(SLIDER_WIDTH,SLIDER_HEIGHT));
lineMagSlider.setMajorTickSpacing(1);
lineMagSlider.setSnapToTicks(true);
lineMagSlider.setExtent(1);
setLineMag(this.lineMag);
lineMagSlider.setValue(this.lineMag);
lineMagComps[0].setToolTipText(
"Change the line magnification");
lineMagSlider.setToolTipText(
"Slide to set line magnification factor");
String str = "Mag=" + Integer.toString(getLineMag());
lineMagLbl =
GuiUtils.getFixedWidthLabel(StringUtil.padLeft(str, 4));
str = truncateNumericString(Double.toString(baseLRes*Math.abs(getLineMag())), 1);
str = " Res=" + str + kmLbl;
lineResLbl =
GuiUtils.getFixedWidthLabel(StringUtil.padLeft(str, 4));
amSettingProperties = oldAmSettingProperties;
GuiUtils.tmpInsets = dfltGridSpacing;
lMagPanel = GuiUtils.doLayout(new Component[] {
lineMagLbl,
GuiUtils.inset(lineMagComps[1],
new Insets(0, 4, 0, 0)), lineResLbl, }, 4,
GuiUtils.WT_N, GuiUtils.WT_N);
propComp = GuiUtils.hbox(new Component[] { new JLabel(" "), lMagPanel }, 2);
addPropComp(PROP_LMAG, propComp = lMagPanel);
} else if (prop.equals(PROP_EMAG)) {
boolean oldAmSettingProperties = amSettingProperties;
amSettingProperties = true;
ChangeListener elementListener = new ChangeListener() {
public void stateChanged(
javax.swing.event.ChangeEvent evt) {
if (amSettingProperties) {
return;
}
elementMagSliderChanged(true);
getGeoLocationInfo();
}
};
JComponent[] elementMagComps =
GuiUtils.makeSliderPopup(SLIDER_MIN, SLIDER_MAX, 0,
elementListener);
elementMagSlider = (JSlider) elementMagComps[1];
elementMagSlider.setPreferredSize(new Dimension(SLIDER_WIDTH,SLIDER_HEIGHT));
elementMagSlider.setExtent(1);
elementMagSlider.setMajorTickSpacing(1);
elementMagSlider.setSnapToTicks(true);
setElementMag(this.elementMag);
elementMagSlider.setValue(this.elementMag);
elementMagComps[0].setToolTipText(
"Change the element magnification");
elementMagSlider.setToolTipText(
"Slide to set element magnification factor");
String str = "Mag=" + Integer.toString(getElementMag());
elementMagLbl =
GuiUtils.getFixedWidthLabel(StringUtil.padLeft(str, 4));
str = truncateNumericString(Double.toString(baseERes*Math.abs(getElementMag())), 1);
str = " Res=" + str + kmLbl;
elementResLbl =
GuiUtils.getFixedWidthLabel(StringUtil.padLeft(str, 4));
amSettingProperties = oldAmSettingProperties;
GuiUtils.tmpInsets = dfltGridSpacing;
eMagPanel = GuiUtils.doLayout(new Component[] {
elementMagLbl,
GuiUtils.inset(elementMagComps[1],
new Insets(0, 4, 0, 0)), elementResLbl, }, 4,
GuiUtils.WT_N, GuiUtils.WT_N);
propComp = GuiUtils.hbox(new Component[] { new JLabel(" "), eMagPanel }, 2);
addPropComp(PROP_EMAG, propComp = eMagPanel);
}
if (propComp != null) {
allComps.add(GuiUtils.rLabel(labelArray[propIdx]));
allComps.add(GuiUtils.left(propComp));
}
}
GuiUtils.tmpInsets = GRID_INSETS;
JPanel imagePanel = GuiUtils.doLayout(allComps, 2, GuiUtils.WT_NY,
GuiUtils.WT_N);
getGeoLocationInfo();
return GuiUtils.top(imagePanel);
}
| protected JComponent doMakeContents() {
String[] propArray = getAdvancedProps();
String[] labelArray = getAdvancedLabels();
Insets dfltGridSpacing = new Insets(4, 0, 4, 0);
String dfltLblSpacing = " ";
List allComps = new ArrayList();
for (int propIdx = 0; propIdx < propArray.length; propIdx++) {
JComponent propComp = null;
String prop = propArray[propIdx];
if (prop.equals(PROP_TYPE)) {
coordinateTypeComboBox = new JComboBox(coordinateTypes);
coordinateTypeComboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
int selectedIndex = coordinateTypeComboBox.getSelectedIndex();
flipLocationPanel(selectedIndex);
}
});
propComp = (JComponent)coordinateTypeComboBox;
}
else if (prop.equals(PROP_LOC)) {
locationComboBox = new JComboBox(locations);
setPlace(this.place);
locationComboBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String selected =
translatePlace((String)locationComboBox.getSelectedItem());
setPlace(selected);
cyclePlace();
}
});
propComp = (JComponent)locationComboBox;
addPropComp(PROP_LOC, propComp);
ActionListener latLonChange =new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String type = getCoordinateType();
if (type.equals(TYPE_LATLON)) {
setLatitude();
setLongitude();
} else {
setLine();
setElement();
}
}
};
FocusListener linEleFocusChange = new FocusListener() {
public void focusGained(FocusEvent fe) {
}
public void focusLost(FocusEvent fe) {
setLine();
setElement();
}
};
latLonWidget = new LatLonWidget(latLonChange);
FocusListener latLonFocusChange = new FocusListener() {
public void focusGained(FocusEvent fe) {
}
public void focusLost(FocusEvent fe) {
setLatitude();
setLongitude();
}
};
if (!this.isLineEle) {
latLonWidget.setLatLon((Double.toString(this.latitude)),
(Double.toString(this.longitude)));
}
String lineStr = "";
String eleStr = "";
setLine(this.line);
setElement(this.element);
if ((this.line > 0) && (this.element > 0)) {
lineStr =Integer.toString(this.line);
eleStr =Integer.toString(this.element);
}
centerLineFld = new JTextField(lineStr, 3);
centerLineFld.addFocusListener(linEleFocusChange);
final String lineField = "";
centerElementFld = new JTextField(eleStr, 3);
centerElementFld.addFocusListener(linEleFocusChange);
final JButton centerPopupBtn =
GuiUtils.getImageButton(
"/auxdata/ui/icons/MapIcon16.png", getClass());
centerPopupBtn.setToolTipText("Center on current displays");
centerPopupBtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
dataSource.getDataContext().getIdv().getIdvUIManager().popupCenterMenu(
centerPopupBtn, latLonWidget);
}
});
JComponent centerPopup = GuiUtils.inset(centerPopupBtn,
new Insets(0, 0, 0, 4));
GuiUtils.tmpInsets = dfltGridSpacing;
JTextField latFld = latLonWidget.getLatField();
JTextField lonFld = latLonWidget.getLonField();
latFld.addFocusListener(latLonFocusChange);
lonFld.addFocusListener(latLonFocusChange);
latLonPanel = GuiUtils.hbox(new Component[] {
centerLatLbl = GuiUtils.rLabel(" Lat:" + dfltLblSpacing),
latFld,
centerLonLbl = GuiUtils.rLabel(" Lon:" + dfltLblSpacing),
lonFld,
new JLabel(" "), centerPopup
});
lineElementPanel =
GuiUtils.hbox(new Component[] {
centerLineLbl =
GuiUtils.rLabel(" Line:" + dfltLblSpacing),
centerLineFld,
centerElementLbl = GuiUtils.rLabel(" Element:"
+ dfltLblSpacing),
centerElementFld });
locationPanel = new GuiUtils.CardLayoutPanel();
locationPanel.addCard(latLonPanel);
locationPanel.addCard(lineElementPanel);
if (propComp != null) {
allComps.add(GuiUtils.rLabel(labelArray[propIdx]));
allComps.add(GuiUtils.left(propComp));
}
propComp = GuiUtils.hbox(new Component[] { locationPanel }, 1);
if (propComp != null) {
allComps.add(GuiUtils.rLabel(" "));
allComps.add(GuiUtils.left(propComp));
}
propComp = null;
} else if (prop.equals(PROP_SIZE)) {
ActionListener sizeChange =new ActionListener() {
public void actionPerformed(ActionEvent ae) {
getGeoLocationInfo();
}
};
FocusListener sizeFocusChange = new FocusListener() {
public void focusGained(FocusEvent fe) {
}
public void focusLost(FocusEvent fe) {
getGeoLocationInfo();
}
};
setNumLines(this.numLines);
numLinesFld = new JTextField(Integer.toString(this.numLines), 4);
numLinesFld.addActionListener(sizeChange);
numLinesFld.addFocusListener(sizeFocusChange);
setNumEles(this.numEles);
numElementsFld = new JTextField(Integer.toString(this.numEles), 4);
numElementsFld.addActionListener(sizeChange);
numElementsFld.addFocusListener(sizeFocusChange);
numLinesFld.setToolTipText("Number of lines");
numElementsFld.setToolTipText("Number of elements");
GuiUtils.tmpInsets = dfltGridSpacing;
sizeLbl = GuiUtils.lLabel("");
fullResBtn = GuiUtils.makeImageButton(
"/auxdata/ui/icons/arrow_out.png", this,
"setToFullResolution");
fullResBtn.setContentAreaFilled(false);
fullResBtn.setToolTipText("Set to full resolution");
lockBtn =
GuiUtils.getToggleImageButton(IdvUIManager.ICON_UNLOCK,
IdvUIManager.ICON_LOCK, 0, 0, true);
lockBtn.setContentAreaFilled(false);
lockBtn.setSelected(true);
lockBtn.setToolTipText(
"Unlock to automatically change size when changing magnification");
JLabel rawSizeLbl = new JLabel(" Raw size: " + previewDirBlk[8]
+ " X " + previewDirBlk[9]);
JPanel sizePanel =
GuiUtils.left(GuiUtils.doLayout(new Component[] {
numLinesFld,
new JLabel(" X "), numElementsFld, sizeLbl, fullResBtn, lockBtn,
rawSizeLbl }, 7, GuiUtils.WT_N, GuiUtils.WT_N));
addPropComp(PROP_SIZE, propComp = sizePanel);
} else if (prop.equals(PROP_MAG)) {
propComp = GuiUtils.hbox(new Component[] { new JLabel("") }, 1);
addPropComp(PROP_MAG, propComp);
} else if (prop.equals(PROP_LMAG)) {
boolean oldAmSettingProperties = amSettingProperties;
amSettingProperties = true;
ChangeListener lineListener =
new javax.swing.event.ChangeListener() {
public void stateChanged(ChangeEvent evt) {
if (amSettingProperties) {
return;
}
lineMagSliderChanged(!lockBtn.isSelected());
getGeoLocationInfo();
}
};
JComponent[] lineMagComps =
GuiUtils.makeSliderPopup(SLIDER_MIN, SLIDER_MAX, 0,
lineListener);
lineMagSlider = (JSlider) lineMagComps[1];
lineMagSlider.setPreferredSize(new Dimension(SLIDER_WIDTH,SLIDER_HEIGHT));
lineMagSlider.setMajorTickSpacing(1);
lineMagSlider.setSnapToTicks(true);
lineMagSlider.setExtent(1);
setLineMag(this.lineMag);
lineMagSlider.setValue(this.lineMag);
lineMagComps[0].setToolTipText(
"Change the line magnification");
lineMagSlider.setToolTipText(
"Slide to set line magnification factor");
String str = "Mag=" + Integer.toString(getLineMag());
lineMagLbl =
GuiUtils.getFixedWidthLabel(StringUtil.padLeft(str, 4));
str = truncateNumericString(Double.toString(baseLRes*Math.abs(getLineMag())), 1);
str = " Res=" + str + kmLbl;
lineResLbl =
GuiUtils.getFixedWidthLabel(StringUtil.padLeft(str, 4));
amSettingProperties = oldAmSettingProperties;
GuiUtils.tmpInsets = dfltGridSpacing;
lMagPanel = GuiUtils.doLayout(new Component[] {
lineMagLbl,
GuiUtils.inset(lineMagComps[1],
new Insets(0, 4, 0, 0)), lineResLbl, }, 4,
GuiUtils.WT_N, GuiUtils.WT_N);
propComp = GuiUtils.hbox(new Component[] { new JLabel(" "), lMagPanel }, 2);
addPropComp(PROP_LMAG, propComp = lMagPanel);
} else if (prop.equals(PROP_EMAG)) {
boolean oldAmSettingProperties = amSettingProperties;
amSettingProperties = true;
ChangeListener elementListener = new ChangeListener() {
public void stateChanged(
javax.swing.event.ChangeEvent evt) {
if (amSettingProperties) {
return;
}
elementMagSliderChanged(true);
getGeoLocationInfo();
}
};
JComponent[] elementMagComps =
GuiUtils.makeSliderPopup(SLIDER_MIN, SLIDER_MAX, 0,
elementListener);
elementMagSlider = (JSlider) elementMagComps[1];
elementMagSlider.setPreferredSize(new Dimension(SLIDER_WIDTH,SLIDER_HEIGHT));
elementMagSlider.setExtent(1);
elementMagSlider.setMajorTickSpacing(1);
elementMagSlider.setSnapToTicks(true);
setElementMag(this.elementMag);
elementMagSlider.setValue(this.elementMag);
elementMagComps[0].setToolTipText(
"Change the element magnification");
elementMagSlider.setToolTipText(
"Slide to set element magnification factor");
String str = "Mag=" + Integer.toString(getElementMag());
elementMagLbl =
GuiUtils.getFixedWidthLabel(StringUtil.padLeft(str, 4));
str = truncateNumericString(Double.toString(baseERes*Math.abs(getElementMag())), 1);
str = " Res=" + str + kmLbl;
elementResLbl =
GuiUtils.getFixedWidthLabel(StringUtil.padLeft(str, 4));
amSettingProperties = oldAmSettingProperties;
GuiUtils.tmpInsets = dfltGridSpacing;
eMagPanel = GuiUtils.doLayout(new Component[] {
elementMagLbl,
GuiUtils.inset(elementMagComps[1],
new Insets(0, 4, 0, 0)), elementResLbl, }, 4,
GuiUtils.WT_N, GuiUtils.WT_N);
propComp = GuiUtils.hbox(new Component[] { new JLabel(" "), eMagPanel }, 2);
addPropComp(PROP_EMAG, propComp = eMagPanel);
}
if (propComp != null) {
allComps.add(GuiUtils.rLabel(labelArray[propIdx]));
allComps.add(GuiUtils.left(propComp));
}
}
GuiUtils.tmpInsets = GRID_INSETS;
JPanel imagePanel = GuiUtils.doLayout(allComps, 2, GuiUtils.WT_NY,
GuiUtils.WT_N);
getGeoLocationInfo();
return GuiUtils.top(imagePanel);
}
|
diff --git a/src/org/omegat/util/Preferences.java b/src/org/omegat/util/Preferences.java
index 273aac28..d3b8e6d6 100644
--- a/src/org/omegat/util/Preferences.java
+++ b/src/org/omegat/util/Preferences.java
@@ -1,556 +1,556 @@
/**************************************************************************
OmegaT - Computer Assisted Translation (CAT) tool
with fuzzy matching, translation memory, keyword search,
glossaries, and translation leveraging into updated projects.
Copyright (C) 2000-2006 Keith Godfrey, Maxym Mykhalchuk, and Henry Pijffers
2007 Zoltan Bartko
2008-2009 Didier Briel
2010 Wildrich Fourie, Antonio Vilei, Didier Briel
2011 John Moran, Didier Briel
Home page: http://www.omegat.org/
Support center: http://groups.yahoo.com/group/OmegaT/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
**************************************************************************/
package org.omegat.util;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.omegat.filters2.TranslationException;
import org.omegat.util.xml.XMLBlock;
import org.omegat.util.xml.XMLStreamReader;
/**
* Class to load & save OmegaT preferences. All methods are static here.
*
* @author Keith Godfrey
* @author Maxym Mykhalchuk
* @author Henry Pijffers
* @author Zoltan Bartko - [email protected]
* @author Didier Briel
* @author Wildrich Fourie
* @author Antonio Vilei
* @author John Moran
*/
public class Preferences {
/** OmegaT-wide Preferences Filename */
public static final String FILE_PREFERENCES = "omegat.prefs";
// preference names
public static final String SOURCE_LOCALE = "source_lang";
public static final String TARGET_LOCALE = "target_lang";
public static final String CURRENT_FOLDER = "current_folder";
public static final String SOURCE_FOLDER = "source_folder";
public static final String TARGET_FOLDER = "target_folder";
public static final String TM_FOLDER = "tm_folder";
public static final String DICT_FOLDER = "dict_folder";
public static final String GLOSSARY_FOLDER = "glossary_folder";
public static final String MAINWINDOW_WIDTH = "screen_width";
public static final String MAINWINDOW_HEIGHT = "screen_height";
public static final String MAINWINDOW_X = "screen_x";
public static final String MAINWINDOW_Y = "screen_y";
public static final String MAINWINDOW_LAYOUT = "docking_layout";
// Project files window size and position
public static final String PROJECT_FILES_WINDOW_WIDTH = "project_files_window_width";
public static final String PROJECT_FILES_WINDOW_HEIGHT = "project_files_window_height";
public static final String PROJECT_FILES_WINDOW_X = "project_files_window_x";
public static final String PROJECT_FILES_WINDOW_Y = "project_files_window_y";
// Using the main font for the Project Files window
public static final String PROJECT_FILES_USE_FONT = "project_files_use_font";
// Search window size and position
public static final String SEARCHWINDOW_WIDTH = "search_window_width";
public static final String SEARCHWINDOW_HEIGHT = "search_window_height";
public static final String SEARCHWINDOW_X = "search_window_x";
public static final String SEARCHWINDOW_Y = "search_window_y";
public static final String SEARCHWINDOW_SEARCH_TYPE = "search_window_search_type";
public static final String SEARCHWINDOW_CASE_SENSITIVE = "search_window_case_sensitive";
public static final String SEARCHWINDOW_SEARCH_SOURCE = "search_window_search_source";
public static final String SEARCHWINDOW_SEARCH_TARGET = "search_window_search_target";
public static final String SEARCHWINDOW_SEARCH_NOTES = "search_window_search_notes";
public static final String SEARCHWINDOW_REG_EXPRESSIONS = "search_window_reg_expressions";
public static final String SEARCHWINDOW_TM_SEARCH = "search_window_tm_search";
public static final String SEARCHWINDOW_ALL_RESULTS = "search_window_all_results";
public static final String SEARCHWINDOW_ADVANCED_VISIBLE = "search_window_advanced_visible";
public static final String SEARCHWINDOW_SEARCH_AUTHOR = "search_window_search_author";
public static final String SEARCHWINDOW_AUTHOR_NAME = "search_window_author_name";
public static final String SEARCHWINDOW_DATE_FROM = "search_window_date_from";
public static final String SEARCHWINDOW_DATE_FROM_VALUE = "search_window_date_from_value";
public static final String SEARCHWINDOW_DATE_TO = "search_window_date_to";
public static final String SEARCHWINDOW_DATE_TO_VALUE = "search_window_date_to_value";
public static final String SEARCHWINDOW_NUMBER_OF_RESULTS = "search_window_number_of_results";
public static final String SEARCHWINDOW_DIR = "search_window_dir";
public static final String SEARCHWINDOW_SEARCH_FILES = "search_window_search_files";
public static final String SEARCHWINDOW_RECURSIVE = "search_window_search_recursive";
// Tag validation window size and position
public static final String TAGVWINDOW_WIDTH = "tagv_window_width";
public static final String TAGVWINDOW_HEIGHT = "tagv_window_height";
public static final String TAGVWINDOW_X = "tagv_window_x";
public static final String TAGVWINDOW_Y = "tagv_window_y";
// Help window size and position
public static final String HELPWINDOW_WIDTH = "help_window_width";
public static final String HELPWINDOW_HEIGHT = "help_window_height";
public static final String HELPWINDOW_X = "help_window_x";
public static final String HELPWINDOW_Y = "help_window_y";
/** Use the TAB button to advance to the next segment */
public static final String USE_TAB_TO_ADVANCE = "tab_advance";
/** Always confirm Quit, even if the project is saved */
public static final String ALWAYS_CONFIRM_QUIT = "always_confirm_quit";
public static final String ALLOW_GOOGLE_TRANSLATE = "allow_google_translate";
public static final String ALLOW_GOOGLE2_TRANSLATE = "allow_google2_translate";
public static final String ALLOW_BELAZAR_TRANSLATE = "allow_belazar_translate";
public static final String ALLOW_APERTIUM_TRANSLATE = "allow_apertium_translate";
/** Enable TransTips */
public static final String TRANSTIPS = "transtips";
/** TransTips Option: Only match exact words */
public static final String TRANSTIPS_EXACT_SEARCH = "transtips_exact_search";
/** Mark the translated segments with a different color */
public static final String MARK_TRANSLATED_SEGMENTS = "mark_translated_segments";
/** Mark the untranslated segments with a different color */
public static final String MARK_UNTRANSLATED_SEGMENTS = "mark_untranslated_segments";
/** Workflow Option: Don't Insert Source Text Into Translated Segment */
public static final String DONT_INSERT_SOURCE_TEXT = "wf_noSourceText";
/** Workflow Option: Allow translation to be equal to source */
public static final String ALLOW_TRANS_EQUAL_TO_SRC = "wf_allowTransEqualToSrc";
/** Workflow Option: Insert Best Match Into Translated Segment */
public static final String BEST_MATCH_INSERT = "wf_insertBestMatch";
/** Workflow Option: Minimal Similarity Of the Best Fuzzy Match to insert */
public static final String BEST_MATCH_MINIMAL_SIMILARITY = "wf_minimalSimilarity";
/**
* Default Value of Workflow Option: Minimal Similarity Of the Best Fuzzy
* Match to insert
*/
public static final String BEST_MATCH_MINIMAL_SIMILARITY_DEFAULT = "80";
/** Workflow Option: Insert Explanatory Text before the Best Fuzzy Match */
public static final String BEST_MATCH_EXPLANATORY_TEXT = "wf_explanatoryText";
/** Workflow Option: Export current segment */
public static final String EXPORT_CURRENT_SEGMENT = "wf_exportCurrentSegment";
/** Workflow Option: Go To Next Untranslated Segment stops when there is at least one
alternative translation */
public static final String STOP_ON_ALTERNATIVE_TRANSLATION="wf_stopOnAlternativeTranslation";
/** Tag Validation Option: Don't check printf-tags */
public static final String DONT_CHECK_PRINTF_TAGS = "tagValidation_noCheck";
/** Tag Validation Option: check simple printf-tags */
public static final String CHECK_SIMPLE_PRINTF_TAGS = "tagValidation_simpleCheck";
/** Tag Validation Option: check all printf-tags */
public static final String CHECK_ALL_PRINTF_TAGS = "tagValidation_elaborateCheck";
/** Tag Validation Option: check simple java MessageFormat pattern tags */
public static final String CHECK_JAVA_PATTERN_TAGS = "tagValidation_javaMessageFormatSimplePatternCheck";
/** Tag Validation Option: check user defined tags according to regexp.*/
public static final String CHECK_CUSTOM_PATTERN = "tagValidation_customPattern";
/** Tag Validation Option: check target for text that should have been removed according to regexp.*/
public static final String CHECK_REMOVE_PATTERN = "tagValidation_removePattern";
/** Team option: author ID */
public static final String TEAM_AUTHOR = "team_Author";
/**
* allow automatic spell checking or not
*/
public static final String ALLOW_AUTO_SPELLCHECKING = "allow_auto_spellchecking";
/**
* The location of the spell checker dictionaries
*/
public static final String SPELLCHECKER_DICTIONARY_DIRECTORY = "spellcheker_dir";
/**
* URL of the dictionary repository
*/
public static final String SPELLCHECKER_DICTIONARY_URL = "dictionary_url";
/**
* The location of the scripts
*/
public static final String SCRIPTS_DIRECTORY = "scripts_dir";
/** Quick script names */
public static final String SCRIPTS_QUICK_1 = "scripts_quick_1";
public static final String SCRIPTS_QUICK_2 = "scripts_quick_2";
public static final String SCRIPTS_QUICK_3 = "scripts_quick_3";
public static final String SCRIPTS_QUICK_4 = "scripts_quick_4";
public static final String SCRIPTS_QUICK_5 = "scripts_quick_5";
public static final String SCRIPTS_QUICK_6 = "scripts_quick_6";
public static final String SCRIPTS_QUICK_7 = "scripts_quick_7";
public static final String SCRIPTS_QUICK_8 = "scripts_quick_8";
public static final String SCRIPTS_QUICK_9 = "scripts_quick_9";
public static final String SCRIPTS_QUICK_0 = "scripts_quick_0";
/**
* display the segment sources
*/
public static final String DISPLAY_SEGMENT_SOURCES = "display_segment_sources";
/**
* mark unique segments
*/
public static final String MARK_NON_UNIQUE_SEGMENTS = "mark_non_unique_segments";
/**
* display modification info (author and modification date)
*/
public static final String DISPLAY_MODIFICATION_INFO = "display_modification_info";
/** External TMX options: Display level 2 tags */
public static final String EXT_TMX_SHOW_LEVEL2 = "ext_tmx_show_level2";
/** External TMX options: Use / for stand-alone tags */
public static final String EXT_TMX_USE_SLASH = "ext_tmx_use_slash";
/** View options: Show all sources in bold */
public static final String VIEW_OPTION_SOURCE_ALL_BOLD = "view_option_source_all_bold";
/** View options: Mark first non-unique */
public static final String VIEW_OPTION_UNIQUE_FIRST = "view_option_unique_first";
/** Proxy options: User name for proxy access */
public static final String PROXY_USER_NAME = "proxy_user_name";
/** Proxy options: Password for proxy access */
public static final String PROXY_PASSWORD = "proxy_password";
/**
* Version of file filters. Unfortunately cannot put it into filters itself
* for backwards compatibility reasons.
*/
public static final String FILTERS_VERSION = "filters_version";
public static final String LT_DISABLED = "lt_disabled";
/** Private constructor, because this file is singleton */
static {
m_loaded = false;
m_preferenceMap = new HashMap<String, Integer>(64);
m_nameList = new ArrayList<String>(32);
m_valList = new ArrayList<String>(32);
m_changed = false;
doLoad();
}
/**
* Returns the defaultValue of some preference out of OmegaT's preferences
* file.
* <p>
* If the key is not found, returns the empty string.
*
* @param key
* key of the key to look up, usually OConsts.PREF_...
* @return preference defaultValue as a string
*/
public static String getPreference(String key) {
if (key == null || key.equals(""))
return "";
if (!m_loaded)
doLoad();
Integer i = m_preferenceMap.get(key);
String v = "";
if (i != null) {
// mapping exists - recover defaultValue
v = m_valList.get(i);
}
return v;
}
/**
* Returns true if the preference is in OmegaT's preferences
* file.
* <p>
* If the key is not found return false
*
* @param key
* key of the key to look up, usually OConsts.PREF_...
* @return true if preferences exists
*/
public static boolean existsPreference(String key) {
boolean exists = false;
if (key == null)
exists = false;
if (!m_loaded)
doLoad();
Integer i = m_preferenceMap.get(key);
if (i != null) {
exists = true;
}
return exists;
}
/**
* Returns the boolean defaultValue of some preference.
* <p>
* Returns true if the preference exists and is equal to "true", false
* otherwise (no such preference, or it's equal to "false", etc).
*
* @param key
* preference key, usually OConsts.PREF_...
* @return preference defaultValue as a boolean
*/
public static boolean isPreference(String key) {
return "true".equals(getPreference(key));
}
/**
* Returns the value of some preference out of OmegaT's preferences file, if
* it exists.
* <p>
* If the key is not found, returns the default value provided and sets the
* preference to the default value.
*
* @param key
* name of the key to look up, usually OConsts.PREF_...
* @param defaultValue
* default value for the key
* @return preference value as a string
*/
public static String getPreferenceDefault(String key, String defaultValue) {
String val = getPreference(key);
if (val.equals("")) {
val = defaultValue;
setPreference(key, defaultValue);
}
return val;
}
/**
* Returns the value of some preference out of OmegaT's preferences file, if
* it exists.
* <p>
* @param key
* name of the key to look up, usually OConsts.PREF_...
* @return preference value as a string
*/
public static String getPreferenceDefaultAllowEmptyString(String key) {
String val = getPreference(key);
return val;
}
/**
* Returns the integer value of some preference out of OmegaT's preferences
* file, if it exists.
* <p>
* If the key is not found, returns the default value provided and sets the
* preference to the default value.
*
* @param key
* name of the key to look up, usually OConsts.PREF_...
* @param defaultValue
* default value for the key
* @return preference value as an integer
*/
public static int getPreferenceDefault(String key, int defaultValue) {
String val = getPreferenceDefault(key, Integer.toString(defaultValue));
int res = defaultValue;
try {
res = Integer.parseInt(val);
} catch (NumberFormatException nfe) {
}
return res;
}
/**
* Sets the value of some preference.
*
* @param name
* preference key name, usually Preferences.PREF_...
* @param value
* preference value as a string
*/
public static void setPreference(String name, String value) {
m_changed = true;
if (name != null && name.length() != 0 && value != null) {
if (!m_loaded)
doLoad();
Integer i = m_preferenceMap.get(name);
if (i == null) {
// defaultValue doesn't exist - add it
i = m_valList.size();
m_preferenceMap.put(name, i);
m_valList.add(value);
m_nameList.add(name);
} else {
// mapping exists - reset defaultValue to new
m_valList.set(i.intValue(), value);
}
}
}
/**
* Sets the boolean value of some preference.
*
* @param name
* preference key name, usually Preferences.PREF_...
* @param boolvalue
* preference defaultValue as a boolean
*/
public static void setPreference(String name, boolean boolvalue) {
setPreference(name, String.valueOf(boolvalue));
}
/**
* Sets the int value of some preference.
*
* @param name
* preference key name, usually Preferences.PREF_...
* @param intvalue
* preference value as an integer
*/
public static void setPreference(String name, int intvalue) {
setPreference(name, String.valueOf(intvalue));
}
public static void save() {
try {
if (m_changed)
doSave();
} catch (IOException e) {
Log.logErrorRB("PM_ERROR_SAVE");
Log.log(e);
}
}
private static void doLoad() {
try {
// mark as loaded - if the load fails, there's no use
// trying again later
m_loaded = true;
XMLStreamReader xml = new XMLStreamReader();
xml.killEmptyBlocks();
xml.setStream(new File(StaticUtils.getConfigDir() + FILE_PREFERENCES));
XMLBlock blk;
List<XMLBlock> lst;
m_preferenceMap.clear();
String pref;
String val;
// advance to omegat tag
if (xml.advanceToTag("omegat") == null)
return;
// advance to project tag
if ((blk = xml.advanceToTag("preference")) == null)
return;
String ver = blk.getAttribute("version");
if (ver != null && !ver.equals("1.0")) {
// unsupported preference file version - abort read
return;
}
lst = xml.closeBlock(blk);
if (lst == null)
return;
for (int i = 0; i < lst.size(); i++) {
blk = lst.get(i);
if (blk.isClose())
continue;
if (!blk.isTag())
continue;
pref = blk.getTagName();
blk = lst.get(++i);
- if (blk.isClose()) {
- //allow empty string as a preference value
+ if (blk.isClose()) {
+ //allow empty string as a preference value
val = "";
- } else {
+ } else {
val = blk.getText();
- }
+ }
if (pref != null && val != null) {
// valid match - record these
m_preferenceMap.put(pref, m_valList.size());
m_nameList.add(pref);
m_valList.add(val);
}
}
} catch (TranslationException te) {
// error loading preference file - keep whatever was
// loaded then return gracefully to calling function
// print an error to the console as an FYI
Log.logWarningRB("PM_WARNING_PARSEERROR_ON_READ");
Log.log(te);
} catch (IndexOutOfBoundsException e3) {
// error loading preference file - keep whatever was
// loaded then return gracefully to calling function
// print an error to the console as an FYI
Log.logWarningRB("PM_WARNING_PARSEERROR_ON_READ");
Log.log(e3);
} catch (UnsupportedEncodingException e3) {
// unsupported encoding - forget about it
Log.logErrorRB("PM_UNSUPPORTED_ENCODING");
Log.log(e3);
} catch (FileNotFoundException ex) {
// there is no config file yet
} catch (IOException e4) {
// can't read file - forget about it and move on
Log.logErrorRB("PM_ERROR_READING_FILE");
Log.log(e4);
}
}
private static void doSave() throws IOException {
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(
StaticUtils.getConfigDir() + FILE_PREFERENCES), "UTF-8"));
out.write("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");
out.write("<omegat>\n");
out.write(" <preference version=\"1.0\">\n");
for (int i = 0; i < m_nameList.size(); i++) {
String name = m_nameList.get(i);
String val = StaticUtils.makeValidXML(m_valList.get(i));
out.write(" <" + name + ">");
out.write(val);
out.write("</" + name + ">\n");
}
out.write(" </preference>\n");
out.write("</omegat>\n");
out.close();
m_changed = false;
}
private static boolean m_loaded;
private static boolean m_changed;
// use a hash map for fast lookup of data
// use array lists for orderly recovery of it for saving to disk
private static List<String> m_nameList;
private static List<String> m_valList;
private static Map<String, Integer> m_preferenceMap;
}
| false | true | private static void doLoad() {
try {
// mark as loaded - if the load fails, there's no use
// trying again later
m_loaded = true;
XMLStreamReader xml = new XMLStreamReader();
xml.killEmptyBlocks();
xml.setStream(new File(StaticUtils.getConfigDir() + FILE_PREFERENCES));
XMLBlock blk;
List<XMLBlock> lst;
m_preferenceMap.clear();
String pref;
String val;
// advance to omegat tag
if (xml.advanceToTag("omegat") == null)
return;
// advance to project tag
if ((blk = xml.advanceToTag("preference")) == null)
return;
String ver = blk.getAttribute("version");
if (ver != null && !ver.equals("1.0")) {
// unsupported preference file version - abort read
return;
}
lst = xml.closeBlock(blk);
if (lst == null)
return;
for (int i = 0; i < lst.size(); i++) {
blk = lst.get(i);
if (blk.isClose())
continue;
if (!blk.isTag())
continue;
pref = blk.getTagName();
blk = lst.get(++i);
if (blk.isClose()) {
//allow empty string as a preference value
val = "";
} else {
val = blk.getText();
}
if (pref != null && val != null) {
// valid match - record these
m_preferenceMap.put(pref, m_valList.size());
m_nameList.add(pref);
m_valList.add(val);
}
}
} catch (TranslationException te) {
// error loading preference file - keep whatever was
// loaded then return gracefully to calling function
// print an error to the console as an FYI
Log.logWarningRB("PM_WARNING_PARSEERROR_ON_READ");
Log.log(te);
} catch (IndexOutOfBoundsException e3) {
// error loading preference file - keep whatever was
// loaded then return gracefully to calling function
// print an error to the console as an FYI
Log.logWarningRB("PM_WARNING_PARSEERROR_ON_READ");
Log.log(e3);
} catch (UnsupportedEncodingException e3) {
// unsupported encoding - forget about it
Log.logErrorRB("PM_UNSUPPORTED_ENCODING");
Log.log(e3);
} catch (FileNotFoundException ex) {
// there is no config file yet
} catch (IOException e4) {
// can't read file - forget about it and move on
Log.logErrorRB("PM_ERROR_READING_FILE");
Log.log(e4);
}
}
| private static void doLoad() {
try {
// mark as loaded - if the load fails, there's no use
// trying again later
m_loaded = true;
XMLStreamReader xml = new XMLStreamReader();
xml.killEmptyBlocks();
xml.setStream(new File(StaticUtils.getConfigDir() + FILE_PREFERENCES));
XMLBlock blk;
List<XMLBlock> lst;
m_preferenceMap.clear();
String pref;
String val;
// advance to omegat tag
if (xml.advanceToTag("omegat") == null)
return;
// advance to project tag
if ((blk = xml.advanceToTag("preference")) == null)
return;
String ver = blk.getAttribute("version");
if (ver != null && !ver.equals("1.0")) {
// unsupported preference file version - abort read
return;
}
lst = xml.closeBlock(blk);
if (lst == null)
return;
for (int i = 0; i < lst.size(); i++) {
blk = lst.get(i);
if (blk.isClose())
continue;
if (!blk.isTag())
continue;
pref = blk.getTagName();
blk = lst.get(++i);
if (blk.isClose()) {
//allow empty string as a preference value
val = "";
} else {
val = blk.getText();
}
if (pref != null && val != null) {
// valid match - record these
m_preferenceMap.put(pref, m_valList.size());
m_nameList.add(pref);
m_valList.add(val);
}
}
} catch (TranslationException te) {
// error loading preference file - keep whatever was
// loaded then return gracefully to calling function
// print an error to the console as an FYI
Log.logWarningRB("PM_WARNING_PARSEERROR_ON_READ");
Log.log(te);
} catch (IndexOutOfBoundsException e3) {
// error loading preference file - keep whatever was
// loaded then return gracefully to calling function
// print an error to the console as an FYI
Log.logWarningRB("PM_WARNING_PARSEERROR_ON_READ");
Log.log(e3);
} catch (UnsupportedEncodingException e3) {
// unsupported encoding - forget about it
Log.logErrorRB("PM_UNSUPPORTED_ENCODING");
Log.log(e3);
} catch (FileNotFoundException ex) {
// there is no config file yet
} catch (IOException e4) {
// can't read file - forget about it and move on
Log.logErrorRB("PM_ERROR_READING_FILE");
Log.log(e4);
}
}
|
diff --git a/Java/src/com/sample/onpremise/AddMerchandise.java b/Java/src/com/sample/onpremise/AddMerchandise.java
index 6d653f0..65654f0 100755
--- a/Java/src/com/sample/onpremise/AddMerchandise.java
+++ b/Java/src/com/sample/onpremise/AddMerchandise.java
@@ -1,173 +1,173 @@
package com.sample.onpremise;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;
public class AddMerchandise {
public static void main(String [] args){
Properties props = new Properties();
try {
props.load(new FileInputStream("AddMerchandise.properties"));
String username = props.getProperty("username");
String passsword = props.getProperty("password");
if (username == null || username.trim().equals("") ||
- passsword == null || passsword.trim().equals("")){
+ password == null || password.trim().equals("")){
throw new IllegalArgumentException("Please provide a username and password in the properties file");
}
String clientId = props.getProperty("client.id");
String clientSecret = props.getProperty("client.secret");
if (clientId == null || clientId.trim().equals("") ||
clientSecret == null || clientSecret.trim().equals("")){
throw new IllegalArgumentException("Please provide a valid client id and client secret in the properties file");
}
String loginURL = props.getProperty("login.url");
String name = props.getProperty("merchandise.name");
String price = props.getProperty("merchandise.price");
String desc = props.getProperty("merchandise.description");
String inventory = props.getProperty("merchandise.inventory");
- ForceLogin login = login2ForceDotCom(username, passsword,
+ ForceLogin login = login2ForceDotCom(username, password,
clientId, clientSecret,
loginURL);
if (login != null){
String merchId = addMerchandise(login, name, price, desc, inventory);
if (merchId != null){
System.out.println("Merchandise record created successfully. Id="+merchId);
}
}
}
catch(IOException e){
e.printStackTrace();
}
}
/* private static ForceLogin login2ForceDotCom(String uName,
String pwd,
String id,
String secret,
String url){
String postURL = (url==null || url.equals(""))?"https://login.salesforce.com":url;
postURL+="/services/oauth2/token?grant_type=password&client_id="+id+"&client_secret="+secret+"&username="+uName+"&password="+pwd;
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpPost post = new HttpPost(postURL);
try {
HttpResponse response = httpclient.execute(post);
final int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK) {
System.out.println("Error authenticating to Force.com:"+statusCode);
System.out.println("Error is:"+EntityUtils.toString(response.getEntity()));
return null;
}
String result = EntityUtils.toString(response.getEntity());
JSONObject object = (JSONObject) new JSONTokener(result).nextValue();
ForceLogin login = new AddMerchandise().new ForceLogin();
login.accessToken = object.getString("access_token");
login.instanceUrl= object.getString("instance_url");
return login;
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
} */
/* public static String addMerchandise(ForceLogin login,
String name,
String price,
String desc,
String inventory){
JSONObject mechandise = new JSONObject();
try {
if (name != null && !name.trim().equals(""))
mechandise.put("Name", name);
if (price != null && !price.trim().equals(""))
mechandise.put("Price__c", price);
if (desc != null && !desc.trim().equals(""))
mechandise.put("Description__c", desc);
if (inventory != null && !inventory.trim().equals(""))
mechandise.put("Total_Inventory__c", inventory);
String restResourceURI = login.instanceUrl + "/services/data/v23.0/sobjects/Merchandise__c/";
HttpPost post = new HttpPost(restResourceURI);
StringEntity se = new StringEntity(mechandise.toString());
post.setEntity(se);
post.setHeader("Authorization", "OAuth " + login.accessToken);
post.setHeader("Content-type", "application/json");
DefaultHttpClient client = new DefaultHttpClient();
HttpResponse resp = client.execute(post);
String result = EntityUtils.toString(resp.getEntity());
if (resp.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED)
{
JSONObject ret = ((JSONArray) new JSONTokener(result).nextValue()).getJSONObject(0);
System.out.println("Could not create new Merchandise record:"+resp.getStatusLine().getStatusCode());
System.out.println("Error code:"+ret.getString("errorCode"));
System.out.println("Error message:"+ret.getString("message"));
return null;
}
else{
return ((JSONObject) new JSONTokener(result).nextValue()).getString("id");
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
} */
public class ForceLogin {
private String instanceUrl;
private String accessToken;
public String getInstanceUrl()
{
return instanceUrl;
}
public void setInstanceUrl(String i)
{
instanceUrl = i;
}
public String getAccessToken()
{
return accessToken;
}
public void setAccessToken(String a)
{
accessToken = a;
}
}
}
| false | true | public static void main(String [] args){
Properties props = new Properties();
try {
props.load(new FileInputStream("AddMerchandise.properties"));
String username = props.getProperty("username");
String passsword = props.getProperty("password");
if (username == null || username.trim().equals("") ||
passsword == null || passsword.trim().equals("")){
throw new IllegalArgumentException("Please provide a username and password in the properties file");
}
String clientId = props.getProperty("client.id");
String clientSecret = props.getProperty("client.secret");
if (clientId == null || clientId.trim().equals("") ||
clientSecret == null || clientSecret.trim().equals("")){
throw new IllegalArgumentException("Please provide a valid client id and client secret in the properties file");
}
String loginURL = props.getProperty("login.url");
String name = props.getProperty("merchandise.name");
String price = props.getProperty("merchandise.price");
String desc = props.getProperty("merchandise.description");
String inventory = props.getProperty("merchandise.inventory");
ForceLogin login = login2ForceDotCom(username, passsword,
clientId, clientSecret,
loginURL);
if (login != null){
String merchId = addMerchandise(login, name, price, desc, inventory);
if (merchId != null){
System.out.println("Merchandise record created successfully. Id="+merchId);
}
}
}
catch(IOException e){
e.printStackTrace();
}
}
| public static void main(String [] args){
Properties props = new Properties();
try {
props.load(new FileInputStream("AddMerchandise.properties"));
String username = props.getProperty("username");
String passsword = props.getProperty("password");
if (username == null || username.trim().equals("") ||
password == null || password.trim().equals("")){
throw new IllegalArgumentException("Please provide a username and password in the properties file");
}
String clientId = props.getProperty("client.id");
String clientSecret = props.getProperty("client.secret");
if (clientId == null || clientId.trim().equals("") ||
clientSecret == null || clientSecret.trim().equals("")){
throw new IllegalArgumentException("Please provide a valid client id and client secret in the properties file");
}
String loginURL = props.getProperty("login.url");
String name = props.getProperty("merchandise.name");
String price = props.getProperty("merchandise.price");
String desc = props.getProperty("merchandise.description");
String inventory = props.getProperty("merchandise.inventory");
ForceLogin login = login2ForceDotCom(username, password,
clientId, clientSecret,
loginURL);
if (login != null){
String merchId = addMerchandise(login, name, price, desc, inventory);
if (merchId != null){
System.out.println("Merchandise record created successfully. Id="+merchId);
}
}
}
catch(IOException e){
e.printStackTrace();
}
}
|
diff --git a/dexlib/src/main/java/org/jf/dexlib/CodeItem.java b/dexlib/src/main/java/org/jf/dexlib/CodeItem.java
index 5bf50e5..4db48cd 100644
--- a/dexlib/src/main/java/org/jf/dexlib/CodeItem.java
+++ b/dexlib/src/main/java/org/jf/dexlib/CodeItem.java
@@ -1,1039 +1,1038 @@
/*
* [The "BSD licence"]
* Copyright (c) 2009 Ben Gruver
* 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.jf.dexlib;
import org.jf.dexlib.Code.*;
import org.jf.dexlib.Code.Format.Instruction20t;
import org.jf.dexlib.Code.Format.Instruction30t;
import org.jf.dexlib.Code.Format.Instruction21c;
import org.jf.dexlib.Code.Format.Instruction31c;
import org.jf.dexlib.Util.*;
import org.jf.dexlib.Debug.DebugInstructionIterator;
import java.util.List;
import java.util.ArrayList;
public class CodeItem extends Item<CodeItem> {
private int registerCount;
private int inWords;
private int outWords;
private DebugInfoItem debugInfo;
private Instruction[] instructions;
private TryItem[] tries;
private EncodedCatchHandler[] encodedCatchHandlers;
private ClassDataItem.EncodedMethod parent;
/**
* Creates a new uninitialized <code>CodeItem</code>
* @param dexFile The <code>DexFile</code> that this item belongs to
*/
public CodeItem(DexFile dexFile) {
super(dexFile);
}
/**
* Creates a new <code>CodeItem</code> with the given values.
* @param dexFile The <code>DexFile</code> that this item belongs to
* @param registerCount the number of registers that the method containing this code uses
* @param inWords the number of 2-byte words that the parameters to the method containing this code take
* @param outWords the maximum number of 2-byte words for the arguments of any method call in this code
* @param debugInfo the debug information for this code/method
* @param instructions the instructions for this code item
* @param tries an array of the tries defined for this code/method
* @param encodedCatchHandlers an array of the exception handlers defined for this code/method
*/
private CodeItem(DexFile dexFile,
int registerCount,
int inWords,
int outWords,
DebugInfoItem debugInfo,
Instruction[] instructions,
TryItem[] tries,
EncodedCatchHandler[] encodedCatchHandlers) {
super(dexFile);
this.registerCount = registerCount;
this.inWords = inWords;
this.outWords = outWords;
this.debugInfo = debugInfo;
if (debugInfo != null) {
debugInfo.setParent(this);
}
this.instructions = instructions;
this.tries = tries;
this.encodedCatchHandlers = encodedCatchHandlers;
}
/**
* Returns a new <code>CodeItem</code> with the given values.
* @param dexFile The <code>DexFile</code> that this item belongs to
* @param registerCount the number of registers that the method containing this code uses
* @param inWords the number of 2-byte words that the parameters to the method containing this code take
* @param outWords the maximum number of 2-byte words for the arguments of any method call in this code
* @param debugInfo the debug information for this code/method
* @param instructions the instructions for this code item
* @param tries a list of the tries defined for this code/method or null if none
* @param encodedCatchHandlers a list of the exception handlers defined for this code/method or null if none
* @return a new <code>CodeItem</code> with the given values.
*/
public static CodeItem getInternedCodeItem(DexFile dexFile,
int registerCount,
int inWords,
int outWords,
DebugInfoItem debugInfo,
List<Instruction> instructions,
List<TryItem> tries,
List<EncodedCatchHandler> encodedCatchHandlers) {
TryItem[] triesArray = null;
EncodedCatchHandler[] encodedCatchHandlersArray = null;
Instruction[] instructionsArray = null;
if (tries != null && tries.size() > 0) {
triesArray = new TryItem[tries.size()];
tries.toArray(triesArray);
}
if (encodedCatchHandlers != null && encodedCatchHandlers.size() > 0) {
encodedCatchHandlersArray = new EncodedCatchHandler[encodedCatchHandlers.size()];
encodedCatchHandlers.toArray(encodedCatchHandlersArray);
}
if (instructions != null && instructions.size() > 0) {
instructionsArray = new Instruction[instructions.size()];
instructions.toArray(instructionsArray);
}
CodeItem codeItem = new CodeItem(dexFile, registerCount, inWords, outWords, debugInfo, instructionsArray,
triesArray, encodedCatchHandlersArray);
return dexFile.CodeItemsSection.intern(codeItem);
}
/** {@inheritDoc} */
protected void readItem(Input in, ReadContext readContext) {
this.registerCount = in.readShort();
this.inWords = in.readShort();
this.outWords = in.readShort();
int triesCount = in.readShort();
this.debugInfo = (DebugInfoItem)readContext.getOffsettedItemByOffset(ItemType.TYPE_DEBUG_INFO_ITEM,
in.readInt());
if (this.debugInfo != null) {
this.debugInfo.setParent(this);
}
int instructionCount = in.readInt();
final ArrayList<Instruction> instructionList = new ArrayList<Instruction>();
byte[] encodedInstructions = in.readBytes(instructionCount * 2);
InstructionIterator.IterateInstructions(dexFile, encodedInstructions,
new InstructionIterator.ProcessInstructionDelegate() {
public void ProcessInstruction(int index, Instruction instruction) {
instructionList.add(instruction);
}
});
this.instructions = new Instruction[instructionList.size()];
instructionList.toArray(instructions);
if (triesCount > 0) {
in.alignTo(4);
//we need to read in the catch handlers first, so save the offset to the try items for future reference
int triesOffset = in.getCursor();
in.setCursor(triesOffset + 8 * triesCount);
//read in the encoded catch handlers
int encodedHandlerStart = in.getCursor();
int handlerCount = in.readUnsignedLeb128();
SparseArray<EncodedCatchHandler> handlerMap = new SparseArray<EncodedCatchHandler>(handlerCount);
encodedCatchHandlers = new EncodedCatchHandler[handlerCount];
for (int i=0; i<handlerCount; i++) {
int position = in.getCursor() - encodedHandlerStart;
encodedCatchHandlers[i] = new EncodedCatchHandler(dexFile, in);
handlerMap.append(position, encodedCatchHandlers[i]);
}
int codeItemEnd = in.getCursor();
//now go back and read the tries
in.setCursor(triesOffset);
tries = new TryItem[triesCount];
for (int i=0; i<triesCount; i++) {
tries[i] = new TryItem(in, handlerMap);
}
//and now back to the end of the code item
in.setCursor(codeItemEnd);
}
}
/** {@inheritDoc} */
protected int placeItem(int offset) {
offset += 16 + getInstructionsLength();
if (tries != null && tries.length > 0) {
if (offset % 4 != 0) {
offset+=2;
}
offset += tries.length * 8;
int encodedCatchHandlerBaseOffset = offset;
offset += Leb128Utils.unsignedLeb128Size(encodedCatchHandlers.length);
for (EncodedCatchHandler encodedCatchHandler: encodedCatchHandlers) {
offset = encodedCatchHandler.place(offset, encodedCatchHandlerBaseOffset);
}
}
return offset;
}
/** {@inheritDoc} */
protected void writeItem(final AnnotatedOutput out) {
int instructionsLength = getInstructionsLength()/2;
if (out.annotates()) {
out.annotate(0, parent.method.getMethodString());
out.annotate(2, "registers_size: 0x" + Integer.toHexString(registerCount) + " (" + registerCount + ")");
out.annotate(2, "ins_size: 0x" + Integer.toHexString(inWords) + " (" + inWords + ")");
out.annotate(2, "outs_size: 0x" + Integer.toHexString(outWords) + " (" + outWords + ")");
int triesLength = tries==null?0:tries.length;
out.annotate(2, "tries_size: 0x" + Integer.toHexString(triesLength) + " (" + triesLength + ")");
if (debugInfo == null) {
out.annotate(4, "debug_info_off:");
} else {
out.annotate(4, "debug_info_off: 0x" + debugInfo.getOffset());
}
out.annotate(4, "insns_size: 0x" + Integer.toHexString(instructionsLength) + " (" +
(instructionsLength) + ")");
}
out.writeShort(registerCount);
out.writeShort(inWords);
out.writeShort(outWords);
if (tries == null) {
out.writeShort(0);
} else {
out.writeShort(tries.length);
}
if (debugInfo == null) {
out.writeInt(0);
} else {
out.writeInt(debugInfo.getOffset());
}
int currentCodeOffset = 0;
for (Instruction instruction: instructions) {
currentCodeOffset += instruction.getSize(currentCodeOffset);
}
out.writeInt(instructionsLength);
currentCodeOffset = 0;
for (Instruction instruction: instructions) {
currentCodeOffset = instruction.write(out, currentCodeOffset);
}
if (tries != null && tries.length > 0) {
if (out.annotates()) {
if ((currentCodeOffset % 4) != 0) {
out.annotate("padding");
out.writeShort(0);
}
int index = 0;
for (TryItem tryItem: tries) {
out.annotate(0, "[0x" + Integer.toHexString(index++) + "] try_item");
out.indent();
tryItem.writeTo(out);
out.deindent();
}
out.annotate("handler_count: 0x" + Integer.toHexString(encodedCatchHandlers.length) + "(" +
encodedCatchHandlers.length + ")");
out.writeUnsignedLeb128(encodedCatchHandlers.length);
index = 0;
for (EncodedCatchHandler encodedCatchHandler: encodedCatchHandlers) {
out.annotate(0, "[" + Integer.toHexString(index++) + "] encoded_catch_handler");
out.indent();
encodedCatchHandler.writeTo(out);
out.deindent();
}
} else {
if ((currentCodeOffset % 4) != 0) {
out.writeShort(0);
}
for (TryItem tryItem: tries) {
tryItem.writeTo(out);
}
out.writeUnsignedLeb128(encodedCatchHandlers.length);
for (EncodedCatchHandler encodedCatchHandler: encodedCatchHandlers) {
encodedCatchHandler.writeTo(out);
}
}
}
}
/** {@inheritDoc} */
public ItemType getItemType() {
return ItemType.TYPE_CODE_ITEM;
}
/** {@inheritDoc} */
public String getConciseIdentity() {
return "code_item @0x" + Integer.toHexString(getOffset());
}
/** {@inheritDoc} */
public int compareTo(CodeItem other) {
if (parent == null) {
if (other.parent == null) {
return 0;
}
return -1;
}
if (other.parent == null) {
return 1;
}
return parent.method.compareTo(other.parent.method);
}
/**
* @return the register count
*/
public int getRegisterCount() {
return registerCount;
}
/**
* @return an array of the instructions in this code item
*/
public Instruction[] getInstructions() {
return instructions;
}
/**
* @return an array of the <code>TryItem</code> objects in this <code>CodeItem</code>
*/
public TryItem[] getTries() {
return tries;
}
/**
* @return an array of the <code>EncodedCatchHandler</code> objects in this <code>CodeItem</code>
*/
public EncodedCatchHandler[] getHandlers() {
return encodedCatchHandlers;
}
/**
* @return the <code>DebugInfoItem</code> associated with this <code>CodeItem</code>
*/
public DebugInfoItem getDebugInfo() {
return debugInfo;
}
/**
* Sets the <code>MethodIdItem</code> of the method that this <code>CodeItem</code> is associated with
* @param encodedMethod the <code>EncodedMethod</code> of the method that this <code>CodeItem</code> is associated
* with
*/
protected void setParent(ClassDataItem.EncodedMethod encodedMethod) {
this.parent = encodedMethod;
}
/**
* @return the MethodIdItem of the method that this CodeItem belongs to
*/
public ClassDataItem.EncodedMethod getParent() {
return parent;
}
/**
* Used by OdexUtil to update this <code>CodeItem</code> with a deodexed version of the instructions
* @param newInstructions the new instructions to use for this code item
*/
public void updateCode(Instruction[] newInstructions) {
this.instructions = newInstructions;
}
private int getInstructionsLength() {
int offset = 0;
for (Instruction instruction: instructions) {
offset += instruction.getSize(offset);
}
return offset;
}
/**
* Go through the instructions and perform any of the following fixes that are applicable
* - Replace const-string instruction with const-string/jumbo, when the string index is too big
* - Replace goto and goto/16 with a larger version of goto, when the target is too far away
* TODO: we should be able to replace if-* instructions with targets that are too far away with a negated if followed by a goto/32 to the original target
* TODO: remove multiple nops that occur before a switch/array data pseudo instruction. In some cases, multiple smali-baksmali cycles with changes in between could cause nops to start piling up
*
* The above fixes are applied iteratively, until no more fixes have been performed
*/
public void fixInstructions(boolean fixStringConst, boolean fixGoto) {
boolean didSomething = false;
do
{
didSomething = false;
int currentCodeOffset = 0;
for (int i=0; i<instructions.length; i++) {
Instruction instruction = instructions[i];
if (fixGoto && instruction.opcode == Opcode.GOTO) {
int offset = ((OffsetInstruction)instruction).getOffset();
if (((byte)offset) != offset) {
//the offset doesn't fit within a byte, we need to upgrade to a goto/16 or goto/32
if ((short)offset == offset) {
//the offset fits in a short, so upgrade to a goto/16 h
replaceInstructionAtOffset(currentCodeOffset, new Instruction20t(Opcode.GOTO_16, offset));
}
else {
//The offset won't fit into a short, we have to upgrade to a goto/32
replaceInstructionAtOffset(currentCodeOffset, new Instruction30t(Opcode.GOTO_32, offset));
}
didSomething = true;
break;
}
} else if (fixGoto && instruction.opcode == Opcode.GOTO_16) {
int offset = ((OffsetInstruction)instruction).getOffset();
if (((short)offset) != offset) {
//the offset doesn't fit within a short, we need to upgrade to a goto/32
replaceInstructionAtOffset(currentCodeOffset, new Instruction30t(Opcode.GOTO_32, offset));
didSomething = true;
break;
}
} else if (fixStringConst && instruction.opcode == Opcode.CONST_STRING) {
Instruction21c constStringInstruction = (Instruction21c)instruction;
if (constStringInstruction.getReferencedItem().getIndex() > 0xFFFF) {
replaceInstructionAtOffset(currentCodeOffset, new Instruction31c(Opcode.CONST_STRING_JUMBO,
(short)constStringInstruction.getRegisterA(),
constStringInstruction.getReferencedItem()));
didSomething = true;
break;
}
}
currentCodeOffset += instruction.getSize(currentCodeOffset);
}
}while(didSomething);
}
private void replaceInstructionAtOffset(int offset, Instruction replacementInstruction) {
Instruction originalInstruction = null;
int[] originalInstructionOffsets = new int[instructions.length+1];
SparseIntArray originalSwitchOffsetByOriginalSwitchDataOffset = new SparseIntArray();
int currentCodeOffset = 0;
int instructionIndex = 0;
int i;
for (i=0; i<instructions.length; i++) {
Instruction instruction = instructions[i];
if (currentCodeOffset == offset) {
originalInstruction = instruction;
instructionIndex = i;
}
if (instruction.opcode == Opcode.PACKED_SWITCH || instruction.opcode == Opcode.SPARSE_SWITCH) {
OffsetInstruction offsetInstruction = (OffsetInstruction)instruction;
int switchDataOffset = currentCodeOffset + offsetInstruction.getOffset() * 2;
if (originalSwitchOffsetByOriginalSwitchDataOffset.indexOfKey(switchDataOffset) < 0) {
originalSwitchOffsetByOriginalSwitchDataOffset.put(switchDataOffset, currentCodeOffset);
}
}
originalInstructionOffsets[i] = currentCodeOffset;
currentCodeOffset += instruction.getSize(currentCodeOffset);
}
//add the offset just past the end of the last instruction, to help when fixing up try blocks that end
//at the end of the method
originalInstructionOffsets[i] = currentCodeOffset;
if (originalInstruction == null) {
throw new RuntimeException("There is no instruction at offset " + offset);
}
instructions[instructionIndex] = replacementInstruction;
//if we're replacing the instruction with one of the same size, we don't have to worry about fixing
//up any offsets
if (originalInstruction.getSize(offset) == replacementInstruction.getSize(offset)) {
return;
}
//TODO: replace these with a callable delegate
final SparseIntArray originalOffsetsByNewOffset = new SparseIntArray();
final SparseIntArray newOffsetsByOriginalOffset = new SparseIntArray();
currentCodeOffset = 0;
for (i=0; i<instructions.length; i++) {
Instruction instruction = instructions[i];
int originalOffset = originalInstructionOffsets[i];
originalOffsetsByNewOffset.append(currentCodeOffset, originalOffset);
newOffsetsByOriginalOffset.append(originalOffset, currentCodeOffset);
currentCodeOffset += instruction.getSize(currentCodeOffset);
}
//add the offset just past the end of the last instruction, to help when fixing up try blocks that end
//at the end of the method
originalOffsetsByNewOffset.append(currentCodeOffset, originalInstructionOffsets[i]);
newOffsetsByOriginalOffset.append(originalInstructionOffsets[i], currentCodeOffset);
//update any "offset" instructions, or switch data instructions
currentCodeOffset = 0;
for (i=0; i<instructions.length; i++) {
Instruction instruction = instructions[i];
if (instruction instanceof OffsetInstruction) {
OffsetInstruction offsetInstruction = (OffsetInstruction)instruction;
assert originalOffsetsByNewOffset.indexOfKey(currentCodeOffset) >= 0;
int originalOffset = originalOffsetsByNewOffset.get(currentCodeOffset);
int originalInstructionTarget = originalOffset + offsetInstruction.getOffset() * 2;
assert newOffsetsByOriginalOffset.indexOfKey(originalInstructionTarget) >= 0;
int newInstructionTarget = newOffsetsByOriginalOffset.get(originalInstructionTarget);
int newOffset = (newInstructionTarget - currentCodeOffset) / 2;
if (newOffset != offsetInstruction.getOffset()) {
offsetInstruction.updateOffset(newOffset);
}
} else if (instruction instanceof MultiOffsetInstruction) {
MultiOffsetInstruction multiOffsetInstruction = (MultiOffsetInstruction)instruction;
assert originalOffsetsByNewOffset.indexOfKey(currentCodeOffset) >= 0;
int originalDataOffset = originalOffsetsByNewOffset.get(currentCodeOffset);
int originalSwitchOffset = originalSwitchOffsetByOriginalSwitchDataOffset.get(originalDataOffset);
if (originalSwitchOffset == 0) {
- //TODO: is it safe to skip an unreferenced switch data instruction? Or should it throw an exception?
- continue;
+ throw new RuntimeException("This method contains an unreferenced switch data block, and can't be automatically fixed.");
}
assert newOffsetsByOriginalOffset.indexOfKey(originalSwitchOffset) >= 0;
int newSwitchOffset = newOffsetsByOriginalOffset.get(originalSwitchOffset);
int[] targets = multiOffsetInstruction.getTargets();
for (int t=0; t<targets.length; t++) {
int originalTargetOffset = originalSwitchOffset + targets[t]*2;
assert newOffsetsByOriginalOffset.indexOfKey(originalTargetOffset) >= 0;
int newTargetOffset = newOffsetsByOriginalOffset.get(originalTargetOffset);
int newOffset = (newTargetOffset - newSwitchOffset)/2;
if (newOffset != targets[t]) {
multiOffsetInstruction.updateTarget(t, newOffset);
}
}
}
currentCodeOffset += instruction.getSize(currentCodeOffset);
}
if (debugInfo != null) {
final byte[] encodedDebugInfo = debugInfo.getEncodedDebugInfo();
ByteArrayInput debugInput = new ByteArrayInput(encodedDebugInfo);
DebugInstructionFixer debugInstructionFixer = new DebugInstructionFixer(encodedDebugInfo,
newOffsetsByOriginalOffset, originalOffsetsByNewOffset);
DebugInstructionIterator.IterateInstructions(debugInput, debugInstructionFixer);
assert debugInstructionFixer.result != null;
if (debugInstructionFixer.result != null) {
debugInfo.setEncodedDebugInfo(debugInstructionFixer.result);
}
}
if (encodedCatchHandlers != null) {
for (EncodedCatchHandler encodedCatchHandler: encodedCatchHandlers) {
if (encodedCatchHandler.catchAllHandlerAddress != -1) {
assert newOffsetsByOriginalOffset.indexOfKey(encodedCatchHandler.catchAllHandlerAddress*2) >= 0;
encodedCatchHandler.catchAllHandlerAddress =
newOffsetsByOriginalOffset.get(encodedCatchHandler.catchAllHandlerAddress*2)/2;
}
for (EncodedTypeAddrPair handler: encodedCatchHandler.handlers) {
assert newOffsetsByOriginalOffset.indexOfKey(handler.handlerAddress*2) >= 0;
handler.handlerAddress = newOffsetsByOriginalOffset.get(handler.handlerAddress*2)/2;
}
}
}
if (this.tries != null) {
for (TryItem tryItem: tries) {
int startAddress = tryItem.startAddress;
int endAddress = tryItem.startAddress + tryItem.instructionCount;
assert newOffsetsByOriginalOffset.indexOfKey(startAddress * 2) >= 0;
tryItem.startAddress = newOffsetsByOriginalOffset.get(startAddress * 2)/2;
assert newOffsetsByOriginalOffset.indexOfKey(endAddress * 2) >= 0;
tryItem.instructionCount = newOffsetsByOriginalOffset.get(endAddress * 2)/2 - tryItem.startAddress;
}
}
}
private class DebugInstructionFixer extends DebugInstructionIterator.ProcessRawDebugInstructionDelegate {
private int address = 0;
private SparseIntArray newOffsetsByOriginalOffset;
private SparseIntArray originalOffsetsByNewOffset;
private final byte[] originalEncodedDebugInfo;
public byte[] result = null;
public DebugInstructionFixer(byte[] originalEncodedDebugInfo, SparseIntArray newOffsetsByOriginalOffset,
SparseIntArray originalOffsetsByNewOffset) {
this.newOffsetsByOriginalOffset = newOffsetsByOriginalOffset;
this.originalOffsetsByNewOffset = originalOffsetsByNewOffset;
this.originalEncodedDebugInfo = originalEncodedDebugInfo;
}
@Override
public void ProcessAdvancePC(int startOffset, int length, int addressDelta) {
address += addressDelta;
if (result != null) {
return;
}
int newOffset = newOffsetsByOriginalOffset.get(address*2, -1);
//The address might not point to an actual instruction in some cases, for example, if an AdvancePC
//instruction was inserted just before a "special" instruction, to fix up the offsets for a previous
//instruction replacement.
//In this case, it should be safe to skip, because there will be another AdvancePC/SpecialOpcode that will
//bump up the address to point to a valid instruction before anything (line/local/etc.) is emitted
if (newOffset == -1) {
return;
}
assert newOffset != -1;
newOffset = newOffset / 2;
if (newOffset != address) {
int newAddressDelta = newOffset - (address - addressDelta);
assert newAddressDelta > 0;
int addressDiffSize = Leb128Utils.unsignedLeb128Size(newAddressDelta);
result = new byte[originalEncodedDebugInfo.length + addressDiffSize - (length - 1)];
System.arraycopy(originalEncodedDebugInfo, 0, result, 0, startOffset);
result[startOffset] = 0x01; //DBG_ADVANCE_PC debug opcode
Leb128Utils.writeUnsignedLeb128(newAddressDelta, result, startOffset+1);
System.arraycopy(originalEncodedDebugInfo, startOffset+length, result,
startOffset + addressDiffSize + 1,
originalEncodedDebugInfo.length - (startOffset + addressDiffSize + 1));
}
}
@Override
public void ProcessSpecialOpcode(int startOffset, int debugOpcode, int lineDelta,
int addressDelta) {
address += addressDelta;
if (result != null) {
return;
}
int newOffset = newOffsetsByOriginalOffset.get(address*2, -1);
assert newOffset != -1;
newOffset = newOffset / 2;
if (newOffset != address) {
int newAddressDelta = newOffset - (address - addressDelta);
assert newAddressDelta > 0;
//if the new address delta won't fit in the special opcode, we need to insert
//an additional DBG_ADVANCE_PC opcode
if (lineDelta < 2 && newAddressDelta > 16 || lineDelta > 1 && newAddressDelta > 15) {
int additionalAddressDelta = newOffset - address;
int additionalAddressDeltaSize = Leb128Utils.signedLeb128Size(additionalAddressDelta);
result = new byte[originalEncodedDebugInfo.length + additionalAddressDeltaSize + 1];
System.arraycopy(originalEncodedDebugInfo, 0, result, 0, startOffset);
result[startOffset] = 0x01; //DBG_ADVANCE_PC
Leb128Utils.writeUnsignedLeb128(additionalAddressDelta, result, startOffset+1);
System.arraycopy(originalEncodedDebugInfo, startOffset, result,
startOffset+additionalAddressDeltaSize+1,
result.length - (startOffset+additionalAddressDeltaSize+1));
} else {
result = new byte[originalEncodedDebugInfo.length];
System.arraycopy(originalEncodedDebugInfo, 0, result, 0, result.length);
result[startOffset] = DebugInfoBuilder.calculateSpecialOpcode(lineDelta,
newAddressDelta);
}
}
}
}
public static class TryItem {
/**
* The address (in 2-byte words) within the code where the try block starts
*/
private int startAddress;
/**
* The number of 2-byte words that the try block covers
*/
private int instructionCount;
/**
* The associated exception handler
*/
public final EncodedCatchHandler encodedCatchHandler;
/**
* Construct a new <code>TryItem</code> with the given values
* @param startAddress the address (in 2-byte words) within the code where the try block starts
* @param instructionCount the number of 2-byte words that the try block covers
* @param encodedCatchHandler the associated exception handler
*/
public TryItem(int startAddress, int instructionCount, EncodedCatchHandler encodedCatchHandler) {
this.startAddress = startAddress;
this.instructionCount = instructionCount;
this.encodedCatchHandler = encodedCatchHandler;
}
/**
* This is used internally to construct a new <code>TryItem</code> while reading in a <code>DexFile</code>
* @param in the Input object to read the <code>TryItem</code> from
* @param encodedCatchHandlers a SparseArray of the EncodedCatchHandlers for this <code>CodeItem</code>. The
* key should be the offset of the EncodedCatchHandler from the beginning of the encoded_catch_handler_list
* structure.
*/
private TryItem(Input in, SparseArray<EncodedCatchHandler> encodedCatchHandlers) {
startAddress = in.readInt();
instructionCount = in.readShort();
encodedCatchHandler = encodedCatchHandlers.get(in.readShort());
if (encodedCatchHandler == null) {
throw new RuntimeException("Could not find the EncodedCatchHandler referenced by this TryItem");
}
}
/**
* Writes the <code>TryItem</code> to the given <code>AnnotatedOutput</code> object
* @param out the <code>AnnotatedOutput</code> object to write to
*/
private void writeTo(AnnotatedOutput out) {
if (out.annotates()) {
out.annotate(4, "start_addr: 0x" + Integer.toHexString(startAddress));
out.annotate(2, "insn_count: 0x" + Integer.toHexString(instructionCount) + " (" + instructionCount +
")");
out.annotate(2, "handler_off: 0x" + Integer.toHexString(encodedCatchHandler.getOffsetInList()));
}
out.writeInt(startAddress);
out.writeShort(instructionCount);
out.writeShort(encodedCatchHandler.getOffsetInList());
}
/**
* @return The address (in 2-byte words) within the code where the try block starts
*/
public int getStartAddress() {
return startAddress;
}
/**
* @return The number of 2-byte words that the try block covers
*/
public int getInstructionCount() {
return instructionCount;
}
}
public static class EncodedCatchHandler {
/**
* An array of the individual exception handlers
*/
public final EncodedTypeAddrPair[] handlers;
/**
* The address within the code (in 2-byte words) for the catch all handler, or -1 if there is no catch all
* handler
*/
private int catchAllHandlerAddress;
private int baseOffset;
private int offset;
/**
* Constructs a new <code>EncodedCatchHandler</code> with the given values
* @param handlers an array of the individual exception handlers
* @param catchAllHandlerAddress The address within the code (in 2-byte words) for the catch all handler, or -1
* if there is no catch all handler
*/
public EncodedCatchHandler(EncodedTypeAddrPair[] handlers, int catchAllHandlerAddress) {
this.handlers = handlers;
this.catchAllHandlerAddress = catchAllHandlerAddress;
}
/**
* This is used internally to construct a new <code>EncodedCatchHandler</code> while reading in a
* <code>DexFile</code>
* @param dexFile the <code>DexFile</code> that is being read in
* @param in the Input object to read the <code>EncodedCatchHandler</code> from
*/
private EncodedCatchHandler(DexFile dexFile, Input in) {
int handlerCount = in.readSignedLeb128();
if (handlerCount < 0) {
handlers = new EncodedTypeAddrPair[-1 * handlerCount];
} else {
handlers = new EncodedTypeAddrPair[handlerCount];
}
for (int i=0; i<handlers.length; i++) {
handlers[i] = new EncodedTypeAddrPair(dexFile, in);
}
if (handlerCount <= 0) {
catchAllHandlerAddress = in.readUnsignedLeb128();
} else {
catchAllHandlerAddress = -1;
}
}
/**
* Returns the "Catch All" handler address for this <code>EncodedCatchHandler</code>
* @return
*/
public int getCatchAllHandlerAddress() {
return catchAllHandlerAddress;
}
/**
* @return the offset of this <code>EncodedCatchHandler</code> from the beginning of the
* encoded_catch_handler_list structure
*/
private int getOffsetInList() {
return offset-baseOffset;
}
/**
* Places the <code>EncodedCatchHandler</code>, storing the offset and baseOffset, and returning the offset
* immediately following this <code>EncodedCatchHandler</code>
* @param offset the offset of this <code>EncodedCatchHandler</code> in the <code>DexFile</code>
* @param baseOffset the offset of the beginning of the encoded_catch_handler_list structure in the
* <code>DexFile</code>
* @return the offset immediately following this <code>EncodedCatchHandler</code>
*/
private int place(int offset, int baseOffset) {
this.offset = offset;
this.baseOffset = baseOffset;
int size = handlers.length;
if (catchAllHandlerAddress > -1) {
size *= -1;
offset += Leb128Utils.unsignedLeb128Size(catchAllHandlerAddress);
}
offset += Leb128Utils.signedLeb128Size(size);
for (EncodedTypeAddrPair handler: handlers) {
offset += handler.getSize();
}
return offset;
}
/**
* Writes the <code>EncodedCatchHandler</code> to the given <code>AnnotatedOutput</code> object
* @param out the <code>AnnotatedOutput</code> object to write to
*/
private void writeTo(AnnotatedOutput out) {
if (out.annotates()) {
out.annotate("size: 0x" + Integer.toHexString(handlers.length) + " (" + handlers.length + ")");
int size = handlers.length;
if (catchAllHandlerAddress > -1) {
size = size * -1;
}
out.writeSignedLeb128(size);
int index = 0;
for (EncodedTypeAddrPair handler: handlers) {
out.annotate(0, "[" + index++ + "] encoded_type_addr_pair");
out.indent();
handler.writeTo(out);
out.deindent();
}
if (catchAllHandlerAddress > -1) {
out.annotate("catch_all_addr: 0x" + Integer.toHexString(catchAllHandlerAddress));
out.writeUnsignedLeb128(catchAllHandlerAddress);
}
} else {
int size = handlers.length;
if (catchAllHandlerAddress > -1) {
size = size * -1;
}
out.writeSignedLeb128(size);
for (EncodedTypeAddrPair handler: handlers) {
handler.writeTo(out);
}
if (catchAllHandlerAddress > -1) {
out.writeUnsignedLeb128(catchAllHandlerAddress);
}
}
}
@Override
public int hashCode() {
int hash = 0;
for (EncodedTypeAddrPair handler: handlers) {
hash = hash * 31 + handler.hashCode();
}
hash = hash * 31 + catchAllHandlerAddress;
return hash;
}
@Override
public boolean equals(Object o) {
if (this==o) {
return true;
}
if (o==null || !this.getClass().equals(o.getClass())) {
return false;
}
EncodedCatchHandler other = (EncodedCatchHandler)o;
if (handlers.length != other.handlers.length || catchAllHandlerAddress != other.catchAllHandlerAddress) {
return false;
}
for (int i=0; i<handlers.length; i++) {
if (!handlers[i].equals(other.handlers[i])) {
return false;
}
}
return true;
}
}
public static class EncodedTypeAddrPair {
/**
* The type of the <code>Exception</code> that this handler handles
*/
public final TypeIdItem exceptionType;
/**
* The address (in 2-byte words) in the code of the handler
*/
private int handlerAddress;
/**
* Constructs a new <code>EncodedTypeAddrPair</code> with the given values
* @param exceptionType the type of the <code>Exception</code> that this handler handles
* @param handlerAddress the address (in 2-byte words) in the code of the handler
*/
public EncodedTypeAddrPair(TypeIdItem exceptionType, int handlerAddress) {
this.exceptionType = exceptionType;
this.handlerAddress = handlerAddress;
}
/**
* This is used internally to construct a new <code>EncodedTypeAddrPair</code> while reading in a
* <code>DexFile</code>
* @param dexFile the <code>DexFile</code> that is being read in
* @param in the Input object to read the <code>EncodedCatchHandler</code> from
*/
private EncodedTypeAddrPair(DexFile dexFile, Input in) {
exceptionType = dexFile.TypeIdsSection.getItemByIndex(in.readUnsignedLeb128());
handlerAddress = in.readUnsignedLeb128();
}
/**
* @return the size of this <code>EncodedTypeAddrPair</code>
*/
private int getSize() {
return Leb128Utils.unsignedLeb128Size(exceptionType.getIndex()) +
Leb128Utils.unsignedLeb128Size(handlerAddress);
}
/**
* Writes the <code>EncodedTypeAddrPair</code> to the given <code>AnnotatedOutput</code> object
* @param out the <code>AnnotatedOutput</code> object to write to
*/
private void writeTo(AnnotatedOutput out) {
if (out.annotates()) {
out.annotate("exception_type: " + exceptionType.getTypeDescriptor());
out.writeUnsignedLeb128(exceptionType.getIndex());
out.annotate("handler_addr: 0x" + Integer.toHexString(handlerAddress));
out.writeUnsignedLeb128(handlerAddress);
} else {
out.writeUnsignedLeb128(exceptionType.getIndex());
out.writeUnsignedLeb128(handlerAddress);
}
}
public int getHandlerAddress() {
return handlerAddress;
}
@Override
public int hashCode() {
return exceptionType.hashCode() * 31 + handlerAddress;
}
@Override
public boolean equals(Object o) {
if (this==o) {
return true;
}
if (o==null || !this.getClass().equals(o.getClass())) {
return false;
}
EncodedTypeAddrPair other = (EncodedTypeAddrPair)o;
return exceptionType == other.exceptionType && handlerAddress == other.handlerAddress;
}
}
}
| true | true | private void replaceInstructionAtOffset(int offset, Instruction replacementInstruction) {
Instruction originalInstruction = null;
int[] originalInstructionOffsets = new int[instructions.length+1];
SparseIntArray originalSwitchOffsetByOriginalSwitchDataOffset = new SparseIntArray();
int currentCodeOffset = 0;
int instructionIndex = 0;
int i;
for (i=0; i<instructions.length; i++) {
Instruction instruction = instructions[i];
if (currentCodeOffset == offset) {
originalInstruction = instruction;
instructionIndex = i;
}
if (instruction.opcode == Opcode.PACKED_SWITCH || instruction.opcode == Opcode.SPARSE_SWITCH) {
OffsetInstruction offsetInstruction = (OffsetInstruction)instruction;
int switchDataOffset = currentCodeOffset + offsetInstruction.getOffset() * 2;
if (originalSwitchOffsetByOriginalSwitchDataOffset.indexOfKey(switchDataOffset) < 0) {
originalSwitchOffsetByOriginalSwitchDataOffset.put(switchDataOffset, currentCodeOffset);
}
}
originalInstructionOffsets[i] = currentCodeOffset;
currentCodeOffset += instruction.getSize(currentCodeOffset);
}
//add the offset just past the end of the last instruction, to help when fixing up try blocks that end
//at the end of the method
originalInstructionOffsets[i] = currentCodeOffset;
if (originalInstruction == null) {
throw new RuntimeException("There is no instruction at offset " + offset);
}
instructions[instructionIndex] = replacementInstruction;
//if we're replacing the instruction with one of the same size, we don't have to worry about fixing
//up any offsets
if (originalInstruction.getSize(offset) == replacementInstruction.getSize(offset)) {
return;
}
//TODO: replace these with a callable delegate
final SparseIntArray originalOffsetsByNewOffset = new SparseIntArray();
final SparseIntArray newOffsetsByOriginalOffset = new SparseIntArray();
currentCodeOffset = 0;
for (i=0; i<instructions.length; i++) {
Instruction instruction = instructions[i];
int originalOffset = originalInstructionOffsets[i];
originalOffsetsByNewOffset.append(currentCodeOffset, originalOffset);
newOffsetsByOriginalOffset.append(originalOffset, currentCodeOffset);
currentCodeOffset += instruction.getSize(currentCodeOffset);
}
//add the offset just past the end of the last instruction, to help when fixing up try blocks that end
//at the end of the method
originalOffsetsByNewOffset.append(currentCodeOffset, originalInstructionOffsets[i]);
newOffsetsByOriginalOffset.append(originalInstructionOffsets[i], currentCodeOffset);
//update any "offset" instructions, or switch data instructions
currentCodeOffset = 0;
for (i=0; i<instructions.length; i++) {
Instruction instruction = instructions[i];
if (instruction instanceof OffsetInstruction) {
OffsetInstruction offsetInstruction = (OffsetInstruction)instruction;
assert originalOffsetsByNewOffset.indexOfKey(currentCodeOffset) >= 0;
int originalOffset = originalOffsetsByNewOffset.get(currentCodeOffset);
int originalInstructionTarget = originalOffset + offsetInstruction.getOffset() * 2;
assert newOffsetsByOriginalOffset.indexOfKey(originalInstructionTarget) >= 0;
int newInstructionTarget = newOffsetsByOriginalOffset.get(originalInstructionTarget);
int newOffset = (newInstructionTarget - currentCodeOffset) / 2;
if (newOffset != offsetInstruction.getOffset()) {
offsetInstruction.updateOffset(newOffset);
}
} else if (instruction instanceof MultiOffsetInstruction) {
MultiOffsetInstruction multiOffsetInstruction = (MultiOffsetInstruction)instruction;
assert originalOffsetsByNewOffset.indexOfKey(currentCodeOffset) >= 0;
int originalDataOffset = originalOffsetsByNewOffset.get(currentCodeOffset);
int originalSwitchOffset = originalSwitchOffsetByOriginalSwitchDataOffset.get(originalDataOffset);
if (originalSwitchOffset == 0) {
//TODO: is it safe to skip an unreferenced switch data instruction? Or should it throw an exception?
continue;
}
assert newOffsetsByOriginalOffset.indexOfKey(originalSwitchOffset) >= 0;
int newSwitchOffset = newOffsetsByOriginalOffset.get(originalSwitchOffset);
int[] targets = multiOffsetInstruction.getTargets();
for (int t=0; t<targets.length; t++) {
int originalTargetOffset = originalSwitchOffset + targets[t]*2;
assert newOffsetsByOriginalOffset.indexOfKey(originalTargetOffset) >= 0;
int newTargetOffset = newOffsetsByOriginalOffset.get(originalTargetOffset);
int newOffset = (newTargetOffset - newSwitchOffset)/2;
if (newOffset != targets[t]) {
multiOffsetInstruction.updateTarget(t, newOffset);
}
}
}
currentCodeOffset += instruction.getSize(currentCodeOffset);
}
if (debugInfo != null) {
final byte[] encodedDebugInfo = debugInfo.getEncodedDebugInfo();
ByteArrayInput debugInput = new ByteArrayInput(encodedDebugInfo);
DebugInstructionFixer debugInstructionFixer = new DebugInstructionFixer(encodedDebugInfo,
newOffsetsByOriginalOffset, originalOffsetsByNewOffset);
DebugInstructionIterator.IterateInstructions(debugInput, debugInstructionFixer);
assert debugInstructionFixer.result != null;
if (debugInstructionFixer.result != null) {
debugInfo.setEncodedDebugInfo(debugInstructionFixer.result);
}
}
if (encodedCatchHandlers != null) {
for (EncodedCatchHandler encodedCatchHandler: encodedCatchHandlers) {
if (encodedCatchHandler.catchAllHandlerAddress != -1) {
assert newOffsetsByOriginalOffset.indexOfKey(encodedCatchHandler.catchAllHandlerAddress*2) >= 0;
encodedCatchHandler.catchAllHandlerAddress =
newOffsetsByOriginalOffset.get(encodedCatchHandler.catchAllHandlerAddress*2)/2;
}
for (EncodedTypeAddrPair handler: encodedCatchHandler.handlers) {
assert newOffsetsByOriginalOffset.indexOfKey(handler.handlerAddress*2) >= 0;
handler.handlerAddress = newOffsetsByOriginalOffset.get(handler.handlerAddress*2)/2;
}
}
}
if (this.tries != null) {
for (TryItem tryItem: tries) {
int startAddress = tryItem.startAddress;
int endAddress = tryItem.startAddress + tryItem.instructionCount;
assert newOffsetsByOriginalOffset.indexOfKey(startAddress * 2) >= 0;
tryItem.startAddress = newOffsetsByOriginalOffset.get(startAddress * 2)/2;
assert newOffsetsByOriginalOffset.indexOfKey(endAddress * 2) >= 0;
tryItem.instructionCount = newOffsetsByOriginalOffset.get(endAddress * 2)/2 - tryItem.startAddress;
}
}
}
| private void replaceInstructionAtOffset(int offset, Instruction replacementInstruction) {
Instruction originalInstruction = null;
int[] originalInstructionOffsets = new int[instructions.length+1];
SparseIntArray originalSwitchOffsetByOriginalSwitchDataOffset = new SparseIntArray();
int currentCodeOffset = 0;
int instructionIndex = 0;
int i;
for (i=0; i<instructions.length; i++) {
Instruction instruction = instructions[i];
if (currentCodeOffset == offset) {
originalInstruction = instruction;
instructionIndex = i;
}
if (instruction.opcode == Opcode.PACKED_SWITCH || instruction.opcode == Opcode.SPARSE_SWITCH) {
OffsetInstruction offsetInstruction = (OffsetInstruction)instruction;
int switchDataOffset = currentCodeOffset + offsetInstruction.getOffset() * 2;
if (originalSwitchOffsetByOriginalSwitchDataOffset.indexOfKey(switchDataOffset) < 0) {
originalSwitchOffsetByOriginalSwitchDataOffset.put(switchDataOffset, currentCodeOffset);
}
}
originalInstructionOffsets[i] = currentCodeOffset;
currentCodeOffset += instruction.getSize(currentCodeOffset);
}
//add the offset just past the end of the last instruction, to help when fixing up try blocks that end
//at the end of the method
originalInstructionOffsets[i] = currentCodeOffset;
if (originalInstruction == null) {
throw new RuntimeException("There is no instruction at offset " + offset);
}
instructions[instructionIndex] = replacementInstruction;
//if we're replacing the instruction with one of the same size, we don't have to worry about fixing
//up any offsets
if (originalInstruction.getSize(offset) == replacementInstruction.getSize(offset)) {
return;
}
//TODO: replace these with a callable delegate
final SparseIntArray originalOffsetsByNewOffset = new SparseIntArray();
final SparseIntArray newOffsetsByOriginalOffset = new SparseIntArray();
currentCodeOffset = 0;
for (i=0; i<instructions.length; i++) {
Instruction instruction = instructions[i];
int originalOffset = originalInstructionOffsets[i];
originalOffsetsByNewOffset.append(currentCodeOffset, originalOffset);
newOffsetsByOriginalOffset.append(originalOffset, currentCodeOffset);
currentCodeOffset += instruction.getSize(currentCodeOffset);
}
//add the offset just past the end of the last instruction, to help when fixing up try blocks that end
//at the end of the method
originalOffsetsByNewOffset.append(currentCodeOffset, originalInstructionOffsets[i]);
newOffsetsByOriginalOffset.append(originalInstructionOffsets[i], currentCodeOffset);
//update any "offset" instructions, or switch data instructions
currentCodeOffset = 0;
for (i=0; i<instructions.length; i++) {
Instruction instruction = instructions[i];
if (instruction instanceof OffsetInstruction) {
OffsetInstruction offsetInstruction = (OffsetInstruction)instruction;
assert originalOffsetsByNewOffset.indexOfKey(currentCodeOffset) >= 0;
int originalOffset = originalOffsetsByNewOffset.get(currentCodeOffset);
int originalInstructionTarget = originalOffset + offsetInstruction.getOffset() * 2;
assert newOffsetsByOriginalOffset.indexOfKey(originalInstructionTarget) >= 0;
int newInstructionTarget = newOffsetsByOriginalOffset.get(originalInstructionTarget);
int newOffset = (newInstructionTarget - currentCodeOffset) / 2;
if (newOffset != offsetInstruction.getOffset()) {
offsetInstruction.updateOffset(newOffset);
}
} else if (instruction instanceof MultiOffsetInstruction) {
MultiOffsetInstruction multiOffsetInstruction = (MultiOffsetInstruction)instruction;
assert originalOffsetsByNewOffset.indexOfKey(currentCodeOffset) >= 0;
int originalDataOffset = originalOffsetsByNewOffset.get(currentCodeOffset);
int originalSwitchOffset = originalSwitchOffsetByOriginalSwitchDataOffset.get(originalDataOffset);
if (originalSwitchOffset == 0) {
throw new RuntimeException("This method contains an unreferenced switch data block, and can't be automatically fixed.");
}
assert newOffsetsByOriginalOffset.indexOfKey(originalSwitchOffset) >= 0;
int newSwitchOffset = newOffsetsByOriginalOffset.get(originalSwitchOffset);
int[] targets = multiOffsetInstruction.getTargets();
for (int t=0; t<targets.length; t++) {
int originalTargetOffset = originalSwitchOffset + targets[t]*2;
assert newOffsetsByOriginalOffset.indexOfKey(originalTargetOffset) >= 0;
int newTargetOffset = newOffsetsByOriginalOffset.get(originalTargetOffset);
int newOffset = (newTargetOffset - newSwitchOffset)/2;
if (newOffset != targets[t]) {
multiOffsetInstruction.updateTarget(t, newOffset);
}
}
}
currentCodeOffset += instruction.getSize(currentCodeOffset);
}
if (debugInfo != null) {
final byte[] encodedDebugInfo = debugInfo.getEncodedDebugInfo();
ByteArrayInput debugInput = new ByteArrayInput(encodedDebugInfo);
DebugInstructionFixer debugInstructionFixer = new DebugInstructionFixer(encodedDebugInfo,
newOffsetsByOriginalOffset, originalOffsetsByNewOffset);
DebugInstructionIterator.IterateInstructions(debugInput, debugInstructionFixer);
assert debugInstructionFixer.result != null;
if (debugInstructionFixer.result != null) {
debugInfo.setEncodedDebugInfo(debugInstructionFixer.result);
}
}
if (encodedCatchHandlers != null) {
for (EncodedCatchHandler encodedCatchHandler: encodedCatchHandlers) {
if (encodedCatchHandler.catchAllHandlerAddress != -1) {
assert newOffsetsByOriginalOffset.indexOfKey(encodedCatchHandler.catchAllHandlerAddress*2) >= 0;
encodedCatchHandler.catchAllHandlerAddress =
newOffsetsByOriginalOffset.get(encodedCatchHandler.catchAllHandlerAddress*2)/2;
}
for (EncodedTypeAddrPair handler: encodedCatchHandler.handlers) {
assert newOffsetsByOriginalOffset.indexOfKey(handler.handlerAddress*2) >= 0;
handler.handlerAddress = newOffsetsByOriginalOffset.get(handler.handlerAddress*2)/2;
}
}
}
if (this.tries != null) {
for (TryItem tryItem: tries) {
int startAddress = tryItem.startAddress;
int endAddress = tryItem.startAddress + tryItem.instructionCount;
assert newOffsetsByOriginalOffset.indexOfKey(startAddress * 2) >= 0;
tryItem.startAddress = newOffsetsByOriginalOffset.get(startAddress * 2)/2;
assert newOffsetsByOriginalOffset.indexOfKey(endAddress * 2) >= 0;
tryItem.instructionCount = newOffsetsByOriginalOffset.get(endAddress * 2)/2 - tryItem.startAddress;
}
}
}
|
diff --git a/servicewrapper/servicewrapper-service-ncbiblast/src/uk/org/mygrid/cagrid/servicewrapper/service/ncbiblast/invoker/NCBIBlastJobUtils.java b/servicewrapper/servicewrapper-service-ncbiblast/src/uk/org/mygrid/cagrid/servicewrapper/service/ncbiblast/invoker/NCBIBlastJobUtils.java
index c84fb9f..aed7708 100644
--- a/servicewrapper/servicewrapper-service-ncbiblast/src/uk/org/mygrid/cagrid/servicewrapper/service/ncbiblast/invoker/NCBIBlastJobUtils.java
+++ b/servicewrapper/servicewrapper-service-ncbiblast/src/uk/org/mygrid/cagrid/servicewrapper/service/ncbiblast/invoker/NCBIBlastJobUtils.java
@@ -1,167 +1,167 @@
package uk.org.mygrid.cagrid.servicewrapper.service.ncbiblast.invoker;
import gov.nih.nci.cagrid.common.Utils;
import gov.nih.nci.cagrid.metadata.service.Fault;
import java.io.StringReader;
import java.rmi.RemoteException;
import org.apache.log4j.Logger;
import org.jdom.Document;
import org.jdom.output.XMLOutputter;
import schema.EBIApplicationResult;
import uk.org.mygrid.cagrid.domain.common.JobStatus;
import uk.org.mygrid.cagrid.domain.ncbiblast.NCBIBLASTOutput;
import uk.org.mygrid.cagrid.servicewrapper.service.ncbiblast.converter.NCBIBlastConverter;
import uk.org.mygrid.cagrid.servicewrapper.service.ncbiblast.job.service.globus.resource.NCBIBlastJobResource;
import uk.org.mygrid.cagrid.servicewrapper.serviceinvoker.InvokerException;
import uk.org.mygrid.cagrid.servicewrapper.serviceinvoker.ncbiblast.NCBIBlastInvoker;
/**
* Utility methods for updating an NCBIBlast job resource.
*
* @author Stian Soiland-Reyes
*
*/
public class NCBIBlastJobUtils {
private static Logger logger = Logger.getLogger(NCBIBlastJobUtils.class);
private NCBIBlastInvoker invoker = InvokerFactory.getInvoker();
private NCBIBlastConverter converter = new NCBIBlastConverter();
/**
* Update the {@link JobStatus} of the given job.
*
* @param job
* @throws RemoteException
*/
public void updateStatus(NCBIBlastJobResource job) throws RemoteException {
if (isFinished(job) && job.getNCBIBlastOutput() != null
|| job.getFault() != null) {
// No need to check status again, and the return data has been
// fetched
return;
}
String jobID = job.getJobID();
if (jobID == null || jobID.equals("")) {
// Too early, no job id set yet
return;
}
String status;
try {
status = invoker.checkStatus(jobID);
} catch (InvokerException e) {
logger.warn("Could not check status for " + jobID, e);
job.setFault(new Fault("Could not check status for " + jobID,
"Can't check status"));
throw new RemoteException("Could not check status for " + jobID, e);
}
logger.info("Status for " + jobID + " is " + status);
JobStatus jobStatus;
try {
jobStatus = JobStatus.fromValue(status.toLowerCase());
} catch (IllegalArgumentException ex) {
job.setFault(new Fault("Unknown status type for " + jobID + ": "
+ status, "Unknown status"));
logger.warn("Unknown status type for " + jobID + ": " + status, ex);
throw new RemoteException("Unknown status type " + status);
}
job.setJobStatus(jobStatus);
}
/**
* Update the outputs of a given job. If the job status is not
* {@link JobStatus#done}, or the output has already been fetched, this
* method does nothing.
*
* @param job
* @throws RemoteException
*/
public void updateOutputs(NCBIBlastJobResource job) throws RemoteException {
if (!job.getJobStatus().equals(JobStatus.done)
|| job.getNCBIBlastOutput() != null) {
// Too early/late
return;
}
String jobID = job.getJobID();
if (jobID == null || jobID.equals("")) {
// Too early, no job id set yet
return;
}
Document data;
try {
data = invoker.poll(jobID);
} catch (InvokerException e) {
job.setFault(new Fault("Can't poll for job ID " + jobID,
"Can't poll"));
logger.warn("Can't poll for jobID " + jobID, e);
throw new RemoteException("Can't poll for jobID " + jobID, e);
}
XMLOutputter xmlOutputter = new XMLOutputter();
String dataString = xmlOutputter.outputString(data);
StringReader xmlReader = new StringReader(dataString);
EBIApplicationResult eBIApplicationResult;
try {
eBIApplicationResult = (EBIApplicationResult) Utils.deserializeObject(xmlReader,
EBIApplicationResult.class);
job.setEBIApplicationResult(eBIApplicationResult);
} catch (Exception e) {
- logger.warn("Could not parse/serialize returned data:\n" + dataString);
+ logger.warn("Could not parse/serialize returned data:\n" + dataString, e);
}
logger.info("Data returned for " + jobID + " is: \n" + dataString);
NCBIBLASTOutput output = converter.convertNCBIBlastOutput(data);
job.setNCBIBlastOutput(output);
}
/**
* Check if a job is finished. A job is considered finish if it has a job
* status (not updated), and the status is either {@link JobStatus#error},
* {@link JobStatus#not_found} or {@link JobStatus#done} - in which case it
* also need to have a
* {@link NCBIBlastJobResource#getNCBIBlastOutput()}.
*
* @param job
* @return <code>true</code> if the job is considered finished.
*/
public boolean isFinished(NCBIBlastJobResource job) {
JobStatus jobStatus = job.getJobStatus();
if (jobStatus == null) {
return false;
}
if (jobStatus.equals(JobStatus.error)
|| jobStatus.equals(JobStatus.not_found)) {
return true;
}
if (jobStatus.equals(JobStatus.done)
&& job.getNCBIBlastOutput() != null) {
return true;
}
return false;
}
/**
* Update faults. Currently does not do much, as faults are set on
* occurrence. If the
* {@link NCBIBlastJobResource#getNCBIBlastOutput()} is not null, the
* current fault is removed.
*
* @param job
* @throws RemoteException
*/
public void updateFault(NCBIBlastJobResource job) throws RemoteException {
if (job.getNCBIBlastOutput() != null) {
// No fault anymore
job.setFault(null);
}
}
}
| true | true | public void updateOutputs(NCBIBlastJobResource job) throws RemoteException {
if (!job.getJobStatus().equals(JobStatus.done)
|| job.getNCBIBlastOutput() != null) {
// Too early/late
return;
}
String jobID = job.getJobID();
if (jobID == null || jobID.equals("")) {
// Too early, no job id set yet
return;
}
Document data;
try {
data = invoker.poll(jobID);
} catch (InvokerException e) {
job.setFault(new Fault("Can't poll for job ID " + jobID,
"Can't poll"));
logger.warn("Can't poll for jobID " + jobID, e);
throw new RemoteException("Can't poll for jobID " + jobID, e);
}
XMLOutputter xmlOutputter = new XMLOutputter();
String dataString = xmlOutputter.outputString(data);
StringReader xmlReader = new StringReader(dataString);
EBIApplicationResult eBIApplicationResult;
try {
eBIApplicationResult = (EBIApplicationResult) Utils.deserializeObject(xmlReader,
EBIApplicationResult.class);
job.setEBIApplicationResult(eBIApplicationResult);
} catch (Exception e) {
logger.warn("Could not parse/serialize returned data:\n" + dataString);
}
logger.info("Data returned for " + jobID + " is: \n" + dataString);
NCBIBLASTOutput output = converter.convertNCBIBlastOutput(data);
job.setNCBIBlastOutput(output);
}
| public void updateOutputs(NCBIBlastJobResource job) throws RemoteException {
if (!job.getJobStatus().equals(JobStatus.done)
|| job.getNCBIBlastOutput() != null) {
// Too early/late
return;
}
String jobID = job.getJobID();
if (jobID == null || jobID.equals("")) {
// Too early, no job id set yet
return;
}
Document data;
try {
data = invoker.poll(jobID);
} catch (InvokerException e) {
job.setFault(new Fault("Can't poll for job ID " + jobID,
"Can't poll"));
logger.warn("Can't poll for jobID " + jobID, e);
throw new RemoteException("Can't poll for jobID " + jobID, e);
}
XMLOutputter xmlOutputter = new XMLOutputter();
String dataString = xmlOutputter.outputString(data);
StringReader xmlReader = new StringReader(dataString);
EBIApplicationResult eBIApplicationResult;
try {
eBIApplicationResult = (EBIApplicationResult) Utils.deserializeObject(xmlReader,
EBIApplicationResult.class);
job.setEBIApplicationResult(eBIApplicationResult);
} catch (Exception e) {
logger.warn("Could not parse/serialize returned data:\n" + dataString, e);
}
logger.info("Data returned for " + jobID + " is: \n" + dataString);
NCBIBLASTOutput output = converter.convertNCBIBlastOutput(data);
job.setNCBIBlastOutput(output);
}
|
diff --git a/accountvalidator/java/src/hx/bankcheck/accountvalidator/impl/ChecksumB6.java b/accountvalidator/java/src/hx/bankcheck/accountvalidator/impl/ChecksumB6.java
index 59c5dfe..0af2593 100644
--- a/accountvalidator/java/src/hx/bankcheck/accountvalidator/impl/ChecksumB6.java
+++ b/accountvalidator/java/src/hx/bankcheck/accountvalidator/impl/ChecksumB6.java
@@ -1,66 +1,68 @@
package hx.bankcheck.accountvalidator.impl;
import hx.bankcheck.accountvalidator.ChecksumValidator;
import hx.bankcheck.accountvalidator.exceptions.ValidationException;
/**
* <b>Variante 1: </b><br/>
*
* Modulus 11, Gewichtung 2 ,3 ,4 ,5 ,6 ,7 ,8 ,9 ,3<br/>
*
* Kontonummern,die an der 1. Stelle der 10-stelligen Kontonummer den Wert 1-9
* beinhalten, sind nach der Methode 20 zu pr�fen. Alle anderen Kontonummern
* sind nach der Variante 2 zu pr�fen. <br/>
*
* Testkontonummer (richtig): 9110000000<br/>
* Testkontonummer (falsch): 9111000000 <br/>
*
* <b>Variante 2: </b><br/>
*
* Modulus 11, Gewichtung 2, 4,8, 5, 10, 9, 7, 3, 6, 1, 2, 4 <br/>
*
* Die Berechnung erfolgt nach der Methode 53.<br/>
*
* Testkontonummer (richtig) mit BLZ 80053782: 487310018 <br/>
* Testkontonummer (falsch) mit BLZ 80053762: 467310018 <br/>
* Testkontonummer (falsch) mit BLZ 80053772: 477310018<br/>
*
* @author Sascha D�mer ([email protected]) - LM Internet Services AG
* @version 1.0
*
*/
public class ChecksumB6 implements ChecksumValidator {
private static final int[] WEIGHTS_ALTERANTIVE1 = { 3, 9, 8, 7, 6, 5, 4, 3,
2 };
private static final int[] WEIGHTS_ALTERANTIVE2 = { 4, 2, 1, 6, 3, 7, 9,
10, 5, 8, 4, 2 };
private int alternative = 0;
@Override
public boolean validate(int[] accountNumber, int[] bankNumber)
throws ValidationException {
if (accountNumber[0] == 0) {
+ setAlternative(1);
return new Checksum53(WEIGHTS_ALTERANTIVE2).validate(accountNumber,
bankNumber);
} else {
+ setAlternative(0);
return new Checksum20(WEIGHTS_ALTERANTIVE1).validate(accountNumber);
}
}
/**
* @param alternative
* the alternative to set
*/
public void setAlternative(int alternative) {
this.alternative = alternative;
}
/**
* @return the alternative
*/
public int getAlternative() {
return alternative;
}
}
| false | true | public boolean validate(int[] accountNumber, int[] bankNumber)
throws ValidationException {
if (accountNumber[0] == 0) {
return new Checksum53(WEIGHTS_ALTERANTIVE2).validate(accountNumber,
bankNumber);
} else {
return new Checksum20(WEIGHTS_ALTERANTIVE1).validate(accountNumber);
}
}
| public boolean validate(int[] accountNumber, int[] bankNumber)
throws ValidationException {
if (accountNumber[0] == 0) {
setAlternative(1);
return new Checksum53(WEIGHTS_ALTERANTIVE2).validate(accountNumber,
bankNumber);
} else {
setAlternative(0);
return new Checksum20(WEIGHTS_ALTERANTIVE1).validate(accountNumber);
}
}
|
diff --git a/src/main/org/jboss/jmx/adaptor/snmp/agent/AttributeTableMapper.java b/src/main/org/jboss/jmx/adaptor/snmp/agent/AttributeTableMapper.java
index 771d26b..4c05233 100644
--- a/src/main/org/jboss/jmx/adaptor/snmp/agent/AttributeTableMapper.java
+++ b/src/main/org/jboss/jmx/adaptor/snmp/agent/AttributeTableMapper.java
@@ -1,343 +1,343 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt in the distribution for a
* full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.jmx.adaptor.snmp.agent;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
import javax.management.MBeanServer;
import javax.management.ObjectName;
import org.jboss.jmx.adaptor.snmp.config.attribute.ManagedBean;
import org.jboss.jmx.adaptor.snmp.config.attribute.MappedAttribute;
import org.jboss.logging.Logger;
import org.snmp4j.smi.OID;
import org.snmp4j.smi.OctetString;
import org.snmp4j.smi.Variable;
/**
* @author [email protected]
*
*/
public class AttributeTableMapper {
private SortedSet<OID> tables = new TreeSet<OID>();
// private SortedSet<OID> tableRowEntrys = new TreeSet<OID>();
/**
* keep an index of the OID from attributes.xml
*/
private SortedMap<OID, BindEntry> tableMappings = new TreeMap<OID, BindEntry>();
// private SortedMap<OID, BindEntry> tableRowEntryMappings = new TreeMap<OID, BindEntry>();
private MBeanServer server;
private Logger log;
public AttributeTableMapper(MBeanServer server, Logger log) {
this.server = server;
this.log = log;
}
/**
*
* @param oid
* @return
*/
public BindEntry getTableBinding(OID oid, boolean isRowEntry) {
Set<Entry<OID,BindEntry>> entries = null;
// if(isRowEntry) {
// entries = tableRowEntryMappings.entrySet();
// } else {
entries = tableMappings.entrySet();
// }
for (Entry<OID,BindEntry> entry : entries) {
if (oid.startsWith(entry.getKey())) {
BindEntry value = entry.getValue();
BindEntry bindEntry = (BindEntry) value.clone();
int[] oidValue = oid.getValue();
int[] subOid = new int[oid.size() - entry.getKey().size()];
System.arraycopy(oidValue, entry.getKey().size(), subOid, 0, oid.size() - entry.getKey().size());
if(subOid.length > 0) {
bindEntry.setTableIndexOID(new OID(subOid));
}
return bindEntry;
}
}
return null;
}
public OID getNextTable(OID oid) {
OID currentOID = oid;
// means that the oid is the one from the table itself
boolean isRowEntry = false;
if(tables.contains(oid)) {
currentOID = oid.append(1);
}
// if(tableRowEntrys.contains(currentOID)) {
// currentOID = oid.append(1);
// isRowEntry = true;
// }
BindEntry be = getTableBinding(currentOID, isRowEntry);
// if(be == null) {
// be = getTableBinding(currentOID, true);
// isRowEntry = true;
// }
if(be == null) {
return null; // it's not there
}
Object val = null;
try {
val = server.getAttribute(be.getMbean(), be.getAttr().getName());
} catch(Exception e) {
log.error("Impossible to fetch " + be.getAttr().getName());
return null;
}
OID tableIndexOID = be.getTableIndexOID();
if(tableIndexOID == null) {
if(val instanceof Map) {
- Set<Object> keySet = ((Map)val).keySet();
+ Set<Object> keySet = new TreeSet(((Map)val).keySet());
if(keySet.size() > 0) {
return new OID(currentOID.append("'" + keySet.iterator().next().toString() + "'"));
} else {
return null;
}
} else {
return new OID(currentOID).append(1);
}
}
if(val instanceof List) {
int index = Integer.valueOf(tableIndexOID.toString());
if(index - 1 < 0) {
return null;
}
index++;
if(index <= ((List)val).size()) {
return new OID(currentOID.trim().append(index));
} else {
// if(isRowEntry) {
// return new OID(currentOID.trim().trim().append(2).append(1));
// } else {
return null;
// }
}
}
if(val instanceof Map) {
// if(tableIndexOID.size() <= 1) {
// int index = Integer.valueOf(tableIndexOID.toString());
// if(index - 1 < 0) {
// return null;
// }
// index++;
// if(index <= ((Map)val).size()) {
// return new OID(currentOID.trim().append(index));
// } else {
// Set<Object> keySet = ((Map)val).keySet();
// if(keySet.size() > 0) {
// return new OID(currentOID.trim().trim().append(2).append("'" + keySet.iterator().next().toString() + "'"));
// } else {
// return null;
// }
// }
// } else {
String key = new String(tableIndexOID.toByteArray());
- Iterator<Object> keySet = ((Map)val).keySet().iterator();
+ Iterator<Object> keySet = new TreeSet(((Map)val).keySet()).iterator();
while (keySet.hasNext()) {
Object entryKey = keySet.next();
if(entryKey.equals(key)) {
if(keySet.hasNext()) {
Object nextKey = keySet.next();
OID nextOID = new OID(currentOID);
nextOID.trim(tableIndexOID.size());
nextOID.append("'" + nextKey + "'");
return nextOID;
} else {
return null;
}
}
}
return null;
// }
}
if (val instanceof int[]) {
int index = Integer.valueOf(tableIndexOID.toString());
if(index - 1 < 0) {
return null;
}
index++;
if(index <= ((int[])val).length) {
return new OID(currentOID.trim().append(index));
} else {
if(isRowEntry) {
return new OID(currentOID.trim().trim().append(2).append(1));
} else {
return null;
}
}
}
if (val instanceof long[]) {
int index = Integer.valueOf(tableIndexOID.toString());
if(index - 1 < 0) {
return null;
}
index++;
if(index <= ((long[])val).length) {
return new OID(currentOID.trim().append(index));
} else {
if(isRowEntry) {
return new OID(currentOID.trim().trim().append(2).append(1));
} else {
return null;
}
}
}
if (val instanceof boolean[]) {
int index = Integer.valueOf(tableIndexOID.toString());
if(index - 1 < 0) {
return null;
}
index++;
if(index <= ((boolean[])val).length) {
return new OID(currentOID.trim().append(index));
} else {
if(isRowEntry) {
return new OID(currentOID.trim().trim().append(2).append(1));
} else {
return null;
}
}
}
if (val instanceof Object[]) {
int index = Integer.valueOf(tableIndexOID.toString());
if(index - 1 < 0) {
return null;
}
index++;
if(index <= ((Object[])val).length) {
return new OID(currentOID.trim().append(index));
} else {
if(isRowEntry) {
return new OID(currentOID.trim().trim().append(2).append(1));
} else {
return null;
}
}
}
return null;
}
/**
*
* @param mmb
* @param oname
*/
public void addTableMapping(ManagedBean mmb, MappedAttribute ma) {
String oid;
String oidPrefix = mmb.getOidPrefix();
if (oidPrefix != null) {
oid = oidPrefix + ma.getOid();
} else {
oid = ma.getOid();
}
OID coid = new OID(oid);
BindEntry be = new BindEntry(coid, mmb.getName(), ma.getName());
be.setReadWrite(ma.isReadWrite());
be.setTable(ma.isAttributeTable());
if (log.isTraceEnabled())
log.trace("New bind entry " + be);
if (tables.contains(coid)) {
log.info("Duplicate oid " + coid + RequestHandlerImpl.SKIP_ENTRY);
}
if (mmb == null || mmb.equals("")) {
log.info("Invalid mbean name for oid " + coid + RequestHandlerImpl.SKIP_ENTRY);
}
if (ma == null || ma.equals("")) {
log.info("Invalid attribute name " + ma + " for oid " + coid
+ RequestHandlerImpl.SKIP_ENTRY);
}
// tableRowEntrys.add(coid);
tables.add(coid.trim());
// tableRowEntryMappings.put(new OID(coid).append(1), be);
tableMappings.put(new OID(coid), be);
// tableMappings.put(new OID(coid.trim()), be);
}
public boolean belongsToTables(OID oid) {
for (OID attributeOID : tables) {
if (oid.startsWith(attributeOID)) {
return true;
}
}
return false;
}
public void removeTableMapping(ManagedBean mmb, MappedAttribute ma) {
}
public Variable getIndexValue(OID oid) {
BindEntry be = getTableBinding(oid, true);
Object val = null;
if(be == null) {
return null;
}
try {
val = server.getAttribute(be.getMbean(), be.getAttr().getName());
} catch(Exception e) {
log.error("Impossible to fetch " + be.getAttr().getName());
return null;
}
OID tableIndexOID = be.getTableIndexOID();
if(val instanceof List) {
return new OctetString("" + oid.get(oid.size()-1));
}
if(val instanceof Map) {
int index = oid.get(oid.size()-1);
int i = 1;
for(Object key : ((Map) val).keySet()) {
if(i == index) {
return new OctetString((String)key);
}
i++;
}
}
if (val instanceof int[]) {
return new OctetString("" + oid.get(oid.size()-1));
}
if (val instanceof long[]) {
return new OctetString("" + oid.get(oid.size()-1));
}
if (val instanceof boolean[]) {
return new OctetString("" + oid.get(oid.size()-1));
}
if (val instanceof Object[]) {
return new OctetString("" + oid.get(oid.size()-1));
}
return null;
}
}
| false | true | public OID getNextTable(OID oid) {
OID currentOID = oid;
// means that the oid is the one from the table itself
boolean isRowEntry = false;
if(tables.contains(oid)) {
currentOID = oid.append(1);
}
// if(tableRowEntrys.contains(currentOID)) {
// currentOID = oid.append(1);
// isRowEntry = true;
// }
BindEntry be = getTableBinding(currentOID, isRowEntry);
// if(be == null) {
// be = getTableBinding(currentOID, true);
// isRowEntry = true;
// }
if(be == null) {
return null; // it's not there
}
Object val = null;
try {
val = server.getAttribute(be.getMbean(), be.getAttr().getName());
} catch(Exception e) {
log.error("Impossible to fetch " + be.getAttr().getName());
return null;
}
OID tableIndexOID = be.getTableIndexOID();
if(tableIndexOID == null) {
if(val instanceof Map) {
Set<Object> keySet = ((Map)val).keySet();
if(keySet.size() > 0) {
return new OID(currentOID.append("'" + keySet.iterator().next().toString() + "'"));
} else {
return null;
}
} else {
return new OID(currentOID).append(1);
}
}
if(val instanceof List) {
int index = Integer.valueOf(tableIndexOID.toString());
if(index - 1 < 0) {
return null;
}
index++;
if(index <= ((List)val).size()) {
return new OID(currentOID.trim().append(index));
} else {
// if(isRowEntry) {
// return new OID(currentOID.trim().trim().append(2).append(1));
// } else {
return null;
// }
}
}
if(val instanceof Map) {
// if(tableIndexOID.size() <= 1) {
// int index = Integer.valueOf(tableIndexOID.toString());
// if(index - 1 < 0) {
// return null;
// }
// index++;
// if(index <= ((Map)val).size()) {
// return new OID(currentOID.trim().append(index));
// } else {
// Set<Object> keySet = ((Map)val).keySet();
// if(keySet.size() > 0) {
// return new OID(currentOID.trim().trim().append(2).append("'" + keySet.iterator().next().toString() + "'"));
// } else {
// return null;
// }
// }
// } else {
String key = new String(tableIndexOID.toByteArray());
Iterator<Object> keySet = ((Map)val).keySet().iterator();
while (keySet.hasNext()) {
Object entryKey = keySet.next();
if(entryKey.equals(key)) {
if(keySet.hasNext()) {
Object nextKey = keySet.next();
OID nextOID = new OID(currentOID);
nextOID.trim(tableIndexOID.size());
nextOID.append("'" + nextKey + "'");
return nextOID;
} else {
return null;
}
}
}
return null;
// }
}
if (val instanceof int[]) {
int index = Integer.valueOf(tableIndexOID.toString());
if(index - 1 < 0) {
return null;
}
index++;
if(index <= ((int[])val).length) {
return new OID(currentOID.trim().append(index));
} else {
if(isRowEntry) {
return new OID(currentOID.trim().trim().append(2).append(1));
} else {
return null;
}
}
}
if (val instanceof long[]) {
int index = Integer.valueOf(tableIndexOID.toString());
if(index - 1 < 0) {
return null;
}
index++;
if(index <= ((long[])val).length) {
return new OID(currentOID.trim().append(index));
} else {
if(isRowEntry) {
return new OID(currentOID.trim().trim().append(2).append(1));
} else {
return null;
}
}
}
if (val instanceof boolean[]) {
int index = Integer.valueOf(tableIndexOID.toString());
if(index - 1 < 0) {
return null;
}
index++;
if(index <= ((boolean[])val).length) {
return new OID(currentOID.trim().append(index));
} else {
if(isRowEntry) {
return new OID(currentOID.trim().trim().append(2).append(1));
} else {
return null;
}
}
}
if (val instanceof Object[]) {
int index = Integer.valueOf(tableIndexOID.toString());
if(index - 1 < 0) {
return null;
}
index++;
if(index <= ((Object[])val).length) {
return new OID(currentOID.trim().append(index));
} else {
if(isRowEntry) {
return new OID(currentOID.trim().trim().append(2).append(1));
} else {
return null;
}
}
}
return null;
}
| public OID getNextTable(OID oid) {
OID currentOID = oid;
// means that the oid is the one from the table itself
boolean isRowEntry = false;
if(tables.contains(oid)) {
currentOID = oid.append(1);
}
// if(tableRowEntrys.contains(currentOID)) {
// currentOID = oid.append(1);
// isRowEntry = true;
// }
BindEntry be = getTableBinding(currentOID, isRowEntry);
// if(be == null) {
// be = getTableBinding(currentOID, true);
// isRowEntry = true;
// }
if(be == null) {
return null; // it's not there
}
Object val = null;
try {
val = server.getAttribute(be.getMbean(), be.getAttr().getName());
} catch(Exception e) {
log.error("Impossible to fetch " + be.getAttr().getName());
return null;
}
OID tableIndexOID = be.getTableIndexOID();
if(tableIndexOID == null) {
if(val instanceof Map) {
Set<Object> keySet = new TreeSet(((Map)val).keySet());
if(keySet.size() > 0) {
return new OID(currentOID.append("'" + keySet.iterator().next().toString() + "'"));
} else {
return null;
}
} else {
return new OID(currentOID).append(1);
}
}
if(val instanceof List) {
int index = Integer.valueOf(tableIndexOID.toString());
if(index - 1 < 0) {
return null;
}
index++;
if(index <= ((List)val).size()) {
return new OID(currentOID.trim().append(index));
} else {
// if(isRowEntry) {
// return new OID(currentOID.trim().trim().append(2).append(1));
// } else {
return null;
// }
}
}
if(val instanceof Map) {
// if(tableIndexOID.size() <= 1) {
// int index = Integer.valueOf(tableIndexOID.toString());
// if(index - 1 < 0) {
// return null;
// }
// index++;
// if(index <= ((Map)val).size()) {
// return new OID(currentOID.trim().append(index));
// } else {
// Set<Object> keySet = ((Map)val).keySet();
// if(keySet.size() > 0) {
// return new OID(currentOID.trim().trim().append(2).append("'" + keySet.iterator().next().toString() + "'"));
// } else {
// return null;
// }
// }
// } else {
String key = new String(tableIndexOID.toByteArray());
Iterator<Object> keySet = new TreeSet(((Map)val).keySet()).iterator();
while (keySet.hasNext()) {
Object entryKey = keySet.next();
if(entryKey.equals(key)) {
if(keySet.hasNext()) {
Object nextKey = keySet.next();
OID nextOID = new OID(currentOID);
nextOID.trim(tableIndexOID.size());
nextOID.append("'" + nextKey + "'");
return nextOID;
} else {
return null;
}
}
}
return null;
// }
}
if (val instanceof int[]) {
int index = Integer.valueOf(tableIndexOID.toString());
if(index - 1 < 0) {
return null;
}
index++;
if(index <= ((int[])val).length) {
return new OID(currentOID.trim().append(index));
} else {
if(isRowEntry) {
return new OID(currentOID.trim().trim().append(2).append(1));
} else {
return null;
}
}
}
if (val instanceof long[]) {
int index = Integer.valueOf(tableIndexOID.toString());
if(index - 1 < 0) {
return null;
}
index++;
if(index <= ((long[])val).length) {
return new OID(currentOID.trim().append(index));
} else {
if(isRowEntry) {
return new OID(currentOID.trim().trim().append(2).append(1));
} else {
return null;
}
}
}
if (val instanceof boolean[]) {
int index = Integer.valueOf(tableIndexOID.toString());
if(index - 1 < 0) {
return null;
}
index++;
if(index <= ((boolean[])val).length) {
return new OID(currentOID.trim().append(index));
} else {
if(isRowEntry) {
return new OID(currentOID.trim().trim().append(2).append(1));
} else {
return null;
}
}
}
if (val instanceof Object[]) {
int index = Integer.valueOf(tableIndexOID.toString());
if(index - 1 < 0) {
return null;
}
index++;
if(index <= ((Object[])val).length) {
return new OID(currentOID.trim().append(index));
} else {
if(isRowEntry) {
return new OID(currentOID.trim().trim().append(2).append(1));
} else {
return null;
}
}
}
return null;
}
|
diff --git a/src/main/java/net/pms/newgui/TranscodingTab.java b/src/main/java/net/pms/newgui/TranscodingTab.java
index 683d29ba8..153554da2 100644
--- a/src/main/java/net/pms/newgui/TranscodingTab.java
+++ b/src/main/java/net/pms/newgui/TranscodingTab.java
@@ -1,955 +1,955 @@
/*
* PS3 Media Server, for streaming any medias to your PS3.
* Copyright (C) 2008 A.Brochard
*
* 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; version 2
* of the License only.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package net.pms.newgui;
import com.jgoodies.forms.builder.PanelBuilder;
import com.jgoodies.forms.factories.Borders;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
import com.sun.jna.Platform;
import java.awt.*;
import java.awt.event.*;
import java.util.ArrayList;
import java.util.Locale;
import javax.swing.*;
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 net.pms.Messages;
import net.pms.PMS;
import net.pms.configuration.PmsConfiguration;
import net.pms.encoders.Player;
import net.pms.encoders.PlayerFactory;
import net.pms.util.FormLayoutUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class TranscodingTab {
private static final Logger LOGGER = LoggerFactory.getLogger(TranscodingTab.class);
private static final String COMMON_COL_SPEC = "left:pref, 3dlu, pref:grow";
private static final String COMMON_ROW_SPEC = "4*(pref, 3dlu), pref, 9dlu, pref, 9dlu:grow, pref";
private static final String EMPTY_COL_SPEC = "left:pref, 3dlu, pref:grow";
private static final String EMPTY_ROW_SPEC = "p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p , 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 3dlu, p, 20dlu, p, 3dlu, p, 3dlu, p";
private static final String LEFT_COL_SPEC = "left:pref, pref, pref, pref, 0:grow";
private static final String LEFT_ROW_SPEC = "fill:10:grow, 3dlu, p, 3dlu, p, 3dlu, p";
private static final String MAIN_COL_SPEC = "left:pref, pref, 7dlu, pref, pref, fill:10:grow";
private static final String MAIN_ROW_SPEC = "fill:10:grow";
private final PmsConfiguration configuration;
private ComponentOrientation orientation;
TranscodingTab(PmsConfiguration configuration) {
this.configuration = configuration;
// Apply the orientation for the locale
Locale locale = new Locale(configuration.getLanguage());
orientation = ComponentOrientation.getOrientation(locale);
}
private JCheckBox disableSubs;
private JTextField forcetranscode;
private JTextField notranscode;
private JTextField maxbuffer;
private JComboBox nbcores;
private DefaultMutableTreeNode parent[];
private JPanel tabbedPanel;
private CardLayout cl;
private JTextField abitrate;
private JTree tree;
private JCheckBox forcePCM;
public static JCheckBox forceDTSinPCM;
private JComboBox channels;
private JComboBox vq;
private JCheckBox ac3remux;
private JCheckBox mpeg2remux;
private JCheckBox chapter_support;
private JTextField chapter_interval;
private JCheckBox videoHWacceleration;
private JTextField langs;
private JTextField defaultsubs;
private JTextField forcedsub;
private JTextField forcedtags;
private JTextField alternateSubFolder;
private JButton folderSelectButton;
private JCheckBox subs;
private JTextField defaultaudiosubs;
private JComboBox subtitleCodePage;
private JTextField defaultfont;
private JButton fontselect;
private JCheckBox fribidi;
private JTextField ass_scale;
private JTextField ass_outline;
private JTextField ass_shadow;
private JTextField ass_margin;
private JButton subColor;
/*
* 16 cores is the maximum allowed by MEncoder as of MPlayer r34863.
* Revisions before that allowed only 8.
*/
private static final int MAX_CORES = 16;
private void updateEngineModel() {
ArrayList<String> engines = new ArrayList<>();
Object root = tree.getModel().getRoot();
for (int i = 0; i < tree.getModel().getChildCount(root); i++) {
Object firstChild = tree.getModel().getChild(root, i);
if (!tree.getModel().isLeaf(firstChild)) {
for (int j = 0; j < tree.getModel().getChildCount(firstChild); j++) {
Object secondChild = tree.getModel().getChild(firstChild, j);
if (secondChild instanceof TreeNodeSettings) {
TreeNodeSettings tns = (TreeNodeSettings) secondChild;
if (tns.isEnable() && tns.getPlayer() != null) {
engines.add(tns.getPlayer().id());
}
}
}
}
}
configuration.setEnginesAsList(engines);
}
private void handleCardComponentChange(Component component) {
tabbedPanel.setPreferredSize(component.getPreferredSize());
tabbedPanel.getParent().invalidate();
tabbedPanel.getParent().validate();
tabbedPanel.getParent().repaint();
}
public JComponent build() {
String colSpec = FormLayoutUtil.getColSpec(MAIN_COL_SPEC, orientation);
FormLayout mainlayout = new FormLayout(colSpec, MAIN_ROW_SPEC);
PanelBuilder builder = new PanelBuilder(mainlayout);
builder.setBorder(Borders.DLU4_BORDER);
builder.setOpaque(true);
CellConstraints cc = new CellConstraints();
if (!configuration.isHideAdvancedOptions()) {
builder.add(buildRightTabbedPanel(), FormLayoutUtil.flip(cc.xyw(4, 1, 3), colSpec, orientation));
builder.add(buildLeft(), FormLayoutUtil.flip(cc.xy(2, 1), colSpec, orientation));
} else {
builder.add(buildRightTabbedPanel(), FormLayoutUtil.flip(cc.xyw(2, 1, 5), colSpec, orientation));
builder.add(buildLeft(), FormLayoutUtil.flip(cc.xy(2, 1), colSpec, orientation));
}
JPanel panel = builder.getPanel();
// Apply the orientation to the panel and all components in it
panel.applyComponentOrientation(orientation);
return panel;
}
private JComponent buildRightTabbedPanel() {
cl = new CardLayout();
tabbedPanel = new JPanel(cl);
tabbedPanel.setBorder(BorderFactory.createEmptyBorder());
JScrollPane scrollPane = new JScrollPane(tabbedPanel);
scrollPane.setBorder(BorderFactory.createEmptyBorder());
return scrollPane;
}
public JComponent buildLeft() {
String colSpec = FormLayoutUtil.getColSpec(LEFT_COL_SPEC, orientation);
FormLayout layout = new FormLayout(colSpec, LEFT_ROW_SPEC);
PanelBuilder builder = new PanelBuilder(layout);
builder.setBorder(Borders.EMPTY_BORDER);
builder.setOpaque(false);
CellConstraints cc = new CellConstraints();
CustomJButton but = new CustomJButton(LooksFrame.readImageIcon("button-arrow-down.png"));
but.setToolTipText(Messages.getString("TrTab2.6"));
but.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
TreePath path = tree.getSelectionModel().getSelectionPath();
if (path != null && path.getLastPathComponent() instanceof TreeNodeSettings) {
TreeNodeSettings node = ((TreeNodeSettings) path.getLastPathComponent());
if (node.getPlayer() != null) {
DefaultTreeModel dtm = (DefaultTreeModel) tree.getModel(); // get the tree model
//now get the index of the selected node in the DefaultTreeModel
int index = dtm.getIndexOfChild(node.getParent(), node);
// if selected node is first, return (can't move it up)
if (index < node.getParent().getChildCount() - 1) {
dtm.insertNodeInto(node, (DefaultMutableTreeNode) node.getParent(), index + 1); // move the node
dtm.reload();
for (int i = 0; i < tree.getRowCount(); i++) {
tree.expandRow(i);
}
tree.getSelectionModel().setSelectionPath(new TreePath(node.getPath()));
updateEngineModel();
}
}
}
}
});
builder.add(but, FormLayoutUtil.flip(cc.xy(2, 3), colSpec, orientation));
CustomJButton but2 = new CustomJButton(LooksFrame.readImageIcon("button-arrow-up.png"));
but2.setToolTipText(Messages.getString("TrTab2.6"));
but2.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
TreePath path = tree.getSelectionModel().getSelectionPath();
if (path != null && path.getLastPathComponent() instanceof TreeNodeSettings) {
TreeNodeSettings node = ((TreeNodeSettings) path.getLastPathComponent());
if (node.getPlayer() != null) {
DefaultTreeModel dtm = (DefaultTreeModel) tree.getModel(); // get the tree model
//now get the index of the selected node in the DefaultTreeModel
int index = dtm.getIndexOfChild(node.getParent(), node);
// if selected node is first, return (can't move it up)
if (index != 0) {
dtm.insertNodeInto(node, (DefaultMutableTreeNode) node.getParent(), index - 1); // move the node
dtm.reload();
for (int i = 0; i < tree.getRowCount(); i++) {
tree.expandRow(i);
}
tree.getSelectionModel().setSelectionPath(new TreePath(node.getPath()));
updateEngineModel();
}
}
}
}
});
builder.add(but2, FormLayoutUtil.flip(cc.xy(3, 3), colSpec, orientation));
CustomJButton but3 = new CustomJButton(LooksFrame.readImageIcon("button-toggleengine.png"));
but3.setToolTipText(Messages.getString("TrTab2.0"));
but3.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
TreePath path = tree.getSelectionModel().getSelectionPath();
if (path != null && path.getLastPathComponent() instanceof TreeNodeSettings && ((TreeNodeSettings) path.getLastPathComponent()).getPlayer() != null) {
((TreeNodeSettings) path.getLastPathComponent()).setEnable(!((TreeNodeSettings) path.getLastPathComponent()).isEnable());
updateEngineModel();
tree.updateUI();
}
}
});
builder.add(but3, FormLayoutUtil.flip(cc.xy(4, 3), colSpec, orientation));
DefaultMutableTreeNode root = new DefaultMutableTreeNode(Messages.getString("TrTab2.11"));
TreeNodeSettings commonEnc = new TreeNodeSettings(Messages.getString("TrTab2.5"), null, buildCommon());
commonEnc.getConfigPanel().addComponentListener(new ComponentAdapter() {
@Override
public void componentShown(ComponentEvent e) {
handleCardComponentChange(e.getComponent());
}
});
tabbedPanel.add(commonEnc.id(), commonEnc.getConfigPanel());
root.add(commonEnc);
parent = new DefaultMutableTreeNode[5];
parent[0] = new DefaultMutableTreeNode(Messages.getString("TrTab2.14"));
parent[1] = new DefaultMutableTreeNode(Messages.getString("TrTab2.15"));
parent[2] = new DefaultMutableTreeNode(Messages.getString("TrTab2.16"));
parent[3] = new DefaultMutableTreeNode(Messages.getString("TrTab2.17"));
parent[4] = new DefaultMutableTreeNode(Messages.getString("TrTab2.18"));
root.add(parent[0]);
root.add(parent[1]);
root.add(parent[2]);
root.add(parent[3]);
root.add(parent[4]);
tree = new JTree(new DefaultTreeModel(root)) {
private static final long serialVersionUID = -6703434752606636290L;
};
tree.setRootVisible(false);
tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
tree.addTreeSelectionListener(new TreeSelectionListener() {
@Override
public void valueChanged(TreeSelectionEvent e) {
if (e.getNewLeadSelectionPath() != null && e.getNewLeadSelectionPath().getLastPathComponent() instanceof TreeNodeSettings) {
TreeNodeSettings tns = (TreeNodeSettings) e.getNewLeadSelectionPath().getLastPathComponent();
cl.show(tabbedPanel, tns.id());
}
}
});
tree.setRequestFocusEnabled(false);
tree.setCellRenderer(new TreeRenderer());
JScrollPane pane = new JScrollPane(tree, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
builder.add(pane, FormLayoutUtil.flip(cc.xyw(2, 1, 4), colSpec, orientation));
builder.addLabel(Messages.getString("TrTab2.19"), FormLayoutUtil.flip(cc.xyw(2, 5, 4), colSpec, orientation));
builder.addLabel(Messages.getString("TrTab2.20"), FormLayoutUtil.flip(cc.xyw(2, 7, 4), colSpec, orientation));
JPanel panel = builder.getPanel();
// Apply the orientation to the panel and all components in it
panel.applyComponentOrientation(orientation);
return panel;
}
public void addEngines() {
ArrayList<Player> disPlayers = new ArrayList<>();
ArrayList<Player> ordPlayers = new ArrayList<>();
PMS r = PMS.get();
for (String id : configuration.getEnginesAsList(r.getRegistry())) {
//boolean matched = false;
for (Player p : PlayerFactory.getAllPlayers()) {
if (p.id().equals(id)) {
ordPlayers.add(p);
if (p.isGPUAccelerationReady()) {
videoHWacceleration.setEnabled(true);
videoHWacceleration.setSelected(configuration.isGPUAcceleration());
}
//matched = true;
}
}
}
for (Player p : PlayerFactory.getAllPlayers()) {
if (!ordPlayers.contains(p)) {
ordPlayers.add(p);
disPlayers.add(p);
}
}
for (Player p : ordPlayers) {
TreeNodeSettings en = new TreeNodeSettings(p.name(), p, null);
if (disPlayers.contains(p)) {
en.setEnable(false);
}
JComponent jc = en.getConfigPanel();
if (jc == null) {
jc = buildEmpty();
}
jc.addComponentListener(new ComponentAdapter() {
@Override
public void componentShown(ComponentEvent e) {
handleCardComponentChange(e.getComponent());
}
});
tabbedPanel.add(en.id(), jc);
parent[p.purpose()].add(en);
}
for (int i = 0; i < tree.getRowCount(); i++) {
tree.expandRow(i);
}
tree.setSelectionRow(0);
}
public JComponent buildEmpty() {
String colSpec = FormLayoutUtil.getColSpec(EMPTY_COL_SPEC, orientation);
FormLayout layout = new FormLayout(colSpec, EMPTY_ROW_SPEC);
PanelBuilder builder = new PanelBuilder(layout);
builder.setBorder(Borders.EMPTY_BORDER);
builder.setOpaque(false);
CellConstraints cc = new CellConstraints();
builder.addSeparator(Messages.getString("TrTab2.1"), FormLayoutUtil.flip(cc.xyw(1, 1, 3), colSpec, orientation));
JPanel panel = builder.getPanel();
// Apply the orientation to the panel and all components in it
panel.applyComponentOrientation(orientation);
return panel;
}
public JComponent buildCommon() {
String colSpec = FormLayoutUtil.getColSpec(COMMON_COL_SPEC, orientation);
FormLayout layout = new FormLayout(colSpec, COMMON_ROW_SPEC);
PanelBuilder builder = new PanelBuilder(layout);
builder.setBorder(Borders.EMPTY_BORDER);
builder.setOpaque(false);
CellConstraints cc = new CellConstraints();
JComponent cmp = builder.addSeparator(Messages.getString("NetworkTab.5"), FormLayoutUtil.flip(cc.xyw(1, 1, 3), colSpec, orientation));
cmp = (JComponent) cmp.getComponent(0);
cmp.setFont(cmp.getFont().deriveFont(Font.BOLD));
disableSubs = new JCheckBox(Messages.getString("TrTab2.51"),configuration.isDisableSubtitles());
disableSubs.setContentAreaFilled(false);
disableSubs.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
configuration.setDisableSubtitles((e.getStateChange() == ItemEvent.SELECTED));
}
});
if (!configuration.isHideAdvancedOptions()) {
builder.addLabel(Messages.getString("TrTab2.23"), FormLayoutUtil.flip(cc.xy(1, 3), colSpec, orientation));
maxbuffer = new JTextField("" + configuration.getMaxMemoryBufferSize());
maxbuffer.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
try {
int ab = Integer.parseInt(maxbuffer.getText());
configuration.setMaxMemoryBufferSize(ab);
} catch (NumberFormatException nfe) {
LOGGER.debug("Could not parse max memory buffer size from \"" + maxbuffer.getText() + "\"");
}
}
});
builder.add(maxbuffer, FormLayoutUtil.flip(cc.xy(3, 3), colSpec, orientation));
String nCpusLabel = String.format(Messages.getString("TrTab2.24"), Runtime.getRuntime().availableProcessors());
builder.addLabel(nCpusLabel, FormLayoutUtil.flip(cc.xy(1, 5), colSpec, orientation));
String[] guiCores = new String[MAX_CORES];
for (int i = 0; i < MAX_CORES; i++) {
guiCores[i] = Integer.toString(i + 1);
}
nbcores = new JComboBox(guiCores);
nbcores.setEditable(false);
int nbConfCores = configuration.getNumberOfCpuCores();
if (nbConfCores > 0 && nbConfCores <= MAX_CORES) {
nbcores.setSelectedItem(Integer.toString(nbConfCores));
} else {
nbcores.setSelectedIndex(0);
}
nbcores.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
configuration.setNumberOfCpuCores(Integer.parseInt(e.getItem().toString()));
}
});
builder.add(nbcores, FormLayoutUtil.flip(cc.xy(3, 5), colSpec, orientation));
chapter_support = new JCheckBox(Messages.getString("TrTab2.52"), configuration.isChapterSupport());
chapter_support.setContentAreaFilled(false);
chapter_support.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
configuration.setChapterSupport((e.getStateChange() == ItemEvent.SELECTED));
chapter_interval.setEnabled(configuration.isChapterSupport());
}
});
builder.add(chapter_support, FormLayoutUtil.flip(cc.xy(1, 7), colSpec, orientation));
chapter_interval = new JTextField("" + configuration.getChapterInterval());
chapter_interval.setEnabled(configuration.isChapterSupport());
chapter_interval.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
try {
int ab = Integer.parseInt(chapter_interval.getText());
configuration.setChapterInterval(ab);
} catch (NumberFormatException nfe) {
LOGGER.debug("Could not parse chapter interval from \"" + chapter_interval.getText() + "\"");
}
}
});
builder.add(chapter_interval, FormLayoutUtil.flip(cc.xy(3, 7), colSpec, orientation));
builder.add(disableSubs, FormLayoutUtil.flip(cc.xy(1, 9), colSpec, orientation));
} else {
builder.add(disableSubs, FormLayoutUtil.flip(cc.xy(1, 3), colSpec, orientation));
}
JTabbedPane setupTabbedPanel = new JTabbedPane();
setupTabbedPanel.setUI(new CustomTabbedPaneUI());
setupTabbedPanel.addTab(Messages.getString("TrTab2.67"), buildVideoSetupPanel());
setupTabbedPanel.addTab(Messages.getString("TrTab2.68"), buildAudioSetupPanel());
setupTabbedPanel.addTab(Messages.getString("MEncoderVideo.8"), buildSubtitlesSetupPanel());
if (!configuration.isHideAdvancedOptions()) {
builder.add(setupTabbedPanel, FormLayoutUtil.flip(cc.xywh(1, 11, 3, 3), colSpec, orientation));
}
JPanel panel = builder.getPanel();
panel.applyComponentOrientation(orientation);
return panel;
}
private JComponent buildVideoSetupPanel() {
String colSpec = FormLayoutUtil.getColSpec("left:pref, 2dlu, pref:grow", orientation);
FormLayout layout = new FormLayout(colSpec, "$lgap, 2*(pref, 2dlu), 10dlu, 10dlu, 3*(pref, 2dlu), pref");
PanelBuilder builder = new PanelBuilder(layout);
builder.setBorder(Borders.DLU4_BORDER);
CellConstraints cc = new CellConstraints();
videoHWacceleration = new JCheckBox(Messages.getString("TrTab2.70"), configuration.isGPUAcceleration());
videoHWacceleration.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
configuration.setGPUAcceleration((e.getStateChange() == ItemEvent.SELECTED));
}
});
builder.add(videoHWacceleration, FormLayoutUtil.flip(cc.xy(1, 2), colSpec, orientation));
videoHWacceleration.setEnabled(false);
mpeg2remux = new JCheckBox(Messages.getString("MEncoderVideo.39") + (Platform.isWindows() ? " " + Messages.getString("TrTab2.21") : ""), configuration.isMencoderRemuxMPEG2());
mpeg2remux.setContentAreaFilled(false);
mpeg2remux.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
configuration.setMencoderRemuxMPEG2((e.getStateChange() == ItemEvent.SELECTED));
}
});
builder.add(mpeg2remux, FormLayoutUtil.flip(cc.xyw(1, 6, 3), colSpec, orientation));
JComponent cmp = builder.addSeparator(Messages.getString("TrTab2.7"), FormLayoutUtil.flip(cc.xyw(1, 8, 3), colSpec, orientation));
cmp = (JComponent) cmp.getComponent(0);
cmp.setFont(cmp.getFont().deriveFont(Font.BOLD));
builder.add(new JLabel(Messages.getString("TrTab2.32")), FormLayoutUtil.flip(cc.xy(1, 10), colSpec, orientation));
Object data[] = new Object[] {
configuration.getMPEG2MainSettings(), /* current setting */
String.format("Automatic (Wired) /* %s */", Messages.getString("TrTab2.71")),
String.format("Automatic (Wireless) /* %s */", Messages.getString("TrTab2.72")),
String.format("keyint=5:vqscale=1:vqmin=2 /* %s */", Messages.getString("TrTab2.60")), /* great */
String.format("keyint=5:vqscale=1:vqmin=1 /* %s */", Messages.getString("TrTab2.61")), /* lossless */
String.format("keyint=5:vqscale=2:vqmin=3 /* %s */", Messages.getString("TrTab2.62")), /* good (wired) */
String.format("keyint=25:vqmax=5:vqmin=2 /* %s */", Messages.getString("TrTab2.63")), /* good (wireless) */
String.format("keyint=25:vqmax=7:vqmin=2 /* %s */", Messages.getString("TrTab2.64")), /* medium (wireless) */
String.format("keyint=25:vqmax=8:vqmin=3 /* %s */", Messages.getString("TrTab2.65")) /* low */
};
MyComboBoxModel cbm = new MyComboBoxModel(data);
vq = new JComboBox(cbm);
vq.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
String s = (String) e.getItem();
if (s.indexOf("/*") > -1) {
s = s.substring(0, s.indexOf("/*")).trim();
}
configuration.setMPEG2MainSettings(s);
}
}
});
vq.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
vq.getItemListeners()[0].itemStateChanged(new ItemEvent(vq, 0, vq.getEditor().getItem(), ItemEvent.SELECTED));
}
});
vq.setEditable(true);
builder.add(vq, FormLayoutUtil.flip(cc.xy(3, 10), colSpec, orientation));
builder.add(new JLabel(Messages.getString("TrTab2.8")), FormLayoutUtil.flip(cc.xy(1, 12), colSpec, orientation));
notranscode = new JTextField(configuration.getNoTranscode());
notranscode.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
configuration.setNoTranscode(notranscode.getText());
}
});
builder.add(notranscode, FormLayoutUtil.flip(cc.xy(3, 12), colSpec, orientation));
builder.addLabel(Messages.getString("TrTab2.9"), FormLayoutUtil.flip(cc.xy(1, 14), colSpec, orientation));
forcetranscode = new JTextField(configuration.getForceTranscode());
forcetranscode.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
configuration.setForceTranscode(forcetranscode.getText());
}
});
builder.add(forcetranscode, FormLayoutUtil.flip(cc.xy(3, 14), colSpec, orientation));
JPanel panel = builder.getPanel();
panel.applyComponentOrientation(orientation);
return panel;
}
private JComponent buildAudioSetupPanel() {
String colSpec = FormLayoutUtil.getColSpec("left:pref, 2dlu, pref:grow", orientation);
FormLayout layout = new FormLayout(colSpec, "$lgap, pref, 2dlu, 4*(pref, 2dlu), pref, 12dlu, 3*(pref, 2dlu), pref:grow");
PanelBuilder builder = new PanelBuilder(layout);
builder.setBorder(Borders.DLU4_BORDER);
CellConstraints cc = new CellConstraints();
builder.addLabel(Messages.getString("TrTab2.50"), FormLayoutUtil.flip(cc.xy(1, 2), colSpec, orientation));
channels = new JComboBox(new Object[]{Messages.getString("TrTab2.55"), Messages.getString("TrTab2.56") /*, "8 channels 7.1" */}); // 7.1 not supported by Mplayer :\
channels.setEditable(false);
if (configuration.getAudioChannelCount() == 2) {
channels.setSelectedIndex(0);
} else {
channels.setSelectedIndex(1);
}
channels.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
configuration.setAudioChannelCount(Integer.parseInt(e.getItem().toString().substring(0, 1)));
}
});
builder.add(channels, FormLayoutUtil.flip(cc.xy(3, 2), colSpec, orientation));
forcePCM = new JCheckBox(Messages.getString("TrTab2.27"), configuration.isUsePCM());
forcePCM.setContentAreaFilled(false);
forcePCM.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
configuration.setUsePCM(e.getStateChange() == ItemEvent.SELECTED);
}
});
builder.add(forcePCM, FormLayoutUtil.flip(cc.xy(1, 4), colSpec, orientation));
ac3remux = new JCheckBox(Messages.getString("TrTab2.26") + " " + (Platform.isWindows() ? Messages.getString("TrTab2.21") : ""));
if (configuration.isRemuxAC3()) {
ac3remux.setSelected(true);
}
ac3remux.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
configuration.setRemuxAC3((e.getStateChange() == ItemEvent.SELECTED));
}
});
builder.add(ac3remux, FormLayoutUtil.flip(cc.xyw(1, 6, 3), colSpec, orientation));
forceDTSinPCM = new JCheckBox(Messages.getString("TrTab2.28") + (Platform.isWindows() ? " " + Messages.getString("TrTab2.21") : ""), configuration.isDTSEmbedInPCM());
forceDTSinPCM.setContentAreaFilled(false);
forceDTSinPCM.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
configuration.setDTSEmbedInPCM(forceDTSinPCM.isSelected());
if (configuration.isDTSEmbedInPCM()) {
JOptionPane.showMessageDialog(
(JFrame) (SwingUtilities.getWindowAncestor((Component) PMS.get().getFrame())),
Messages.getString("TrTab2.10"),
Messages.getString("Dialog.Information"),
JOptionPane.INFORMATION_MESSAGE);
}
}
});
builder.add(forceDTSinPCM, FormLayoutUtil.flip(cc.xyw(1, 8, 3), colSpec, orientation));
builder.addLabel(Messages.getString("TrTab2.29"), FormLayoutUtil.flip(cc.xy(1, 10), colSpec, orientation));
abitrate = new JTextField("" + configuration.getAudioBitrate());
abitrate.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
try {
int ab = Integer.parseInt(abitrate.getText());
configuration.setAudioBitrate(ab);
} catch (NumberFormatException nfe) {
LOGGER.debug("Could not parse audio bitrate from \"" + abitrate.getText() + "\"");
}
}
});
builder.add(abitrate, FormLayoutUtil.flip(cc.xy(3, 10), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.7"), FormLayoutUtil.flip(cc.xy(1, 12), colSpec, orientation));
langs = new JTextField(configuration.getAudioLanguages());
langs.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
configuration.setAudioLanguages(langs.getText());
}
});
builder.add(langs, FormLayoutUtil.flip(cc.xy(3, 12), colSpec, orientation));
JPanel panel = builder.getPanel();
panel.applyComponentOrientation(orientation);
return panel;
}
private JComponent buildSubtitlesSetupPanel() {
String colSpec = FormLayoutUtil.getColSpec("left:pref, 3dlu, p:grow, 3dlu, right:p:grow, 3dlu, p:grow, 3dlu, right:p:grow,3dlu, p:grow, 3dlu, right:p:grow,3dlu, pref:grow", orientation);
FormLayout layout = new FormLayout(colSpec, "$lgap, 7*(pref, 3dlu), pref");
final PanelBuilder builder = new PanelBuilder(layout);
builder.setBorder(Borders.DLU4_BORDER);
CellConstraints cc = new CellConstraints();
builder.addLabel(Messages.getString("MEncoderVideo.9"), FormLayoutUtil.flip(cc.xy(1, 2), colSpec, orientation));
defaultsubs = new JTextField(configuration.getSubtitlesLanguages());
defaultsubs.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
configuration.setSubtitlesLanguages(defaultsubs.getText());
}
});
builder.add(defaultsubs, FormLayoutUtil.flip(cc.xyw(3, 2, 5), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.94"), FormLayoutUtil.flip(cc.xy(9, 2, CellConstraints.RIGHT, CellConstraints.CENTER), colSpec, orientation));
forcedsub = new JTextField(configuration.getForcedSubtitleLanguage());
forcedsub.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
configuration.setForcedSubtitleLanguage(forcedsub.getText());
}
});
builder.add(forcedsub, FormLayoutUtil.flip(cc.xy(11, 2), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.95"), FormLayoutUtil.flip(cc.xy(13, 2, CellConstraints.RIGHT, CellConstraints.CENTER), colSpec, orientation));
forcedtags = new JTextField(configuration.getForcedSubtitleTags());
forcedtags.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
configuration.setForcedSubtitleTags(forcedtags.getText());
}
});
builder.add(forcedtags, FormLayoutUtil.flip(cc.xy(15, 2), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.10"), FormLayoutUtil.flip(cc.xy(1, 4), colSpec, orientation));
defaultaudiosubs = new JTextField(configuration.getAudioSubLanguages());
defaultaudiosubs.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
configuration.setAudioSubLanguages(defaultaudiosubs.getText());
}
});
builder.add(defaultaudiosubs, FormLayoutUtil.flip(cc.xyw(3, 4, 13), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.37"), FormLayoutUtil.flip(cc.xyw(1, 6, 2), colSpec, orientation));
alternateSubFolder = new JTextField(configuration.getAlternateSubsFolder());
alternateSubFolder.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
configuration.setAlternateSubsFolder(alternateSubFolder.getText());
}
});
builder.add(alternateSubFolder, FormLayoutUtil.flip(cc.xyw(3, 6, 12), colSpec, orientation));
folderSelectButton = new JButton("...");
folderSelectButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser chooser;
try {
chooser = new JFileChooser();
} catch (Exception ee) {
chooser = new JFileChooser(new RestrictedFileSystemView());
}
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnVal = chooser.showDialog((Component) e.getSource(), Messages.getString("FoldTab.28"));
if (returnVal == JFileChooser.APPROVE_OPTION) {
alternateSubFolder.setText(chooser.getSelectedFile().getAbsolutePath());
configuration.setAlternateSubsFolder(chooser.getSelectedFile().getAbsolutePath());
}
}
});
builder.add(folderSelectButton, FormLayoutUtil.flip(cc.xy(15, 6), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.11"), FormLayoutUtil.flip(cc.xy(1, 8), colSpec, orientation));
Object data[] = new Object[]{
configuration.getSubtitlesCodepage(),
Messages.getString("MEncoderVideo.96"),
Messages.getString("MEncoderVideo.97"),
Messages.getString("MEncoderVideo.98"),
Messages.getString("MEncoderVideo.99"),
Messages.getString("MEncoderVideo.100"),
Messages.getString("MEncoderVideo.101"),
Messages.getString("MEncoderVideo.102"),
Messages.getString("MEncoderVideo.103"),
Messages.getString("MEncoderVideo.104"),
Messages.getString("MEncoderVideo.105"),
Messages.getString("MEncoderVideo.106"),
Messages.getString("MEncoderVideo.107"),
Messages.getString("MEncoderVideo.108"),
Messages.getString("MEncoderVideo.109"),
Messages.getString("MEncoderVideo.110"),
Messages.getString("MEncoderVideo.111"),
Messages.getString("MEncoderVideo.112"),
Messages.getString("MEncoderVideo.113"),
Messages.getString("MEncoderVideo.114"),
Messages.getString("MEncoderVideo.115"),
Messages.getString("MEncoderVideo.116"),
Messages.getString("MEncoderVideo.117"),
Messages.getString("MEncoderVideo.118"),
Messages.getString("MEncoderVideo.119"),
Messages.getString("MEncoderVideo.120"),
Messages.getString("MEncoderVideo.121"),
Messages.getString("MEncoderVideo.122"),
Messages.getString("MEncoderVideo.123"),
Messages.getString("MEncoderVideo.124")
};
MyComboBoxModel cbm = new MyComboBoxModel(data);
subtitleCodePage = new JComboBox(cbm);
subtitleCodePage.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
String s = (String) e.getItem();
int offset = s.indexOf("/*");
if (offset > -1) {
s = s.substring(0, offset).trim();
}
configuration.setSubtitlesCodepage(s);
}
}
});
subtitleCodePage.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
subtitleCodePage.getItemListeners()[0].itemStateChanged(new ItemEvent(subtitleCodePage, 0, subtitleCodePage.getEditor().getItem(), ItemEvent.SELECTED));
}
});
subtitleCodePage.setEditable(true);
builder.add(subtitleCodePage, FormLayoutUtil.flip(cc.xyw(3, 8, 7), colSpec, orientation));
fribidi = new JCheckBox(Messages.getString("MEncoderVideo.23"));
fribidi.setContentAreaFilled(false);
if (configuration.isMencoderSubFribidi()) {
fribidi.setSelected(true);
}
fribidi.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
configuration.setMencoderSubFribidi(e.getStateChange() == ItemEvent.SELECTED);
}
});
builder.add(fribidi, FormLayoutUtil.flip(cc.xyw(11, 8, 4), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.24"), FormLayoutUtil.flip(cc.xy(1, 10), colSpec, orientation));
defaultfont = new JTextField(configuration.getFont());
defaultfont.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
configuration.setFont(defaultfont.getText());
}
});
builder.add(defaultfont, FormLayoutUtil.flip(cc.xyw(3, 10, 12), colSpec, orientation));
fontselect = new CustomJButton("...");
fontselect.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
chooser.setFileFilter(new FontFileFilter());
int returnVal = chooser.showDialog((Component) e.getSource(), Messages.getString("MEncoderVideo.25"));
if (returnVal == JFileChooser.APPROVE_OPTION) {
defaultfont.setText(chooser.getSelectedFile().getAbsolutePath());
configuration.setFont(chooser.getSelectedFile().getAbsolutePath());
}
}
});
builder.add(fontselect, FormLayoutUtil.flip(cc.xy(15, 10), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.12"), FormLayoutUtil.flip(cc.xy(1, 12), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.133"), FormLayoutUtil.flip(cc.xy(1, 12, CellConstraints.RIGHT, CellConstraints.CENTER), colSpec, orientation));
ass_scale = new JTextField(configuration.getAssScale());
ass_scale.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
configuration.setAssScale(ass_scale.getText());
}
});
builder.addLabel(Messages.getString("MEncoderVideo.13"), FormLayoutUtil.flip(cc.xy(5, 12), colSpec, orientation));
ass_outline = new JTextField(configuration.getAssOutline());
ass_outline.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
configuration.setAssOutline(ass_outline.getText());
}
});
builder.addLabel(Messages.getString("MEncoderVideo.14"), FormLayoutUtil.flip(cc.xy(9, 12), colSpec, orientation));
ass_shadow = new JTextField(configuration.getAssShadow());
ass_shadow.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
configuration.setAssShadow(ass_shadow.getText());
}
});
builder.addLabel(Messages.getString("MEncoderVideo.15"), FormLayoutUtil.flip(cc.xy(13, 12), colSpec, orientation));
ass_margin = new JTextField(configuration.getAssMargin());
ass_margin.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
configuration.setAssMargin(ass_margin.getText());
}
});
builder.add(ass_scale, FormLayoutUtil.flip(cc.xy(3, 12), colSpec, orientation));
builder.add(ass_outline, FormLayoutUtil.flip(cc.xy(7, 12), colSpec, orientation));
builder.add(ass_shadow, FormLayoutUtil.flip(cc.xy(11, 12), colSpec, orientation));
builder.add(ass_margin, FormLayoutUtil.flip(cc.xy(15, 12), colSpec, orientation));
subs = new JCheckBox(Messages.getString("MEncoderVideo.22"), configuration.isAutoloadSubtitles());
subs.setContentAreaFilled(false);
subs.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
configuration.setAutoloadSubtitles((e.getStateChange() == ItemEvent.SELECTED));
}
});
- builder.add(subs, FormLayoutUtil.flip(cc.xyw(1, 14, 13), colSpec, orientation));
+ builder.add(subs, FormLayoutUtil.flip(cc.xyw(1, 14, 11), colSpec, orientation));
subColor = new JButton();
subColor.setText(Messages.getString("MEncoderVideo.31"));
subColor.setBackground(new Color(configuration.getSubsColor()));
subColor.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Color newColor = JColorChooser.showDialog(
SwingUtilities.getWindowAncestor((Component) PMS.get().getFrame()),
Messages.getString("MEncoderVideo.125"),
subColor.getBackground()
);
if (newColor != null) {
subColor.setBackground(newColor);
configuration.setSubsColor(newColor.getRGB());
}
}
});
builder.add(subColor, FormLayoutUtil.flip(cc.xyw(13, 14, 3), colSpec, orientation));
final JPanel panel = builder.getPanel();
boolean enable = !configuration.isDisableSubtitles();
for (Component component : panel.getComponents()) {
component.setEnabled(enable);
}
disableSubs.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
// If Disable Subtitles is not selected, subtitles are enabled
boolean enabled = e.getStateChange() != ItemEvent.SELECTED;
for (Component component : panel.getComponents()) {
component.setEnabled(enabled);
}
}
});
panel.applyComponentOrientation(orientation);
return panel;
}
}
| true | true | private JComponent buildSubtitlesSetupPanel() {
String colSpec = FormLayoutUtil.getColSpec("left:pref, 3dlu, p:grow, 3dlu, right:p:grow, 3dlu, p:grow, 3dlu, right:p:grow,3dlu, p:grow, 3dlu, right:p:grow,3dlu, pref:grow", orientation);
FormLayout layout = new FormLayout(colSpec, "$lgap, 7*(pref, 3dlu), pref");
final PanelBuilder builder = new PanelBuilder(layout);
builder.setBorder(Borders.DLU4_BORDER);
CellConstraints cc = new CellConstraints();
builder.addLabel(Messages.getString("MEncoderVideo.9"), FormLayoutUtil.flip(cc.xy(1, 2), colSpec, orientation));
defaultsubs = new JTextField(configuration.getSubtitlesLanguages());
defaultsubs.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
configuration.setSubtitlesLanguages(defaultsubs.getText());
}
});
builder.add(defaultsubs, FormLayoutUtil.flip(cc.xyw(3, 2, 5), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.94"), FormLayoutUtil.flip(cc.xy(9, 2, CellConstraints.RIGHT, CellConstraints.CENTER), colSpec, orientation));
forcedsub = new JTextField(configuration.getForcedSubtitleLanguage());
forcedsub.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
configuration.setForcedSubtitleLanguage(forcedsub.getText());
}
});
builder.add(forcedsub, FormLayoutUtil.flip(cc.xy(11, 2), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.95"), FormLayoutUtil.flip(cc.xy(13, 2, CellConstraints.RIGHT, CellConstraints.CENTER), colSpec, orientation));
forcedtags = new JTextField(configuration.getForcedSubtitleTags());
forcedtags.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
configuration.setForcedSubtitleTags(forcedtags.getText());
}
});
builder.add(forcedtags, FormLayoutUtil.flip(cc.xy(15, 2), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.10"), FormLayoutUtil.flip(cc.xy(1, 4), colSpec, orientation));
defaultaudiosubs = new JTextField(configuration.getAudioSubLanguages());
defaultaudiosubs.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
configuration.setAudioSubLanguages(defaultaudiosubs.getText());
}
});
builder.add(defaultaudiosubs, FormLayoutUtil.flip(cc.xyw(3, 4, 13), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.37"), FormLayoutUtil.flip(cc.xyw(1, 6, 2), colSpec, orientation));
alternateSubFolder = new JTextField(configuration.getAlternateSubsFolder());
alternateSubFolder.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
configuration.setAlternateSubsFolder(alternateSubFolder.getText());
}
});
builder.add(alternateSubFolder, FormLayoutUtil.flip(cc.xyw(3, 6, 12), colSpec, orientation));
folderSelectButton = new JButton("...");
folderSelectButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser chooser;
try {
chooser = new JFileChooser();
} catch (Exception ee) {
chooser = new JFileChooser(new RestrictedFileSystemView());
}
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnVal = chooser.showDialog((Component) e.getSource(), Messages.getString("FoldTab.28"));
if (returnVal == JFileChooser.APPROVE_OPTION) {
alternateSubFolder.setText(chooser.getSelectedFile().getAbsolutePath());
configuration.setAlternateSubsFolder(chooser.getSelectedFile().getAbsolutePath());
}
}
});
builder.add(folderSelectButton, FormLayoutUtil.flip(cc.xy(15, 6), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.11"), FormLayoutUtil.flip(cc.xy(1, 8), colSpec, orientation));
Object data[] = new Object[]{
configuration.getSubtitlesCodepage(),
Messages.getString("MEncoderVideo.96"),
Messages.getString("MEncoderVideo.97"),
Messages.getString("MEncoderVideo.98"),
Messages.getString("MEncoderVideo.99"),
Messages.getString("MEncoderVideo.100"),
Messages.getString("MEncoderVideo.101"),
Messages.getString("MEncoderVideo.102"),
Messages.getString("MEncoderVideo.103"),
Messages.getString("MEncoderVideo.104"),
Messages.getString("MEncoderVideo.105"),
Messages.getString("MEncoderVideo.106"),
Messages.getString("MEncoderVideo.107"),
Messages.getString("MEncoderVideo.108"),
Messages.getString("MEncoderVideo.109"),
Messages.getString("MEncoderVideo.110"),
Messages.getString("MEncoderVideo.111"),
Messages.getString("MEncoderVideo.112"),
Messages.getString("MEncoderVideo.113"),
Messages.getString("MEncoderVideo.114"),
Messages.getString("MEncoderVideo.115"),
Messages.getString("MEncoderVideo.116"),
Messages.getString("MEncoderVideo.117"),
Messages.getString("MEncoderVideo.118"),
Messages.getString("MEncoderVideo.119"),
Messages.getString("MEncoderVideo.120"),
Messages.getString("MEncoderVideo.121"),
Messages.getString("MEncoderVideo.122"),
Messages.getString("MEncoderVideo.123"),
Messages.getString("MEncoderVideo.124")
};
MyComboBoxModel cbm = new MyComboBoxModel(data);
subtitleCodePage = new JComboBox(cbm);
subtitleCodePage.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
String s = (String) e.getItem();
int offset = s.indexOf("/*");
if (offset > -1) {
s = s.substring(0, offset).trim();
}
configuration.setSubtitlesCodepage(s);
}
}
});
subtitleCodePage.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
subtitleCodePage.getItemListeners()[0].itemStateChanged(new ItemEvent(subtitleCodePage, 0, subtitleCodePage.getEditor().getItem(), ItemEvent.SELECTED));
}
});
subtitleCodePage.setEditable(true);
builder.add(subtitleCodePage, FormLayoutUtil.flip(cc.xyw(3, 8, 7), colSpec, orientation));
fribidi = new JCheckBox(Messages.getString("MEncoderVideo.23"));
fribidi.setContentAreaFilled(false);
if (configuration.isMencoderSubFribidi()) {
fribidi.setSelected(true);
}
fribidi.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
configuration.setMencoderSubFribidi(e.getStateChange() == ItemEvent.SELECTED);
}
});
builder.add(fribidi, FormLayoutUtil.flip(cc.xyw(11, 8, 4), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.24"), FormLayoutUtil.flip(cc.xy(1, 10), colSpec, orientation));
defaultfont = new JTextField(configuration.getFont());
defaultfont.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
configuration.setFont(defaultfont.getText());
}
});
builder.add(defaultfont, FormLayoutUtil.flip(cc.xyw(3, 10, 12), colSpec, orientation));
fontselect = new CustomJButton("...");
fontselect.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
chooser.setFileFilter(new FontFileFilter());
int returnVal = chooser.showDialog((Component) e.getSource(), Messages.getString("MEncoderVideo.25"));
if (returnVal == JFileChooser.APPROVE_OPTION) {
defaultfont.setText(chooser.getSelectedFile().getAbsolutePath());
configuration.setFont(chooser.getSelectedFile().getAbsolutePath());
}
}
});
builder.add(fontselect, FormLayoutUtil.flip(cc.xy(15, 10), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.12"), FormLayoutUtil.flip(cc.xy(1, 12), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.133"), FormLayoutUtil.flip(cc.xy(1, 12, CellConstraints.RIGHT, CellConstraints.CENTER), colSpec, orientation));
ass_scale = new JTextField(configuration.getAssScale());
ass_scale.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
configuration.setAssScale(ass_scale.getText());
}
});
builder.addLabel(Messages.getString("MEncoderVideo.13"), FormLayoutUtil.flip(cc.xy(5, 12), colSpec, orientation));
ass_outline = new JTextField(configuration.getAssOutline());
ass_outline.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
configuration.setAssOutline(ass_outline.getText());
}
});
builder.addLabel(Messages.getString("MEncoderVideo.14"), FormLayoutUtil.flip(cc.xy(9, 12), colSpec, orientation));
ass_shadow = new JTextField(configuration.getAssShadow());
ass_shadow.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
configuration.setAssShadow(ass_shadow.getText());
}
});
builder.addLabel(Messages.getString("MEncoderVideo.15"), FormLayoutUtil.flip(cc.xy(13, 12), colSpec, orientation));
ass_margin = new JTextField(configuration.getAssMargin());
ass_margin.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
configuration.setAssMargin(ass_margin.getText());
}
});
builder.add(ass_scale, FormLayoutUtil.flip(cc.xy(3, 12), colSpec, orientation));
builder.add(ass_outline, FormLayoutUtil.flip(cc.xy(7, 12), colSpec, orientation));
builder.add(ass_shadow, FormLayoutUtil.flip(cc.xy(11, 12), colSpec, orientation));
builder.add(ass_margin, FormLayoutUtil.flip(cc.xy(15, 12), colSpec, orientation));
subs = new JCheckBox(Messages.getString("MEncoderVideo.22"), configuration.isAutoloadSubtitles());
subs.setContentAreaFilled(false);
subs.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
configuration.setAutoloadSubtitles((e.getStateChange() == ItemEvent.SELECTED));
}
});
builder.add(subs, FormLayoutUtil.flip(cc.xyw(1, 14, 13), colSpec, orientation));
subColor = new JButton();
subColor.setText(Messages.getString("MEncoderVideo.31"));
subColor.setBackground(new Color(configuration.getSubsColor()));
subColor.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Color newColor = JColorChooser.showDialog(
SwingUtilities.getWindowAncestor((Component) PMS.get().getFrame()),
Messages.getString("MEncoderVideo.125"),
subColor.getBackground()
);
if (newColor != null) {
subColor.setBackground(newColor);
configuration.setSubsColor(newColor.getRGB());
}
}
});
builder.add(subColor, FormLayoutUtil.flip(cc.xyw(13, 14, 3), colSpec, orientation));
final JPanel panel = builder.getPanel();
boolean enable = !configuration.isDisableSubtitles();
for (Component component : panel.getComponents()) {
component.setEnabled(enable);
}
disableSubs.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
// If Disable Subtitles is not selected, subtitles are enabled
boolean enabled = e.getStateChange() != ItemEvent.SELECTED;
for (Component component : panel.getComponents()) {
component.setEnabled(enabled);
}
}
});
panel.applyComponentOrientation(orientation);
return panel;
}
| private JComponent buildSubtitlesSetupPanel() {
String colSpec = FormLayoutUtil.getColSpec("left:pref, 3dlu, p:grow, 3dlu, right:p:grow, 3dlu, p:grow, 3dlu, right:p:grow,3dlu, p:grow, 3dlu, right:p:grow,3dlu, pref:grow", orientation);
FormLayout layout = new FormLayout(colSpec, "$lgap, 7*(pref, 3dlu), pref");
final PanelBuilder builder = new PanelBuilder(layout);
builder.setBorder(Borders.DLU4_BORDER);
CellConstraints cc = new CellConstraints();
builder.addLabel(Messages.getString("MEncoderVideo.9"), FormLayoutUtil.flip(cc.xy(1, 2), colSpec, orientation));
defaultsubs = new JTextField(configuration.getSubtitlesLanguages());
defaultsubs.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
configuration.setSubtitlesLanguages(defaultsubs.getText());
}
});
builder.add(defaultsubs, FormLayoutUtil.flip(cc.xyw(3, 2, 5), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.94"), FormLayoutUtil.flip(cc.xy(9, 2, CellConstraints.RIGHT, CellConstraints.CENTER), colSpec, orientation));
forcedsub = new JTextField(configuration.getForcedSubtitleLanguage());
forcedsub.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
configuration.setForcedSubtitleLanguage(forcedsub.getText());
}
});
builder.add(forcedsub, FormLayoutUtil.flip(cc.xy(11, 2), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.95"), FormLayoutUtil.flip(cc.xy(13, 2, CellConstraints.RIGHT, CellConstraints.CENTER), colSpec, orientation));
forcedtags = new JTextField(configuration.getForcedSubtitleTags());
forcedtags.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
configuration.setForcedSubtitleTags(forcedtags.getText());
}
});
builder.add(forcedtags, FormLayoutUtil.flip(cc.xy(15, 2), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.10"), FormLayoutUtil.flip(cc.xy(1, 4), colSpec, orientation));
defaultaudiosubs = new JTextField(configuration.getAudioSubLanguages());
defaultaudiosubs.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
configuration.setAudioSubLanguages(defaultaudiosubs.getText());
}
});
builder.add(defaultaudiosubs, FormLayoutUtil.flip(cc.xyw(3, 4, 13), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.37"), FormLayoutUtil.flip(cc.xyw(1, 6, 2), colSpec, orientation));
alternateSubFolder = new JTextField(configuration.getAlternateSubsFolder());
alternateSubFolder.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
configuration.setAlternateSubsFolder(alternateSubFolder.getText());
}
});
builder.add(alternateSubFolder, FormLayoutUtil.flip(cc.xyw(3, 6, 12), colSpec, orientation));
folderSelectButton = new JButton("...");
folderSelectButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser chooser;
try {
chooser = new JFileChooser();
} catch (Exception ee) {
chooser = new JFileChooser(new RestrictedFileSystemView());
}
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int returnVal = chooser.showDialog((Component) e.getSource(), Messages.getString("FoldTab.28"));
if (returnVal == JFileChooser.APPROVE_OPTION) {
alternateSubFolder.setText(chooser.getSelectedFile().getAbsolutePath());
configuration.setAlternateSubsFolder(chooser.getSelectedFile().getAbsolutePath());
}
}
});
builder.add(folderSelectButton, FormLayoutUtil.flip(cc.xy(15, 6), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.11"), FormLayoutUtil.flip(cc.xy(1, 8), colSpec, orientation));
Object data[] = new Object[]{
configuration.getSubtitlesCodepage(),
Messages.getString("MEncoderVideo.96"),
Messages.getString("MEncoderVideo.97"),
Messages.getString("MEncoderVideo.98"),
Messages.getString("MEncoderVideo.99"),
Messages.getString("MEncoderVideo.100"),
Messages.getString("MEncoderVideo.101"),
Messages.getString("MEncoderVideo.102"),
Messages.getString("MEncoderVideo.103"),
Messages.getString("MEncoderVideo.104"),
Messages.getString("MEncoderVideo.105"),
Messages.getString("MEncoderVideo.106"),
Messages.getString("MEncoderVideo.107"),
Messages.getString("MEncoderVideo.108"),
Messages.getString("MEncoderVideo.109"),
Messages.getString("MEncoderVideo.110"),
Messages.getString("MEncoderVideo.111"),
Messages.getString("MEncoderVideo.112"),
Messages.getString("MEncoderVideo.113"),
Messages.getString("MEncoderVideo.114"),
Messages.getString("MEncoderVideo.115"),
Messages.getString("MEncoderVideo.116"),
Messages.getString("MEncoderVideo.117"),
Messages.getString("MEncoderVideo.118"),
Messages.getString("MEncoderVideo.119"),
Messages.getString("MEncoderVideo.120"),
Messages.getString("MEncoderVideo.121"),
Messages.getString("MEncoderVideo.122"),
Messages.getString("MEncoderVideo.123"),
Messages.getString("MEncoderVideo.124")
};
MyComboBoxModel cbm = new MyComboBoxModel(data);
subtitleCodePage = new JComboBox(cbm);
subtitleCodePage.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (e.getStateChange() == ItemEvent.SELECTED) {
String s = (String) e.getItem();
int offset = s.indexOf("/*");
if (offset > -1) {
s = s.substring(0, offset).trim();
}
configuration.setSubtitlesCodepage(s);
}
}
});
subtitleCodePage.getEditor().getEditorComponent().addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
subtitleCodePage.getItemListeners()[0].itemStateChanged(new ItemEvent(subtitleCodePage, 0, subtitleCodePage.getEditor().getItem(), ItemEvent.SELECTED));
}
});
subtitleCodePage.setEditable(true);
builder.add(subtitleCodePage, FormLayoutUtil.flip(cc.xyw(3, 8, 7), colSpec, orientation));
fribidi = new JCheckBox(Messages.getString("MEncoderVideo.23"));
fribidi.setContentAreaFilled(false);
if (configuration.isMencoderSubFribidi()) {
fribidi.setSelected(true);
}
fribidi.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
configuration.setMencoderSubFribidi(e.getStateChange() == ItemEvent.SELECTED);
}
});
builder.add(fribidi, FormLayoutUtil.flip(cc.xyw(11, 8, 4), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.24"), FormLayoutUtil.flip(cc.xy(1, 10), colSpec, orientation));
defaultfont = new JTextField(configuration.getFont());
defaultfont.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
configuration.setFont(defaultfont.getText());
}
});
builder.add(defaultfont, FormLayoutUtil.flip(cc.xyw(3, 10, 12), colSpec, orientation));
fontselect = new CustomJButton("...");
fontselect.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JFileChooser chooser = new JFileChooser();
chooser.setFileFilter(new FontFileFilter());
int returnVal = chooser.showDialog((Component) e.getSource(), Messages.getString("MEncoderVideo.25"));
if (returnVal == JFileChooser.APPROVE_OPTION) {
defaultfont.setText(chooser.getSelectedFile().getAbsolutePath());
configuration.setFont(chooser.getSelectedFile().getAbsolutePath());
}
}
});
builder.add(fontselect, FormLayoutUtil.flip(cc.xy(15, 10), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.12"), FormLayoutUtil.flip(cc.xy(1, 12), colSpec, orientation));
builder.addLabel(Messages.getString("MEncoderVideo.133"), FormLayoutUtil.flip(cc.xy(1, 12, CellConstraints.RIGHT, CellConstraints.CENTER), colSpec, orientation));
ass_scale = new JTextField(configuration.getAssScale());
ass_scale.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
configuration.setAssScale(ass_scale.getText());
}
});
builder.addLabel(Messages.getString("MEncoderVideo.13"), FormLayoutUtil.flip(cc.xy(5, 12), colSpec, orientation));
ass_outline = new JTextField(configuration.getAssOutline());
ass_outline.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
configuration.setAssOutline(ass_outline.getText());
}
});
builder.addLabel(Messages.getString("MEncoderVideo.14"), FormLayoutUtil.flip(cc.xy(9, 12), colSpec, orientation));
ass_shadow = new JTextField(configuration.getAssShadow());
ass_shadow.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
configuration.setAssShadow(ass_shadow.getText());
}
});
builder.addLabel(Messages.getString("MEncoderVideo.15"), FormLayoutUtil.flip(cc.xy(13, 12), colSpec, orientation));
ass_margin = new JTextField(configuration.getAssMargin());
ass_margin.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
configuration.setAssMargin(ass_margin.getText());
}
});
builder.add(ass_scale, FormLayoutUtil.flip(cc.xy(3, 12), colSpec, orientation));
builder.add(ass_outline, FormLayoutUtil.flip(cc.xy(7, 12), colSpec, orientation));
builder.add(ass_shadow, FormLayoutUtil.flip(cc.xy(11, 12), colSpec, orientation));
builder.add(ass_margin, FormLayoutUtil.flip(cc.xy(15, 12), colSpec, orientation));
subs = new JCheckBox(Messages.getString("MEncoderVideo.22"), configuration.isAutoloadSubtitles());
subs.setContentAreaFilled(false);
subs.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
configuration.setAutoloadSubtitles((e.getStateChange() == ItemEvent.SELECTED));
}
});
builder.add(subs, FormLayoutUtil.flip(cc.xyw(1, 14, 11), colSpec, orientation));
subColor = new JButton();
subColor.setText(Messages.getString("MEncoderVideo.31"));
subColor.setBackground(new Color(configuration.getSubsColor()));
subColor.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
Color newColor = JColorChooser.showDialog(
SwingUtilities.getWindowAncestor((Component) PMS.get().getFrame()),
Messages.getString("MEncoderVideo.125"),
subColor.getBackground()
);
if (newColor != null) {
subColor.setBackground(newColor);
configuration.setSubsColor(newColor.getRGB());
}
}
});
builder.add(subColor, FormLayoutUtil.flip(cc.xyw(13, 14, 3), colSpec, orientation));
final JPanel panel = builder.getPanel();
boolean enable = !configuration.isDisableSubtitles();
for (Component component : panel.getComponents()) {
component.setEnabled(enable);
}
disableSubs.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
// If Disable Subtitles is not selected, subtitles are enabled
boolean enabled = e.getStateChange() != ItemEvent.SELECTED;
for (Component component : panel.getComponents()) {
component.setEnabled(enabled);
}
}
});
panel.applyComponentOrientation(orientation);
return panel;
}
|
diff --git a/src/parchment/render/ReportRenderEngine.java b/src/parchment/render/ReportRenderEngine.java
index d88937e..d9e31d5 100644
--- a/src/parchment/render/ReportRenderEngine.java
+++ b/src/parchment/render/ReportRenderEngine.java
@@ -1,22 +1,22 @@
/*
* ReportRenderEngine.java
*
* Copyright (c) 2009 Operational Dynamics Consulting Pty Ltd
*
* The code in this file, and the program it is a part of, are made available
* to you by its authors under the terms of the "GNU General Public Licence,
* version 2" See the LICENCE file for the terms governing usage and
* redistribution.
*/
package parchment.render;
import org.gnome.gtk.PaperSize;
import quill.textbase.Series;
public class ReportRenderEngine extends RenderEngine
{
public ReportRenderEngine(PaperSize paper, Series series) {
- super(PaperSize.A4, series);
+ super(paper, series);
}
}
| true | true | public ReportRenderEngine(PaperSize paper, Series series) {
super(PaperSize.A4, series);
}
| public ReportRenderEngine(PaperSize paper, Series series) {
super(paper, series);
}
|
diff --git a/SilkSpawners.java b/SilkSpawners.java
index 01519a6..9130fb8 100644
--- a/SilkSpawners.java
+++ b/SilkSpawners.java
@@ -1,634 +1,635 @@
/*
Copyright (c) 2012, Mushroom Hostage
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 <organization> 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 <COPYRIGHT HOLDER> 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 me.exphc.SilkSpawners;
import java.util.Collections;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.UUID;
import java.util.Iterator;
import java.util.logging.Logger;
import java.util.concurrent.ConcurrentHashMap;
import java.util.Formatter;
import java.lang.Byte;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.io.*;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.plugin.*;
import org.bukkit.event.*;
import org.bukkit.event.block.*;
import org.bukkit.event.player.*;
import org.bukkit.entity.*;
import org.bukkit.Material.*;
import org.bukkit.material.*;
import org.bukkit.block.*;
import org.bukkit.entity.*;
import org.bukkit.command.*;
import org.bukkit.inventory.*;
import org.bukkit.configuration.*;
import org.bukkit.configuration.file.*;
import org.bukkit.scheduler.*;
import org.bukkit.enchantments.*;
import org.bukkit.*;
import org.bukkit.craftbukkit.block.CraftCreatureSpawner;
import net.minecraft.server.CraftingManager;
import org.bukkit.craftbukkit.enchantments.CraftEnchantment;
class SilkSpawnersBlockListener implements Listener {
static Logger log = Logger.getLogger("Minecraft");
SilkSpawners plugin;
public SilkSpawnersBlockListener(SilkSpawners plugin) {
this.plugin = plugin;
Bukkit.getServer().getPluginManager().registerEvents(this, plugin);
}
@EventHandler(priority = EventPriority.NORMAL)
public void onBlockBreak(final BlockBreakEvent event) {
if (event.isCancelled()) {
return;
}
Block block = event.getBlock();
if (block.getType() != Material.MOB_SPAWNER) {
return;
}
Player player = event.getPlayer();
CraftCreatureSpawner spawner = new CraftCreatureSpawner(block);
CreatureType creatureType = spawner.getCreatureType();
plugin.informPlayer(player, plugin.getCreatureName(creatureType)+" spawner broken");
// If using silk touch, drop spawner itself
ItemStack tool = player.getItemInHand();
boolean silkTouch = tool != null && tool.containsEnchantment(Enchantment.SILK_TOUCH);
ItemStack dropItem;
World world = player.getWorld();
if (silkTouch && plugin.hasPermission(player, "silkspawners.silkdrop")) {
// Drop spawner
dropItem = plugin.newSpawnerItem(creatureType);
world.dropItemNaturally(block.getLocation(), dropItem);
return;
}
if (plugin.hasPermission(player, "silkspawners.destroydrop")) {
if (plugin.getConfig().getBoolean("destroyDropEgg")) {
// Drop egg
dropItem = plugin.creature2Egg.get(creatureType);
world.dropItemNaturally(block.getLocation(), dropItem);
}
int addXP = plugin.getConfig().getInt("destroyDropXP");
if (addXP != 0) {
ExperienceOrb orb = world.spawn(block.getLocation(), ExperienceOrb.class);
orb.setExperience(addXP);
}
int dropBars = plugin.getConfig().getInt("destroyDropBars");
if (dropBars != 0) {
world.dropItem(block.getLocation(), new ItemStack(Material.IRON_FENCE, dropBars));
}
}
}
@EventHandler(priority = EventPriority.NORMAL)
public void onBlockPlace(final BlockPlaceEvent event) {
if (event.isCancelled()) {
return;
}
Block blockPlaced = event.getBlockPlaced();
if (blockPlaced.getType() != Material.MOB_SPAWNER) {
return;
}
Player player = event.getPlayer();
// https://bukkit.atlassian.net/browse/BUKKIT-596 - BlockPlaceEvent getItemInHand() loses enchantments
// so, have to get item from player instead
//ItemStack item = event.getItemInHand();
ItemStack item = player.getItemInHand();
// Get data from item
short entityID = plugin.getStoredSpawnerItemEntityID(item);
if (entityID == 0) {
plugin.informPlayer(player, "Placing default spawner");
entityID = plugin.defaultEntityID;
if (entityID == 0) {
// "default default"; defer to Minecraft
return;
}
}
CreatureType creature = plugin.eid2Creature.get(entityID);
if (creature == null) {
plugin.informPlayer(player, "No creature associated with spawner");
return;
}
plugin.informPlayer(player, plugin.getCreatureName(creature)+" spawner placed");
// Bukkit 1.1-R3 regressed from 1.1-R1, ignores block state update on onBlockPlace
// TODO: file or find bug about this, get it fixed so can remove this lame workaround
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new SilkSpawnersSetCreatureTask(creature, blockPlaced, plugin, player), 0);
}
@EventHandler(priority = EventPriority.NORMAL)
public void onPlayerInteract(PlayerInteractEvent event) {
if (event.isCancelled()) {
return;
}
ItemStack item = event.getItem();
Block block = event.getClickedBlock();
Player player = event.getPlayer();
// Clicked spawner with monster egg to change type
if (event.getAction() == Action.LEFT_CLICK_BLOCK &&
item != null && item.getTypeId() == plugin.SPAWN_EGG_ID &&
block != null && block.getType() == Material.MOB_SPAWNER) {
if (!plugin.hasPermission(player, "silkspawners.changetypewithegg")) {
player.sendMessage("You do not have permission to change spawners with spawn eggs");
return;
}
short entityID = item.getDurability();
CreatureType creatureType = plugin.eid2Creature.get(entityID);
if (creatureType == null) {
player.sendMessage("Unrecognized creature in spawn egg ("+entityID+")");
return;
}
plugin.setSpawnerType(block, creatureType, player);
// Consume egg
if (plugin.getConfig().getBoolean("consumeEgg", true)) {
PlayerInventory inventory = player.getInventory();
int slot = inventory.getHeldItemSlot();
ItemStack eggs = inventory.getItem(slot);
if (eggs.getAmount() == 1) {
// Common case.. one egg, used up
inventory.clear(slot);
} else {
// Cannot legitimately get >1 egg per slot, but should support it regardless
inventory.setItem(slot, new ItemStack(plugin.SPAWN_EGG_ID, eggs.getAmount() - 1, entityID));
}
}
}
}
}
class SilkSpawnersSetCreatureTask implements Runnable {
CreatureType creature;
Block blockPlaced;
SilkSpawners plugin;
Player player;
public SilkSpawnersSetCreatureTask(CreatureType creature, Block blockPlaced, SilkSpawners plugin, Player player) {
this.creature = creature;
this.blockPlaced = blockPlaced;
this.plugin = plugin;
this.player = player;
}
public void run() {
/* non-Bukkit-API method
CraftCreatureSpawner spawner = new CraftCreatureSpawner(blockPlaced);
if (spawner == null) {
plugin.informPlayer(player, "Failed to find placed spawner, creature not set");
return;
}
spawner.setCreatureType(creature);
*/
BlockState bs = blockPlaced.getState(); // yes, it is bs
if (!(bs instanceof CreatureSpawner)) {
plugin.informPlayer(player, "Failed to get block state, creature not set");
return;
}
CreatureSpawner spawner = (CreatureSpawner)bs;
spawner.setCreatureType(creature);
bs.update();
}
}
public class SilkSpawners extends JavaPlugin {
static Logger log = Logger.getLogger("Minecraft");
SilkSpawnersBlockListener blockListener;
ConcurrentHashMap<CreatureType,ItemStack> creature2Egg;
ConcurrentHashMap<Short,CreatureType> eid2Creature;
ConcurrentHashMap<CreatureType,Short> creature2Eid;
static ConcurrentHashMap<Short,Short> legacyID2Eid;
ConcurrentHashMap<CreatureType,String> creature2DisplayName;
ConcurrentHashMap<String,CreatureType> name2Creature;
short defaultEntityID;
boolean usePermissions;
// Some modded versions of craftbukkit-1.1-R3 lack Material.MONSTER_EGG, so hardcode the ID
final static int SPAWN_EGG_ID = 383; // http://www.minecraftwiki.net/wiki/Data_values
public void onEnable() {
loadConfig();
if (getConfig().getBoolean("craftableSpawners", true)) {
loadRecipes();
}
// Listeners
blockListener = new SilkSpawnersBlockListener(this);
log.info("SilkSpawners enabled");
}
public boolean hasPermission(Player player, String node) {
if (usePermissions) {
return player.hasPermission(node);
} else {
if (node.equals("silkspawners.info") ||
node.equals("silkspawners.silkdrop") ||
node.equals("silkspawners.destroydrop") ||
node.equals("silkspawners.viewtype")) {
return true;
} else {
return player.isOp();
}
}
}
private void loadConfig() {
getConfig().options().copyDefaults(true);
saveConfig();
+ reloadConfig();
creature2Egg = new ConcurrentHashMap<CreatureType,ItemStack>();
eid2Creature = new ConcurrentHashMap<Short,CreatureType>();
creature2Eid = new ConcurrentHashMap<CreatureType,Short>();
legacyID2Eid = new ConcurrentHashMap<Short,Short>();
creature2DisplayName = new ConcurrentHashMap<CreatureType,String>();
name2Creature = new ConcurrentHashMap<String,CreatureType>();
// Creature info
MemorySection creatureSection = (MemorySection)getConfig().get("creatures");
for (String creatureString: creatureSection.getKeys(false)) {
CreatureType creatureType = CreatureType.fromName(creatureString);
if (creatureType == null) {
log.info("Invalid creature type: " + creatureString);
continue;
}
// TODO: http://www.minecraftwiki.net/wiki/Data_values#Entity_IDs in Bukkit?
short entityID = (short)getConfig().getInt("creatures."+creatureString+".entityID");
//ItemStack eggItem = new ItemStack(Material.MONSTER_EGG, 1, entityID);
ItemStack eggItem = new ItemStack(SPAWN_EGG_ID, 1, entityID);
creature2Egg.put(creatureType, eggItem);
eid2Creature.put(new Short(entityID), creatureType);
creature2Eid.put(creatureType, new Short(entityID));
short legacyID = (short)getConfig().getInt("creatures."+creatureString+".legacyID");
legacyID2Eid.put(new Short(legacyID), new Short(entityID));
// In-game name for user display, and other recognized names for user input lookup
String displayName = getConfig().getString("creatures."+creatureString+".displayName");
if (displayName == null) {
displayName = creatureString;
}
creature2DisplayName.put(creatureType, displayName);
List<String> aliases = getConfig().getStringList("creatures."+creatureString+".aliases");
aliases.add(displayName.toLowerCase().replace(" ", ""));
aliases.add(creatureString.toLowerCase().replace(" ", ""));
aliases.add(entityID+"");
aliases.add("#"+legacyID);
for (String alias: aliases) {
name2Creature.put(alias, creatureType);
}
}
// Get the entity ID of the creatures to spawn on damage 0 spawners, or otherwise not override
// (then will default to Minecraft's default of pigs)
defaultEntityID = 0;
String defaultCreatureString = getConfig().getString("defaultCreature", null);
if (defaultCreatureString != null) {
CreatureType defaultCreatureType = name2Creature.get(defaultCreatureString);
if (defaultCreatureType != null) {
ItemStack defaultItemStack = creature2Egg.get(defaultCreatureType);
if (defaultItemStack != null) {
defaultEntityID = defaultItemStack.getDurability();
log.info("Default monster spawner set to "+creature2DisplayName.get(defaultCreatureType));
} else {
log.info("Unable to lookup name of " + defaultCreatureString);
}
} else {
log.info("Invalid creature type: " + defaultCreatureString);
}
}
usePermissions = getConfig().getBoolean("usePermissions", false);
}
private void loadRecipes() {
try {
Material.valueOf("MONSTER_EGG");
} catch (Exception e) {
log.info("Your Bukkit is missing Material.MONSTER_EGG; disabling craftableSpawners");
return;
}
for (ItemStack egg: creature2Egg.values()) {
short entityID = egg.getDurability();
CreatureType creatureType = eid2Creature.get(entityID);
ItemStack spawnerItem = newSpawnerItem(creatureType);
ShapelessRecipe recipe = new ShapelessRecipe(spawnerItem);
// TODO: ShapedRecipe, box
recipe.addIngredient(8, Material.IRON_FENCE);
// Bukkit addIngredient() only accepts Material, not type id, so if MONSTER_EGG isn't
// available we can't add it
recipe.addIngredient(Material.MONSTER_EGG, (int)entityID);
if (getConfig().getBoolean("workaroundBukkitBug602", true)) {
// Workaround Bukkit bug:
// https://bukkit.atlassian.net/browse/BUKKIT-602 Enchantments lost on crafting recipe output
// CraftBukkit/src/main/java/org/bukkit/craftbukkit/inventory/CraftShapelessRecipe.java
ArrayList<MaterialData> ingred = recipe.getIngredientList();
Object[] data = new Object[ingred.size()];
int i = 0;
for (MaterialData mdata : ingred) {
int id = mdata.getItemTypeId();
byte dmg = mdata.getData();
data[i] = new net.minecraft.server.ItemStack(id, 1, dmg);
i++;
}
// Convert Bukkit ItemStack to net.minecraft.server.ItemStack
int id = recipe.getResult().getTypeId();
int amount = recipe.getResult().getAmount();
short durability = recipe.getResult().getDurability();
Map<Enchantment, Integer> enchantments = recipe.getResult().getEnchantments();
net.minecraft.server.ItemStack result = new net.minecraft.server.ItemStack(id, amount, durability);
for (Map.Entry<Enchantment, Integer> entry : enchantments.entrySet()) {
result.addEnchantment(CraftEnchantment.getRaw(entry.getKey()), entry.getValue().intValue());
}
CraftingManager.getInstance().registerShapelessRecipe(result, data);
} else {
Bukkit.getServer().addRecipe(recipe);
}
}
}
public void onDisable() {
log.info("SilkSpawners disabled");
}
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
if (!cmd.getName().equalsIgnoreCase("spawner")) {
return false;
}
if (!(sender instanceof Player)) {
// Would like to handle the non-player (console command) case, but, I use the block the
// player is looking at, so...
return false;
}
Player player = (Player)sender;
if (args.length == 0) {
// Get spawner type
if (!hasPermission(player, "silkspawners.viewtype")) {
sender.sendMessage("You do not have permission to view the spawner type");
return true;
}
Block block = getSpawnerFacing(player);
if (block == null) {
sender.sendMessage("You must be looking directly at a spawner to use this command");
return false;
}
CraftCreatureSpawner spawner = new CraftCreatureSpawner(block);
if (spawner == null) {
sender.sendMessage("Failed to find spawner");
return true;
}
CreatureType creatureType = spawner.getCreatureType();
sender.sendMessage(getCreatureName(creatureType) + " spawner");
} else {
// Set or get spawner
Block block = getSpawnerFacing(player);
String creatureString = args[0];
CreatureType creatureType = name2Creature.get(creatureString);
if (creatureType == null) {
sender.sendMessage("Unrecognized creature "+creatureString);
return true;
}
if (block != null) {
if (!hasPermission(player, "silkspawners.changetype")) {
player.sendMessage("You do not have permission to change spawners with /spawner");
return true;
}
setSpawnerType(block, creatureType, player);
} else {
// Get free spawner item in hand
if (!hasPermission(player, "silkspawners.freeitem")) {
if (hasPermission(player, "silkspawners.viewtype")) {
sender.sendMessage("You must be looking directly at a spawner to use this command");
} else {
sender.sendMessage("You do not have permission to use this command");
}
return true;
}
if (player.getItemInHand() != null && player.getItemInHand().getType() != Material.AIR) {
sender.sendMessage("To use this command, empty your hand (to get a free spawner item) or point at an existing spawner (to change the spawner type)");
return true;
}
player.setItemInHand(newSpawnerItem(creatureType));
sender.sendMessage(getCreatureName(creatureType) + " spawner");
}
}
return true;
}
// Set spawner type from user
public void setSpawnerType(Block block, CreatureType creatureType, Player player) {
// TODO: use Bukkit CreatureSpawner, get block state
CraftCreatureSpawner spawner = new CraftCreatureSpawner(block);
if (spawner == null) {
player.sendMessage("Failed to find spawner, creature not set");
return;
}
spawner.setCreatureType(creatureType);
player.sendMessage(getCreatureName(creatureType) + " spawner");
}
// Return the spawner block the player is looking at, or null if isn't
private Block getSpawnerFacing(Player player) {
Block block = player.getTargetBlock(null, getConfig().getInt("spawnerCommandReachDistance", 6));
if (block == null || block.getType() != Material.MOB_SPAWNER) {
return null;
}
return block;
}
// Get a creature name suitable for displaying to the user
// CreatureType getName has internal names like 'LavaSlime', this will return
// the in-game name like 'Magma Cube'
public String getCreatureName(CreatureType creature) {
String displayName = creature2DisplayName.get(creature);
if (displayName == null) {
displayName = "("+creature.getName()+")";
}
return displayName;
}
// Create a tagged a mob spawner _item_ with its entity ID so we know what it spawns
// This is not part of vanilla
public ItemStack newSpawnerItem(CreatureType creatureType) {
Short entityIDObject = creature2Eid.get(creatureType);
if (entityIDObject == null) {
log.info("newSpawnerItem("+creatureType+") unexpectedly failed to lookup entityID");
return null;
}
short entityID = entityIDObject.shortValue();
ItemStack item = new ItemStack(Material.MOB_SPAWNER, 1, entityID);
// Tag the entity ID several ways, for compatibility
// Bukkit bug resets durability on spawners
// https://bukkit.atlassian.net/browse/BUKKIT-329 MobSpawner should retains durability/data values.
// Try it anyways, just in case the bug has been fixed
item.setDurability(entityID);
// TODO: Creaturebox compatibility
// see http://dev.bukkit.org/server-mods/creaturebox/pages/trading-mob-spawners/
//item.addUnsafeEnchantment(Enchantment.OXYGEN, entityID);
item.addUnsafeEnchantment(Enchantment.SILK_TOUCH, entityID);
return item;
}
// Get the entity ID
public static short getStoredSpawnerItemEntityID(ItemStack item) {
short id = item.getDurability();
if (id != 0) {
return id;
}
// TODO: compatibility with Creaturebox's 0-22
/*
id = (short)item.getEnchantmentLevel(Enchantment.OXYGEN);
if (id != 0) {
return id;
}*/
id = (short)item.getEnchantmentLevel(Enchantment.SILK_TOUCH);
if (id != 0) {
return id;
}
// Creaturebox compatibility
short legacyID = (short)item.getEnchantmentLevel(Enchantment.OXYGEN);
// Bukkit API doesn't allow you tell if an enchantment is present vs. level 0 (=pigs),
// so ignore if level 0. This is a disadvantage of creaturebox's tagging system.
if (legacyID != 0) {
id = legacyID2Eid.get(legacyID);
if (id != 0) {
return id;
}
}
return 0;
}
public void informPlayer(Player player, String message) {
if (hasPermission(player, "silkspawners.info")) {
player.sendMessage(message);
}
}
}
| true | true | private void loadConfig() {
getConfig().options().copyDefaults(true);
saveConfig();
creature2Egg = new ConcurrentHashMap<CreatureType,ItemStack>();
eid2Creature = new ConcurrentHashMap<Short,CreatureType>();
creature2Eid = new ConcurrentHashMap<CreatureType,Short>();
legacyID2Eid = new ConcurrentHashMap<Short,Short>();
creature2DisplayName = new ConcurrentHashMap<CreatureType,String>();
name2Creature = new ConcurrentHashMap<String,CreatureType>();
// Creature info
MemorySection creatureSection = (MemorySection)getConfig().get("creatures");
for (String creatureString: creatureSection.getKeys(false)) {
CreatureType creatureType = CreatureType.fromName(creatureString);
if (creatureType == null) {
log.info("Invalid creature type: " + creatureString);
continue;
}
// TODO: http://www.minecraftwiki.net/wiki/Data_values#Entity_IDs in Bukkit?
short entityID = (short)getConfig().getInt("creatures."+creatureString+".entityID");
//ItemStack eggItem = new ItemStack(Material.MONSTER_EGG, 1, entityID);
ItemStack eggItem = new ItemStack(SPAWN_EGG_ID, 1, entityID);
creature2Egg.put(creatureType, eggItem);
eid2Creature.put(new Short(entityID), creatureType);
creature2Eid.put(creatureType, new Short(entityID));
short legacyID = (short)getConfig().getInt("creatures."+creatureString+".legacyID");
legacyID2Eid.put(new Short(legacyID), new Short(entityID));
// In-game name for user display, and other recognized names for user input lookup
String displayName = getConfig().getString("creatures."+creatureString+".displayName");
if (displayName == null) {
displayName = creatureString;
}
creature2DisplayName.put(creatureType, displayName);
List<String> aliases = getConfig().getStringList("creatures."+creatureString+".aliases");
aliases.add(displayName.toLowerCase().replace(" ", ""));
aliases.add(creatureString.toLowerCase().replace(" ", ""));
aliases.add(entityID+"");
aliases.add("#"+legacyID);
for (String alias: aliases) {
name2Creature.put(alias, creatureType);
}
}
// Get the entity ID of the creatures to spawn on damage 0 spawners, or otherwise not override
// (then will default to Minecraft's default of pigs)
defaultEntityID = 0;
String defaultCreatureString = getConfig().getString("defaultCreature", null);
if (defaultCreatureString != null) {
CreatureType defaultCreatureType = name2Creature.get(defaultCreatureString);
if (defaultCreatureType != null) {
ItemStack defaultItemStack = creature2Egg.get(defaultCreatureType);
if (defaultItemStack != null) {
defaultEntityID = defaultItemStack.getDurability();
log.info("Default monster spawner set to "+creature2DisplayName.get(defaultCreatureType));
} else {
log.info("Unable to lookup name of " + defaultCreatureString);
}
} else {
log.info("Invalid creature type: " + defaultCreatureString);
}
}
usePermissions = getConfig().getBoolean("usePermissions", false);
}
| private void loadConfig() {
getConfig().options().copyDefaults(true);
saveConfig();
reloadConfig();
creature2Egg = new ConcurrentHashMap<CreatureType,ItemStack>();
eid2Creature = new ConcurrentHashMap<Short,CreatureType>();
creature2Eid = new ConcurrentHashMap<CreatureType,Short>();
legacyID2Eid = new ConcurrentHashMap<Short,Short>();
creature2DisplayName = new ConcurrentHashMap<CreatureType,String>();
name2Creature = new ConcurrentHashMap<String,CreatureType>();
// Creature info
MemorySection creatureSection = (MemorySection)getConfig().get("creatures");
for (String creatureString: creatureSection.getKeys(false)) {
CreatureType creatureType = CreatureType.fromName(creatureString);
if (creatureType == null) {
log.info("Invalid creature type: " + creatureString);
continue;
}
// TODO: http://www.minecraftwiki.net/wiki/Data_values#Entity_IDs in Bukkit?
short entityID = (short)getConfig().getInt("creatures."+creatureString+".entityID");
//ItemStack eggItem = new ItemStack(Material.MONSTER_EGG, 1, entityID);
ItemStack eggItem = new ItemStack(SPAWN_EGG_ID, 1, entityID);
creature2Egg.put(creatureType, eggItem);
eid2Creature.put(new Short(entityID), creatureType);
creature2Eid.put(creatureType, new Short(entityID));
short legacyID = (short)getConfig().getInt("creatures."+creatureString+".legacyID");
legacyID2Eid.put(new Short(legacyID), new Short(entityID));
// In-game name for user display, and other recognized names for user input lookup
String displayName = getConfig().getString("creatures."+creatureString+".displayName");
if (displayName == null) {
displayName = creatureString;
}
creature2DisplayName.put(creatureType, displayName);
List<String> aliases = getConfig().getStringList("creatures."+creatureString+".aliases");
aliases.add(displayName.toLowerCase().replace(" ", ""));
aliases.add(creatureString.toLowerCase().replace(" ", ""));
aliases.add(entityID+"");
aliases.add("#"+legacyID);
for (String alias: aliases) {
name2Creature.put(alias, creatureType);
}
}
// Get the entity ID of the creatures to spawn on damage 0 spawners, or otherwise not override
// (then will default to Minecraft's default of pigs)
defaultEntityID = 0;
String defaultCreatureString = getConfig().getString("defaultCreature", null);
if (defaultCreatureString != null) {
CreatureType defaultCreatureType = name2Creature.get(defaultCreatureString);
if (defaultCreatureType != null) {
ItemStack defaultItemStack = creature2Egg.get(defaultCreatureType);
if (defaultItemStack != null) {
defaultEntityID = defaultItemStack.getDurability();
log.info("Default monster spawner set to "+creature2DisplayName.get(defaultCreatureType));
} else {
log.info("Unable to lookup name of " + defaultCreatureString);
}
} else {
log.info("Invalid creature type: " + defaultCreatureString);
}
}
usePermissions = getConfig().getBoolean("usePermissions", false);
}
|
diff --git a/docdoku-cli-android/src/com/docdoku/android/plm/network/HttpGetTask.java b/docdoku-cli-android/src/com/docdoku/android/plm/network/HttpGetTask.java
index 869f4fe2f..f9302d79b 100644
--- a/docdoku-cli-android/src/com/docdoku/android/plm/network/HttpGetTask.java
+++ b/docdoku-cli-android/src/com/docdoku/android/plm/network/HttpGetTask.java
@@ -1,108 +1,108 @@
/*
* DocDoku, Professional Open Source
* Copyright 2006 - 2013 DocDoku SARL
*
* This file is part of DocDokuPLM.
*
* DocDokuPLM is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* DocDokuPLM 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with DocDokuPLM. If not, see <http://www.gnu.org/licenses/>.
*/
package com.docdoku.android.plm.network;
import android.util.Base64;
import android.util.Log;
import com.docdoku.android.plm.network.listeners.HttpGetListener;
import java.io.*;
import java.net.*;
/**
*
* @author: Martin Devillers
*/
public class HttpGetTask extends HttpTask<String, Void, String>{
private HttpGetListener httpGetListener;
public HttpGetTask(HttpGetListener httpGetListener){
super();
this.httpGetListener = httpGetListener;
}
public HttpGetTask(String host, int port, String username, String password, HttpGetListener httpGetListener) throws UnsupportedEncodingException {
this.host = host;
this.port = port;
id = Base64.encode((username + ":" + password).getBytes("ISO-8859-1"), Base64.DEFAULT);
this.httpGetListener = httpGetListener;
}
@Override
protected String doInBackground(String... strings) {
String result = ERROR_UNKNOWN;
try {
URL url = createURL(strings[0]);
Log.i("com.docdoku.android.plm.client","Sending HttpGet request to url: " + url);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Authorization", "Basic " + new String(id, "US-ASCII"));
conn.connect();
int responseCode = conn.getResponseCode();
Log.i("com.docdoku.android.plm.client","Response code: " + responseCode);
if (responseCode == 200){
Log.i("com.docdoku.android.plm.client", "Response headers: " + conn.getHeaderFields());
Log.i("com.docdoku.android.plm.client", "Response message: " + conn.getResponseMessage());
InputStream in = (InputStream) conn.getContent();
result = inputStreamToString(in);
Log.i("com.docdoku.android.plm.client", "Response content: " + result);
in.close();
}else{
- analyzeHttpErrorCode(responseCode);
+ result = analyzeHttpErrorCode(responseCode);
}
conn.disconnect();
} catch (MalformedURLException e) {
Log.e("com.docdoku.android.plm.client","ERROR: MalformedURLException");
result = ERROR_URL;
e.printStackTrace();
} catch (ProtocolException e) {
Log.e("com.docdoku.android.plm.client","ERROR: ProtocolException");
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
Log.e("com.docdoku.android.plm.client", "ERROR: UnsupportedEncodingException");
e.printStackTrace();
} catch (IOException e) {
Log.e("com.docdoku.android.plm.client","ERROR: IOException");
e.printStackTrace();
Log.e("com.docdoku.android.plm.client", "Exception message: " + e.getMessage());
} catch (ArrayIndexOutOfBoundsException e){
Log.e("com.docdoku.android.plm.client", "ERROR: No Url provided for the Get query");
e.printStackTrace();
} catch (URISyntaxException e) {
Log.e("com.docdoku.android.plm", "URISyntaxException message: " + e.getMessage());
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
return result;
}
@Override
protected void onPostExecute(String result){
super.onPostExecute(result);
if (httpGetListener != null){
httpGetListener.onHttpGetResult(result);
}
}
}
| true | true | protected String doInBackground(String... strings) {
String result = ERROR_UNKNOWN;
try {
URL url = createURL(strings[0]);
Log.i("com.docdoku.android.plm.client","Sending HttpGet request to url: " + url);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Authorization", "Basic " + new String(id, "US-ASCII"));
conn.connect();
int responseCode = conn.getResponseCode();
Log.i("com.docdoku.android.plm.client","Response code: " + responseCode);
if (responseCode == 200){
Log.i("com.docdoku.android.plm.client", "Response headers: " + conn.getHeaderFields());
Log.i("com.docdoku.android.plm.client", "Response message: " + conn.getResponseMessage());
InputStream in = (InputStream) conn.getContent();
result = inputStreamToString(in);
Log.i("com.docdoku.android.plm.client", "Response content: " + result);
in.close();
}else{
analyzeHttpErrorCode(responseCode);
}
conn.disconnect();
} catch (MalformedURLException e) {
Log.e("com.docdoku.android.plm.client","ERROR: MalformedURLException");
result = ERROR_URL;
e.printStackTrace();
} catch (ProtocolException e) {
Log.e("com.docdoku.android.plm.client","ERROR: ProtocolException");
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
Log.e("com.docdoku.android.plm.client", "ERROR: UnsupportedEncodingException");
e.printStackTrace();
} catch (IOException e) {
Log.e("com.docdoku.android.plm.client","ERROR: IOException");
e.printStackTrace();
Log.e("com.docdoku.android.plm.client", "Exception message: " + e.getMessage());
} catch (ArrayIndexOutOfBoundsException e){
Log.e("com.docdoku.android.plm.client", "ERROR: No Url provided for the Get query");
e.printStackTrace();
} catch (URISyntaxException e) {
Log.e("com.docdoku.android.plm", "URISyntaxException message: " + e.getMessage());
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
return result;
}
| protected String doInBackground(String... strings) {
String result = ERROR_UNKNOWN;
try {
URL url = createURL(strings[0]);
Log.i("com.docdoku.android.plm.client","Sending HttpGet request to url: " + url);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Authorization", "Basic " + new String(id, "US-ASCII"));
conn.connect();
int responseCode = conn.getResponseCode();
Log.i("com.docdoku.android.plm.client","Response code: " + responseCode);
if (responseCode == 200){
Log.i("com.docdoku.android.plm.client", "Response headers: " + conn.getHeaderFields());
Log.i("com.docdoku.android.plm.client", "Response message: " + conn.getResponseMessage());
InputStream in = (InputStream) conn.getContent();
result = inputStreamToString(in);
Log.i("com.docdoku.android.plm.client", "Response content: " + result);
in.close();
}else{
result = analyzeHttpErrorCode(responseCode);
}
conn.disconnect();
} catch (MalformedURLException e) {
Log.e("com.docdoku.android.plm.client","ERROR: MalformedURLException");
result = ERROR_URL;
e.printStackTrace();
} catch (ProtocolException e) {
Log.e("com.docdoku.android.plm.client","ERROR: ProtocolException");
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
Log.e("com.docdoku.android.plm.client", "ERROR: UnsupportedEncodingException");
e.printStackTrace();
} catch (IOException e) {
Log.e("com.docdoku.android.plm.client","ERROR: IOException");
e.printStackTrace();
Log.e("com.docdoku.android.plm.client", "Exception message: " + e.getMessage());
} catch (ArrayIndexOutOfBoundsException e){
Log.e("com.docdoku.android.plm.client", "ERROR: No Url provided for the Get query");
e.printStackTrace();
} catch (URISyntaxException e) {
Log.e("com.docdoku.android.plm", "URISyntaxException message: " + e.getMessage());
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
return result;
}
|
diff --git a/src/java/net/bbm485/db/DBManager.java b/src/java/net/bbm485/db/DBManager.java
index 411b679..42fc95a 100644
--- a/src/java/net/bbm485/db/DBManager.java
+++ b/src/java/net/bbm485/db/DBManager.java
@@ -1,151 +1,153 @@
package net.bbm485.db;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import com.google.gson.GsonBuilder;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.util.JSON;
import org.bson.types.ObjectId;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import net.bbm485.exceptions.UserNotFoundException;
public class DBManager {
private Mongo mongo;
private DB db;
private DBCollection collection;
private String dbName;
private String collectionName;
/**
* * Getters and Setters **
*/
public String getDbName() {
return dbName;
}
public String getCollectionName() {
return collectionName;
}
private void setDbName(String dbName) {
this.dbName = dbName;
}
private void setCollectionName(String collectionName) {
this.collectionName = collectionName;
}
/**
* * End of Getters and Setters **
*/
public DBManager(String dbName, String collectionName) {
setDbName(dbName);
setCollectionName(collectionName);
initializeDB();
}
private void initializeDB() {
try {
mongo = new Mongo();
db = mongo.getDB(dbName);
collection = db.getCollection(collectionName);
}
catch (UnknownHostException ex) {
Logger.getLogger(DBManager.class.getName()).log(Level.SEVERE, null, ex);
}
catch (Exception ex) {
Logger.getLogger(DBManager.class.getName()).log(Level.SEVERE, null, ex);
}
}
public User getUser(String userId) throws UserNotFoundException {
try {
DBObject obj = new BasicDBObject("_id", new ObjectId(userId));
DBObject userObj = collection.findOne(obj);
User user = convertDBObject2User(userObj);
+ if (user == null)
+ throw new Exception();
return user;
}
- catch (IllegalArgumentException e) {
+ catch (Exception e) {
JSONObject errorMsg = new JSONObject();
try {
errorMsg.put("fieldName", "userId").put("rejectedValue", userId);
}
catch (JSONException ex) {
}
throw new UserNotFoundException(errorMsg);
}
}
public void createUser(User user) {
DBObject dbObj = (DBObject) JSON.parse(user.toJson());
collection.insert(dbObj);
ObjectId id = (ObjectId) dbObj.get("_id");
user.setId(id.toString());
collection.update(dbObj, (DBObject) JSON.parse(user.toJson()));
}
public ArrayList<User> getUserList() {
ArrayList<User> userList = new ArrayList<User>();
DBCursor cursor = collection.find();
while (cursor.hasNext())
userList.add(convertDBObject2User(cursor.next()));
return userList;
}
public void updateUser(String userId, JSONObject info) throws UserNotFoundException {
try {
DBObject obj = new BasicDBObject("_id", new ObjectId(userId));
DBObject userObj = collection.findOne(obj);
User foundUser = convertDBObject2User(userObj);
foundUser.updateInfo(info);
collection.update(userObj, convertUser2DBObject(foundUser));
}
catch (Exception e) {
JSONObject errorMsg = new JSONObject();
try {
errorMsg.put("fieldName", "userId").put("rejectedValue", userId);
}
catch (JSONException ex) {
}
throw new UserNotFoundException(errorMsg);
}
}
public void deleteUser(String userId) throws UserNotFoundException {
try {
DBObject obj = new BasicDBObject("_id", new ObjectId(userId));
DBObject userObj = collection.findOne(obj);
collection.remove(userObj);
}
catch (Exception e) {
JSONObject errorMsg = new JSONObject();
try {
errorMsg.put("fieldName", "userId").put("rejectedValue", userId);
}
catch (JSONException ex) {
}
throw new UserNotFoundException(errorMsg);
}
}
private DBObject convertUser2DBObject(User user) {
return (DBObject) JSON.parse(user.toJson());
}
private User convertDBObject2User(DBObject obj) {
return new GsonBuilder().serializeNulls().create().fromJson(JSON.serialize(obj), User.class);
}
}
| false | true | public User getUser(String userId) throws UserNotFoundException {
try {
DBObject obj = new BasicDBObject("_id", new ObjectId(userId));
DBObject userObj = collection.findOne(obj);
User user = convertDBObject2User(userObj);
return user;
}
catch (IllegalArgumentException e) {
JSONObject errorMsg = new JSONObject();
try {
errorMsg.put("fieldName", "userId").put("rejectedValue", userId);
}
catch (JSONException ex) {
}
throw new UserNotFoundException(errorMsg);
}
}
| public User getUser(String userId) throws UserNotFoundException {
try {
DBObject obj = new BasicDBObject("_id", new ObjectId(userId));
DBObject userObj = collection.findOne(obj);
User user = convertDBObject2User(userObj);
if (user == null)
throw new Exception();
return user;
}
catch (Exception e) {
JSONObject errorMsg = new JSONObject();
try {
errorMsg.put("fieldName", "userId").put("rejectedValue", userId);
}
catch (JSONException ex) {
}
throw new UserNotFoundException(errorMsg);
}
}
|
diff --git a/src/view/PokeSearchPanel.java b/src/view/PokeSearchPanel.java
index 37736df..555ddd8 100644
--- a/src/view/PokeSearchPanel.java
+++ b/src/view/PokeSearchPanel.java
@@ -1,138 +1,138 @@
/**
*
*/
package view;
import java.awt.BorderLayout;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import view.pokedex.PokedexScreen;
import data.DataFetch;
/**
* @author jimiford
*
*/
@SuppressWarnings("serial")
public class PokeSearchPanel extends JPanel {
private static final String DEFAULT = "Search Pokemon...";
private boolean override;
private DataFetch df;
private JTextArea jta;
private JScrollPane jsp;
private JTable table;
private PokeListener listen;
private PokedexScreen PSpanel;
public PokeSearchPanel(PokeListener listen) {
super(new BorderLayout());
this.listen = listen;
this.df = DataFetch.getInstance();
this.table = new JTable();
this.table.getTableHeader().setReorderingAllowed(false);
this.jsp = new JScrollPane(table);
this.jta = new JTextArea(DEFAULT);
this.initActions();
this.add(jsp, BorderLayout.CENTER);
this.add(jta, BorderLayout.NORTH);
PSpanel = new PokedexScreen();
this.updateModel();
}
public JTable getTable() {
return this.table;
}
public void updateModel() {
if(jta.getText().equals(DEFAULT)) {
// TableModel atm = df.getDefaultPokemonModel();
this.table.setModel(df.getDefaultPokemonModel());
} else {
this.table.setModel(df.getSearchPokemonModel(jta.getText()));
}
}
private void initActions() {
this.jta.addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent e) {
if(jta.getText().equals(DEFAULT)) {
jta.setText("");
}
}
@Override
public void focusLost(FocusEvent e) {
if(jta.getText().equals("")) {
jta.setText(DEFAULT);
updateModel();
}
}
});
this.jta.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
if(e.getKeyChar() == KeyEvent.VK_ESCAPE) {
jta.setText(DEFAULT);
}
updateModel();
}
});
this.table.addMouseListener(new MouseListener(){
@Override
- public void mouseClicked(MouseEvent arg0) {
+ public void mouseClicked(MouseEvent e) {
int index = table.getSelectedRow();
if(index != -1){
String pokemon = (String) table.getValueAt(index, 1);
// TODO call the setPokedexEntry(pokemon) method in PokedexScreen and switch views
}
}
@Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
});
}
}
| true | true | private void initActions() {
this.jta.addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent e) {
if(jta.getText().equals(DEFAULT)) {
jta.setText("");
}
}
@Override
public void focusLost(FocusEvent e) {
if(jta.getText().equals("")) {
jta.setText(DEFAULT);
updateModel();
}
}
});
this.jta.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
if(e.getKeyChar() == KeyEvent.VK_ESCAPE) {
jta.setText(DEFAULT);
}
updateModel();
}
});
this.table.addMouseListener(new MouseListener(){
@Override
public void mouseClicked(MouseEvent arg0) {
int index = table.getSelectedRow();
if(index != -1){
String pokemon = (String) table.getValueAt(index, 1);
// TODO call the setPokedexEntry(pokemon) method in PokedexScreen and switch views
}
}
@Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
});
}
| private void initActions() {
this.jta.addFocusListener(new FocusListener() {
@Override
public void focusGained(FocusEvent e) {
if(jta.getText().equals(DEFAULT)) {
jta.setText("");
}
}
@Override
public void focusLost(FocusEvent e) {
if(jta.getText().equals("")) {
jta.setText(DEFAULT);
updateModel();
}
}
});
this.jta.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
if(e.getKeyChar() == KeyEvent.VK_ESCAPE) {
jta.setText(DEFAULT);
}
updateModel();
}
});
this.table.addMouseListener(new MouseListener(){
@Override
public void mouseClicked(MouseEvent e) {
int index = table.getSelectedRow();
if(index != -1){
String pokemon = (String) table.getValueAt(index, 1);
// TODO call the setPokedexEntry(pokemon) method in PokedexScreen and switch views
}
}
@Override
public void mouseEntered(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent arg0) {
// TODO Auto-generated method stub
}
@Override
public void mouseReleased(MouseEvent arg0) {
// TODO Auto-generated method stub
}
});
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.