answer
stringlengths 17
10.2M
|
|---|
package stexfires.util;
import java.util.Locale;
import java.util.Objects;
import java.util.function.UnaryOperator;
/**
* @author Mathias Kalb
* @since 0.1
*/
public enum StringUnaryOperatorType {
LOWER_CASE,
UPPER_CASE,
TRIM_TO_NULL,
TRIM_TO_EMPTY,
REMOVE_HORIZONTAL_WHITESPACE,
REMOVE_WHITESPACE,
REMOVE_VERTICAL_WHITESPACE,
REVERSE;
private static final String EMPTY = "";
public static UnaryOperator<String> prefix(String prefix) {
Objects.requireNonNull(prefix);
return value -> value == null ? prefix : prefix + value;
}
public static UnaryOperator<String> postfix(String postfix) {
Objects.requireNonNull(postfix);
return value -> value == null ? postfix : value + postfix;
}
public static UnaryOperator<String> stringUnaryOperator(StringUnaryOperatorType stringUnaryOperatorType) {
Objects.requireNonNull(stringUnaryOperatorType);
return value -> operate(stringUnaryOperatorType, value, null);
}
public static UnaryOperator<String> stringUnaryOperator(StringUnaryOperatorType stringUnaryOperatorType, Locale locale) {
Objects.requireNonNull(stringUnaryOperatorType);
Objects.requireNonNull(locale);
return value -> operate(stringUnaryOperatorType, value, locale);
}
private static String operate(StringUnaryOperatorType stringUnaryOperatorType, String value) {
return operate(stringUnaryOperatorType, value, null);
}
private static String operate(StringUnaryOperatorType stringUnaryOperatorType, String value, Locale locale) {
Objects.requireNonNull(stringUnaryOperatorType);
String result = null;
switch (stringUnaryOperatorType) {
case LOWER_CASE:
if (value != null) {
if (locale != null) {
result = value.toLowerCase(locale);
} else {
result = value.toLowerCase();
}
}
break;
case UPPER_CASE:
if (value != null) {
if (locale != null) {
result = value.toUpperCase(locale);
} else {
result = value.toUpperCase();
}
}
break;
case TRIM_TO_EMPTY:
if (value != null) {
result = value.trim();
} else {
result = EMPTY;
}
break;
case TRIM_TO_NULL:
if (value != null) {
result = value.trim();
if (result.isEmpty()) {
result = null;
}
}
break;
case REMOVE_HORIZONTAL_WHITESPACE:
if (value != null) {
result = value.replaceAll("\\h", "");
}
break;
case REMOVE_WHITESPACE:
if (value != null) {
result = value.replaceAll("\\s", "");
}
break;
case REMOVE_VERTICAL_WHITESPACE:
if (value != null) {
result = value.replaceAll("\\v", "");
}
break;
case REVERSE:
if (value != null) {
result = new StringBuilder(value).reverse().toString();
}
break;
default:
result = value;
}
return result;
}
public UnaryOperator<String> stringUnaryOperator() {
return value -> operate(this, value, null);
}
public UnaryOperator<String> stringUnaryOperator(Locale locale) {
Objects.requireNonNull(locale);
return value -> operate(this, value, locale);
}
public String operate(String value) {
return operate(this, value);
}
public String operate(String value, Locale locale) {
Objects.requireNonNull(locale);
return operate(this, value, locale);
}
}
|
package ui.components.pickers;
import javafx.scene.Node;
import javafx.scene.control.Label;
/**
* This class is used to represent a repo in RepositoryPicker.
*
* It contains selected attribute to indicate whether the repo is selected.
* These attributes are used in order to produce appropriate label through getNode()
*/
public class PickerRepository implements Comparable<PickerRepository> {
private static final String BALLOT_BOX = "";
private static final String BALLOT_BOX_WITH_CHECK = "";
private final String repositoryId;
private boolean isSelected = false;
public PickerRepository(String repositoryId) {
this.repositoryId = repositoryId;
}
public String getRepositoryId() {
return repositoryId;
}
public Node getNode() {
Label repoLabel = new Label();
if (isSelected) {
repoLabel.setText(BALLOT_BOX_WITH_CHECK + " " + repositoryId);
} else {
repoLabel.setText(BALLOT_BOX + " " + repositoryId);
}
return repoLabel;
}
public void setSelected(boolean isSelected) {
this.isSelected = isSelected;
}
public boolean isSelected() {
return this.isSelected;
}
@Override
public boolean equals(Object o) {
if (!(o instanceof PickerRepository)) {
return false;
}
PickerRepository other = (PickerRepository) o;
return repositoryId.equalsIgnoreCase(other.getRepositoryId());
}
@Override
public int hashCode() {
return repositoryId.toLowerCase().hashCode();
}
@Override
public int compareTo(PickerRepository o) {
return repositoryId.toLowerCase().compareTo(o.getRepositoryId().toLowerCase());
}
}
|
package xdi2.example.client;
import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import xdi2.client.XDIClient;
import xdi2.client.http.XDIHttpClient;
import xdi2.core.io.XDIWriter;
import xdi2.core.io.XDIWriterRegistry;
import xdi2.core.xri3.XDI3Segment;
import xdi2.core.xri3.XDI3Statement;
import xdi2.messaging.Message;
import xdi2.messaging.MessageEnvelope;
import xdi2.messaging.MessageResult;
public class SimpleClientSample {
static XDIWriter writer = XDIWriterRegistry.forFormat("XDI/JSON", null);
static XDIClient client = new XDIHttpClient("http://localhost:8080/xdi/mem-graph");
static void doSet() throws Exception {
MessageEnvelope messageEnvelope = new MessageEnvelope();
Message message = messageEnvelope.getMessage(XDI3Segment.create("=sender"), true);
message.createSetOperation(XDI3Statement.create("=markus<+name>&/&/\"Markus\""));
client.send(messageEnvelope, null);
}
static void doGet() throws Exception {
MessageEnvelope messageEnvelope = new MessageEnvelope();
Message message = messageEnvelope.getMessage(XDI3Segment.create("=sender"), true);
message.createGetOperation(XDI3Segment.create("()"));
MessageResult messageResult = new MessageResult();
client.send(messageEnvelope, messageResult);
writer.write(messageResult.getGraph(), System.out);
}
static void doDel() throws Exception {
MessageEnvelope messageEnvelope = new MessageEnvelope();
Message message = messageEnvelope.getMessage(XDI3Segment.create("=sender"), true);
message.createDelOperation(XDI3Segment.create("()"));
client.send(messageEnvelope, null);
}
public static void main(String[] args) throws Exception {
LogManager.getLogger("xdi2").setLevel(Level.OFF);
// run a $set message
System.out.println("Running $set");
doSet();
System.out.println();
// run a $get message
System.out.println("Running $get");
doGet();
System.out.println();
// run a $del message
System.out.println("Running $del");
doDel();
System.out.println();
// run a $get message
System.out.println("Running $get");
doGet();
System.out.println();
}
}
|
package org.smoothbuild.db.hashed;
import static com.google.common.truth.Truth.assertThat;
import static java.lang.Byte.MAX_VALUE;
import static java.lang.Byte.MIN_VALUE;
import static java.lang.String.format;
import static okio.ByteString.encodeUtf8;
import static org.smoothbuild.io.fs.base.Path.path;
import static org.smoothbuild.testing.StringCreators.illegalString;
import static org.smoothbuild.testing.common.AssertCall.assertCall;
import static org.smoothbuild.util.Lists.list;
import static org.smoothbuild.util.io.Okios.writeAndClose;
import java.io.IOException;
import java.math.BigInteger;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
import org.junit.jupiter.params.provider.ValueSource;
import org.smoothbuild.db.hashed.exc.CorruptedHashedDbException;
import org.smoothbuild.db.hashed.exc.DecodeHashSequenceException;
import org.smoothbuild.db.hashed.exc.DecodeStringException;
import org.smoothbuild.db.hashed.exc.NoSuchDataException;
import org.smoothbuild.testing.TestingContextImpl;
import okio.ByteString;
public class HashedDbTest extends TestingContextImpl {
private final ByteString bytes1 = ByteString.encodeUtf8("aaa");
private final ByteString bytes2 = ByteString.encodeUtf8("bbb");
private HashingBufferedSink sink;
private Hash hash;
private ByteString byteString;
@Test
public void db_doesnt_contain_not_written_data() throws CorruptedHashedDbException {
assertThat(hashedDb().contains(Hash.of(33)))
.isFalse();
}
@Test
public void db_contains_written_data() throws Exception {
sink = hashedDb().sink();
sink.close();
assertThat(hashedDb().contains(sink.hash()))
.isTrue();
}
@Test
public void reading_not_written_value_fails() {
hash = Hash.of("abc");
assertCall(() -> hashedDb().source(hash))
.throwsException(new NoSuchDataException(hash));
}
@Test
public void written_data_can_be_read_back() throws Exception {
sink = hashedDb().sink();
byteString = encodeUtf8("abc");
sink.write(byteString);
sink.close();
assertThat(hashedDb().source(sink.hash()).readUtf8())
.isEqualTo("abc");
}
@Test
public void written_zero_length_data_can_be_read_back() throws Exception {
sink = hashedDb().sink();
sink.close();
assertThat(hashedDb().source(sink.hash()).readByteString())
.isEqualTo(ByteString.of());
}
@Test
public void bytes_written_twice_can_be_read_back() throws Exception {
sink = hashedDb().sink();
sink.write(bytes1);
sink.close();
sink = hashedDb().sink();
sink.write(bytes1);
sink.close();
assertThat(hashedDb().source(sink.hash()).readByteString())
.isEqualTo(bytes1);
}
@Test
public void hashes_for_different_data_are_different() throws Exception {
sink = hashedDb().sink();
sink.write(bytes1);
sink.close();
hash = sink.hash();
sink = hashedDb().sink();
sink.write(bytes2);
sink.close();
assertThat(sink.hash())
.isNotEqualTo(hash);
}
@Test
public void written_data_is_not_visible_until_close_is_invoked() throws Exception {
byteString = ByteString.of(new byte[1024 * 1024]);
hash = Hash.of(byteString);
sink = hashedDb().sink();
sink.write(byteString);
assertCall(() -> hashedDb().source(hash))
.throwsException(new NoSuchDataException(hash));
}
@Test
public void getting_hash_when_sink_is_not_closed_causes_exception() throws Exception {
sink = hashedDb().sink();
assertCall(() -> sink.hash())
.throwsException(IllegalStateException.class);
}
// tests for corrupted db
@Test
public void when_hash_points_to_directory_then_contains_causes_corrupted_exception()
throws Exception {
hash = Hash.of(33);
hashedDbFileSystem().createDir(path(hash.toString()));
assertCall(() -> hashedDb().contains(hash))
.throwsException(new CorruptedHashedDbException(
"Corrupted HashedDb. '" + hash + "' is a directory not a data file."));
}
@Test
public void when_hash_points_to_directory_then_source_causes_corrupted_exception()
throws IOException {
hash = Hash.of(33);
hashedDbFileSystem().createDir(path(hash.toString()));
assertCall(() -> hashedDb().source(hash))
.throwsException(new CorruptedHashedDbException(
format("Corrupted HashedDb at %s. '%s' is a directory not a data file.", hash, hash)));
}
@Test
public void when_hash_points_to_directory_then_sink_causes_corrupted_exception()
throws IOException {
hash = Hash.of(bytes1);
hashedDbFileSystem().createDir(path(hash.toHexString()));
assertCall(() -> hashedDb().sink().write(bytes1).close())
.throwsException(new IOException(
"Corrupted HashedDb. Cannot store data at '" + hash + "' as it is a directory."));
}
@Nested
class _big_integer {
@ParameterizedTest
@MethodSource("allByteValues")
public void with_single_byte_value_can_be_read_back(int value) throws Exception {
hash = hashedDb().writeByte((byte) value);
assertThat(hashedDb().readBigInteger(hash))
.isEqualTo(BigInteger.valueOf(value));
}
@ParameterizedTest
@ValueSource(ints = {Integer.MIN_VALUE, 1_000_000, Integer.MAX_VALUE})
public void with_given_value_can_be_read_back(int value) throws Exception {
BigInteger bigInteger = BigInteger.valueOf(value);
hash = hashedDb().writeBigInteger(bigInteger);
assertThat(hashedDb().readBigInteger(hash))
.isEqualTo(bigInteger);
}
private static Stream<Arguments> allByteValues() {
return IntStream.rangeClosed(Byte.MIN_VALUE, Byte.MAX_VALUE)
.mapToObj(Arguments::of);
}
}
@Nested
class _boolean {
@Test
public void with_true_value_can_be_read_back() throws Exception {
hash = hashedDb().writeBoolean(true);
assertThat(hashedDb().readBoolean(hash))
.isTrue();
}
@Test
public void with_false_value_can_be_read_back() throws Exception {
hash = hashedDb().writeBoolean(false);
assertThat(hashedDb().readBoolean(hash))
.isFalse();
}
}
@Nested
class _byte {
@ParameterizedTest
@MethodSource("allByteValues")
public void with_given_value_can_be_read_back(int value) throws Exception {
hash = hashedDb().writeByte((byte) value);
assertThat(hashedDb().readByte(hash))
.isEqualTo(value);
}
private static Stream<Arguments> allByteValues() {
return IntStream.rangeClosed(MIN_VALUE, MAX_VALUE)
.mapToObj(Arguments::of);
}
}
@Nested
class _string {
@ParameterizedTest
@ValueSource(strings = {"", "a", "abc", "!@
public void with_given_value_can_be_read_back() throws Exception {
hash = hashedDb().writeString("abc");
assertThat(hashedDb().readString(hash))
.isEqualTo("abc");
}
@Test
public void illegal_string_causes_decode_exception() throws Exception {
hash = Hash.of("abc");
writeAndClose(hashedDbFileSystem().sink(path(hash.toHexString())), s -> s.write(illegalString()));
assertCall(() -> hashedDb().readString(hash))
.throwsException(new DecodeStringException(hash, null));
}
}
@Nested
class _sequence {
@Test
public void with_no_elements_can_be_read_back() throws Exception {
hash = hashedDb().writeSequence();
assertThat(hashedDb().readSequence(hash))
.isEqualTo(list());
}
@Test
public void with_one_element_can_be_read_back() throws Exception {
hash = hashedDb().writeSequence(Hash.of("abc"));
assertThat(hashedDb().readSequence(hash))
.isEqualTo(list(Hash.of("abc")));
}
@Test
public void with_two_elements_can_be_read_back() throws Exception {
hash = hashedDb().writeSequence(Hash.of("abc"), Hash.of("def"));
assertThat(hashedDb().readSequence(hash))
.isEqualTo(list(Hash.of("abc"), Hash.of("def")));
}
@Test
public void not_written_sequence_of_hashes_cannot_be_read_back() {
hash = Hash.of("abc");
assertCall(() -> hashedDb().readSequence(hash))
.throwsException(new NoSuchDataException(hash));
}
@Test
public void corrupted_sequence_of_hashes_cannot_be_read_back() throws Exception {
hash = hashedDb().writeString("12345");
assertCall(() -> hashedDb().readSequence(hash))
.throwsException(new DecodeHashSequenceException(hash, 5));
}
}
}
|
package org.intermine.web;
import java.util.Comparator;
/**
* Comparator used for ordering templates by description length.
* @author kmr
*/
public class TemplateComparator implements Comparator
{
/**
* Compare two TemplateQuery objects by length of description.
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
public int compare(Object arg0, Object arg1) {
TemplateQuery template0 = (TemplateQuery) arg0;
TemplateQuery template1 = (TemplateQuery) arg1;
if (template0.title.length() < template1.title.length()) {
return -1;
} else {
if (template0.title.length() > template1.title.length()) {
return 1;
} else {
return 0;
}
}
}
}
|
package org.intermine.web.struts;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.intermine.api.InterMineAPI;
import org.intermine.api.profile.ProfileManager;
import org.intermine.web.logic.profile.LoginHandler;
import org.intermine.web.logic.session.SessionMethods;
/**
* Action to handle button presses on the main tile
*
* @author Mark Woodbridge
*/
public class LoginAction extends LoginHandler
{
/**
* Method called for login in
*
* @param mapping The ActionMapping used to select this instance
* @param form The optional ActionForm bean for this request (if any)
* @param request The HTTP request we are processing
* @param response The HTTP response we are creating
* @return an ActionForward object defining where control goes next
* @exception Exception if the application business logic throws an exception
*/
@Override public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws Exception {
HttpSession session = request.getSession();
final InterMineAPI im = SessionMethods.getInterMineAPI(session);
ProfileManager pm = im.getProfileManager();
LoginForm lf = (LoginForm) form;
ActionErrors errors = lf.validate(mapping, request);
if (!errors.isEmpty()) {
saveErrors(request, (ActionMessages) errors);
return mapping.findForward("login");
}
Map<String, String> renamedBags = doLogin(request, response, session, pm, lf.getUsername(),
lf.getPassword());
recordMessage(new ActionMessage("login.loggedin", lf.getUsername()), request);
if (renamedBags.size() > 0) {
for (String initName : renamedBags.keySet()) {
recordMessage(new ActionMessage("login.renamedbags", initName,
renamedBags.get(initName)), request);
}
return mapping.findForward("mymine");
}
// don't return user to the page they logged in from in certain situations
// eg. if they were in the middle of uploading a list
if (lf.returnToString != null && lf.returnToString.startsWith("/")
&& lf.returnToString.indexOf("error") == -1
&& lf.returnToString.indexOf("bagUploadConfirm") == -1) {
return new ActionForward(lf.returnToString);
}
return mapping.findForward("mymine");
}
}
|
package skin.support.app;
import android.content.Context;
import android.os.Build;
import android.support.annotation.NonNull;
import android.support.v4.view.LayoutInflaterFactory;
import android.support.v4.view.ViewCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.VectorEnabledTintResources;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewParent;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import skin.support.utils.SkinLog;
import skin.support.widget.SkinCompatSupportable;
public class SkinCompatDelegate implements LayoutInflaterFactory {
private final AppCompatActivity mAppCompatActivity;
private SkinCompatViewInflater mSkinCompatViewInflater;
private List<WeakReference<SkinCompatSupportable>> mSkinHelpers = new ArrayList<>();
private SkinCompatDelegate(AppCompatActivity appCompatActivity) {
mAppCompatActivity = appCompatActivity;
}
@Override
public View onCreateView(View parent, String name, Context context, AttributeSet attrs) {
View view = createView(parent, name, context, attrs);
if (view == null) {
return null;
}
if (view instanceof SkinCompatSupportable) {
mSkinHelpers.add(new WeakReference<SkinCompatSupportable>((SkinCompatSupportable) view));
}
return view;
}
public View createView(View parent, final String name, @NonNull Context context,
@NonNull AttributeSet attrs) {
final boolean isPre21 = Build.VERSION.SDK_INT < 21;
if (mSkinCompatViewInflater == null) {
mSkinCompatViewInflater = new SkinCompatViewInflater();
}
// We only want the View to inherit its context if we're running pre-v21
final boolean inheritContext = isPre21 && shouldInheritContext((ViewParent) parent);
return mSkinCompatViewInflater.createView(parent, name, context, attrs, inheritContext,
isPre21, /* Only read android:theme pre-L (L+ handles this anyway) */
true, /* Read read app:theme as a fallback at all times for legacy reasons */
VectorEnabledTintResources.shouldBeUsed() /* Only tint wrap the context if enabled */
);
}
private boolean shouldInheritContext(ViewParent parent) {
if (parent == null) {
// The initial parent is null so just return false
return false;
}
final View windowDecor = mAppCompatActivity.getWindow().getDecorView();
while (true) {
if (parent == null) {
// Bingo. We've hit a view which has a null parent before being terminated from
// the loop. This is (most probably) because it's the root view in an inflation
// call, therefore we should inherit. This works as the inflated layout is only
// added to the hierarchy at the end of the inflate() call.
return true;
} else if (parent == windowDecor || !(parent instanceof View)
|| ViewCompat.isAttachedToWindow((View) parent)) {
// We have either hit the window's decor view, a parent which isn't a View
// (i.e. ViewRootImpl), or an attached view, so we know that the original parent
// is currently added to the view hierarchy. This means that it has not be
// inflated in the current inflate() call and we should not inherit the context.
return false;
}
parent = parent.getParent();
}
}
public static SkinCompatDelegate create(AppCompatActivity appCompatActivity) {
return new SkinCompatDelegate(appCompatActivity);
}
public void applySkin() {
if (mSkinHelpers != null || !mSkinHelpers.isEmpty()) {
SkinLog.d("size - " + mSkinHelpers.size());
for (WeakReference ref : mSkinHelpers) {
if (ref != null && ref.get() != null) {
((SkinCompatSupportable) ref.get()).applySkin();
}
}
}
}
}
|
package org.keycloak.social;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
/**
* @author <a href="mailto:sthorger@redhat.com">Stian Thorgersen</a>
*/
public class IdentityProviderState {
private final Map<String, Object> state = Collections.synchronizedMap(new HashMap<String, Object>());
public boolean contains(String key) {
return state.containsKey(key);
}
public void put(String key, Object value) {
state.put(key, value);
}
@SuppressWarnings("unchecked")
public <T> T remove(String key) {
return (T) state.remove(key);
}
}
|
/**
*
* $Id: SubmitEditDeleteCITest.java,v 1.1 2009-07-13 17:45:12 pandyas Exp $
*
* $Log: not supported by cvs2svn $
* Revision 1.1 2009/07/07 17:46:54 pandyas
* modified according to the recommended directory layout for BDA
*
* Revision 1.2 2008/10/01 23:54:11 schroedn
* Junit test fixes for caMOD 2.5 - revision 1
*
* Revision 1.1 2008/05/12 16:29:06 pandyas
* Modified name for consistency
*
* Revision 1.7 2006/04/27 15:08:52 pandyas
* Modified while testing caMod 2.1
*
* Revision 1.6 2006/04/17 19:37:34 pandyas
* caMod 2.1 OM changes
*
* Revision 1.5 2005/12/14 20:14:35 pandyas
* Added JavaDocs
*
*
*/
package unit.web.submission;
import java.util.ResourceBundle;
import junit.framework.Test;
import junit.framework.TestSuite;
import unit.web.base.BaseModelNeededTest;
import com.meterware.httpunit.*;
/** This is a simple example of using HttpUnit to read and understand web pages. * */
public class SubmitEditDeleteCITest extends BaseModelNeededTest {
public SubmitEditDeleteCITest(String testName) {
super(testName);
}
protected void setUp() throws Exception {
ResourceBundle theBundle = ResourceBundle.getBundle("test");
String theUsername = theBundle.getString("username");
String thePassword = theBundle.getString("password");
loginToApplication(theUsername, thePassword);
createModel();
}
protected void tearDown() throws Exception {
deleteModel();
logoutOfApplication();
}
public static Test suite() {
TestSuite suite = new TestSuite(SubmitEditDeleteCITest.class);
return suite;
}
public void testAddAntibody() throws Exception {
navigateToModelForEditing(myModelName);
//Adding
WebLink theLink = myWebConversation.getCurrentPage().getFirstMatchingLink(WebLink.MATCH_CONTAINED_TEXT, "Enter Antibody");
assertNotNull("Unable to find link to add a Antibody", theLink);
WebResponse theCurrentPage = theLink.click();
assertCurrentPageContains("(if Antibody is not listed, then please");
WebForm theForm = theCurrentPage.getFormWithName("antibodyForm");
theForm.setParameter("name", "anti-CTLA-4 antibody");
theCurrentPage = theForm.submit();
assertCurrentPageContains("You have successfully added an Antibody to this model!");
//Editing
theLink = myWebConversation.getCurrentPage().getFirstMatchingLink(WebLink.MATCH_CONTAINED_TEXT, "anti-CTLA-4 antibody");
assertNotNull("Unable to find link to edit a Antibody", theLink);
theCurrentPage = theLink.click();
assertCurrentPageContains("(if Antibody is not listed, then please");
theForm = theCurrentPage.getFormWithName("antibodyForm");
theForm.setParameter("name", "anti-CTLA-4 antibody");
theForm.setParameter("type", "Male Only");
theCurrentPage = theForm.submit();
assertCurrentPageContains("You have successfully edited an Antibody.");
//Deleting
theLink = myWebConversation.getCurrentPage().getFirstMatchingLink(WebLink.MATCH_CONTAINED_TEXT, "anti-CTLA-4 antibody");
assertNotNull("Unable to find link to delete a Antibody", theLink);
theCurrentPage = theLink.click();
assertCurrentPageContains("(if Antibody is not listed, then please");
theForm = theCurrentPage.getFormWithName("antibodyForm");
theForm.getSubmitButton( "submitAction", "Delete" ).click();
assertCurrentPageContains("You have successfully deleted an Antibody.");
}
public void testAddBacteria() throws Exception {
navigateToModelForEditing(myModelName);
//Adding
WebLink theLink = myWebConversation.getCurrentPage().getFirstMatchingLink(WebLink.MATCH_CONTAINED_TEXT, "Enter Bacteria");
assertNotNull("Unable to find link to add a Bacteria", theLink);
WebResponse theCurrentPage = theLink.click();
assertCurrentPageContains("(if Bacteria is not listed, then please");
WebForm theForm = theCurrentPage.getFormWithName("bacteriaForm");
theForm.setParameter("name", "helicobacter felis");
theCurrentPage = theForm.submit();
assertCurrentPageContains("You have successfully added a Bacteria to this model!");
//Editing
theLink = myWebConversation.getCurrentPage().getFirstMatchingLink(WebLink.MATCH_CONTAINED_TEXT, "helicobacter felis");
assertNotNull("Unable to find link to edit a Bacteria", theLink);
theCurrentPage = theLink.click();
assertCurrentPageContains("(if Antibody is not listed, then please");
theForm = theCurrentPage.getFormWithName("bacteriaForm");
theForm.setParameter("name", "helicobacter felis");
theForm.setParameter("type", "Male Only");
theCurrentPage = theForm.submit();
assertCurrentPageContains("You have successfully edited a Bacteria.");
//Deleting
theLink = myWebConversation.getCurrentPage().getFirstMatchingLink(WebLink.MATCH_CONTAINED_TEXT, "helicobacter felis");
assertNotNull("Unable to find link to delete a Bacteria", theLink);
theCurrentPage = theLink.click();
assertCurrentPageContains("(if Bacteria is not listed, then please");
theForm = theCurrentPage.getFormWithName("bacteriaForm");
theForm.getSubmitButton( "submitAction", "Delete" ).click();
assertCurrentPageContains("You have successfully deleted a Bacteria.");
}
public void testAddChemicalDrug() throws Exception {
navigateToModelForEditing(myModelName);
//Adding
// We may or may not have to hit the agreement link
WebLink theLink = myWebConversation.getCurrentPage().getFirstMatchingLink(WebLink.MATCH_CONTAINED_TEXT, "Enter Chemical/Drug");
assertNotNull("Unable to find link to enter a Chemical/Drug", theLink);
WebResponse theCurrentPage = theLink.click();
assertCurrentPageContains("(if Chemical/Drug is not listed, then please");
WebForm theForm = theCurrentPage.getFormWithName("chemicalDrugForm");
theForm.setParameter("name", "1,3-butadiene");
theCurrentPage = theForm.submit();
assertCurrentPageContains("You have successfully added a Chemical / Drug to this model!");
//Editing
theLink = myWebConversation.getCurrentPage().getFirstMatchingLink(WebLink.MATCH_CONTAINED_TEXT, "1,3-butadiene");
assertNotNull("Unable to find link to edit a Chemical/Drug", theLink);
theCurrentPage = theLink.click();
assertCurrentPageContains("(if Chemical/Drug is not listed, then please");
theForm = theCurrentPage.getFormWithName("chemicalDrugForm");
theForm.setParameter("name", "1,3-butadiene");
theForm.setParameter("nscNumber", "123");
theCurrentPage = theForm.submit();
assertCurrentPageContains("You have successfully edited a Chemical / Drug.");
//Deleting
theLink = myWebConversation.getCurrentPage().getFirstMatchingLink(WebLink.MATCH_CONTAINED_TEXT, "1,3-butadiene");
assertNotNull("Unable to find link to delete a Chemical/Drug", theLink);
theCurrentPage = theLink.click();
assertCurrentPageContains("(if Chemical/Drug is not listed, then please");
theForm = theCurrentPage.getFormWithName("chemicalDrugForm");
theForm.getSubmitButton( "submitAction", "Delete" ).click();
assertCurrentPageContains("You have successfully deleted a Chemical / Drug.");
}
public void testAddEnvironmentalFactor() throws Exception {
navigateToModelForEditing(myModelName);
//Adding
WebLink theLink = myWebConversation.getCurrentPage().getFirstMatchingLink(WebLink.MATCH_CONTAINED_TEXT, "Enter Environmental Factor");
assertNotNull("Unable to find link to add a Environmental Factor", theLink);
WebResponse theCurrentPage = theLink.click();
assertCurrentPageContains("(if Enviromental Factor is not listed, then please");
WebForm theForm = theCurrentPage.getFormWithName("environmentalFactorForm");
theForm.setParameter("name", "mainstream cigarette smoke (MCS)");
theCurrentPage = theForm.submit();
assertCurrentPageContains("You have successfully added an Environmental Factor to this model!");
//Editing
theLink = myWebConversation.getCurrentPage().getFirstMatchingLink(WebLink.MATCH_CONTAINED_TEXT, "mainstream cig");
assertNotNull("Unable to find link to edit a Environmental Factor", theLink);
theCurrentPage = theLink.click();
assertCurrentPageContains("(if Enviromental Factor is not listed, then please");
theForm = theCurrentPage.getFormWithName("environmentalFactorForm");
theForm.setParameter("name", "mainstream cigarette smoke (MCS)");
theForm.setParameter("administrativeRoute", "intravenous");
theCurrentPage = theForm.submit();
assertCurrentPageContains("You have successfully edited an Environmental Factor.");
//Deleting
theLink = myWebConversation.getCurrentPage().getFirstMatchingLink(WebLink.MATCH_CONTAINED_TEXT, "mainstream cigarette");
assertNotNull("Unable to find link to delete a Environmental Factor", theLink);
theCurrentPage = theLink.click();
assertCurrentPageContains("(if Enviromental Factor is not listed, then please");
theForm = theCurrentPage.getFormWithName("environmentalFactorForm");
theForm.getSubmitButton( "submitAction", "Delete" ).click();
assertCurrentPageContains("You have successfully deleted an Environmental Factor.");
}
public void testAddGeneDelivery() throws Exception {
navigateToModelForEditing(myModelName);
//Adding
WebLink theLink = myWebConversation.getCurrentPage().getFirstMatchingLink(WebLink.MATCH_CONTAINED_TEXT,
"Enter Gene Delivery");
assertNotNull("Unable to find link to add a Gene Delivery", theLink);
WebResponse theCurrentPage = theLink.click();
assertCurrentPageContains("(if Viral Vector is not listed, then please");
WebForm theForm = theCurrentPage.getFormWithName("geneDeliveryForm");
theForm.setParameter("viralVector", "Adenovirus");
theForm.setParameter("geneInVirus", "123");
theCurrentPage = theForm.submit();
assertCurrentPageContains("You have successfully added a Gene Delivery to this model!");
//Editing
theLink = myWebConversation.getCurrentPage().getFirstMatchingLink(WebLink.MATCH_CONTAINED_TEXT, "123");
assertNotNull("Unable to find link to edit a Gene Delivery", theLink);
theCurrentPage = theLink.click();
assertCurrentPageContains("(if Viral Vector is not listed, then please");
theForm = theCurrentPage.getFormWithName("geneDeliveryForm");
theForm.setParameter("viralVector", "Adenovirus");
theForm.setParameter("geneInVirus", "456");
theCurrentPage = theForm.submit();
assertCurrentPageContains("You have successfully edited a Gene Delivery.");
//Deleting
theLink = myWebConversation.getCurrentPage().getFirstMatchingLink(WebLink.MATCH_CONTAINED_TEXT, "456");
assertNotNull("Unable to find link to delete a Gene Delivery", theLink);
theCurrentPage = theLink.click();
assertCurrentPageContains("(if Viral Vector is not listed, then please");
theForm = theCurrentPage.getFormWithName("geneDeliveryForm");
theForm.getSubmitButton( "submitAction", "Delete" ).click();
assertCurrentPageContains("You have successfully deleted a Gene Delivery.");
}
public void testAddGrowthFactor() throws Exception {
navigateToModelForEditing(myModelName);
//Adding
WebLink theLink = myWebConversation.getCurrentPage().getFirstMatchingLink(WebLink.MATCH_CONTAINED_TEXT, "Enter Growth Factor");
assertNotNull("Unable to find link to add a Growth Factor", theLink);
WebResponse theCurrentPage = theLink.click();
assertCurrentPageContains("(if Growth Factor is not listed, then please");
WebForm theForm = theCurrentPage.getFormWithName("growthFactorForm");
theForm.setParameter("name", "insulin-like growth factor 1 (IGF1) (IGF-1) (human recombinant)");
theCurrentPage = theForm.submit();
assertCurrentPageContains("You have successfully added a Growth Factor to this model!");
//Editing
theLink = myWebConversation.getCurrentPage().getFirstMatchingLink(WebLink.MATCH_CONTAINED_TEXT, "insulin-like gro");
assertNotNull("Unable to find link to edit a Growth Factor", theLink);
theCurrentPage = theLink.click();
assertCurrentPageContains("(if Growth Factor is not listed, then please");
theForm = theCurrentPage.getFormWithName("growthFactorForm");
theForm.setParameter("name", "insulin-like growth factor 1 (IGF1) (IGF-1) (human recombinant)");
theForm.setParameter("type", "Male Only");
theCurrentPage = theForm.submit();
assertCurrentPageContains("You have successfully edited a Growth Factor.");
//Deleting
theLink = myWebConversation.getCurrentPage().getFirstMatchingLink(WebLink.MATCH_CONTAINED_TEXT, "insulin-like gro");
assertNotNull("Unable to find link to delete a Growth Factor", theLink);
theCurrentPage = theLink.click();
assertCurrentPageContains("(if Growth Factor is not listed, then please");
theForm = theCurrentPage.getFormWithName("growthFactorForm");
theForm.getSubmitButton( "submitAction", "Delete" ).click();
assertCurrentPageContains("You have successfully deleted a Growth Factor.");
}
public void testAddHormone() throws Exception {
navigateToModelForEditing(myModelName);
//Adding
WebLink theLink = myWebConversation.getCurrentPage().getFirstMatchingLink(WebLink.MATCH_CONTAINED_TEXT, "Enter Hormone");
assertNotNull("Unable to find link to add a Hormone", theLink);
WebResponse theCurrentPage = theLink.click();
assertCurrentPageContains("(if Hormone is not listed, then please");
WebForm theForm = theCurrentPage.getFormWithName("hormoneForm");
theForm.setParameter("name", "estrone");
theCurrentPage = theForm.submit();
assertCurrentPageContains("You have successfully added a Hormone to this model!");
//Editing
theLink = myWebConversation.getCurrentPage().getFirstMatchingLink(WebLink.MATCH_CONTAINED_TEXT, "estrone");
assertNotNull("Unable to find link to edit a Hormone", theLink);
theCurrentPage = theLink.click();
assertCurrentPageContains("(if Hormone is not listed, then please");
theForm = theCurrentPage.getFormWithName("hormoneForm");
theForm.setParameter("name", "estrone");
theForm.setParameter("type", "Male Only");
theCurrentPage = theForm.submit();
assertCurrentPageContains("You have successfully edited a Hormone.");
//Deleting
theLink = myWebConversation.getCurrentPage().getFirstMatchingLink(WebLink.MATCH_CONTAINED_TEXT, "estrone");
assertNotNull("Unable to find link to delete a Hormone", theLink);
theCurrentPage = theLink.click();
assertCurrentPageContains("(if Hormone is not listed, then please");
theForm = theCurrentPage.getFormWithName("hormoneForm");
theForm.getSubmitButton( "submitAction", "Delete" ).click();
assertCurrentPageContains("You have successfully deleted a Hormone.");
}
public void testAddNutritionalFactor() throws Exception {
navigateToModelForEditing(myModelName);
//Adding
WebLink theLink = myWebConversation.getCurrentPage().getFirstMatchingLink(WebLink.MATCH_CONTAINED_TEXT, "Enter Nutritional Factor");
assertNotNull("Unable to find link to add a Nutritional Factor", theLink);
WebResponse theCurrentPage = theLink.click();
assertCurrentPageContains("(if Nutritional Factor is not listed, then please");
WebForm theForm = theCurrentPage.getFormWithName("nutritionalFactorForm");
theForm.setParameter("name", "black tea");
theCurrentPage = theForm.submit();
assertCurrentPageContains("You have successfully added a Nutritional Factor to this model!");
//Editing
theLink = myWebConversation.getCurrentPage().getFirstMatchingLink(WebLink.MATCH_CONTAINED_TEXT, "black tea");
assertNotNull("Unable to find link to edit a Nutritional Factor", theLink);
theCurrentPage = theLink.click();
assertCurrentPageContains("(if Nutritional Factor is not listed, then please");
theForm = theCurrentPage.getFormWithName("nutritionalFactorForm");
theForm.setParameter("name", "black tea");
theForm.setParameter("type", "Male Only");
theCurrentPage = theForm.submit();
assertCurrentPageContains("You have successfully edited a Nutritional Factor.");
//Deleting
theLink = myWebConversation.getCurrentPage().getFirstMatchingLink(WebLink.MATCH_CONTAINED_TEXT, "black tea");
assertNotNull("Unable to find link to delete a Nutritional Factor", theLink);
theCurrentPage = theLink.click();
assertCurrentPageContains("(if Nutritional Factor is not listed, then please");
theForm = theCurrentPage.getFormWithName("nutritionalFactorForm");
theForm.getSubmitButton( "submitAction", "Delete" ).click();
assertCurrentPageContains("You have successfully deleted a Nutritional Factor.");
}
public void testAddPlasmid() throws Exception {
navigateToModelForEditing(myModelName);
//Adding
WebLink theLink = myWebConversation.getCurrentPage().getFirstMatchingLink(WebLink.MATCH_CONTAINED_TEXT, "Enter Plasmid");
assertNotNull("Unable to find link to add a Plasmid", theLink);
WebResponse theCurrentPage = theLink.click();
assertCurrentPageContains("(if Plasmid is not listed, then please");
WebForm theForm = theCurrentPage.getFormWithName("plasmidForm");
theForm.setParameter("name", "control plasmid pPGK");
theCurrentPage = theForm.submit();
assertCurrentPageContains("You have successfully added a Plasmid to this model!");
//Editing
theLink = myWebConversation.getCurrentPage().getFirstMatchingLink(WebLink.MATCH_CONTAINED_TEXT, "estrone");
assertNotNull("Unable to find link to edit a Plasmid", theLink);
theCurrentPage = theLink.click();
assertCurrentPageContains("(if Plasmid is not listed, then please");
theForm = theCurrentPage.getFormWithName("plasmidForm");
theForm.setParameter("name", "control plasmid pPGK");
theForm.setParameter("type", "Male Only");
theCurrentPage = theForm.submit();
assertCurrentPageContains("You have successfully edited a Plasmid.");
//Deleting
theLink = myWebConversation.getCurrentPage().getFirstMatchingLink(WebLink.MATCH_CONTAINED_TEXT, "estrone");
assertNotNull("Unable to find link to delete a Plasmid", theLink);
theCurrentPage = theLink.click();
assertCurrentPageContains("(if Plasmid is not listed, then please");
theForm = theCurrentPage.getFormWithName("plasmidForm");
theForm.getSubmitButton( "submitAction", "Delete" ).click();
assertCurrentPageContains("You have successfully deleted a Plasmid.");
}
public void testAddRadiation() throws Exception {
navigateToModelForEditing(myModelName);
//Adding
WebLink theLink = myWebConversation.getCurrentPage().getFirstMatchingLink(WebLink.MATCH_CONTAINED_TEXT,
"Enter Radiation");
assertNotNull("Unable to find link to add a Radiation", theLink);
WebResponse theCurrentPage = theLink.click();
assertCurrentPageContains("(if Radiation is not listed, then please");
WebForm theForm = theCurrentPage.getFormWithName("radiationForm");
theForm.setParameter("name", "beta-radiation");
theCurrentPage = theForm.submit();
assertCurrentPageContains("You have successfully added a Radiation to this model!");
//Editing
theLink = myWebConversation.getCurrentPage().getFirstMatchingLink(WebLink.MATCH_CONTAINED_TEXT, "beta-rad");
assertNotNull("Unable to find link to edit a Radiation", theLink);
theCurrentPage = theLink.click();
assertCurrentPageContains("(if Radiation is not listed, then please");
theForm = theCurrentPage.getFormWithName("radiationForm");
theForm.setParameter("name", "beta-radiation");
theForm.setParameter("type", "Male Only");
theCurrentPage = theForm.submit();
assertCurrentPageContains("You have successfully edited a Radiation.");
//Deleting
theLink = myWebConversation.getCurrentPage().getFirstMatchingLink(WebLink.MATCH_CONTAINED_TEXT, "beta-radi");
assertNotNull("Unable to find link to delete a Radiation", theLink);
theCurrentPage = theLink.click();
assertCurrentPageContains("(if Radiation is not listed, then please");
theForm = theCurrentPage.getFormWithName("radiationForm");
theForm.getSubmitButton( "submitAction", "Delete" ).click();
assertCurrentPageContains("You have successfully deleted a Radiation.");
}
public void testAddSignalingMolecule() throws Exception {
navigateToModelForEditing(myModelName);
//Adding
WebLink theLink = myWebConversation.getCurrentPage().getFirstMatchingLink(WebLink.MATCH_CONTAINED_TEXT, "Enter Signaling Molecule");
assertNotNull("Unable to find link to add a Signaling Molecule", theLink);
WebResponse theCurrentPage = theLink.click();
assertCurrentPageContains("(if Signaling Molecule is not listed, then please");
WebForm theForm = theCurrentPage.getFormWithName("signalingMoleculeForm");
theForm.setParameter("name", "uroguanylin");
theCurrentPage = theForm.submit();
assertCurrentPageContains("You have successfully added a Signaling Molecule to this model!");
//Editing
theLink = myWebConversation.getCurrentPage().getFirstMatchingLink(WebLink.MATCH_CONTAINED_TEXT, "uroguanylin");
assertNotNull("Unable to find link to edit a Signaling Molecule", theLink);
theCurrentPage = theLink.click();
assertCurrentPageContains("(if Signaling Molecule is not listed, then please");
theForm = theCurrentPage.getFormWithName("signalingMoleculeForm");
theForm.setParameter("name", "uroguanylin");
theForm.setParameter("type", "Male Only");
theCurrentPage = theForm.submit();
assertCurrentPageContains("You have successfully edited a Signaling Molecule.");
//Deleting
theLink = myWebConversation.getCurrentPage().getFirstMatchingLink(WebLink.MATCH_CONTAINED_TEXT, "uroguanylin");
assertNotNull("Unable to find link to delete a Signaling Molecule", theLink);
theCurrentPage = theLink.click();
assertCurrentPageContains("(if Signaling Molecule is not listed, then please");
theForm = theCurrentPage.getFormWithName("signalingMoleculeForm");
theForm.getSubmitButton( "submitAction", "Delete" ).click();
assertCurrentPageContains("You have successfully deleted a Signaling Molecule.");
}
public void testAddSurgeryOther() throws Exception {
navigateToModelForEditing(myModelName);
//Adding
WebLink theLink = myWebConversation.getCurrentPage().getFirstMatchingLink(WebLink.MATCH_CONTAINED_TEXT,
"Enter Surgery/Other");
assertNotNull("Unable to find link to add a Surgery/Other", theLink);
WebResponse theCurrentPage = theLink.click();
assertCurrentPageContains("(if Surgery is not listed, then please");
WebForm theForm = theCurrentPage.getFormWithName("surgeryForm");
theForm.setParameter("name", "splenectomy");
theCurrentPage = theForm.submit();
assertCurrentPageContains("You have successfully added a Surgery / Other to this model!");
//Editing
theLink = myWebConversation.getCurrentPage().getFirstMatchingLink(WebLink.MATCH_CONTAINED_TEXT, "splenectomy");
assertNotNull("Unable to find link to edit a Surgery/Other", theLink);
theCurrentPage = theLink.click();
assertCurrentPageContains("(if Surgery is not listed, then please");
theForm = theCurrentPage.getFormWithName("surgeryForm");
theForm.setParameter("name", "splenectomy");
theForm.setParameter("type", "Male Only");
theCurrentPage = theForm.submit();
assertCurrentPageContains("You have successfully edited a Surgery / Other.");
//Deleting
theLink = myWebConversation.getCurrentPage().getFirstMatchingLink(WebLink.MATCH_CONTAINED_TEXT, "splenectomy");
assertNotNull("Unable to find link to delete a Surgery/Other", theLink);
theCurrentPage = theLink.click();
assertCurrentPageContains("(if Surgery is not listed, then please");
theForm = theCurrentPage.getFormWithName("surgeryForm");
theForm.getSubmitButton( "submitAction", "Delete" ).click();
assertCurrentPageContains("You have successfully deleted a Surgery / Other.");
}
public void testAddTransposon() throws Exception {
navigateToModelForEditing(myModelName);
//Adding
WebLink theLink = myWebConversation.getCurrentPage().getFirstMatchingLink(WebLink.MATCH_CONTAINED_TEXT, "Enter Transposon");
assertNotNull("Unable to find link to add a Transposon", theLink);
WebResponse theCurrentPage = theLink.click();
assertCurrentPageContains("(if Transposon is not listed, then please");
WebForm theForm = theCurrentPage.getFormWithName("hormoneForm");
theForm.setParameter("name", "firefly luciferase");
theCurrentPage = theForm.submit();
assertCurrentPageContains("You have successfully added a Transposon to this model!");
//Editing
theLink = myWebConversation.getCurrentPage().getFirstMatchingLink(WebLink.MATCH_CONTAINED_TEXT, "firefly luciferase");
assertNotNull("Unable to find link to edit a Transposon", theLink);
theCurrentPage = theLink.click();
assertCurrentPageContains("(if Transposon is not listed, then please");
theForm = theCurrentPage.getFormWithName("hormoneForm");
theForm.setParameter("name", "firefly luciferase");
theForm.setParameter("type", "Male Only");
theCurrentPage = theForm.submit();
assertCurrentPageContains("You have successfully edited a Transposon.");
//Deleting
theLink = myWebConversation.getCurrentPage().getFirstMatchingLink(WebLink.MATCH_CONTAINED_TEXT, "firefly luciferase");
assertNotNull("Unable to find link to delete a Transposon", theLink);
theCurrentPage = theLink.click();
assertCurrentPageContains("(if Transposon is not listed, then please");
theForm = theCurrentPage.getFormWithName("hormoneForm");
theForm.getSubmitButton( "submitAction", "Delete" ).click();
assertCurrentPageContains("You have successfully deleted a Transposon.");
}
public void testAddViralTreatment() throws Exception {
navigateToModelForEditing(myModelName);
//Adding
WebLink theLink = myWebConversation.getCurrentPage().getFirstMatchingLink(WebLink.MATCH_CONTAINED_TEXT,
"Enter Viral Treatment");
assertNotNull("Unable to find link to add a Viral Treatment", theLink);
WebResponse theCurrentPage = theLink.click();
assertCurrentPageContains("(if Virus is not listed, then please");
WebForm theForm = theCurrentPage.getFormWithName("viralTreatmentForm");
theForm.setParameter("name", "vaccinia virus");
theCurrentPage = theForm.submit();
assertCurrentPageContains("You have successfully added a Viral Treatment to this model!");
//Editing
theLink = myWebConversation.getCurrentPage().getFirstMatchingLink(WebLink.MATCH_CONTAINED_TEXT, "vaccinia virus");
assertNotNull("Unable to find link to edit a Viral Treatment", theLink);
theCurrentPage = theLink.click();
assertCurrentPageContains("(if Virus is not listed, then please");
theForm = theCurrentPage.getFormWithName("viralTreatmentForm");
theForm.setParameter("name", "vaccinia virus");
theForm.setParameter("type", "Male Only");
theCurrentPage = theForm.submit();
assertCurrentPageContains("You have successfully edited a Viral Treatment.");
//Deleting
theLink = myWebConversation.getCurrentPage().getFirstMatchingLink(WebLink.MATCH_CONTAINED_TEXT, "vaccinia virus");
assertNotNull("Unable to find link to delete a Viral Treatment", theLink);
theCurrentPage = theLink.click();
assertCurrentPageContains("(if Virus is not listed, then please");
theForm = theCurrentPage.getFormWithName("viralTreatmentForm");
theForm.getSubmitButton( "submitAction", "Delete" ).click();
assertCurrentPageContains("You have successfully deleted a Viral Treatment.");
}
}
|
package org.uddi.api_v3;
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.namespace.QName;
import javax.xml.transform.stream.StreamSource;
import static junit.framework.Assert.fail;
import static junit.framework.Assert.assertEquals;
import org.junit.Test;
import org.uddi.api_v3.AuthToken;
import org.uddi.api_v3.ObjectFactory;
public class AuthInfoTest {
private final static String EXPECTED_XML_FRAGMENT = "<fragment xmlns:ns3=\"urn:uddi-org:api_v3\" xmlns:ns2=\"http://www.w3.org/2000/09/xmldsig
+" <ns3:authInfo>AuthInfo String</ns3:authInfo>\n"
+"</fragment>";
/**
* Testing going from object to XML using JAXB using a XML Fragment.
*/
@Test
public void marshall()
{
try {
JAXBContext jaxbContext=JAXBContext.newInstance("org.uddi.api_v3");
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
marshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
ObjectFactory factory = new ObjectFactory();
AuthToken authToken = factory.createAuthToken();
authToken.setAuthInfo("AuthInfo String");
StringWriter writer = new StringWriter();
JAXBElement<AuthToken> element = new JAXBElement<AuthToken>(new QName("","fragment"),AuthToken.class,authToken);
marshaller.marshal(element,writer);
String actualXml=writer.toString();
assertEquals(EXPECTED_XML_FRAGMENT, actualXml);
} catch (JAXBException jaxbe) {
fail("No exception should be thrown");
}
}
/**
* Unmarshall an xml fragment.
*/
@Test public void unmarshall()
{
try {
JAXBContext jaxbContext=JAXBContext.newInstance("org.uddi.api_v3");
Unmarshaller unMarshaller = jaxbContext.createUnmarshaller();
StringReader reader = new StringReader(EXPECTED_XML_FRAGMENT);
JAXBElement<AuthToken> element = unMarshaller.unmarshal(new StreamSource(reader),AuthToken.class);
String infoString = element.getValue().getAuthInfo();
assertEquals("AuthInfo String", infoString);
} catch (JAXBException jaxbe) {
fail("No exception should be thrown");
}
}
}
|
package app.hongs.dh.search;
import app.hongs.Cnst;
import app.hongs.Core;
import app.hongs.CoreLogger;
import app.hongs.HongsException;
import app.hongs.dh.lucene.LuceneRecord;
import app.hongs.util.Synt;
import app.hongs.util.Tool;
import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.IndexableField;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TopDocs;
import org.apache.lucene.search.ScoreDoc;
/**
*
* @author Hongs
*/
public class SearchHelper {
private final LuceneRecord that;
public SearchHelper(LuceneRecord that) {
this.that = that;
}
public final LuceneRecord getRecord( ) {
return that;
}
/**
*
* @param rd
* @return
* @throws HongsException
*/
public Map counts(Map rd) throws HongsException {
IndexSearcher finder = that.getFinder();
IndexReader reader = that.getReader();
Map resp = new HashMap();
Map cnts = new HashMap();
resp.put( "info" , cnts );
int topz = Synt.declare(rd.get(Cnst.RN_KEY), 0);
Set<String> cntz = Synt.asTerms(rd.get(Cnst.RB_KEY) );
Map<String, Map<String, Integer>> counts = new HashMap( );
Map<String, Map<String, Integer>> countz = new HashMap( );
Map<String, Set<String >> countx = new HashMap();
/
if (cntz != null && !cntz.isEmpty()) {
Map<String, Map> fields = that.getFields();
for(String x : cntz) {
String[] a = x.split(":", 2);
if (a[0].startsWith ("-")) {
a[0] = a[0].substring(1);
if (!fields.containsKey(a[0])) {
throw new HongsException.Common("Field "+a[0]+" not exists");
}
if (a.length > 1) {
if (!countx.containsKey(a[0])) {
countx.put(a[0], new HashSet());
}
countx.get(a[0]).add(a[1]);
}
} else {
if (!fields.containsKey(a[0])) {
throw new HongsException.Common("Field "+a[0]+" not exists");
}
if (a.length > 1) {
if (!countz.containsKey(a[0])) {
countz.put(a[0], new HashMap());
}
countz.get(a[0]).put(a[1] , 0);
} else {
if (!counts.containsKey(a[0])) {
counts.put(a[0], new HashMap());
}
}
}
}
}
/
Map<String, Map<String, Integer>> counts2 = new HashMap();
Map<String, Map<String, Integer>> countz2 = new HashMap();
Map<String, Set<String>> countx2 = new HashMap();
Map<String, Map<String, Integer>> counts3 = new HashMap();
Map<String, Map<String, Integer>> countz3 = new HashMap();
Map<String, Set<String>> countx3 = new HashMap();
Set<String> cxts = new HashSet();
cxts.addAll(counts.keySet());
cxts.addAll(countz.keySet());
/**
* ,
* ,
* ,
* .
*
* ,
* .
*
* LinkedIn .
*/
for(String k : cxts) {
Set vs = null;
Object vo = rd.get(k);
if (vo instanceof Map) {
Map vm = (Map) vo ;
if (vm.containsKey(Cnst.EQ_REL)) {
vs = Synt.asSet(vm.get(Cnst.EQ_REL));
} else
if (vm.containsKey(Cnst.IN_REL)) {
vs = Synt.asSet(vm.get(Cnst.IN_REL));
}
} else {
if (vo!= null && !"".equals(vo)) {
vs = Synt.asSet(rd.get( k ));
}
}
if (vs == null) {
if (counts.containsKey(k)) {
counts2.put(k, counts.get(k));
}
if (countz.containsKey(k)) {
countz2.put(k, countz.get(k));
}
if (countx.containsKey(k)) {
countx2.put(k, countx.get(k));
}
} else {
Map<String, Integer> va = counts.get(k);
Map<String, Integer> vz = countz.get(k);
Set<String > vx = countx.get(k);
counts3.clear();
countz3.clear();
countx3.clear();
if (va != null) {
counts3.put(k, va);
}
if (vx != null) {
countx3.put(k, vx);
}
if (vz != null) {
countz3.put(k, vz);
} else {
vz = new HashMap();
countz3.put(k, vz);
countz .put(k, vz);
}
for(Object v : vs) {
String s = v.toString();
if (vx == null || ! vx.contains(s)) {
vz.put( s, 0 );
}
}
Map xd = new HashMap();
xd.putAll(rd);
xd.remove( k);
counts(xd, counts3, countz3, countx3, reader, finder);
}
}
int z = counts(rd, counts2, countz2, countx2, reader, finder);
cnts.put("__total__", z);
/
Map<String, List<Map.Entry<String, Integer>>> cntlst = new HashMap();
for (Map.Entry<String, Map<String, Integer>> et : counts.entrySet()) {
String k = et.getKey();
int t = topz;
if (t != 0) {
Map c = countz.get(k);
if (c != null) {
t = t - c.size( );
}
if (t <= 0 ) {
continue;
}
}
List<Map.Entry<String, Integer>> l = new ArrayList(et.getValue().entrySet());
Collections.sort( l, new Sorted());
if (t != 0 && t < l.size()) {
l = l.subList( 0, t );
}
cntlst.put(k, l);
}
for (Map.Entry<String, Map<String, Integer>> et : countz.entrySet()) {
String k = et.getKey();
List<Map.Entry<String, Integer>> l = new ArrayList(et.getValue().entrySet());
List<Map.Entry<String, Integer>> a = cntlst.get(k);
if ( null != a ) {
l.addAll(a );
}
Collections.sort( l, new Sorted());
cntlst.put(k, l);
}
for (Map.Entry<String, List<Map.Entry<String, Integer>>> et : cntlst.entrySet()) {
List<Object[]> a = new ArrayList();
for (Map.Entry<String, Integer> e : et.getValue()) {
a.add(new Object[] {
e.getKey(), null, e.getValue()
});
}
cnts.put(et.getKey(), a);
}
return resp;
}
private int counts(Map rd,
Map<String, Map<String, Integer>> counts,
Map<String, Map<String, Integer>> countz,
Map<String, Set<String >> countx,
IndexReader reader, IndexSearcher finder) throws HongsException {
int total = 0;
try {
Query q = that.getQuery(rd);
if (0 < Core.DEBUG && 8 != (8 & Core.DEBUG)) {
CoreLogger.debug("SearchRecord.counts: "+q.toString());
}
TopDocs docz = finder.search(q, 500);
while ( docz.totalHits > 0) {
ScoreDoc[] docs = docz.scoreDocs;
if (!countz.isEmpty() || !counts.isEmpty()) {
for(ScoreDoc dox : docs) {
Document doc = reader.document(dox.doc);
for (Map.Entry<String, Map<String, Integer>> et : countz.entrySet()) {
String k = et .getKey ( );
Map<String, Integer> cntc = et .getValue ( );
IndexableField[] vals = doc.getFields(k);
for(IndexableField vol : vals) {
String val = vol.stringValue();
if (cntc.containsKey(val)) {
cntc.put(val , cntc.get(val) + 1);
}
}
}
for (Map.Entry<String, Map<String, Integer>> et : counts.entrySet()) {
String k = et .getKey ( );
Map<String, Integer> cntc = et .getValue ( );
IndexableField[] vals = doc.getFields(k);
Map<String, Integer> cntu = countz.get (k);
Set<String> cntx = countx.get (k);
Set<String> cntv = cntu != null ? cntu.keySet() : null;
for(IndexableField vol : vals) {
String val = vol.stringValue();
if (cntc.containsKey(val)) {
cntc.put(val , cntc.get(val) + 1);
} else
if ((cntv == null || !cntv.contains(val) )
&& ( cntx == null || !cntx.contains(val))) {
cntc.put(val , 1);
}
}
}
}
}
if (docs.length > 0) {
docz = finder.searchAfter(docs[docs.length - 1], q, 500);
total += docs.length;
} else {
break;
}
}
} catch (IOException ex) {
throw new HongsException.Common(ex);
}
return total;
}
public Map statis(Map rd) throws HongsException {
IndexSearcher finder = that.getFinder();
IndexReader reader = that.getReader();
Map resp = new HashMap();
Map cnts = new HashMap();
resp.put( "info" , cnts );
Set<String> cntz = Synt.asTerms(rd.get(Cnst.RB_KEY));
Map<String, Map<Minmax, Cntsum>> counts = new HashMap();
Map<String, Set<Minmax >> countx = new HashMap();
/
if (cntz != null && !cntz.isEmpty()) {
Map<String, Map> fields = that.getFields();
for(String x : cntz) {
String[] a = x.split(":", 2);
if (a[0].startsWith ("-")) {
a[0] = a[0].substring(1);
if (!fields.containsKey(a[0])) {
throw new HongsException.Common("Field "+a[0]+" not exists");
}
if (a.length > 1) {
if (!countx.containsKey(a[0])) {
countx.put(a[0], new HashSet());
}
Minmax mm = new Minmax(a[1]);
countx.get( a[0] ).add( mm );
}
} else {
if (!fields.containsKey(a[0])) {
throw new HongsException.Common("Field "+a[0]+" not exists");
}
if (a.length > 1) {
if (!counts.containsKey(a[0])) {
counts.put(a[0], new HashMap());
}
Minmax mm = new Minmax(a[1]);
Cntsum cs = new Cntsum( );
counts.get(a[0]).put(mm, cs);
} else {
if (!counts.containsKey(a[0])) {
counts.put(a[0], new HashMap());
}
Minmax mm = new Minmax( "" );
Cntsum cs = new Cntsum( );
counts.get(a[0]).put(mm, cs);
}
}
}
}
/
Map<String, Map<Minmax , Cntsum>> counts2 = new HashMap();
Map<String, Set<Minmax >> countx2 = new HashMap();
Map<String, Map<Minmax , Cntsum>> counts3 = new HashMap();
Map<String, Set<Minmax >> countx3 = new HashMap();
Set<String> cxts = counts.keySet();
/**
* counts
*/
for(String k : cxts) {
Set vs = null;
Object vo = rd.get(k);
if (vo instanceof Map) {
Map vm = (Map) vo ;
if (vm.containsKey (Cnst.RG_REL)) {
vs = Synt.setOf(vm.get(Cnst.RG_REL));
} else
if (vm.containsKey (Cnst.IR_REL)) {
vs = Synt.asSet(vm.get(Cnst.IR_REL));
}
}
if (vs == null || vs.isEmpty()) {
if (counts .containsKey(k)) {
counts2.put(k, counts.get(k));
}
if (countx .containsKey(k)) {
countx2.put(k, countx.get(k));
}
} else {
Map<Minmax , Cntsum> vz = counts.get(k);
Set<Minmax > vx = countx.get(k);
counts3.clear();
countx3.clear();
if (vx != null) {
countx3.put(k, vx);
}
if (vz != null) {
counts3.put(k, vz);
} else {
vz = new HashMap();
counts3.put(k, vz);
}
for(Object v : vs) {
Minmax m = new Minmax(v.toString( ));
if (vx == null || ! vx.contains(m)) {
vz.put( m, new Cntsum() );
}
}
Map xd = new HashMap();
xd.putAll(rd);
xd.remove( k);
statis(xd, counts3, countx3, reader, finder);
}
}
int z = statis(rd, counts2, countx2, reader, finder);
cnts.put("__total__", z);
/
Map<String, List<Map.Entry<Minmax, Cntsum>>> cntlst = new HashMap();
for (Map.Entry<String, Map<Minmax, Cntsum>> et : counts.entrySet()) {
String k = et.getKey();
List<Map.Entry<Minmax, Cntsum>> l = new ArrayList(et.getValue().entrySet());
List<Map.Entry<Minmax, Cntsum>> a = cntlst.get(k);
if ( null != a ) {
l.addAll(a );
}
Collections.sort(l, new Sortes( ));
cntlst.put(k, l);
}
for (Map.Entry<String, List<Map.Entry<Minmax, Cntsum>>> et : cntlst.entrySet()) {
List<Object[]> a = new ArrayList();
for (Map.Entry<Minmax, Cntsum> e : et.getValue()) {
Cntsum c = e.getValue( );
Minmax m = e.getKey( );
String k = m != null ? m.toString() : null;
a.add(new Object[] {
k, null, c.cnt, c.sum ,
c.cnt != 0 ? c.min : 0,
c.cnt != 0 ? c.max : 0
});
}
cnts.put(et.getKey(), a );
}
return resp;
}
private int statis(Map rd,
Map<String, Map<Minmax , Cntsum>> counts,
Map<String, Set<Minmax >> countx,
IndexReader reader, IndexSearcher finder) throws HongsException {
int total = 0;
try {
Query q = that.getQuery(rd);
if (0 < Core.DEBUG && 8 != (8 & Core.DEBUG)) {
CoreLogger.debug("SearchRecord.counts: " +q.toString());
}
TopDocs docz = finder.search(q, 500);
while ( docz.totalHits > 0) {
ScoreDoc[] docs = docz.scoreDocs;
if (!counts.isEmpty()) {
for(ScoreDoc dox : docs) {
Document doc = reader.document(dox.doc);
for (Map.Entry<String, Map<Minmax, Cntsum>> et : counts.entrySet()) {
String k = et .getKey ( );
Map<Minmax, Cntsum> cntc = et .getValue ( );
Set<Minmax > cntx = countx.get (k);
IndexableField[ ] vals = doc.getFields(k);
F : for (IndexableField x: vals) {
double v = x.numericValue( )
. doubleValue( );
for (Map.Entry<Minmax, Cntsum> mc : cntc.entrySet()) {
Minmax m = mc.getKey ( );
/*
* :
* ,
* ;
* ,
* wrar.
*/
if (! m.covers( )) {
if (! m.covers(v)) {
continue;
}
if ( cntx != null)
for(Minmax w : cntx) {
if (w.covers(v)) {
continue F ;
}
}
}
mc.getValue().add(v);
}
}
}
}
}
if (docs.length > 0) {
docz = finder.searchAfter(docs[docs.length - 1], q, 500);
total += docs.length;
} else {
break;
}
}
} catch (IOException ex) {
throw new HongsException.Common(ex);
}
return total;
}
// jdk 1.7
static {
System.setProperty("java.util.Arrays.useLegacyMergeSort", "true");
}
private static class Sorted implements Comparator<Map.Entry<String, Integer>> {
@Override
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
int i1 = o1.getValue(), i2 = o2.getValue();
return i1 == i2 ? 0 : ( i2 > i1 ? 1 : -1 );
}
}
private static class Sortes implements Comparator<Map.Entry<Minmax, Cntsum >> {
@Override
public int compare(Map.Entry<Minmax, Cntsum > o1, Map.Entry<Minmax, Cntsum > o2) {
Minmax k1 = o1.getKey( ), k2 = o2.getKey( );
if ( k1.covers() ) return -1;
if ( k2.covers() ) return 1;
Cntsum x1 = o1.getValue(), x2 = o2.getValue();
return x1.cnt != x2.cnt ? (x2.cnt > x2.cnt ? 1 : -1)
: (x1.sum != x2.sum ? (x2.sum > x1.sum ? 1 : -1) : 0 );
}
}
private static class Cntsum {
public int cnt = 0;
public double sum = 0;
public double min = Double.MIN_VALUE;
public double max = Double.MAX_VALUE;
public void add(double v) {
cnt += 1;
sum += v;
if (min > v || min == Double.MIN_VALUE) {
min = v;
}
if (max < v || max == Double.MAX_VALUE) {
max = v;
}
}
}
private static class Minmax {
public double min = Double.MIN_VALUE;
public double max = Double.MAX_VALUE;
public boolean le = true;
public boolean ge = true;
public Minmax(double n) {
min = max = n;
}
public Minmax(String s) {
Object[] a = Synt.asRange(s);
if (a == null) {
return;
}
if (a[0] != null) {
min = Synt.declare(a[0], min);
}
if (a[1] != null) {
max = Synt.declare(a[1], max);
}
le = (boolean) a[2];
ge = (boolean) a[3];
}
@Override
public String toString() {
if (le && ge
&& min == Double.MIN_VALUE
&& max == Double.MAX_VALUE) {
return "";
}
StringBuilder sb = new StringBuilder();
sb.append(le ? "(" : "[");
sb.append(min != Double.MIN_VALUE ? Tool.toNumStr(min) : "");
sb.append(",");
sb.append(max != Double.MAX_VALUE ? Tool.toNumStr(max) : "");
sb.append(ge ? ")" : "]");
return sb.toString();
}
@Override
public int hashCode() {
return toString().hashCode();
}
@Override
public boolean equals(Object o) {
if (!(o instanceof Minmax)) {
return false;
}
Minmax m = (Minmax) o;
return m.le == le && m.ge == ge
&& m.min == min && m.max == max;
}
public boolean covers(double n) {
if (le) { if (n >= max) {
return false;
}} else { if (n > max) {
return false;
}}
if (ge) { if (n <= min) {
return false;
}} else { if (n < min) {
return false;
}}
return true;
}
public boolean covers() {
return le && ge
&& min == Double.MIN_VALUE
&& max == Double.MAX_VALUE;
}
}
}
|
package isse.mbr.integration;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import isse.mbr.parsing.MiniBrassCompiler;
import isse.mbr.parsing.MiniBrassParseException;
import isse.mbr.tools.BasicTestListener;
import isse.mbr.tools.MiniZincLauncher;
public class VotingCondorcetTest {
String minibrassModel = "test-models/voteCondorcet.mbr";
String minibrassModelNoWinner = "test-models/voteCondorcet_nowinner.mbr";
String minibrassModelTest = "test-models/voteCondorcet_test.mbr";
String minibrassCompiled = "test-models/voteCondorcet_o.mzn";
String minizincModel = "test-models/voteCondorcet.mzn";
String minizincModelTest = "test-models/voteCondorcet_test.mzn";
private MiniBrassCompiler compiler;
private MiniZincLauncher launcher;
@Before
public void setUp() throws Exception {
compiler = new MiniBrassCompiler(true);
launcher = new MiniZincLauncher();
launcher.setUseDefault(false);
launcher.setMinizincGlobals("jacop");
launcher.setFlatzincExecutable("fzn-jacop");
}
@Test
public void testPvsRelationCondercetTest() throws IOException, MiniBrassParseException {
// solution has draws in local results. result is good.
// 1. compile minibrass file
File output = new File(minibrassCompiled);
compiler.compile(new File(minibrassModelTest), output);
Assert.assertTrue(output.exists());
// 2. execute minisearch
BasicTestListener listener = new BasicTestListener();
launcher.addMiniZincResultListener(listener);
launcher.runMiniSearchModel(new File(minizincModelTest), null, 60);
// 3. check solution
Assert.assertTrue(listener.isSolved());
Assert.assertTrue(listener.isOptimal());
//Assert.assertEquals(2, listener.getSolutionCounter());
Assert.assertEquals("2", listener.getLastSolution().get("a"));
}
@Test
public void testPvsRelationCondercetNoWinner() throws IOException, MiniBrassParseException {
// 1. compile minibrass file
File output = new File(minibrassCompiled);
compiler.compile(new File(minibrassModelNoWinner), output);
Assert.assertTrue(output.exists());
// 2. execute minisearch
BasicTestListener listener = new BasicTestListener();
launcher.addMiniZincResultListener(listener);
launcher.runMiniSearchModel(new File(minizincModel), null, 60);
// 3. check solution
Assert.assertTrue(listener.isSolved());
Assert.assertTrue(listener.isOptimal());
//Assert.assertEquals(2, listener.getSolutionCounter());
Assert.assertEquals("2", listener.getLastSolution().get("a"));
}
@Test
public void testPvsRelation() throws IOException, MiniBrassParseException {
// 1. compile minibrass file
File output = new File(minibrassCompiled);
compiler.compile(new File(minibrassModel), output);
Assert.assertTrue(output.exists());
// 2. execute minisearch
BasicTestListener listener = new BasicTestListener();
launcher.addMiniZincResultListener(listener);
launcher.runMiniSearchModel(new File(minizincModel), null, 60);
// 3. check solution
Assert.assertTrue(listener.isSolved());
Assert.assertTrue(listener.isOptimal());
Assert.assertEquals(4, listener.getSolutionCounter());
Assert.assertEquals("3", listener.getLastSolution().get("a"));
}
}
|
package com.jbooktrader.platform.performance;
import com.jbooktrader.platform.chart.*;
import com.jbooktrader.platform.commission.*;
import com.jbooktrader.platform.indicator.*;
import com.jbooktrader.platform.model.*;
import com.jbooktrader.platform.strategy.*;
import java.util.*;
/**
* Performance manager evaluates trading strategy performance based on statistics
* which include various factors, such as net profit, maximum draw down, profit factor, etc.
*
* @author Eugene Kononov
*/
public class PerformanceManager {
private final int multiplier;
private final Commission commission;
private final Strategy strategy;
private PerformanceChartData performanceChartData;
private int trades, profitableTrades, previousPosition;
private double tradeCommission, totalCommission;
private double positionValue;
private double totalBought, totalSold;
private double tradeProfit, grossProfit, grossLoss, netProfit, netProfitAsOfPreviousTrade;
private double peakNetProfit, maxDrawdown;
private boolean isCompletedTrade;
private double sumTradeProfit, sumTradeProfitSquared;
private long timeInMarketStart, timeInMarket;
private long longTrades, shortTrades;
public PerformanceManager(Strategy strategy, int multiplier, Commission commission) {
this.strategy = strategy;
this.multiplier = multiplier;
this.commission = commission;
}
public void createPerformanceChartData(BarSize barSize, List<Indicator> indicators) {
performanceChartData = new PerformanceChartData(barSize, indicators);
}
public PerformanceChartData getPerformanceChartData() {
return performanceChartData;
}
public int getTrades() {
return trades;
}
public double getBias() {
if (trades == 0) {
return 0;
}
return 100 * (longTrades - shortTrades) / (double) trades;
}
public double getAveDuration() {
if (trades == 0) {
return 0;
}
// average number of minutes per trade
return (double) timeInMarket / (trades * 1000 * 60);
}
public boolean getIsCompletedTrade() {
return isCompletedTrade;
}
public double getPercentProfitableTrades() {
return (trades == 0) ? 0 : (100.0d * profitableTrades / trades);
}
public double getAverageProfitPerTrade() {
return (trades == 0) ? 0 : netProfit / trades;
}
public double getProfitFactor() {
double profitFactor = 0;
if (grossProfit > 0) {
profitFactor = (grossLoss == 0) ? Double.POSITIVE_INFINITY : grossProfit / grossLoss;
}
return profitFactor;
}
public double getMaxDrawdown() {
return maxDrawdown;
}
public double getTradeProfit() {
return tradeProfit;
}
public Commission getCommission() {
return commission;
}
public double getTradeCommission() {
return tradeCommission;
}
public double getNetProfit() {
return totalSold - totalBought + positionValue - totalCommission;
}
public double getKellyCriterion() {
int unprofitableTrades = trades - profitableTrades;
if (profitableTrades > 0) {
if (unprofitableTrades > 0) {
double aveProfit = grossProfit / profitableTrades;
double aveLoss = grossLoss / unprofitableTrades;
double winLossRatio = aveProfit / aveLoss;
double probabilityOfWin = profitableTrades / (double) trades;
double kellyCriterion = probabilityOfWin - (1 - probabilityOfWin) / winLossRatio;
kellyCriterion *= 100;
return kellyCriterion;
}
return 100;
}
return 0;
}
public double getCPI() {
double cpi = getPerformanceIndex() * getKellyCriterion() * getProfitFactor();
cpi *= (getNetProfit() / 10000.0);
if (getAveDuration() != 0) {
cpi /= Math.sqrt(getAveDuration());
} else {
cpi = 0;
}
return cpi;
}
public double getPerformanceIndex() {
double pi = 0;
if (trades > 0) {
double stDev = Math.sqrt(trades * sumTradeProfitSquared - sumTradeProfit * sumTradeProfit) / trades;
pi = (stDev == 0) ? Double.POSITIVE_INFINITY : Math.sqrt(trades) * getAverageProfitPerTrade() / stDev;
}
return pi;
}
public void updatePositionValue(double price, int position) {
positionValue = position * price * multiplier;
}
public void updateOnTrade(int quantity, double avgFillPrice, int position) {
long snapshotTime = strategy.getMarketBook().getSnapshot().getTime();
if (position != 0) {
if (timeInMarketStart == 0) {
timeInMarketStart = snapshotTime;
}
} else {
timeInMarket += (snapshotTime - timeInMarketStart);
timeInMarketStart = 0;
}
double tradeAmount = avgFillPrice * Math.abs(quantity) * multiplier;
if (quantity > 0) {
totalBought += tradeAmount;
} else {
totalSold += tradeAmount;
}
tradeCommission = commission.getCommission(Math.abs(quantity), avgFillPrice);
totalCommission += tradeCommission;
updatePositionValue(avgFillPrice, position);
isCompletedTrade = (previousPosition > 0 && position < previousPosition);
isCompletedTrade = isCompletedTrade || (previousPosition < 0 && position > previousPosition);
if (isCompletedTrade) {
trades++;
if (previousPosition > 0) {
longTrades++;
} else if (previousPosition < 0) {
shortTrades++;
}
netProfit = totalSold - totalBought + positionValue - totalCommission;
peakNetProfit = Math.max(netProfit, peakNetProfit);
maxDrawdown = Math.max(maxDrawdown, peakNetProfit - netProfit);
tradeProfit = netProfit - netProfitAsOfPreviousTrade;
netProfitAsOfPreviousTrade = netProfit;
sumTradeProfit += tradeProfit;
sumTradeProfitSquared += (tradeProfit * tradeProfit);
if (tradeProfit >= 0) {
profitableTrades++;
grossProfit += tradeProfit;
} else {
grossLoss += (-tradeProfit);
}
}
if (Dispatcher.getInstance().getMode() == Mode.BackTest) {
performanceChartData.update(new TimedValue(snapshotTime, netProfit));
}
previousPosition = position;
}
}
|
package com.nflabs.zeppelin.spark;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.apache.spark.SparkConf;
import org.apache.spark.SparkContext;
import org.apache.spark.SparkEnv;
import org.apache.spark.repl.SparkCommandLine;
import org.apache.spark.repl.SparkILoop;
import org.apache.spark.repl.SparkIMain;
import org.apache.spark.repl.SparkJLineCompletion;
import org.apache.spark.scheduler.ActiveJob;
import org.apache.spark.scheduler.DAGScheduler;
import org.apache.spark.scheduler.Stage;
import org.apache.spark.sql.SQLContext;
import org.apache.spark.ui.jobs.JobProgressListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.nflabs.zeppelin.interpreter.Interpreter;
import com.nflabs.zeppelin.interpreter.InterpreterResult;
import com.nflabs.zeppelin.interpreter.InterpreterResult.Code;
import com.nflabs.zeppelin.notebook.Paragraph;
import com.nflabs.zeppelin.notebook.form.Setting;
import com.nflabs.zeppelin.scheduler.Scheduler;
import com.nflabs.zeppelin.scheduler.SchedulerFactory;
import com.nflabs.zeppelin.spark.dep.DependencyResolver;
import scala.Console;
import scala.None;
import scala.Some;
import scala.Tuple2;
import scala.collection.Iterator;
import scala.collection.JavaConversions;
import scala.collection.JavaConverters;
import scala.collection.mutable.HashMap;
import scala.collection.mutable.HashSet;
import scala.tools.nsc.Settings;
import scala.tools.nsc.interpreter.Completion.Candidates;
import scala.tools.nsc.interpreter.Completion.ScalaCompleter;
import scala.tools.nsc.settings.MutableSettings.BooleanSetting;
import scala.tools.nsc.settings.MutableSettings.PathSetting;
public class SparkInterpreter extends Interpreter {
Logger logger = LoggerFactory.getLogger(SparkInterpreter.class);
static {
Interpreter.register("spark", SparkInterpreter.class.getName());
}
private ZeppelinContext z;
private SparkILoop interpreter;
private SparkIMain intp;
private SparkContext sc;
private ByteArrayOutputStream out;
private SQLContext sqlc;
private DependencyResolver dep;
private SparkJLineCompletion completor;
private JobProgressListener sparkListener;
private Map<String, Object> binder;
private SparkEnv env;
static SparkInterpreter _singleton;
public static SparkInterpreter singleton(Properties property){
if(_singleton==null) {
new SparkInterpreter(property);
}
return _singleton;
}
public SparkInterpreter(Properties property) {
super(property);
out = new ByteArrayOutputStream();
if(_singleton==null) {
_singleton = this;
}
}
public synchronized SparkContext getSparkContext(){
Map<String, Object> share = (Map<String, Object>)getProperty().get("share");
if(sc==null){
sc = (SparkContext) share.get("sc");
sparkListener = (JobProgressListener) share.get("sparkListener");
if(sc==null) {
sc = createSparkContext();
env = SparkEnv.get();
sparkListener = new JobProgressListener(sc.getConf());
sc.listenerBus().addListener(sparkListener);
/* Sharing a single spark context across scala repl is not possible at the moment.
* because of spark's limitation.
* 1) Each SparkImain (scala repl) creates classServer but worker (executor uses only the first one)
* 2) creating a SparkContext creates corresponding worker's Executor. which executes tasks and reuse classloader.
* the same Classloader can confuse classes from many different scala repl.
*
* The code below is commented out until this limitation removes
*/
//share.put("sc", sc);
//share.put("sparkEnv", env);
//share.put("sparkListener", sparkListener);
}
}
return sc;
}
public SQLContext getSQLContext(){
if(sqlc==null){
// save / load sc from common share
Map<String, Object> share = (Map<String, Object>)getProperty().get("share");
sqlc = (SQLContext) share.get("sqlc");
if(sqlc==null) {
sqlc = new SQLContext(getSparkContext());
// The same reason with SparkContext, it'll not be shared, so commenting out.
//share.put("sqlc", sqlc);
}
}
return sqlc;
}
public DependencyResolver getDependencyResolver(){
if(dep==null){
// save / load sc from common share
Map<String, Object> share = (Map<String, Object>)getProperty().get("share");
dep = (DependencyResolver) share.get("dep");
if(dep==null) {
dep = new DependencyResolver(intp, sc);
//share.put("dep", dep);
}
}
return dep;
}
public SparkContext createSparkContext(){
System.err.println("
String execUri = System.getenv("SPARK_EXECUTOR_URI");
String[] jars = SparkILoop.getAddedJars();
SparkConf conf = new SparkConf().setMaster(getMaster())
.setAppName("Zeppelin").setJars(jars)
.set("spark.repl.class.uri", interpreter.intp().classServer().uri());
if (execUri != null) {
conf.set("spark.executor.uri", execUri);
}
if (System.getenv("SPARK_HOME") != null) {
conf.setSparkHome(System.getenv("SPARK_HOME"));
}
conf.set("spark.scheduler.mode", "FAIR");
SparkContext sparkContext = new SparkContext(conf);
return sparkContext;
}
public String getMaster() {
String envMaster = System.getenv().get("MASTER");
if(envMaster!=null) return envMaster;
String propMaster = System.getProperty("spark.master");
if(propMaster!=null) return propMaster;
return "local[*]";
}
@Override
public void open(){
Map<String, Object> share = (Map<String, Object>)getProperty().get("share");
URL [] urls = (URL[]) getProperty().get("classloaderUrls");
// Very nice discussion about how scala compiler handle classpath
/*
* > val env = new nsc.Settings(errLogger)
> env.usejavacp.value = true
> val p = new Interpreter(env)
> p.setContextClassLoader
>
Alternatively you can set the class path throuh nsc.Settings.classpath.
>> val settings = new Settings()
>> settings.usejavacp.value = true
>> settings.classpath.value += File.pathSeparator +
>> System.getProperty("java.class.path")
>> val in = new Interpreter(settings) {
>> override protected def parentClassLoader = getClass.getClassLoader
>> }
>> in.setContextClassLoader()
*/
SparkCommandLine command = new SparkCommandLine(scala.collection.JavaConversions.asScalaBuffer((List<String>)getProperty().get("args")).toList());
Settings settings = command.settings();
//Settings settings = new Settings();
// set classpath for scala compiler
PathSetting pathSettings = settings.classpath();
String classpath = "";
List<File> paths = currentClassPath();
for(File f : paths) {
if(classpath.length()>0){
classpath+=File.pathSeparator;
}
classpath+=f.getAbsolutePath();
}
if (urls!=null) {
for(URL u : urls) {
if(classpath.length()>0){
classpath+=File.pathSeparator;
}
classpath+=u.getFile();
}
}
pathSettings.v_$eq(classpath);
settings.scala$tools$nsc$settings$ScalaSettings$_setter_$classpath_$eq(pathSettings);
// set classloader for scala compiler
settings.explicitParentLoader_$eq(new Some<ClassLoader>(Thread.currentThread().getContextClassLoader()));
BooleanSetting b = (BooleanSetting)settings.usejavacp();
b.v_$eq(true);
settings.scala$tools$nsc$settings$StandardScalaSettings$_setter_$usejavacp_$eq(b);
PrintStream printStream = new PrintStream(out);
/* spark interpreter */
this.interpreter = new SparkILoop(null, new PrintWriter(out));
interpreter.settings_$eq(settings);
interpreter.createInterpreter();
intp = interpreter.intp();
intp.setContextClassLoader();
intp.initializeSynchronous();
completor = new SparkJLineCompletion(intp);
sc = getSparkContext();
sqlc = getSQLContext();
dep = getDependencyResolver();
z = new ZeppelinContext(sc, sqlc, dep);
this.interpreter.loadFiles(settings);
intp.interpret("@transient var _binder = new java.util.HashMap[String, Object]()");
binder = (Map<String, Object>) getValue("_binder");
binder.put("sc", sc);
binder.put("sqlc", sqlc);
binder.put("z", z);
binder.put("out", printStream);
intp.interpret("@transient val z = _binder.get(\"z\").asInstanceOf[com.nflabs.zeppelin.spark.ZeppelinContext]");
intp.interpret("@transient val sc = _binder.get(\"sc\").asInstanceOf[org.apache.spark.SparkContext]");
intp.interpret("@transient val sqlc = _binder.get(\"sqlc\").asInstanceOf[org.apache.spark.sql.SQLContext]");
intp.interpret("import org.apache.spark.SparkContext._");
intp.interpret("import sqlc._");
}
private List<File> currentClassPath(){
List<File> paths = classPath(Thread.currentThread().getContextClassLoader());
String[] cps = System.getProperty("java.class.path").split(File.pathSeparator);
if(cps!=null) {
for(String cp : cps) {
paths.add(new File(cp));
}
}
return paths;
}
private List<File> classPath(ClassLoader cl){
List<File> paths = new LinkedList<File>();
if(cl==null)return paths;
if(cl instanceof URLClassLoader) {
URLClassLoader ucl = (URLClassLoader) cl;
URL [] urls = ucl.getURLs();
if(urls!=null) {
for(URL url : urls) {
paths.add(new File(url.getFile()));
}
}
}
return paths;
}
public List<String> completion(String buf, int cursor){
ScalaCompleter c = completor.completer();
Candidates ret = c.complete(buf, cursor);
return scala.collection.JavaConversions.asJavaList(ret.candidates());
}
public void bindValue(String name, Object o){
if ("form".equals(name) && o instanceof Setting) { // form controller injection from Paragraph.jobRun
z.setFormSetting((Setting)o);
}
getResultCode(intp.bindValue(name, o));
}
public Object getValue(String name){
Object ret = intp.valueOfTerm(name);
if (ret instanceof None) {
return null;
} else if (ret instanceof Some) {
return ((Some)ret).get();
} else {
return ret;
}
}
private final String jobGroup = "zeppelin-"+this.hashCode();
/**
* Interpret a single line
*/
public InterpreterResult interpret(String line){
if(line==null || line.trim().length()==0) {
return new InterpreterResult(Code.SUCCESS);
}
return interpret(line.split("\n"));
}
public InterpreterResult interpret(String [] lines){
synchronized(this){
sc.setJobGroup(jobGroup, "Zeppelin", false);
InterpreterResult r = _interpret(lines);
sc.clearJobGroup();
return r;
}
}
public InterpreterResult _interpret(String [] lines){
//Map<String, Object> share = (Map<String, Object>)getProperty().get("share");
//SparkEnv env = (SparkEnv) share.get("sparkEnv");
SparkEnv.set(env);
Console.setOut((java.io.PrintStream) binder.get("out"));
out.reset();
Code r = null;
String incomplete = "";
for(String s : lines) {
scala.tools.nsc.interpreter.Results.Result res = null;
try {
res = intp.interpret(incomplete+s);
} catch (Exception e) {
sc.clearJobGroup();
logger.info("Interpreter exception", e);
return new InterpreterResult(Code.ERROR, e.getMessage());
}
r = getResultCode(res);
if (r == Code.ERROR) {
sc.clearJobGroup();
return new InterpreterResult(r, out.toString());
} else if(r==Code.INCOMPLETE) {
incomplete += s +"\n";
} else {
incomplete = "";
}
}
if (r == Code.INCOMPLETE) {
return new InterpreterResult(r, "Incomplete expression");
} else {
return new InterpreterResult(r, out.toString());
}
}
public void cancel(){
sc.cancelJobGroup(jobGroup);
}
public int getProgress(){
int completedTasks = 0;
int totalTasks = 0;
DAGScheduler scheduler = sc.dagScheduler();
if(scheduler==null) return 0;
HashSet<ActiveJob> jobs = scheduler.activeJobs();
if(jobs==null || jobs.size()==0) return 0;
Iterator<ActiveJob> it = jobs.iterator();
while(it.hasNext()) {
ActiveJob job = it.next();
String g = (String) job.properties().get("spark.jobGroup.id");
if (jobGroup.equals(g)) {
int[] progressInfo = null;
if (sc.version().startsWith("1.0")) {
progressInfo = getProgressFromStage_1_0x(sparkListener, job.finalStage());
} else if (sc.version().startsWith("1.1")){
progressInfo = getProgressFromStage_1_1x(sparkListener, job.finalStage());
} else {
continue;
}
totalTasks+=progressInfo[0];
completedTasks+=progressInfo[1];
}
}
if(totalTasks==0) return 0;
return completedTasks*100/totalTasks;
}
private int [] getProgressFromStage_1_0x(JobProgressListener sparkListener, Stage stage){
int numTasks = stage.numTasks();
int completedTasks = 0;
Method method;
Object completedTaskInfo = null;
try {
method = sparkListener.getClass().getMethod("stageIdToTasksComplete");
completedTaskInfo = JavaConversions.asJavaMap((HashMap<Object, Object>)method.invoke(sparkListener)).get(stage.id());
} catch (NoSuchMethodException | SecurityException e) {
logger.error("Error while getting progress", e);
} catch (IllegalAccessException e) {
logger.error("Error while getting progress", e);
} catch (IllegalArgumentException e) {
logger.error("Error while getting progress", e);
} catch (InvocationTargetException e) {
logger.error("Error while getting progress", e);
}
if(completedTaskInfo!=null) {
completedTasks += (int) completedTaskInfo;
}
List<Stage> parents = JavaConversions.asJavaList(stage.parents());
if(parents!=null) {
for(Stage s : parents) {
int[] p = getProgressFromStage_1_0x(sparkListener, s);
numTasks+= p[0];
completedTasks+= p[1];
}
}
return new int[]{numTasks, completedTasks};
}
private int [] getProgressFromStage_1_1x(JobProgressListener sparkListener, Stage stage){
int numTasks = stage.numTasks();
int completedTasks = 0;
try {
Method stageIdToData = sparkListener.getClass().getMethod("stageIdToData");
HashMap<Tuple2<Object, Object>, Object> stageIdData = (HashMap<Tuple2<Object, Object>, Object>)stageIdToData.invoke(sparkListener);
Class<?> stageUIDataClass = this.getClass().forName("org.apache.spark.ui.jobs.UIData$StageUIData");
Method numCompletedTasks = stageUIDataClass.getMethod("numCompleteTasks");
Set<Tuple2<Object, Object>> keys = JavaConverters.asJavaSetConverter(stageIdData.keySet()).asJava();
for(Tuple2<Object, Object> k : keys) {
if(stage.id() == (int)k._1()) {
Object uiData = stageIdData.get(k).get();
completedTasks += (int)numCompletedTasks.invoke(uiData);
}
}
} catch(Exception e) {
logger.error("Error on getting progress information", e);
}
List<Stage> parents = JavaConversions.asJavaList(stage.parents());
if (parents!=null) {
for(Stage s : parents) {
int[] p = getProgressFromStage_1_1x(sparkListener, s);
numTasks+= p[0];
completedTasks+= p[1];
}
}
return new int[]{numTasks, completedTasks};
}
private Code getResultCode(scala.tools.nsc.interpreter.Results.Result r){
if (r instanceof scala.tools.nsc.interpreter.Results.Success$) {
return Code.SUCCESS;
} else if (r instanceof scala.tools.nsc.interpreter.Results.Incomplete$) {
return Code.INCOMPLETE;
} else {
return Code.ERROR;
}
}
@Override
public void close() {
sc.stop();
interpreter.closeInterpreter();
sc = null;
interpreter = null;
intp = null;
}
@Override
public FormType getFormType() {
return FormType.NATIVE;
}
public JobProgressListener getJobProgressListener(){
return sparkListener;
}
@Override
public Scheduler getScheduler() {
return SchedulerFactory.singleton().createOrGetFIFOScheduler(SparkInterpreter.class.getName()+this.hashCode());
}
}
|
package org.pentaho.di.ui.job.entries.abort;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.ShellAdapter;
import org.eclipse.swt.events.ShellEvent;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.pentaho.di.core.Const;
import org.pentaho.di.job.JobMeta;
import org.pentaho.di.ui.core.gui.WindowProperty;
import org.pentaho.di.ui.core.widget.TextVar;
import org.pentaho.di.ui.job.dialog.JobDialog;
import org.pentaho.di.ui.job.entry.JobEntryDialog;
import org.pentaho.di.job.entries.abort.JobEntryAbort;
import org.pentaho.di.job.entry.JobEntryDialogInterface;
import org.pentaho.di.job.entry.JobEntryInterface;
import org.pentaho.di.repository.Repository;
import org.pentaho.di.ui.trans.step.BaseStepDialog;
import org.pentaho.di.job.entries.abort.Messages;
/**
* This dialog allows you to edit a JobEntry Abort object.
*
* @author Samatar
* @since 10-03-2007
*/
public class JobEntryAbortDialog extends JobEntryDialog implements JobEntryDialogInterface
{
private Label wlName;
private Text wName;
private FormData fdlName, fdName;
private Button wOK, wCancel;
private Listener lsOK, lsCancel;
private JobEntryAbort jobEntry;
private Shell shell;
private SelectionAdapter lsDef;
private boolean changed;
private Label wlMessageAbort;
private TextVar wMessageAbort;
private FormData fdlMessageAbort, fdMessageAbort;
public JobEntryAbortDialog(Shell parent, JobEntryInterface jobEntryInt, Repository rep, JobMeta jobMeta)
{
super(parent, jobEntryInt, rep, jobMeta);
jobEntry = (JobEntryAbort) jobEntryInt;
if (this.jobEntry.getName() == null)
this.jobEntry.setName(Messages.getString("JobEntryAbortDialog.Jobname.Label"));
}
public JobEntryInterface open()
{
Shell parent = getParent();
Display display = parent.getDisplay();
shell = new Shell(parent, props.getJobsDialogStyle());
props.setLook(shell);
JobDialog.setShellImage(shell, jobEntry);
ModifyListener lsMod = new ModifyListener()
{
public void modifyText(ModifyEvent e)
{
jobEntry.setChanged();
}
};
changed = jobEntry.hasChanged();
FormLayout formLayout = new FormLayout();
formLayout.marginWidth = Const.FORM_MARGIN;
formLayout.marginHeight = Const.FORM_MARGIN;
shell.setLayout(formLayout);
shell.setText(Messages.getString("JobEntryAbortDialog.Title"));
int middle = props.getMiddlePct();
int margin = Const.MARGIN;
// Filename line
wlName = new Label(shell, SWT.RIGHT);
wlName.setText(Messages.getString("JobEntryAbortDialog.Label"));
props.setLook(wlName);
fdlName = new FormData();
fdlName.left = new FormAttachment(0, 0);
fdlName.right = new FormAttachment(middle, -margin);
fdlName.top = new FormAttachment(0, margin);
wlName.setLayoutData(fdlName);
wName = new Text(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wName);
wName.addModifyListener(lsMod);
fdName = new FormData();
fdName.left = new FormAttachment(middle, 0);
fdName.top = new FormAttachment(0, margin);
fdName.right = new FormAttachment(100, 0);
wName.setLayoutData(fdName);
// Message line
wlMessageAbort = new Label(shell, SWT.RIGHT);
wlMessageAbort.setText(Messages.getString("JobEntryAbortDialog.MessageAbort.Label"));
props.setLook(wlMessageAbort);
fdlMessageAbort = new FormData();
fdlMessageAbort.left = new FormAttachment(0, 0);
fdlMessageAbort.right = new FormAttachment(middle, 0);
fdlMessageAbort.top = new FormAttachment(wName, margin);
wlMessageAbort.setLayoutData(fdlMessageAbort);
wMessageAbort = new TextVar(jobMeta, shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER);
props.setLook(wMessageAbort);
wMessageAbort.setToolTipText(Messages.getString("JobEntryAbortDialog.MessageAbort.Tooltip"));
wMessageAbort.addModifyListener(lsMod);
fdMessageAbort = new FormData();
fdMessageAbort.left = new FormAttachment(middle, 0);
fdMessageAbort.top = new FormAttachment(wName, margin);
fdMessageAbort.right = new FormAttachment(100, 0);
wMessageAbort.setLayoutData(fdMessageAbort);
wOK = new Button(shell, SWT.PUSH);
wOK.setText(Messages.getString("System.Button.OK"));
wCancel = new Button(shell, SWT.PUSH);
wCancel.setText(Messages.getString("System.Button.Cancel"));
// at the bottom
BaseStepDialog.positionBottomButtons(shell, new Button[] { wOK, wCancel }, margin, wMessageAbort);
// Add listeners
lsCancel = new Listener()
{
public void handleEvent(Event e)
{
cancel();
}
};
lsOK = new Listener()
{
public void handleEvent(Event e)
{
ok();
}
};
wCancel.addListener(SWT.Selection, lsCancel);
wOK.addListener(SWT.Selection, lsOK);
lsDef = new SelectionAdapter()
{
public void widgetDefaultSelected(SelectionEvent e)
{
ok();
}
};
wName.addSelectionListener(lsDef);
// Detect X or ALT-F4 or something that kills this window...
shell.addShellListener(new ShellAdapter()
{
public void shellClosed(ShellEvent e)
{
cancel();
}
});
getData();
BaseStepDialog.setSize(shell);
shell.open();
props.setDialogSize(shell, "JobAbortDialogSize");
while (!shell.isDisposed())
{
if (!display.readAndDispatch())
display.sleep();
}
return jobEntry;
}
public void dispose()
{
WindowProperty winprop = new WindowProperty(shell);
props.setScreen(winprop);
shell.dispose();
}
/**
* Copy information from the meta-data input to the dialog fields.
*/
public void getData()
{
if (jobEntry.getName() != null)
wName.setText(jobEntry.getName());
wName.selectAll();
if (jobEntry.getMessageabort() != null)
wMessageAbort.setText(jobEntry.getMessageabort());
}
private void cancel()
{
jobEntry.setChanged(changed);
jobEntry = null;
dispose();
}
private void ok()
{
jobEntry.setName(wName.getText());
jobEntry.setMessageabort(wMessageAbort.getText());
dispose();
}
public String toString()
{
return this.getClass().getName();
}
}
|
package org.javarosa.form.api;
import org.javarosa.core.model.GroupDef;
import org.javarosa.core.model.IFormElement;
import org.javarosa.core.model.actions.Action;
import org.javarosa.core.model.FormIndex;
import org.javarosa.core.model.QuestionDef;
import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.model.instance.InvalidReferenceException;
import org.javarosa.core.model.instance.TreeElement;
import org.javarosa.core.model.instance.TreeReference;
import java.util.ArrayList;
import java.util.ArrayList;
/**
* This class is used to navigate through an xform and appropriately manipulate
* the FormEntryModel's state.
*/
public class FormEntryController {
public static final int ANSWER_OK = 0;
public static final int ANSWER_REQUIRED_BUT_EMPTY = 1;
public static final int ANSWER_CONSTRAINT_VIOLATED = 2;
public static final int EVENT_BEGINNING_OF_FORM = 0;
public static final int EVENT_END_OF_FORM = 1;
public static final int EVENT_PROMPT_NEW_REPEAT = 2;
public static final int EVENT_QUESTION = 4;
public static final int EVENT_GROUP = 8;
public static final int EVENT_REPEAT = 16;
public static final int EVENT_REPEAT_JUNCTURE = 32;
public final static String FIELD_LIST = "field-list";
private final FormEntryModel model;
private final FormEntrySessionRecorder formEntrySession;
public static final boolean STEP_OVER_GROUP = true;
public static final boolean STEP_INTO_GROUP = false;
/**
* Creates a new form entry controller for the model provided
*/
public FormEntryController(FormEntryModel model) {
this(model, new DummyFormEntrySession());
}
private FormEntryController(FormEntryModel model, FormEntrySessionRecorder formEntrySession) {
this.model = model;
this.formEntrySession = formEntrySession;
}
/**
* Builds controller that records form entry actions to human readable
* format that allows for replaying
*/
public static FormEntryController buildRecordingController(FormEntryModel model) {
return new FormEntryController(model, new FormEntrySession());
}
public FormEntryModel getModel() {
return model;
}
/**
* Attempts to save answer at the current FormIndex into the datamodel.
*/
public int answerQuestion(IAnswerData data) {
return answerQuestion(model.getFormIndex(), data);
}
/**
* Attempts to save the answer at the specified FormIndex into the
* datamodel.
*
* @return OK if save was successful, error if a constraint was violated.
*/
public int answerQuestion(FormIndex index, IAnswerData data) {
QuestionDef q = model.getQuestionPrompt(index).getQuestion();
if (model.getEvent(index) != FormEntryController.EVENT_QUESTION) {
throw new RuntimeException("Non-Question object at the form index.");
}
TreeElement element = model.getTreeElement(index);
// A question is complex when it has a copy tag that needs to be
// evaluated by copying in the correct xml subtree. XXX: The code to
// answer complex questions is incomplete, but luckily this feature is
// rarely used.
boolean complexQuestion = q.isComplex();
boolean hasConstraints = false;
if (element.isRequired() && data == null) {
return ANSWER_REQUIRED_BUT_EMPTY;
}
if (complexQuestion) {
if (hasConstraints) {
//TODO: itemsets: don't currently evaluate constraints for
//itemset/copy -- haven't figured out how handle it yet
throw new RuntimeException("Itemsets do not currently evaluate constraints. Your constraint will not work, please remove it before proceeding.");
} else {
try {
model.getForm().copyItemsetAnswer(q, element, data);
} catch (InvalidReferenceException ire) {
ire.printStackTrace();
throw new RuntimeException("Invalid reference while copying itemset answer: " + ire.getMessage());
}
q.getActionController().triggerActionsFromEvent(Action.EVENT_QUESTION_VALUE_CHANGED, model.getForm());
return ANSWER_OK;
}
} else {
if (!model.getForm().evaluateConstraint(index.getReference(), data)) {
// constraint checking failed
return ANSWER_CONSTRAINT_VIOLATED;
}
commitAnswer(element, index, data);
q.getActionController().triggerActionsFromEvent(Action.EVENT_QUESTION_VALUE_CHANGED, model.getForm());
return ANSWER_OK;
}
}
public int checkQuestionConstraint(IAnswerData data) {
FormIndex index = model.getFormIndex();
QuestionDef q = model.getQuestionPrompt(index).getQuestion();
if (model.getEvent(index) != FormEntryController.EVENT_QUESTION) {
throw new RuntimeException("Non-Question object at the form index.");
}
TreeElement element = model.getTreeElement(index);
if (element.isRequired() && data == null) {
return ANSWER_REQUIRED_BUT_EMPTY;
}
// A question is complex when it has a copy tag that needs to be
// evaluated by copying in the correct xml subtree. XXX: The code to
// answer complex questions is incomplete, but luckily this feature is
// rarely used.
boolean complexQuestion = q.isComplex();
if (complexQuestion) {
// TODO PLM: unsure how to check constraints of 'complex' questions
return ANSWER_OK;
} else {
if (!model.getForm().evaluateConstraint(index.getReference(), data)) {
// constraint checking failed
return ANSWER_CONSTRAINT_VIOLATED;
}
return ANSWER_OK;
}
}
/**
* saveAnswer attempts to save the current answer into the data model
* without doing any constraint checking. Only use this if you know what
* you're doing. For normal form filling you should always use
* answerQuestion or answerCurrentQuestion.
*
* @return true if saved successfully, false otherwise.
*/
public boolean saveAnswer(FormIndex index, IAnswerData data) {
if (model.getEvent(index) != FormEntryController.EVENT_QUESTION) {
throw new RuntimeException("Non-Question object at the form index.");
}
TreeElement element = model.getTreeElement(index);
return commitAnswer(element, index, data);
}
/**
* commitAnswer actually saves the data into the datamodel.
*
* @return true if saved successfully, false otherwise
*/
private boolean commitAnswer(TreeElement element, FormIndex index, IAnswerData data) {
if (data != null) {
formEntrySession.addValueSet(index, data.uncast().getString());
} else {
formEntrySession.addQuestionSkip(index);
}
if (data != null || element.getValue() != null) {
// we should check if the data to be saved is already the same as
// the data in the model, but we can't (no IAnswerData.equals())
model.getForm().setValue(data, index.getReference(), element);
return true;
} else {
return false;
}
}
/**
* Expand any unexpanded repeats at the given FormIndex.
*/
public void expandRepeats(FormIndex index) {
model.createModelIfNecessary(index);
}
/**
* Navigates forward in the form.
*
* @return the next event that should be handled by a view.
*/
public int stepToNextEvent(boolean expandRepeats) {
return stepEvent(true, expandRepeats);
}
public int stepToNextEvent() {
return stepToNextEvent(true);
}
/**
* Find the FormIndex that comes after the given one.
*/
public FormIndex getNextIndex(FormIndex index, boolean expandRepeats) {
return getAdjacentIndex(index, true, expandRepeats);
}
/**
* Find the FormIndex that comes after the given one, expanding any repeats encountered.
*/
public FormIndex getNextIndex(FormIndex index) {
return getAdjacentIndex(index, true, true);
}
/**
* Navigates backward in the form.
*
* @return the next event that should be handled by a view.
*/
public int stepToPreviousEvent() {
// second parameter doesn't matter because stepping backwards never involves descending into repeats
return stepEvent(false, false);
}
/**
* Moves the current FormIndex to the next/previous relevant position.
*
* @param expandRepeats Expand any unexpanded repeat groups
* @return event associated with the new position
*/
private int stepEvent(boolean forward, boolean expandRepeats) {
FormIndex index = model.getFormIndex();
index = getAdjacentIndex(index, forward, expandRepeats);
return jumpToIndex(index, expandRepeats);
}
/**
* Find a FormIndex next to the given one.
*
* NOTE: Leave public for Touchforms
*
* @param forward If true, get the next FormIndex, else get the previous one.
*/
public FormIndex getAdjacentIndex(FormIndex index, boolean forward, boolean expandRepeats) {
boolean descend = true;
boolean relevant;
boolean inForm;
do {
if (forward) {
index = model.incrementIndex(index, descend);
} else {
index = model.decrementIndex(index);
}
//reset all step rules
descend = true;
relevant = true;
inForm = index.isInForm();
if (inForm) {
relevant = model.isIndexRelevant(index);
//If this the current index is a group and it is not relevant
//do _not_ dig into it.
if (!relevant && model.getEvent(index) == FormEntryController.EVENT_GROUP) {
descend = false;
}
}
} while (inForm && !relevant);
if (expandRepeats) {
expandRepeats(index);
}
return index;
}
/**
* Jumps to a given FormIndex. Expands any repeat groups.
*
* @return EVENT for the specified Index.
*/
public int jumpToIndex(FormIndex index) {
return jumpToIndex(index, true);
}
/**
* Jumps to a given FormIndex.
*
* @param expandRepeats Expand any unexpanded repeat groups
* @return EVENT for the specified Index.
*/
public int jumpToIndex(FormIndex index, boolean expandRepeats) {
model.setQuestionIndex(index, expandRepeats);
return model.getEvent(index);
}
/**
* Used by touchforms
*/
@SuppressWarnings("unused")
public FormIndex descendIntoNewRepeat() {
jumpToIndex(model.getForm().descendIntoRepeat(model.getFormIndex(), -1));
newRepeat(model.getFormIndex());
return model.getFormIndex();
}
/**
* Used by touchforms
*/
@SuppressWarnings("unused")
public FormIndex descendIntoRepeat(int n) {
jumpToIndex(model.getForm().descendIntoRepeat(model.getFormIndex(), n));
return model.getFormIndex();
}
/**
* Creates a new repeated instance of the group referenced by the specified
* FormIndex.
*/
public void newRepeat(FormIndex questionIndex) {
try {
model.getForm().createNewRepeat(questionIndex);
formEntrySession.addNewRepeat(questionIndex);
} catch (InvalidReferenceException ire) {
throw new RuntimeException("Invalid reference while copying itemset answer: " + ire.getMessage());
}
}
/**
* Creates a new repeated instance of the group referenced by the current
* FormIndex.
*/
public void newRepeat() {
newRepeat(model.getFormIndex());
}
/**
* Deletes a repeated instance of a group referenced by the specified
* FormIndex.
*/
public FormIndex deleteRepeat(FormIndex questionIndex) {
return model.getForm().deleteRepeat(questionIndex);
}
/**
* Used by touchforms
*/
@SuppressWarnings("unused")
public void deleteRepeat(int n) {
deleteRepeat(model.getForm().descendIntoRepeat(model.getFormIndex(), n));
}
/**
* Sets the current language.
*/
public void setLanguage(String language) {
model.setLanguage(language);
}
public String getFormEntrySessionString() {
return formEntrySession.toString();
}
/**
* getQuestionPrompts for the current index
*/
public FormEntryPrompt[] getQuestionPrompts() throws RuntimeException {
return getQuestionPrompts(getModel().getFormIndex());
}
/**
* Returns an array of relevant question prompts that should be displayed as a single screen.
* If the given form index is a question, it is returned. Otherwise if the
* given index is a field list (and _only_ when it is a field list)
*/
public FormEntryPrompt[] getQuestionPrompts(FormIndex currentIndex) throws RuntimeException {
IFormElement element = this.getModel().getForm().getChild(currentIndex);
//If we're in a group, we will collect of the questions in this group
if (element instanceof GroupDef) {
//Assert that this is a valid condition (only field lists return prompts)
if (!this.isFieldListHost(currentIndex)) {
throw new RuntimeException("Cannot get question prompts from a non-field-list group");
}
// Questions to collect
ArrayList<FormEntryPrompt> questionList = new ArrayList<>();
//Step over all events in this field list and collect them
FormIndex walker = currentIndex;
int event = this.getModel().getEvent(currentIndex);
while (FormIndex.isSubElement(currentIndex, walker)) {
if (event == FormEntryController.EVENT_QUESTION) {
questionList.add(this.getModel().getQuestionPrompt(walker));
}
if (event == FormEntryController.EVENT_PROMPT_NEW_REPEAT) {
//TODO: What if there is a non-deterministic repeat up in the field list?
}
//this handles relevance for us
walker = this.getNextIndex(walker);
event = this.getModel().getEvent(walker);
}
FormEntryPrompt[] questions = new FormEntryPrompt[questionList.size()];
//Populate the array with the collected questions
questionList.toArray(questions);
return questions;
} else {
// We have a question, so just get the one prompt
return new FormEntryPrompt[]{this.getModel().getQuestionPrompt(currentIndex)};
}
}
/**
* A convenience method for determining if the current FormIndex is a group that is/should be
* displayed as a multi-question view of all of its descendants. This is useful for returning
* from the formhierarchy view to a selected index.
*/
public boolean isFieldListHost(FormIndex index) {
// if this isn't a group, return right away
if (!(this.getModel().getForm().getChild(index) instanceof GroupDef)) {
return false;
}
//TODO: Is it possible we need to make sure this group isn't inside of another group which
//is itself a field list? That would make the top group the field list host, not the
//descendant group
GroupDef gd = (GroupDef)this.getModel().getForm().getChild(index); // exceptions?
return (FIELD_LIST.equalsIgnoreCase(gd.getAppearanceAttr()));
}
}
|
package org.qfox.jestful.commons;
import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import org.qfox.jestful.commons.collection.CaseInsensitiveMap;
import org.qfox.jestful.commons.io.IOUtils;
/**
* <p>
* Description:
* </p>
*
* <p>
* Company:
* </p>
*
* @author Payne 646742615@qq.com
*
* @date 201649 7:02:24
*
* @since 1.0.0
*/
public class Multihead implements Cloneable {
private final Disposition disposition;
private final MediaType type;
private final Map<String, String> header;
public Multihead(Map<String, String> header) {
super();
this.header = new CaseInsensitiveMap<String, String>(header);
this.disposition = this.header.containsKey("Content-Disposition") ? Disposition.valueOf(this.header.get("Content-Disposition")) : null;
this.type = this.header.containsKey("Content-Type") ? MediaType.valueOf(this.header.get("Content-Type")) : null;
}
public Multihead(InputStream inputStream) throws IOException {
this.header = new CaseInsensitiveMap<String, String>();
String line = null;
while ((line = IOUtils.readln(inputStream)) != null && line.isEmpty() == false) {
int index = line.indexOf(':');
if (index < 0) {
throw new IllegalArgumentException(line);
}
String key = line.substring(0, index);
String value = line.substring(index + 1);
this.header.put(key.trim(), value.trim());
}
this.disposition = this.header.containsKey("Content-Disposition") ? Disposition.valueOf(this.header.get("Content-Disposition")) : null;
this.type = this.header.containsKey("Content-Type") ? MediaType.valueOf(this.header.get("Content-Type")) : null;
}
public void writeTo(Writer writer) throws IOException {
writer.write(toString());
writer.write(new char[] { '\r', '\n' });
}
public Disposition getDisposition() {
return disposition;
}
public MediaType getType() {
return type;
}
public Map<String, String> getHeader() {
return header;
}
@Override
public Multihead clone() {
return new Multihead(header);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((header == null) ? 0 : header.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Multihead other = (Multihead) obj;
if (header == null) {
if (other.header != null)
return false;
} else if (!header.equals(other.header))
return false;
return true;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
Iterator<Entry<String, String>> iterator = header.entrySet().iterator();
while (iterator.hasNext()) {
Entry<String, String> entry = iterator.next();
builder.append(entry.getKey()).append(": ").append(entry.getValue()).append(iterator.hasNext() ? "\r\n" : "");
}
return builder.toString();
}
}
|
package jreframeworker.core.bytecode.operations;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;
import jreframeworker.core.bytecode.identifiers.BaseMethodsIdentifier;
import jreframeworker.core.bytecode.identifiers.JREFAnnotationIdentifier;
import jreframeworker.core.bytecode.identifiers.MergeMethodsIdentifier;
import jreframeworker.core.bytecode.utils.AnnotationUtils;
import jreframeworker.core.bytecode.utils.BytecodeUtils;
import jreframeworker.ui.PreferencesPage;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassVisitor;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.commons.RemappingMethodAdapter;
import org.objectweb.asm.commons.SimpleRemapper;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.AnnotationNode;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.FieldNode;
import org.objectweb.asm.tree.FrameNode;
import org.objectweb.asm.tree.IincInsnNode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.InsnNode;
import org.objectweb.asm.tree.IntInsnNode;
import org.objectweb.asm.tree.InvokeDynamicInsnNode;
import org.objectweb.asm.tree.JumpInsnNode;
import org.objectweb.asm.tree.LabelNode;
import org.objectweb.asm.tree.LdcInsnNode;
import org.objectweb.asm.tree.LineNumberNode;
import org.objectweb.asm.tree.LookupSwitchInsnNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.objectweb.asm.tree.MethodNode;
import org.objectweb.asm.tree.MultiANewArrayInsnNode;
import org.objectweb.asm.tree.TableSwitchInsnNode;
import org.objectweb.asm.tree.TypeInsnNode;
import org.objectweb.asm.tree.VarInsnNode;
public class Merge {
public static void mergeClasses(File baseClass, File classToMerge, File outputClass) throws IOException {
final String MERGE_RENAME_PREFIX = PreferencesPage.getMergeRenamingPrefix();
// read the classes into ClassNode objects
ClassNode baseClassNode = BytecodeUtils.getClassNode(baseClass);
ClassNode classToMergeClassNode = BytecodeUtils.getClassNode(classToMerge);
// identify methods to merge
MergeMethodsIdentifier mergeMethodsIdentifier = new MergeMethodsIdentifier(classToMergeClassNode);
LinkedList<MethodNode> methodsToMerge = mergeMethodsIdentifier.getMergeMethods();
// get a list of base methods conflicting with methods to merge
BaseMethodsIdentifier baseMethodsIdentifier = new BaseMethodsIdentifier(baseClassNode);
LinkedList<MethodNode> baseMethods = baseMethodsIdentifier.getBaseMethods();
// create a list of methods to rename
LinkedList<MethodNode> methodsToRename = new LinkedList<MethodNode>();
for(MethodNode methodToMerge : methodsToMerge){
for(MethodNode baseMethod : baseMethods){
if(methodToMerge.name.equals(baseMethod.name)){
methodsToRename.add(baseMethod);
continue;
}
}
}
// rename conflicting base methods
LinkedList<String> renamedMethods = new LinkedList<String>();
for(MethodNode methodToRename : methodsToRename){
// first remove any annotations from renamed base methods
// TODO: consider adding base method annotations to the method to merge (ex: @Deprecated??)
// to maintain the cover of the original method annotations
AnnotationUtils.clearMethodAnnotations(methodToRename);
// rename the method
renamedMethods.add(methodToRename.name); // save the original name
String renamedMethodName = MERGE_RENAME_PREFIX + methodToRename.name;
methodToRename.name = renamedMethodName;
// make the method private to hide it from the end user
methodToRename.access = Opcodes.ACC_PRIVATE;
}
// write out the modified base class to a temporary class file
String baseClassName = baseClassNode.name.replace('/', '.');
File modifiedBaseClassFile = File.createTempFile(baseClassName, ".class");
BytecodeUtils.writeClass(baseClassNode, modifiedBaseClassFile);
// adapt a ClassWriter with the MergeAdapter
ClassWriter classWriter = new ClassWriter(ClassWriter.COMPUTE_MAXS | ClassWriter.COMPUTE_FRAMES);
MergeAdapter mergeAdapter = new MergeAdapter(classWriter, classToMergeClassNode, MERGE_RENAME_PREFIX, renamedMethods);
// merge the classes
// modifiedBaseClass, classToMerge -> MergeAdapter -> ClassWriter
FileInputStream modifiedBaseClassFileInputStream = new FileInputStream(modifiedBaseClassFile);
ClassReader modifiedBaseClassReader = new ClassReader(modifiedBaseClassFileInputStream);
modifiedBaseClassReader.accept(mergeAdapter, ClassReader.EXPAND_FRAMES);
modifiedBaseClassFileInputStream.close();
// write the output file
FileOutputStream fos = new FileOutputStream(outputClass);
fos.write(classWriter.toByteArray());
fos.close();
modifiedBaseClassFile.delete();
}
private static class MergeAdapter extends ClassVisitor {
private ClassNode classToMerge;
private String baseClassName;
private String mergeRenamePrefix;
private LinkedList<String> renamedMethods;
public MergeAdapter(ClassVisitor baseClassVisitor, ClassNode classToMerge, String mergeReamePrefix, LinkedList<String> renamedMethods) {
super(Opcodes.ASM5, baseClassVisitor);
this.classToMerge = classToMerge;
this.mergeRenamePrefix = mergeReamePrefix;
this.renamedMethods = renamedMethods;
}
@Override
public void visit(int version, int access, String name, String signature, String superName, String[] interfaces) {
super.visit(version, access, name, signature, superName, interfaces);
baseClassName = name;
}
public void visitEnd() {
// copy each field of the class to merge in to the original class
for (Object o : classToMerge.fields) {
FieldNode fieldNode = (FieldNode) o;
// only insert the field if it is annotated
if(fieldNode.invisibleAnnotations != null){
for(Object o2 : fieldNode.invisibleAnnotations){
AnnotationNode annotationNode = (AnnotationNode) o2;
JREFAnnotationIdentifier checker = new JREFAnnotationIdentifier();
checker.visitAnnotation(annotationNode.desc, false);
if(checker.isDefineFieldAnnotation()){
// insert the field
fieldNode.accept(this);
}
}
}
}
// copy each method of the class to merge that is annotated
// with a jref annotation to the original class
for (Object o : classToMerge.methods) {
MethodNode methodNode = (MethodNode) o;
boolean define = false;
boolean merge = false;
// check if method is annotated with a jref annotation
LinkedList<AnnotationNode> jrefAnnotations = new LinkedList<AnnotationNode>();
if (methodNode.invisibleAnnotations != null) {
for (Object annotationObject : methodNode.invisibleAnnotations) {
AnnotationNode annotation = (AnnotationNode) annotationObject;
// check if the annotation is a jref annotation
JREFAnnotationIdentifier jrefChecker = new JREFAnnotationIdentifier();
jrefChecker.visitAnnotation(annotation.desc, false);
if(jrefChecker.isJREFAnnotation()){
jrefAnnotations.add(annotation);
if(jrefChecker.isDefineMethodAnnotation()){
define = true;
}
if(jrefChecker.isMergeMethodAnnotation()){
merge = true;
}
}
}
}
// if the method is annotated with @DefineMethod or @MergeMethod, add the method
if(define || merge){
// in any case, strip the jref annotations from the method
methodNode.invisibleAnnotations.removeAll(jrefAnnotations);
if(merge){
mergeMethod(methodNode, renamedMethods);
} else {
addMethod(methodNode);
}
}
}
super.visitEnd();
}
/**
* Adds the method to the base class
* @param methodNode
*/
private void addMethod(MethodNode methodNode){
String[] exceptions = new String[methodNode.exceptions.size()];
methodNode.exceptions.toArray(exceptions);
MethodVisitor mv = cv.visitMethod(methodNode.access, methodNode.name, methodNode.desc, methodNode.signature, exceptions);
methodNode.instructions.resetLabels();
// SimpleRemapper -> maps old name to new name
// updates owners and descriptions appropriately
methodNode.accept(new RemappingMethodAdapter(methodNode.access, methodNode.desc, mv, new SimpleRemapper(classToMerge.name, baseClassName)));
}
/**
* Performs some merge changes to the method instructions then adds the method
* @param methodNode
* @param renamedMethods
*/
@SuppressWarnings("unused")
private void mergeMethod(MethodNode methodNode, LinkedList<String> renamedMethods) {
// clean up method instructions
InsnList instructions = methodNode.instructions;
Iterator<AbstractInsnNode> instructionIterator = instructions.iterator();
while (instructionIterator.hasNext()) {
AbstractInsnNode abstractInstruction = instructionIterator.next();
if (abstractInstruction instanceof FieldInsnNode) {
FieldInsnNode instruction = (FieldInsnNode) abstractInstruction;
} else if (abstractInstruction instanceof FrameNode) {
FrameNode instruction = (FrameNode) abstractInstruction;
} else if (abstractInstruction instanceof IincInsnNode) {
IincInsnNode instruction = (IincInsnNode) abstractInstruction;
} else if (abstractInstruction instanceof InsnNode) {
InsnNode instruction = (InsnNode) abstractInstruction;
} else if (abstractInstruction instanceof IntInsnNode) {
IntInsnNode instruction = (IntInsnNode) abstractInstruction;
} else if (abstractInstruction instanceof InvokeDynamicInsnNode) {
InvokeDynamicInsnNode instruction = (InvokeDynamicInsnNode) abstractInstruction;
} else if (abstractInstruction instanceof JumpInsnNode) {
JumpInsnNode instruction = (JumpInsnNode) abstractInstruction;
} else if (abstractInstruction instanceof LabelNode) {
LabelNode instruction = (LabelNode) abstractInstruction;
} else if (abstractInstruction instanceof LdcInsnNode) {
LdcInsnNode instruction = (LdcInsnNode) abstractInstruction;
} else if (abstractInstruction instanceof LineNumberNode) {
LineNumberNode instruction = (LineNumberNode) abstractInstruction;
} else if (abstractInstruction instanceof LookupSwitchInsnNode) {
LookupSwitchInsnNode instruction = (LookupSwitchInsnNode) abstractInstruction;
} else if (abstractInstruction instanceof MethodInsnNode) {
MethodInsnNode instruction = (MethodInsnNode) abstractInstruction;
// check if the method call needs to be changed to a renamed method name
// replace calls to super.x methods with prefix+x calls in the class to merge
// TODO: should check more than just the name, need to check whole method signature
for (String renamedMethod : renamedMethods) {
if (instruction.name.equals(renamedMethod)) {
// this method has been renamed, we need to rename the call as well
instruction.name = mergeRenamePrefix + instruction.name;
// if we renamed it, this call used super.x, so make
// it a virtual invocation instead of special invocation
if (instruction.getOpcode() == Opcodes.INVOKESPECIAL) {
instruction.setOpcode(Opcodes.INVOKEVIRTUAL);
}
}
}
} else if (abstractInstruction instanceof MultiANewArrayInsnNode) {
MultiANewArrayInsnNode instruction = (MultiANewArrayInsnNode) abstractInstruction;
} else if (abstractInstruction instanceof TableSwitchInsnNode) {
TableSwitchInsnNode instruction = (TableSwitchInsnNode) abstractInstruction;
} else if (abstractInstruction instanceof TypeInsnNode) {
TypeInsnNode instruction = (TypeInsnNode) abstractInstruction;
} else if (abstractInstruction instanceof VarInsnNode) {
VarInsnNode instruction = (VarInsnNode) abstractInstruction;
}
}
// finally insert the method
addMethod(methodNode);
}
}
}
|
package kikaha.core.modules.smart;
import io.undertow.Undertow;
import io.undertow.UndertowOptions;
import io.undertow.protocols.ssl.UndertowXnioSsl;
import io.undertow.server.HttpHandler;
import io.undertow.server.handlers.proxy.ProxyClient;
import io.undertow.server.handlers.proxy.ProxyHandler;
import kikaha.config.Config;
import kikaha.core.DeploymentContext;
import kikaha.core.modules.Module;
import kikaha.core.url.URLMatcher;
import lombok.Getter;
import lombok.experimental.var;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.xnio.OptionMap;
import org.xnio.Xnio;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.inject.Singleton;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
@Slf4j
@Getter
@Singleton
public class RewriteRoutesModule implements Module {
@Inject Config config;
List<SmartRouteRule> rewriteRoutes;
List<SmartRouteRule> reverseRoutes;
boolean isHttp2EnabledForProxy;
@PostConstruct
public void loadConfig(){
List<Config> configs = config.getConfigList("server.smart-routes.rewrite");
rewriteRoutes = configs.stream().map( c-> SmartRouteRule.from(c) ).collect(Collectors.toList());
configs = config.getConfigList("server.smart-routes.reverse");
reverseRoutes = configs.stream().map( c-> SmartRouteRule.from(c) ).collect(Collectors.toList());
isHttp2EnabledForProxy = config.getBoolean( "server.smart-routes.reverse-with-http2", true );
}
public void load(final Undertow.Builder server, final DeploymentContext context )
{
try {
deployRewriteRoutes(context);
deployReverseProxyRoutes(context);
} catch ( Throwable cause ) {
throw new RuntimeException( "Failed to load 'Smart Routes' module", cause );
}
}
private void deployRewriteRoutes( final DeploymentContext context )
{
if ( !rewriteRoutes.isEmpty() )
log.info( "Rewrite rules:" );
for ( SmartRouteRule route : rewriteRoutes ) {
log.info( " > " + route );
final HttpHandler rewriteHandler = RewriteRequestHttpHandler.from( route, context.rootHandler() );
context.rootHandler( rewriteHandler );
}
}
private void deployReverseProxyRoutes(final DeploymentContext context) throws URISyntaxException, NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException {
var lastHandler = context.rootHandler();
val ssl = new UndertowXnioSsl( Xnio.getInstance(), OptionMap.EMPTY );
val options = isHttp2EnabledForProxy
? OptionMap.create(UndertowOptions.ENABLE_HTTP2, true)
: OptionMap.EMPTY ;
if ( !reverseRoutes.isEmpty() )
log.info( "Reverse Proxy rules:" );
for ( val rule : reverseRoutes ) {
log.info( " > " + rule );
val target = URLMatcher.compile( rule.target() );
val proxyClient = createClientFor( rule, target, ssl, options );
lastHandler = new ProxyHandler( proxyClient, lastHandler );
}
context.rootHandler( lastHandler );
}
private ProxyClient createClientFor(SmartRouteRule rule, URLMatcher target, UndertowXnioSsl ssl, OptionMap options) throws URISyntaxException {
val proxyClient = new ReverseProxyClient( DefaultMatcher.from( rule ), target );
val uri = asHost(target);
if ( "https".equals( uri.getScheme() ) ) {
proxyClient.addHost(uri, null, ssl, options );
} else
proxyClient.addHost(uri);
return proxyClient.setProblemServerRetry( 60 );
}
private URI asHost(URLMatcher target ) throws URISyntaxException {
val uri = new URI( target.replace( Collections.emptyMap() ) );
return new URI( uri.getScheme() + "://" + uri.getAuthority() + "/" );
}
}
|
package com.orctom.laputa.utils;
import com.orctom.laputa.exception.IllegalArgException;
import com.orctom.laputa.model.Metric;
import com.orctom.laputa.model.MetricCallback;
import org.slf4j.Logger;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class SimpleMetrics {
private final Logger logger;
private final long period;
private final TimeUnit unit;
private Map<String, MutableInt> meters;
private Map<String, Callable<String>> gauges = new LinkedHashMap<>();
private MetricCallback callback;
private ScheduledExecutorService es = Executors.newSingleThreadScheduledExecutor(r -> {
Thread t = Executors.defaultThreadFactory().newThread(r);
t.setName("simple-metrics");
t.setDaemon(true);
return t;
});
private SimpleMetrics(Logger logger, long period, TimeUnit unit) {
if (null == logger) {
throw new IllegalArgException("org.slf4j.Logger is required.");
}
this.logger = logger;
this.period = period;
this.unit = unit;
resetMeters();
startReporter();
}
public static SimpleMetrics create(Logger logger) {
return new SimpleMetrics(logger, 30, TimeUnit.SECONDS);
}
public static SimpleMetrics create(Logger logger, long period, TimeUnit unit) {
return new SimpleMetrics(logger, period, unit);
}
public void resetMeters() {
meters = new LinkedHashMap<>();
}
private void startReporter() {
es.scheduleAtFixedRate(this::report, period, period, unit);
}
public void shutdown() {
try {
unit.sleep(period);
} catch (InterruptedException ignored) {
}
es.shutdown();
meters = null;
gauges = null;
}
public void mark(String key) {
MutableInt meter = meter(key);
meter.increase();
}
public MutableInt meter(String key) {
MutableInt meter = meters.get(key);
if (null != meter) {
return meter;
}
meter = new MutableInt(0);
synchronized (this) {
MutableInt old = meters.put(key, meter);
if (null != old) {
meter.increaseBy(old.getValue());
}
}
return meter;
}
public void gauge(String key, Callable<String> callable) {
gauges.put(key, callable);
}
public void setGaugeIfNotExist(String key, Callable<String> callable) {
gauges.putIfAbsent(key, callable);
}
public void setCallback(MetricCallback callback) {
this.callback = callback;
}
private void report() {
reportGauges();
reportMeters();
}
private void reportGauges() {
for (Map.Entry<String, Callable<String>> entry : gauges.entrySet()) {
try {
String key = entry.getKey();
String value = entry.getValue().call();
logger.info("gauge: {}, {}", key, value);
sendToCallback(key, value);
} catch (Exception e) {
logger.error("failed to collect gauge: {}, due to {}", entry.getKey(), e.getMessage());
logger.error(e.getMessage(), e);
}
}
}
private void reportMeters() {
float duration = unit.toSeconds(period);
for (Map.Entry<String, MutableInt> entry : meters.entrySet()) {
String key = entry.getKey();
MutableInt value = entry.getValue();
int count = value.getAndSet(0);
float rate = count / duration;
logger.info("meter: {}, count: {}, mean: {}/s", entry.getKey(), count, rate);
sendToCallback(key, count, rate);
}
}
private void sendToCallback(String key, String value) {
if (null != callback) {
callback.onMetric(new Metric(key, value));
}
}
private void sendToCallback(String key, int value, float rate) {
if (null != callback) {
callback.onMetric(new Metric(key, value, rate));
}
}
}
|
package org.haxe.lime;
import android.app.Activity;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.content.res.Configuration;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Rect;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Vibrator;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.inputmethod.InputMethodManager;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Window;
import android.view.WindowManager;
import dalvik.system.DexClassLoader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Constructor;
import java.lang.Math;
import java.lang.Runnable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Locale;
import java.util.List;
import org.haxe.extension.Extension;
import org.haxe.HXCPP;
public class GameActivity extends Activity implements SensorEventListener {
private static final int DEVICE_ORIENTATION_UNKNOWN = 0;
private static final int DEVICE_ORIENTATION_PORTRAIT = 1;
private static final int DEVICE_ORIENTATION_PORTRAIT_UPSIDE_DOWN = 2;
private static final int DEVICE_ORIENTATION_LANDSCAPE_RIGHT = 3;
private static final int DEVICE_ORIENTATION_LANDSCAPE_LEFT = 4;
private static final int DEVICE_ORIENTATION_FACE_UP = 5;
private static final int DEVICE_ORIENTATION_FACE_DOWN = 6;
private static final int DEVICE_ROTATION_0 = 0;
private static final int DEVICE_ROTATION_90 = 1;
private static final int DEVICE_ROTATION_180 = 2;
private static final int DEVICE_ROTATION_270 = 3;
private static final String GLOBAL_PREF_FILE = "nmeAppPrefs";
private static float[] accelData = new float[3];
private static GameActivity activity;
private static AssetManager mAssets;
private static int bufferedDisplayOrientation = -1;
private static int bufferedNormalOrientation = -1;
private static Context mContext;
private static List<Extension> extensions;
private static float[] inclinationMatrix = new float[16];
private static HashMap<String, Class> mLoadedClasses = new HashMap<String, Class>();
private static float[] magnetData = new float[3];
private static DisplayMetrics metrics;
private static float[] orientData = new float[3];
private static float[] rotationMatrix = new float[16];
private static SensorManager sensorManager;
private static Rect mVisibleRect = new Rect ();
public Handler mHandler;
private static MainView mMainView;
private MainView mView;
//private Sound _sound;
protected void onCreate (Bundle state) {
super.onCreate (state);
activity = this;
mContext = this;
mHandler = new Handler ();
mAssets = getAssets ();
Extension.assetManager = mAssets;
Extension.callbackHandler = mHandler;
Extension.mainActivity = this;
Extension.mainContext = this;
//_sound = new Sound (getApplication ());
requestWindowFeature (Window.FEATURE_NO_TITLE);
::if WIN_FULLSCREEN::
::if (ANDROID_TARGET_SDK_VERSION < 19)::
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN
| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
::end::
::end::
metrics = new DisplayMetrics ();
getWindowManager ().getDefaultDisplay ().getMetrics (metrics);
::foreach ndlls::
System.loadLibrary ("::name::");
::end::
HXCPP.run ("ApplicationMain");
mView = new MainView (getApplication (), this);
setContentView (mView);
Extension.mainView = mView;
sensorManager = (SensorManager)activity.getSystemService (Context.SENSOR_SERVICE);
if (sensorManager != null) {
sensorManager.registerListener (this, sensorManager.getDefaultSensor (Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_GAME);
sensorManager.registerListener (this, sensorManager.getDefaultSensor (Sensor.TYPE_MAGNETIC_FIELD), SensorManager.SENSOR_DELAY_GAME);
}
mView.getViewTreeObserver ().addOnGlobalLayoutListener (new ViewTreeObserver.OnGlobalLayoutListener () {
@Override public void onGlobalLayout () {
activity.getWindow().getDecorView().getWindowVisibleDisplayFrame (mVisibleRect);
}
});
Extension.packageName = getApplicationContext ().getPackageName ();
if (extensions == null) {
extensions = new ArrayList<Extension> ();
::if (ANDROID_EXTENSIONS != null)::::foreach ANDROID_EXTENSIONS::
extensions.add (new ::__current__:: ());::end::::end::
}
for (Extension extension : extensions) {
extension.onCreate (state);
}
}
// IMMERSIVE MODE SUPPORT
::if (WIN_FULLSCREEN)::::if (ANDROID_TARGET_SDK_VERSION >= 19)::
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if(hasFocus) {
hideSystemUi();
}
}
private void hideSystemUi() {
if (Build.VERSION.SDK_INT >= 19) {
View decorView = this.getWindow().getDecorView();
decorView.setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
}
::end::::end::
public static double CapabilitiesGetPixelAspectRatio () {
return metrics.xdpi / metrics.ydpi;
}
public static double CapabilitiesGetScreenDPI () {
return metrics.xdpi;
}
public static double CapabilitiesGetScreenResolutionX () {
return metrics.widthPixels;
}
public static double CapabilitiesGetScreenResolutionY () {
return metrics.heightPixels;
}
public static String CapabilitiesGetLanguage () {
return Locale.getDefault ().getLanguage ();
}
public static void clearUserPreference (String inId) {
SharedPreferences prefs = activity.getSharedPreferences (GLOBAL_PREF_FILE, MODE_PRIVATE);
SharedPreferences.Editor prefEditor = prefs.edit ();
prefEditor.putString (inId, "");
prefEditor.commit ();
}
public void doPause () {
//_sound.doPause ();
mView.sendActivity (Lime.DEACTIVATE);
mView.onPause ();
if (sensorManager != null) {
sensorManager.unregisterListener (this);
}
}
public void doResume () {
mView.onResume ();
//_sound.doResume ();
mView.sendActivity (Lime.ACTIVATE);
if (sensorManager != null) {
sensorManager.registerListener (this, sensorManager.getDefaultSensor (Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_GAME);
sensorManager.registerListener (this, sensorManager.getDefaultSensor (Sensor.TYPE_MAGNETIC_FIELD), SensorManager.SENSOR_DELAY_GAME);
}
mView.requestFocus ();
}
public static AssetManager getAssetManager () {
return mAssets;
}
public static Context getContext () {
return mContext;
}
public static GameActivity getInstance () {
return activity;
}
public static MainView getMainView () {
return activity.mView;
}
public static byte[] getResource (String inResource) {
try {
InputStream inputStream = mAssets.open (inResource, AssetManager.ACCESS_BUFFER);
long length = inputStream.available ();
byte[] result = new byte[(int)length];
inputStream.read (result);
inputStream.close ();
return result;
} catch (IOException e) {
Log.e ("GameActivity", "getResource" + ":" + e.toString ());
}
return null;
}
public static int getResourceID (String inFilename) {
//::foreach assets::::if (type == "music")::if (inFilename.equals("::id::")) return ::APP_PACKAGE::.R.raw.::flatName::;
//::end::::end::
//::foreach assets::::if (type == "sound")::if (inFilename.equals("::id::")) return ::APP_PACKAGE::.R.raw.::flatName::;
//::end::::end::
return -1;
}
public static float getSoftKeyboardHeight () {
float height = Extension.mainView.getHeight () - mVisibleRect.height ();
if (height < 0) {
return 0;
} else {
return height;
}
}
static public String getSpecialDir (int inWhich) {
//Log.v ("GameActivity", "Get special Dir " + inWhich);
File path = null;
switch (inWhich) {
case 0: // App
return mContext.getPackageCodePath ();
case 1: // Storage
path = mContext.getFilesDir ();
break;
case 2: // Desktop
path = Environment.getDataDirectory ();
break;
case 3: // Docs
path = Environment.getExternalStorageDirectory ();
break;
case 4: // User
path = mContext.getExternalFilesDir (Environment.DIRECTORY_DOWNLOADS);
break;
}
return path == null ? "" : path.getAbsolutePath ();
}
public static String getUserPreference (String inId) {
SharedPreferences prefs = activity.getSharedPreferences (GLOBAL_PREF_FILE, MODE_PRIVATE);
return prefs.getString (inId, "");
}
public static void launchBrowser (String inURL) {
Intent browserIntent = new Intent (Intent.ACTION_VIEW).setData (Uri.parse (inURL));
try {
activity.startActivity (browserIntent);
} catch (Exception e) {
Log.e ("GameActivity", e.toString ());
return;
}
}
private void loadNewSensorData (SensorEvent event) {
final int type = event.sensor.getType ();
if (type == Sensor.TYPE_ACCELEROMETER) {
accelData = event.values.clone ();
Lime.onAccelerate (-accelData[0], -accelData[1], accelData[2]);
}
if (type == Sensor.TYPE_MAGNETIC_FIELD) {
magnetData = event.values.clone ();
//Log.d("GameActivity","new mag: " + magnetData[0] + ", " + magnetData[1] + ", " + magnetData[2]);
}
}
@Override public void onAccuracyChanged (Sensor sensor, int accuracy) {
}
@Override protected void onActivityResult (int requestCode, int resultCode, Intent data) {
for (Extension extension : extensions) {
if (!extension.onActivityResult (requestCode, resultCode, data)) {
return;
}
}
super.onActivityResult (requestCode, resultCode, data);
}
@Override protected void onDestroy () {
for (Extension extension : extensions) {
extension.onDestroy ();
}
// TODO: Wait for result?
mView.sendActivity (Lime.DESTROY);
activity = null;
super.onDestroy ();
}
@Override public void onLowMemory () {
super.onLowMemory ();
for (Extension extension : extensions) {
extension.onLowMemory ();
}
}
@Override protected void onNewIntent (final Intent intent) {
for (Extension extension : extensions) {
extension.onNewIntent (intent);
}
super.onNewIntent (intent);
}
@Override protected void onPause () {
doPause ();
super.onPause ();
for (Extension extension : extensions) {
extension.onPause ();
}
}
@Override protected void onRestart () {
super.onRestart ();
for (Extension extension : extensions) {
extension.onRestart ();
}
}
@Override protected void onResume () {
super.onResume();
doResume();
for (Extension extension : extensions) {
extension.onResume ();
}
}
@Override public void onSensorChanged (SensorEvent event) {
loadNewSensorData (event);
if (accelData != null && magnetData != null) {
boolean foundRotationMatrix = SensorManager.getRotationMatrix (rotationMatrix, inclinationMatrix, accelData, magnetData);
if (foundRotationMatrix) {
SensorManager.getOrientation (rotationMatrix, orientData);
Lime.onOrientationUpdate (orientData[0], orientData[1], orientData[2]);
}
}
Lime.onDeviceOrientationUpdate (prepareDeviceOrientation ());
Lime.onNormalOrientationFound (bufferedNormalOrientation);
}
@Override protected void onStart () {
super.onStart();
::if WIN_FULLSCREEN::::if (ANDROID_TARGET_SDK_VERSION >= 16)::
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
getWindow().getDecorView().setSystemUiVisibility (View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LOW_PROFILE | View.SYSTEM_UI_FLAG_FULLSCREEN);
}
::end::::end::
for (Extension extension : extensions) {
extension.onStart ();
}
}
@Override protected void onStop () {
super.onStop ();
for (Extension extension : extensions) {
extension.onStop ();
}
}
::if (ANDROID_TARGET_SDK_VERSION >= 14)::
@Override public void onTrimMemory (int level) {
if (Build.VERSION.SDK_INT >= 14) {
super.onTrimMemory (level);
for (Extension extension : extensions) {
extension.onTrimMemory (level);
}
}
}
::end::
public static void popView () {
activity.setContentView (activity.mView);
activity.doResume ();
}
public static void postUICallback (final long inHandle) {
activity.mHandler.post (new Runnable () {
@Override public void run () {
Lime.onCallback (inHandle);
}
});
}
private int prepareDeviceOrientation () {
int rawOrientation = getWindow ().getWindowManager ().getDefaultDisplay ().getOrientation ();
if (rawOrientation != bufferedDisplayOrientation) {
bufferedDisplayOrientation = rawOrientation;
}
int screenOrientation = getResources ().getConfiguration ().orientation;
int deviceOrientation = DEVICE_ORIENTATION_UNKNOWN;
if (bufferedNormalOrientation < 0) {
switch (screenOrientation) {
case Configuration.ORIENTATION_LANDSCAPE:
switch (bufferedDisplayOrientation) {
case DEVICE_ROTATION_0:
case DEVICE_ROTATION_180:
bufferedNormalOrientation = DEVICE_ORIENTATION_LANDSCAPE_LEFT;
break;
case DEVICE_ROTATION_90:
case DEVICE_ROTATION_270:
bufferedNormalOrientation = DEVICE_ORIENTATION_PORTRAIT;
break;
default:
bufferedNormalOrientation = DEVICE_ORIENTATION_UNKNOWN;
}
break;
case Configuration.ORIENTATION_PORTRAIT:
switch (bufferedDisplayOrientation) {
case DEVICE_ROTATION_0:
case DEVICE_ROTATION_180:
bufferedNormalOrientation = DEVICE_ORIENTATION_PORTRAIT;
break;
case DEVICE_ROTATION_90:
case DEVICE_ROTATION_270:
bufferedNormalOrientation = DEVICE_ORIENTATION_LANDSCAPE_LEFT;
break;
default:
bufferedNormalOrientation = DEVICE_ORIENTATION_UNKNOWN;
}
break;
default: // ORIENTATION_SQUARE OR ORIENTATION_UNDEFINED
bufferedNormalOrientation = DEVICE_ORIENTATION_UNKNOWN;
}
}
switch (screenOrientation) {
case Configuration.ORIENTATION_LANDSCAPE:
switch (bufferedDisplayOrientation) {
case DEVICE_ROTATION_0:
case DEVICE_ROTATION_270:
deviceOrientation = DEVICE_ORIENTATION_LANDSCAPE_LEFT;
break;
case DEVICE_ROTATION_90:
case DEVICE_ROTATION_180:
deviceOrientation = DEVICE_ORIENTATION_LANDSCAPE_RIGHT;
break;
default: // impossible!
deviceOrientation = DEVICE_ORIENTATION_UNKNOWN;
}
break;
case Configuration.ORIENTATION_PORTRAIT:
switch (bufferedDisplayOrientation) {
case DEVICE_ROTATION_0:
case DEVICE_ROTATION_90:
deviceOrientation = DEVICE_ORIENTATION_PORTRAIT;
break;
case DEVICE_ROTATION_180:
case DEVICE_ROTATION_270:
deviceOrientation = DEVICE_ORIENTATION_PORTRAIT_UPSIDE_DOWN;
break;
default: // impossible!
deviceOrientation = DEVICE_ORIENTATION_UNKNOWN;
}
break;
default: // ORIENTATION_SQUARE OR ORIENTATION_UNDEFINED
deviceOrientation = DEVICE_ORIENTATION_UNKNOWN;
}
return deviceOrientation;
}
public static void pushView (View inView) {
activity.doPause ();
activity.setContentView (inView);
}
public void queueRunnable (Runnable runnable) {
Log.e ("GameActivity", "queueing...");
}
public static void registerExtension (Extension extension) {
if (extensions.indexOf (extension) == -1) {
extensions.add (extension);
}
}
public static void showKeyboard (boolean show) {
if (activity == null) {
return;
}
InputMethodManager mgr = (InputMethodManager)activity.getSystemService (Context.INPUT_METHOD_SERVICE);
mgr.hideSoftInputFromWindow (activity.mView.getWindowToken (), 0);
if (show) {
mgr.toggleSoftInput (InputMethodManager.SHOW_FORCED, 0);
// On the Nexus One, SHOW_FORCED makes it impossible
// to manually dismiss the keyboard.
// On the Droid SHOW_IMPLICIT doesn't bring up the keyboard.
}
}
public static void setUserPreference (String inId, String inPreference) {
SharedPreferences prefs = activity.getSharedPreferences (GLOBAL_PREF_FILE, MODE_PRIVATE);
SharedPreferences.Editor prefEditor = prefs.edit ();
prefEditor.putString (inId, inPreference);
prefEditor.commit ();
}
public static void vibrate (int period, int duration) {
Vibrator v = (Vibrator)activity.getSystemService (Context.VIBRATOR_SERVICE);
if (period == 0) {
v.vibrate (duration);
} else {
int periodMS = (int)Math.ceil (period / 2);
int count = (int)Math.ceil ((duration / period) * 2);
long[] pattern = new long[count];
for (int i = 0; i < count; i++) {
pattern[i] = periodMS;
}
v.vibrate (pattern, -1);
}
}
}
|
package info.tregmine.gamemagic;
import info.tregmine.Tregmine;
import java.util.*;
import org.bukkit.*;
import org.bukkit.block.*;
import org.bukkit.entity.Player;
import org.bukkit.event.*;
import org.bukkit.event.block.*;
import org.bukkit.event.entity.*;
import org.bukkit.event.entity.CreatureSpawnEvent.SpawnReason;
import org.bukkit.event.player.*;
import org.bukkit.inventory.Inventory;
import org.bukkit.plugin.*;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitScheduler;
public class GameMagic extends JavaPlugin implements Listener
{
private Map<Integer, String> portalLookup;
public Tregmine tregmine = null;
public GameMagic()
{
portalLookup = new HashMap<Integer, String>();
}
@Override
public void onEnable()
{
PluginManager pluginMgm = getServer().getPluginManager();
// Check for tregmine plugin
if (tregmine == null) {
Plugin mainPlugin = pluginMgm.getPlugin("tregmine");
if (mainPlugin != null) {
tregmine = (Tregmine)mainPlugin;
} else {
Tregmine.LOGGER.info(getDescription().getName() + " " +
getDescription().getVersion() +
" - could not find Tregmine");
pluginMgm.disablePlugin(this);
return;
}
}
// Register events
pluginMgm.registerEvents(this, this);
pluginMgm.registerEvents(new Gates(this), this);
pluginMgm.registerEvents(new ButtonListener(this), this);
pluginMgm.registerEvents(new SpongeCouponListener(this), this);
WorldCreator alpha = new WorldCreator("alpha");
alpha.environment(World.Environment.NORMAL);
alpha.createWorld();
WorldCreator elva = new WorldCreator("elva");
elva.environment(World.Environment.NORMAL);
elva.createWorld();
WorldCreator treton = new WorldCreator("treton");
treton.environment(World.Environment.NORMAL);
treton.createWorld();
WorldCreator einhome = new WorldCreator("einhome");
einhome.environment(World.Environment.NORMAL);
einhome.createWorld();
WorldCreator citadel = new WorldCreator("citadel");
citadel.environment(World.Environment.NORMAL);
citadel.createWorld();
// Portal in tower of einhome
portalLookup.put(-1488547832, "world");
// Portal in elva
portalLookup.put(-1559526734, "world");
portalLookup.put(-1349166371, "treton");
portalLookup.put(1371197620, "citadel");
// portals in world
portalLookup.put(-973919203, "treton");
portalLookup.put(-777405698, "treton");
portalLookup.put(1259780606, "citadel");
portalLookup.put(690186900, "elva");
portalLookup.put(209068875, "einhome");
// portals in TRETON
portalLookup.put(45939467, "world");
portalLookup.put(-1408237330, "citadel");
portalLookup.put(559131756, "elva");
// portals in CITADEL
portalLookup.put(1609346891, "world");
portalLookup.put(-449465967, "treton");
portalLookup.put(1112623336, "elva");
// Shoot fireworks at spawn
BukkitScheduler scheduler = getServer().getScheduler();
scheduler.scheduleSyncRepeatingTask(this,
new Runnable() {
public void run() {
World world = GameMagic.this.getServer().getWorld("world");
Location loc = world.getSpawnLocation().add(0.5, 0, 0.5);;
FireworksFactory factory = new FireworksFactory();
factory.addColor(Color.BLUE);
factory.addColor(Color.YELLOW);
factory.addType(FireworkEffect.Type.STAR);
factory.shot(loc);
}
}, 100L, 200L);
}
public static int locationChecksum(Location loc)
{
int checksum = (loc.getBlockX() + "," +
loc.getBlockZ() + "," +
loc.getBlockY() + "," +
loc.getWorld().getName()).hashCode();
return checksum;
}
private void gotoWorld(Player player, Location loc)
{
Inventory inventory = player.getInventory();
for (int i = 0; i < inventory.getSize(); i++) {
if (inventory.getItem(i) != null) {
player.sendMessage(ChatColor.RED + "You are carrying too much " +
"for the portal's magic to work.");
return;
}
}
World world = loc.getWorld();
Chunk chunk = world.getChunkAt(loc);
world.loadChunk(chunk);
if (world.isChunkLoaded(chunk)) {
player.teleport(loc);
player.sendMessage(ChatColor.YELLOW + "Thanks for traveling with " +
"TregPort!");
} else {
player.sendMessage(ChatColor.RED + "The portal needs some " +
"preparation. Please try again!");
}
}
@EventHandler
public void buttons(PlayerInteractEvent event)
{
if (event.getAction() == Action.LEFT_CLICK_AIR ||
event.getAction() == Action.RIGHT_CLICK_AIR) {
return;
}
Block block = event.getClickedBlock();
Player player = event.getPlayer();
int checksum = locationChecksum(block.getLocation());
if (!portalLookup.containsKey(checksum)) {
return;
}
String worldName = portalLookup.get(checksum);
Location loc = getServer().getWorld(worldName).getSpawnLocation();
gotoWorld(player, loc);
}
@EventHandler
public void onPlayerBucketFill(PlayerBucketFillEvent event)
{
if ("alpha".equals(event.getPlayer().getWorld().getName())) {
event.setCancelled(true);
}
}
@EventHandler
public void onPlayerBucketEmpty(PlayerBucketEmptyEvent event)
{
if (event.getBlockClicked().getWorld().getName().equalsIgnoreCase(tregmine.getRulelessWorld().getName())) {
return;
}
if (event.getBucket() == Material.LAVA_BUCKET) {
event.setCancelled(true);
}
}
@EventHandler
public void onPlayerPickupItem(PlayerPickupItemEvent event)
{
if ("alpha".equals(event.getPlayer().getWorld().getName())) {
event.setCancelled(true);
}
}
@EventHandler
public void onPlayerDropItem(PlayerDropItemEvent event)
{
if ("alpha".equals(event.getPlayer().getWorld().getName())) {
event.setCancelled(true);
}
}
@EventHandler
public void onCreatureSpawn(CreatureSpawnEvent event)
{
if (event.getSpawnReason() == SpawnReason.SPAWNER_EGG) {
event.setCancelled(true);
}
}
@EventHandler
public void onEntityExplode(EntityExplodeEvent event)
{
if (event.getLocation().getWorld().getName().equalsIgnoreCase(tregmine.getRulelessWorld().getName())) {
return;
}
event.setCancelled(true);
}
@EventHandler
public void onBlockBurn(BlockBurnEvent event)
{
if (event.getBlock().getWorld().getName().equalsIgnoreCase(tregmine.getRulelessWorld().getName())) {
return;
}
event.setCancelled(true);
}
@EventHandler
public void onLeavesDecay(LeavesDecayEvent event)
{
Location l = event.getBlock().getLocation();
Block fence =
event.getBlock()
.getWorld()
.getBlockAt(l.getBlockX(), l.getBlockY() - 1, l.getBlockZ());
if (fence.getType() == Material.FENCE) {
event.setCancelled(true);
}
}
@EventHandler
public void onBlockIgnite(BlockIgniteEvent event)
{
if (event.getBlock().getWorld().getName().equalsIgnoreCase(tregmine.getRulelessWorld().getName())) {
return;
}
event.setCancelled(true);
Location l = event.getBlock().getLocation();
Block block =
event.getBlock()
.getWorld()
.getBlockAt(l.getBlockX(), l.getBlockY() - 1, l.getBlockZ());
if (block.getType() == Material.OBSIDIAN) {
event.setCancelled(false);
}
}
@EventHandler
public void onUseElevator(PlayerInteractEvent event)
{
Player player = event.getPlayer();
Block block = event.getClickedBlock();
if (block == null) {
return;
}
if (block.getType().equals(Material.STONE_BUTTON)) {
Location loc = player.getLocation();
World world = player.getWorld();
Block standOn = world.getBlockAt(loc.getBlockX(), loc.getBlockY()-1, loc.getBlockZ());
if (Material.SPONGE.equals(standOn.getType())) {
Location bLoc = block.getLocation();
Block signBlock = world.getBlockAt(bLoc.getBlockX(), bLoc.getBlockY()+1, bLoc.getBlockZ());
if(signBlock.getState() instanceof Sign) {
Sign sign = (Sign) signBlock.getState();
if (sign.getLine(0).contains("up")) {
sign.setLine(0, ChatColor.DARK_RED + "Elevator");
sign.setLine(2, ChatColor.GOLD + "[" + ChatColor.DARK_GRAY + "UP" + ChatColor.GOLD + "]");
sign.update(true);
player.sendMessage(ChatColor.GREEN + "Elevator Setup!");
}
else if (sign.getLine(0).equals(ChatColor.DARK_RED + "Elevator")
&& sign.getLine(2).equals(ChatColor.GOLD + "[" + ChatColor.DARK_GRAY + "UP" + ChatColor.GOLD + "]")) {
int i = standOn.getLocation().getBlockY();
while (i < 255) {
i++;
Block sponge = event.getPlayer().getWorld().getBlockAt(standOn.getLocation().getBlockX(), i, standOn.getLocation().getBlockZ());
if (sponge.getType().equals(Material.SPONGE)) {
i=256;
Location tp = sponge.getLocation();
tp.setY(tp.getBlockY() + 1.5);
tp.setZ(tp.getBlockZ() + 0.5);
tp.setX(tp.getBlockX() + 0.5);
tp.setPitch(player.getLocation().getPitch());
tp.setYaw(player.getLocation().getYaw());
player.teleport(tp);
}
}
player.sendMessage(ChatColor.AQUA + "Going up");
}
// sign.setLine(0, ChatColor.DARK_PURPLE + "Elevator");
// sign.setLine(2, ChatColor.GOLD + "[ " + ChatColor.DARK_GRAY + "UP" + ChatColor.GOLD + " ]");
if (sign.getLine(0).contains("down")) {
sign.setLine(0, ChatColor.DARK_RED + "Elevator");
sign.setLine(2, ChatColor.GOLD + "[" + ChatColor.DARK_GRAY + "DOWN" + ChatColor.GOLD + "]");
sign.update(true);
player.sendMessage(ChatColor.GREEN + "Elevator Setup!");
}
else if (sign.getLine(0).equals(ChatColor.DARK_RED + "Elevator")
&& sign.getLine(2).equals(ChatColor.GOLD + "[" + ChatColor.DARK_GRAY + "DOWN" + ChatColor.GOLD + "]")) {
int i = standOn.getLocation().getBlockY();
while (i > 0) {
i
Block sponge = event.getPlayer().getWorld().getBlockAt(standOn.getLocation().getBlockX(), i, standOn.getLocation().getBlockZ());
if (sponge.getType().equals(Material.SPONGE)) {
i=0;
Location tp = sponge.getLocation();
tp.setY(tp.getBlockY() + 1.5);
tp.setZ(tp.getBlockZ() + 0.5);
tp.setX(tp.getBlockX() + 0.5);
tp.setPitch(player.getLocation().getPitch());
tp.setYaw(player.getLocation().getYaw());
player.teleport(tp);
}
}
player.sendMessage(ChatColor.AQUA +"Going down");
}
}
}
}
}
}
|
package VASSAL.build.module;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ComponentAdapter;
import java.awt.event.ComponentEvent;
import java.awt.event.KeyEvent;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import java.io.IOException;
import java.net.URL;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.KeyStroke;
import javax.swing.text.BadLocationException;
import javax.swing.text.html.HTMLDocument;
import javax.swing.text.html.HTMLEditorKit;
import javax.swing.text.html.StyleSheet;
import org.apache.commons.lang3.StringUtils;
import VASSAL.build.Buildable;
import VASSAL.build.GameModule;
import VASSAL.command.Command;
import VASSAL.command.CommandEncoder;
import VASSAL.configure.ColorConfigurer;
import VASSAL.configure.FontConfigurer;
import VASSAL.configure.BooleanConfigurer;
import VASSAL.i18n.Resources;
import VASSAL.preferences.Prefs;
import VASSAL.tools.ErrorDialog;
import VASSAL.tools.KeyStrokeSource;
import VASSAL.tools.ScrollPane;
/**
* The chat window component. Displays text messages and accepts input. Also
* acts as a {@link CommandEncoder}, encoding/decoding commands that display
* message in the text area
*/
public class Chatter extends JPanel implements CommandEncoder, Buildable {
private static final long serialVersionUID = 1L;
protected JTextPane conversationPane;
protected HTMLDocument doc;
protected HTMLEditorKit kit;
protected StyleSheet style;
protected JTextField input;
protected JScrollPane scroll = new ScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
protected JScrollPane scroll2 = new ScrollPane(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
protected static final String MY_CHAT_COLOR = "HTMLChatColor"; //$NON-NLS-1$ // Different tags to "restart" w/ new default scheme
protected static final String OTHER_CHAT_COLOR = "HTMLotherChatColor"; //$NON-NLS-1$
protected static final String GAME_MSG1_COLOR = "HTMLgameMessage1Color"; //$NON-NLS-1$
protected static final String GAME_MSG2_COLOR = "HTMLgameMessage2Color"; //$NON-NLS-1$
protected static final String GAME_MSG3_COLOR = "HTMLgameMessage3Color"; //$NON-NLS-1$
protected static final String GAME_MSG4_COLOR = "HTMLgameMessage4Color"; //$NON-NLS-1$
protected static final String GAME_MSG5_COLOR = "HTMLgameMessage5Color"; //$NON-NLS-1$
protected static final String SYS_MSG_COLOR = "HTMLsystemMessageColor"; //$NON-NLS-1$
protected Font myFont;
protected Color gameMsg, gameMsg2, gameMsg3, gameMsg4, gameMsg5;
protected Color systemMsg, myChat, otherChat;
protected JTextArea conversation; // Backward compatibility for overridden classes. Needs something to suppress.
public static String getAnonymousUserName() {
return Resources.getString("Chat.anonymous"); //$NON-NLS-1$
}
public Chatter() {
setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
conversation = new JTextArea(); // For backward override compatibility only.
//BR// Conversation is now a JTextPane w/ HTMLEditorKit to process HTML, which gives us HTML support "for free".
conversationPane = new JTextPane();
conversationPane.setContentType("text/html");
doc = (HTMLDocument) conversationPane.getDocument();
kit = (HTMLEditorKit) conversationPane.getEditorKit();
style = kit.getStyleSheet();
myFont = new Font("SansSerif", Font.PLAIN, 12); // Will be overridden by the font from Chat preferences
try {
for (int i = 0; i < 15; ++i) {
kit.insertHTML(doc, doc.getLength(), "<br>", 0, 0, null);
}
}
catch (BadLocationException ble) {
ErrorDialog.bug(ble);
}
catch (IOException ex) {
ErrorDialog.bug(ex);
}
conversationPane.setEditable(false);
conversationPane.addComponentListener(new ComponentAdapter() {
@Override
public void componentResized(ComponentEvent e) {
scroll.getVerticalScrollBar().setValue(scroll.getVerticalScrollBar().getMaximum());
}
});
input = new JTextField(60);
input.setFocusTraversalKeysEnabled(false);
input.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
send(formatChat(e.getActionCommand()));
input.setText(""); //$NON-NLS-1$
}
});
input.setMaximumSize(new Dimension(input.getMaximumSize().width, input.getPreferredSize().height));
FontMetrics fm = getFontMetrics(myFont);
int fontHeight = fm.getHeight();
conversationPane.setPreferredSize(new Dimension(input.getMaximumSize().width, fontHeight * 10));
scroll.setViewportView(conversationPane);
scroll.getVerticalScrollBar().setUnitIncrement(input.getPreferredSize().height); //Scroll this faster
add(scroll);
add(input);
setPreferredSize(new Dimension(input.getMaximumSize().width, input.getPreferredSize().height + conversationPane.getPreferredSize().height));
}
/**
* Because our Chatters make themselves visible in their constructor, providing a way for an overriding class to
* "turn this chatter off" is friendlier than What Went Before.
*
* @param vis - whether this chatter should be visible
*/
protected void setChatterVisible(boolean vis) {
conversationPane.setVisible(vis);
input.setVisible(vis);
scroll.setVisible(vis);
}
private String formatChat(String text) {
final String id = GlobalOptions.getInstance().getPlayerId();
return String.format("<%s> - %s", id.isEmpty() ? "(" + getAnonymousUserName() + ")" : id, text); //HTML-friendly angle brackets //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
}
public JTextField getInputField() {
return input;
}
/**
* Styles a chat message based on the player who sent it. Presently just distinguishes a chat message "from me" from a chat message "from anyone else".
*
* To make the player colors easy to override in a custom class
* (my modules have logic to assign individual player colors -- beyond the scope of the present effort but a perhaps a fun future addition)
* @param s - chat message from a player
* @return - an entry in our CSS style sheet to use for this chat message
*/
protected String getChatStyle(String s) {
return s.startsWith(formatChat("").trim()) ? "mychat" : "other";
}
/**
* A hook for inserting a console class that accepts commands
* @param s - chat message
* @param style - current style name (contains information that might be useful)
* @param html_allowed - flag if html_processing is enabled for this message (allows console to apply security considerations)
*/
public void consoleHook(String s, String style, boolean html_allowed) {
}
/**
* Display a message in the text area
*/
public void show(String s) {
String style;
boolean html_allowed;
// Choose an appropriate style to display this message in
s = s.trim();
if (!s.isEmpty()) {
if (s.startsWith("*")) {
// Here we just extend the convention of looking at first characters, this time to the second character.
// | = msg1 (w/ HTML parsing explicitly opted in)
// ! = msg2
// ? = msg3
// ~ = msg4
// ` = msg5
// These characters can be pre-pended to Report messages to produce the color changes. The characters themselves are removed before display.
// Reports can also include <b></b> tags for bold and <i></i> for italic.
if (s.startsWith("* |") || s.startsWith("*|")) {
style = "msg";
s = s.replaceFirst("\\|", "");
html_allowed = true;
}
else if (s.startsWith("* !") || s.startsWith("*!")) {
style = "msg2";
s = s.replaceFirst("!", "");
html_allowed = true;
}
else if (s.startsWith("* ?") || s.startsWith("*?")) {
style = "msg3";
s = s.replaceFirst("\\?", "");
html_allowed = true;
}
else if (s.startsWith("* ~") || s.startsWith("*~")) {
style = "msg4";
s = s.replaceFirst("~", "");
html_allowed = true;
}
else if (s.startsWith("* `") || s.startsWith("*`")) {
style = "msg5";
s = s.replaceFirst("`", "");
html_allowed = true;
}
else {
style = "msg";
html_allowed = GlobalOptions.getInstance().chatterHTMLSupport(); // Generic report lines check compatibility flag (so old modules will not break on e.g. "<" in messages)
}
}
else if (s.startsWith("-")) {
style = "sys";
html_allowed = true;
}
else {
style = getChatStyle(s);
html_allowed = false;
}
}
else {
style = "msg";
html_allowed = false;
}
// Disable unwanted HTML tags in contexts where it shouldn't be allowed:
// (1) Anything received from chat channel, for security reasons
// (2) Legacy module "report" text when not explicitly opted in w/ first character or preference setting
if (!html_allowed) {
s = s.replaceAll("<", "<") // This prevents any unwanted tag from functioning
.replaceAll(">", ">"); // This makes sure > doesn't break any of our legit <div> tags
}
// Systematically search through for html image tags. When we find one, try
// to match it with an image from our DataArchive, and substitute the correct
// fully qualified URL into the tag.
URL url;
String keystring = "<img src=\"";
String file, tag, replace;
int base;
while (s.toLowerCase().contains(keystring)) { // Find next key (to-lower so we're not case sensitive)
base = s.toLowerCase().indexOf(keystring);
file = s.substring(base + keystring.length(), s.length()).split("\"")[0]; // Pull the filename out from between the quotes
tag = s.substring(base, base + keystring.length()) + file + "\""; // Reconstruct the part of the tag we want to remove, leaving all attributes after the filename alone, and properly matching the upper/lowercase of the keystring
try {
url = GameModule.getGameModule().getDataArchive().getURL("images/" + file);
replace = "<img src=\"" + url.toString() + "\""; // Fully qualified URL if we are successful. The extra
// space between IMG and SRC in the processed
// version ensures we don't re-find THIS tag as we iterate
}
catch (IOException ex) {
replace = "<img src=\"" + file + "\""; // Or just leave in except alter just enough that we won't find this tag again
}
if (s.contains(tag)) {
s = s.replaceFirst(tag, replace); // Swap in our new URL-laden tag for the old one.
}
else {
break; // If something went wrong in matching up the tag, don't loop forever
}
}
// Now we have to fix up any legacy angle brackets around the word <observer>
keystring = Resources.getString("PlayerRoster.observer");
replace = keystring.replace("<", "<").replace(">", ">");
if (replace != keystring) {
s = s.replace(keystring, replace);
}
// Insert a div of the correct style for our line of text. Module designer
// still free to insert <span> tags and <img> tags and the like in Report
// messages.
try {
kit.insertHTML(doc, doc.getLength(), "\n<div class=" + style + ">" + s + "</div>", 0, 0, null);
}
catch (BadLocationException ble) {
ErrorDialog.bug(ble);
}
catch (IOException ex) {
ErrorDialog.bug(ex);
}
conversationPane.update(conversationPane.getGraphics()); // Force graphics to update
consoleHook(s, style, html_allowed);
}
/**
* Adds or updates a CSS stylesheet entry. Styles in the color, font type, and font size.
* @param s Style name
* @param f Font to use
* @param c Color for text
* @param font_weight Bold? Italic?
* @param size Font size
*/
protected void addStyle(String s, Font f, Color c, String font_weight, int size) {
if ((style == null) || (c == null)) return;
style.addRule(s +
" {color:" +
String.format("#%02x%02x%02x", c.getRed(), c.getGreen(), c.getBlue()) +
"; font-family:" +
f.getFamily() +
"; font-size:" +
(size > 0 ? size : f.getSize()) +
"; " +
((font_weight != "") ? "font-weight:" + font_weight + "; " : "") +
"}");
}
/**
* Build ourselves a CSS stylesheet from our preference font/color settings.
* @param f - Font to use for this stylesheet
*/
protected void makeStyleSheet(Font f) {
if (style == null) {
return;
}
if (f == null) {
if (myFont == null) {
f = new Font("SansSerif", 0, 12);
myFont = f;
}
else {
f = myFont;
}
}
addStyle("body", f, gameMsg, "", 0);
addStyle("p", f, gameMsg, "", 0);
addStyle(".msg", f, gameMsg, "", 0);
addStyle(".msg2", f, gameMsg2, "", 0);
addStyle(".msg3", f, gameMsg3, "", 0);
addStyle(".msg4", f, gameMsg4, "", 0);
addStyle(".msg5", f, gameMsg5, "", 0);
addStyle(".mychat", f, myChat, "bold", 0);
addStyle(".other ", f, otherChat, "bold", 0);
addStyle(".sys", f, systemMsg, "", 0);
// A fun extension would be letting the module designer provide extra class styles.
}
/**
* Set the Font used by the text area
*/
@Override
public void setFont(Font f) {
myFont = f;
if (input != null) {
if (input.getText().isEmpty()) {
input.setText("XXX"); //$NON-NLS-1$
input.setFont(f);
input.setText(""); //$NON-NLS-1$
}
else {
input.setFont(f);
}
}
if (conversationPane != null) {
conversationPane.setFont(f);
}
makeStyleSheet(f); // When font changes, rebuild our stylesheet
}
@Override
public void build(org.w3c.dom.Element e) {
}
@Override
public org.w3c.dom.Element getBuildElement(org.w3c.dom.Document doc) {
return doc.createElement(getClass().getName());
}
/**
* Expects to be added to a GameModule. Adds itself to the controls window and
* registers itself as a {@link CommandEncoder}
*/
@Override
public void addTo(Buildable b) {
GameModule mod = (GameModule) b;
mod.setChatter(this);
mod.addCommandEncoder(this);
mod.addKeyStrokeSource(new KeyStrokeSource(this, WHEN_ANCESTOR_OF_FOCUSED_COMPONENT));
final FontConfigurer chatFont = new FontConfigurer("ChatFont",
Resources.getString("Chatter.chat_font_preference"));
chatFont.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent evt) {
setFont((Font) evt.getNewValue());
}
});
mod.getPlayerWindow().addChatter(this);
chatFont.fireUpdate();
mod.getPrefs().addOption(Resources.getString("Chatter.chat_window"), chatFont); //$NON-NLS-1$
// Bug 10179 - Do not re-read Chat colors each time the Chat Window is
// repainted.
final Prefs globalPrefs = Prefs.getGlobalPrefs();
// game message color
final ColorConfigurer gameMsgColor = new ColorConfigurer(GAME_MSG1_COLOR,
Resources.getString("Chatter.game_messages_preference"), Color.black);
gameMsgColor.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent e) {
gameMsg = (Color) e.getNewValue();
makeStyleSheet(null);
}
});
globalPrefs.addOption(Resources.getString("Chatter.chat_window"), gameMsgColor);
gameMsg = (Color) globalPrefs.getValue(GAME_MSG1_COLOR);
// game message color #2 (messages starting with "!")
final ColorConfigurer gameMsg2Color = new ColorConfigurer(GAME_MSG2_COLOR,
Resources.getString("Chatter.game_messages_preference_2"), new Color(0, 153, 51));
gameMsg2Color.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent e) {
gameMsg2 = (Color) e.getNewValue();
makeStyleSheet(null);
}
});
globalPrefs.addOption(Resources.getString("Chatter.chat_window"), gameMsg2Color);
gameMsg2 = (Color) globalPrefs.getValue(GAME_MSG2_COLOR);
// game message color #3 (messages starting with "?")
final ColorConfigurer gameMsg3Color = new ColorConfigurer(GAME_MSG3_COLOR,
Resources.getString("Chatter.game_messages_preference_3"), new Color(255, 102, 102));
gameMsg3Color.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent e) {
gameMsg3 = (Color) e.getNewValue();
makeStyleSheet(null);
}
});
globalPrefs.addOption(Resources.getString("Chatter.chat_window"), gameMsg3Color);
gameMsg3 = (Color) globalPrefs.getValue(GAME_MSG3_COLOR);
// game message color #4 (messages starting with "~")
final ColorConfigurer gameMsg4Color = new ColorConfigurer(GAME_MSG4_COLOR,
Resources.getString("Chatter.game_messages_preference_4"), new Color(255, 0, 0));
gameMsg4Color.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent e) {
gameMsg4 = (Color) e.getNewValue();
makeStyleSheet(null);
}
});
globalPrefs.addOption(Resources.getString("Chatter.chat_window"), gameMsg4Color);
gameMsg4 = (Color) globalPrefs.getValue(GAME_MSG4_COLOR);
// game message color #5 (messages starting with "`")
final ColorConfigurer gameMsg5Color = new ColorConfigurer(GAME_MSG5_COLOR,
Resources.getString("Chatter.game_messages_preference_5"), new Color(153, 0, 153));
gameMsg5Color.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent e) {
gameMsg5 = (Color) e.getNewValue();
makeStyleSheet(null);
}
});
globalPrefs.addOption(Resources.getString("Chatter.chat_window"), gameMsg5Color);
gameMsg5 = (Color) globalPrefs.getValue(GAME_MSG5_COLOR);
final ColorConfigurer systemMsgColor = new ColorConfigurer(SYS_MSG_COLOR,
Resources.getString("Chatter.system_message_preference"), new Color(160, 160, 160));
systemMsgColor.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent e) {
systemMsg = (Color) e.getNewValue();
makeStyleSheet(null);
}
});
globalPrefs.addOption(Resources.getString("Chatter.chat_window"), systemMsgColor);
systemMsg = (Color) globalPrefs.getValue(SYS_MSG_COLOR);
final ColorConfigurer myChatColor = new ColorConfigurer( MY_CHAT_COLOR,
Resources.getString("Chatter.my_text_preference"), new Color(9, 32, 229) );
myChatColor.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent e) {
myChat = (Color) e.getNewValue();
makeStyleSheet(null);
}
});
globalPrefs.addOption( Resources.getString("Chatter.chat_window"),
myChatColor );
myChat = (Color) globalPrefs.getValue(MY_CHAT_COLOR);
final ColorConfigurer otherChatColor = new ColorConfigurer(OTHER_CHAT_COLOR,
Resources.getString("Chatter.other_text_preference"), new Color (0, 153, 255));
otherChatColor.addPropertyChangeListener(new PropertyChangeListener() {
@Override
public void propertyChange(PropertyChangeEvent e) {
otherChat = (Color) e.getNewValue();
makeStyleSheet(null);
}
});
globalPrefs.addOption( Resources.getString("Chatter.chat_window"), otherChatColor );
otherChat = (Color) globalPrefs.getValue(OTHER_CHAT_COLOR);
makeStyleSheet(myFont);
}
@Override
public void add(Buildable b) {
}
@Override
public Command decode(String s) {
if (s.startsWith("CHAT")) { //$NON-NLS-1$
return new DisplayText(this, s.substring(4));
}
else {
return null;
}
}
@Override
public String encode(Command c) {
if (c instanceof DisplayText) {
return "CHAT" + ((DisplayText) c).msg; //$NON-NLS-1$
}
else if (c instanceof VASSAL.build.module.Chatter.DisplayText) {
return "CHAT" + ((VASSAL.build.module.Chatter.DisplayText) c).getMessage(); //$NON-NLS-1$
}
else {
return null;
}
}
/**
* Displays the message, Also logs and sends to the server a {@link Command}
* that displays this message
*/
public void send(String msg) {
if (msg != null && !msg.isEmpty()) {
show(msg);
GameModule.getGameModule().sendAndLog(new DisplayText(this, msg));
}
}
/**
* Classes other than the Chatter itself may forward KeyEvents to the Chatter by
* using this method
*/
public void keyCommand(KeyStroke e) {
if ((e.getKeyCode() == 0 || e.getKeyCode() == KeyEvent.CHAR_UNDEFINED)
&& !Character.isISOControl(e.getKeyChar())) {
input.setText(input.getText() + e.getKeyChar());
}
else if (e.isOnKeyRelease()) {
switch (e.getKeyCode()) {
case KeyEvent.VK_ENTER:
if (!input.getText().isEmpty())
send(formatChat(input.getText()));
input.setText(""); //$NON-NLS-1$
break;
case KeyEvent.VK_BACK_SPACE:
case KeyEvent.VK_DELETE:
String s = input.getText();
if (!s.isEmpty())
input.setText(s.substring(0, s.length() - 1));
break;
}
}
}
/**
* This is a {@link Command} object that, when executed, displays
* a text message in the Chatter's text area */
public static class DisplayText extends Command {
private String msg;
private Chatter c;
public DisplayText(Chatter c, String s) {
this.c = c;
msg = s;
if (msg.startsWith("<>")) {
msg = "<(" + Chatter.getAnonymousUserName() + ")>" + s.substring(2); // HTML-friendly
// angle brackets
}
else {
msg = s;
}
}
@Override
public void executeCommand() {
c.show(msg);
}
@Override
public Command myUndoCommand() {
return new DisplayText(c, Resources.getString("Chatter.undo_message", msg)); //$NON-NLS-1$
}
public String getMessage() {
return msg;
}
@Override
public String getDetails() {
return msg;
}
}
public static void main(String[] args) {
Chatter chat = new Chatter();
JFrame f = new JFrame();
f.add(chat);
f.pack();
f.setVisible(true);
}
}
|
package gov.nih.nci.camod.util;
import gov.nih.nci.system.client.ApplicationServiceProvider;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import org.LexGrid.LexBIG.LexBIGService.LexBIGService;
/**
* @author EVS Team
* @version 1.0
*
* Modification history
* Initial implementation kim.ong@ngc.com
*
*/
public class RemoteServerUtil {
static private String _serviceInfo = "EvsServiceInfo";
private Properties systemProperties = null;
public RemoteServerUtil() {
}
/**
* Establish a remote LexBIG connection.
*
*/
public static LexBIGService createLexBIGService()
{
LexBIGService lbSvc = null;
String serviceUrl = "http://lexevsapi51.nci.nih.gov/lexevsapi51";
try {
lbSvc = (LexBIGService)ApplicationServiceProvider.getApplicationServiceFromUrl(serviceUrl, "EvsServiceInfo");
} catch (FileNotFoundException e) {
System.out.println("FileNotFound exception in getApplicationService." + e);
e.printStackTrace();
} catch (IOException e) {
System.out.println("IO exception getApplicationService. " + e);
e.printStackTrace();
} catch (Exception e) {
System.out.println("Caught general exception getApplicationService. " + e);
e.printStackTrace();
}
System.out.println("Exiting createLexBIGService");
return lbSvc;
}
/**
* Establish a remote LexBIG connection.
*
*/
public static LexBIGService createLexBIGService(String url)
{
LexBIGService lbSvc = null;
try {
lbSvc = (LexBIGService) ApplicationServiceProvider.getApplicationServiceFromUrl(url, _serviceInfo);
return lbSvc;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
|
package org.bouncycastle.crypto.encodings;
import org.bouncycastle.crypto.AsymmetricBlockCipher;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.InvalidCipherTextException;
import org.bouncycastle.crypto.params.AsymmetricKeyParameter;
import org.bouncycastle.crypto.params.ParametersWithRandom;
import java.security.SecureRandom;
/**
* this does your basic PKCS 1 v1.5 padding - whether or not you should be using this
* depends on your application - see PKCS1 Version 2 for details.
*/
public class PKCS1Encoding
implements AsymmetricBlockCipher
{
/**
* some providers fail to include the leading zero in PKCS1 encoded blocks. If you need to
* work with one of these set the system property org.bouncycastle.pkcs1.strict to false.
* <p>
* The system property is checked during construction of the encoding object, it is set to
* true by default.
* </p>
*/
public static final String STRICT_LENGTH_ENABLED_PROPERTY = "org.bouncycastle.pkcs1.strict";
private static final int HEADER_LENGTH = 10;
private SecureRandom random;
private AsymmetricBlockCipher engine;
private boolean forEncryption;
private boolean forPrivateKey;
private boolean useStrictLength;
/**
* Basic constructor.
* @param cipher
*/
public PKCS1Encoding(
AsymmetricBlockCipher cipher)
{
this.engine = cipher;
this.useStrictLength = useStrict();
}
// for J2ME compatibility
private boolean useStrict()
{
String strict = System.getProperty(STRICT_LENGTH_ENABLED_PROPERTY);
return strict == null || strict.equals("true");
}
public AsymmetricBlockCipher getUnderlyingCipher()
{
return engine;
}
public void init(
boolean forEncryption,
CipherParameters param)
{
AsymmetricKeyParameter kParam;
if (param instanceof ParametersWithRandom)
{
ParametersWithRandom rParam = (ParametersWithRandom)param;
this.random = rParam.getRandom();
kParam = (AsymmetricKeyParameter)rParam.getParameters();
}
else
{
this.random = new SecureRandom();
kParam = (AsymmetricKeyParameter)param;
}
engine.init(forEncryption, param);
this.forPrivateKey = kParam.isPrivate();
this.forEncryption = forEncryption;
}
public int getInputBlockSize()
{
int baseBlockSize = engine.getInputBlockSize();
if (forEncryption)
{
return baseBlockSize - HEADER_LENGTH;
}
else
{
return baseBlockSize;
}
}
public int getOutputBlockSize()
{
int baseBlockSize = engine.getOutputBlockSize();
if (forEncryption)
{
return baseBlockSize;
}
else
{
return baseBlockSize - HEADER_LENGTH;
}
}
public byte[] processBlock(
byte[] in,
int inOff,
int inLen)
throws InvalidCipherTextException
{
if (forEncryption)
{
return encodeBlock(in, inOff, inLen);
}
else
{
return decodeBlock(in, inOff, inLen);
}
}
private byte[] encodeBlock(
byte[] in,
int inOff,
int inLen)
throws InvalidCipherTextException
{
byte[] block = new byte[engine.getInputBlockSize()];
if (forPrivateKey)
{
block[0] = 0x01; // type code 1
for (int i = 1; i != block.length - inLen - 1; i++)
{
block[i] = (byte)0xFF;
}
}
else
{
random.nextBytes(block); // random fill
block[0] = 0x02; // type code 2
// a zero byte marks the end of the padding, so all
// the pad bytes must be non-zero.
for (int i = 1; i != block.length - inLen - 1; i++)
{
while (block[i] == 0)
{
block[i] = (byte)random.nextInt();
}
}
}
block[block.length - inLen - 1] = 0x00; // mark the end of the padding
System.arraycopy(in, inOff, block, block.length - inLen, inLen);
return engine.processBlock(block, 0, block.length);
}
/**
* @exception InvalidCipherTextException if the decrypted block is not in PKCS1 format.
*/
private byte[] decodeBlock(
byte[] in,
int inOff,
int inLen)
throws InvalidCipherTextException
{
byte[] block = engine.processBlock(in, inOff, inLen);
if (block.length < getOutputBlockSize())
{
throw new InvalidCipherTextException("block truncated");
}
byte type = block[0];
if (type != 1 && type != 2)
{
throw new InvalidCipherTextException("unknown block type");
}
if (useStrictLength && block.length != engine.getOutputBlockSize())
{
throw new InvalidCipherTextException("block incorrect size");
}
// find and extract the message block.
int start;
for (start = 1; start != block.length; start++)
{
byte pad = block[start];
if (pad == 0)
{
break;
}
if (type == 1 && pad != (byte)0xff)
{
throw new InvalidCipherTextException("block padding incorrect");
}
}
start++; // data should start at the next byte
if (start > block.length || start < HEADER_LENGTH)
{
throw new InvalidCipherTextException("no data in block");
}
byte[] result = new byte[block.length - start];
System.arraycopy(block, start, result, 0, result.length);
return result;
}
}
|
package jfcraft.gen;
/** Chunk generator phase 2 : structures
*
* Any structure can only span 8 chunks in any direction,
* for a total of 17 chunks span (that's 272 blocks).
*
* @author pquiring
*
* Created : May 8, 2014
*/
import java.util.*;
import javaforce.*;
import javaforce.gl.*;
import jfcraft.data.*;
import jfcraft.block.*;
import jfcraft.entity.*;
import static jfcraft.data.Direction.*;
public class GeneratorPhase2Earth implements GeneratorPhase2Base {
private Chunk chunk;
private Random r = new Random();
public void getIDs() {}
public void generate(Chunk chunk) {
this.chunk = chunk;
synchronized(chunk.lock) {
chunk.needPhase2 = false;
chunk.dirty = true;
r.setSeed(chunk.seed);
if (r.nextInt(100) == 0) {
addCaves();
}
if (r.nextInt(1000) == 0) {
addRavine();
}
if (r.nextInt(10000) == 0) {
// addVillage(); //todo
}
}
}
private void setBlock(int x, int y, int z, char id, int bits) {
if (y < 1) return; //do not change bedrock
if (y > 255) return;
Chunk c = chunk;
while (x < 0) {
c = c.W;
x += 16;
}
while (x > 15) {
c = c.E;
x -= 16;
}
while (z < 0) {
c = c.N;
z += 16;
}
while (z > 15) {
c = c.S;
z -= 16;
}
c.setBlock(x, y, z, id, bits);
}
private void clearBlock(int x, int y, int z) {
if (y < 1) return; //do not change bedrock
if (y > 255) return;
Chunk c = chunk;
while (x < 0) {
c = c.W;
x += 16;
}
while (x > 15) {
c = c.E;
x -= 16;
}
while (z < 0) {
c = c.N;
z += 16;
}
while (z > 15) {
c = c.S;
z -= 16;
}
c.clearBlock(x, y, z);
if (y < 10) {
c.setBlock(x, y, z, Blocks.LAVA, 0);
}
}
private BlockBase getBlock(int x, int y, int z) {
if (y < 0) return null;
if (y > 255) return null;
Chunk c = chunk;
while (x < 0) {
c = c.W;
x += 16;
}
while (x > 15) {
c = c.E;
x -= 16;
}
while (z < 0) {
c = c.N;
z += 16;
}
while (z > 15) {
c = c.S;
z -= 16;
}
return Static.blocks.blocks[c.getID(x,y,z)];
}
private void addCaves() {
//generate caves
// Static.log("cave@" + chunk.cx + "," + chunk.cz);
//start a cave on this chunk, can span max 8 chunks from here in any direction
float elev = r.nextInt((int)chunk.elev[8*16+8]);
float dir = r.nextFloat() * 180f;
doCave(elev, dir, false);
dir += 180;
if (dir > 180) dir -= 360;
doCave(elev, dir, false);
chunk.setBlock(8, (int)elev, 8, Blocks.TORCH, 0); //test
}
private void doCave(float elev, float xzdir, boolean fork) {
float x = 8;
float y = elev;
float z = 8;
int len = 64 + r.nextInt(256);
GLMatrix mat = new GLMatrix();
GLVector3 vecx = new GLVector3();
GLVector3 vecy = new GLVector3();
GLVector3 vecz = new GLVector3();
float width = 3f;
float height = 3f;
float ydir = 0f;
int plen = 0;
float dxzdir = 0, dydir = 0;
do {
if (plen == 0) {
dxzdir = r.nextFloat() * 3f;
dydir = r.nextFloat() * 2f;
plen = 16 + r.nextInt(32);
} else {
plen
}
if (!fork && r.nextInt(150) == 0) {
//fork
float d = r.nextFloat() * 45f;
if (d < 0) d -= 45f; else d += 45f;
doCave(y, xzdir + d, true);
}
mat.setIdentity();
mat.addRotate(xzdir, 0, 1, 0);
mat.addRotate3(ydir, 1, 0, 0);
vecx.set(1, 0, 0);
mat.mult(vecx);
vecy.set(0, 1, 0);
mat.mult(vecy);
vecz.set(0, 0, 1);
mat.mult(vecz);
float xx = vecx.v[0];
float xy = vecx.v[1];
float xz = vecx.v[2];
float yx = vecy.v[0];
float yy = vecy.v[1];
float yz = vecy.v[2];
float zx = vecz.v[0];
float zy = vecz.v[1];
float zz = vecz.v[2];
if (Static.debugCaves) {
clearBlock((int)x,(int)y,(int)z);
} else {
for(float a=0;a<=height;a++) {
//create the curves of the cave walls
float r = (float)Math.sin(Math.toRadians(a / height * 194f)) + 0.25f;
float w = width * r;
float px = x - xx * w / 2f;
float py = y - xy * w / 2f;
float pz = z - xz * w / 2f;
px += yx * a;
py += yy * a;
pz += yz * a;
for(float b = 0;b <= w; b++) {
clearBlock((int)px,(int)py,(int)pz);
px += xx;
py += xy;
pz += xz;
}
}
}
//move at 50% to make sure we get everything
x += zx * 0.50f;
y += zy * 0.50f;
z += zz * 0.50f;
if (y < 10) y = 10;
if (y > 250) y = 250;
xzdir += dxzdir;
if (xzdir > 180) {
xzdir -= 360;
}
if (xzdir < -180) {
xzdir += 360;
}
ydir += dydir;
if (ydir < -3) ydir = -3;
if (ydir > 3) ydir = 3;
width += r.nextFloat() * 0.3f;
if (width > 5) width = 5;
if (width < 2) width = 2;
height += r.nextFloat() * 0.3f;
if (height > 5) height = 5;
if (height < 2) height = 2;
len
//can only go upto 8 chunks beyond start point (should just tapper off)
if (x + width > 128) break;
if (x - width < -128) break;
if (z + width > 128) break;
if (z - width < -128) break;
} while (len > 0);
}
private void addRavine() {
// Static.log("ravine@" + chunk.cx + "," + chunk.cz);
float elev = r.nextInt((int)chunk.elev[8*16+8]);
float dir = r.nextFloat() * 180f;
float height = 30 + r.nextInt(20);
float width = 10 + r.nextInt(5);
float len = 40 + r.nextInt(25);
doRavine(elev, dir, height, width, len);
dir += 180;
doRavine(elev, dir, height, width, len);
chunk.setBlock(8, (int)elev, 8, Blocks.TORCH, 0); //test
}
private void doRavine(float elev, float xzdir, float height, float width, float len) {
float x = 8;
float y = elev;
float z = 8;
GLMatrix mat = new GLMatrix();
GLVector3 vecx = new GLVector3();
GLVector3 vecy = new GLVector3();
GLVector3 vecz = new GLVector3();
float dxzdir = 0;
do {
mat.setIdentity();
mat.addRotate(xzdir, 0, 1, 0);
vecx.set(1, 0, 0);
mat.mult(vecx);
vecy.set(0, 1, 0);
mat.mult(vecy);
vecz.set(0, 0, 1);
mat.mult(vecz);
float xx = vecx.v[0];
float xy = vecx.v[1];
float xz = vecx.v[2];
float yx = vecy.v[0];
float yy = vecy.v[1];
float yz = vecy.v[2];
float zx = vecz.v[0];
float zy = vecz.v[1];
float zz = vecz.v[2];
for(float a=0;a<=height;a++) {
//create the curves of the ravine walls (to create ledges near top)
float p = a * 100f / height;
float r = 0;
if (p < 75) {
//i:0-75 => o:80-100
//f(x) = ((omax - omin) * (x - imin)) / (imax - imin)
r = ((100f-80f) * (p)) / (75f) + 80f;
if (r < 80f || r >100f) {
Static.log("bad r=" + r + ",p=" + p);
}
} else {
//i:75-100 => o:100-0
//f(x) = ((omax - omin) * (x - imin)) / (imax - imin)
r = ((-100f) * (p - 75f)) / (25f) + 100f;
}
float w = width * r / 100f;
if (len < 5f) {
//tapper the end
w /= (5f - len);
}
float px = x - xx * w / 2f;
float py = y - xy * w / 2f;
float pz = z - xz * w / 2f;
px += yx * a;
py += yy * a;
pz += yz * a;
for(float b = 0;b <= w; b++) {
clearBlock((int)px,(int)py,(int)pz);
px += xx;
py += xy;
pz += xz;
}
}
x += zx * 0.50f;
y += zy * 0.50f;
z += zz * 0.50f;
len
} while (len > 0);
}
}
|
package org.openqa.selenium.rc;
import com.google.common.base.Throwables;
import com.google.common.io.Files;
import org.json.JSONObject;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.openqa.selenium.Build;
import org.openqa.selenium.Pages;
import org.openqa.selenium.Proxy;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.environment.GlobalTestEnvironment;
import org.openqa.selenium.environment.InProcessTestEnvironment;
import org.openqa.selenium.environment.TestEnvironment;
import org.openqa.selenium.io.TemporaryFilesystem;
import org.openqa.selenium.net.NetworkUtils;
import org.openqa.selenium.net.PortProber;
import org.openqa.selenium.os.CommandLine;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.HttpRequest;
import org.openqa.selenium.testing.Ignore;
import org.openqa.selenium.testing.InProject;
import org.openqa.selenium.testing.SeleniumTestRunner;
import org.openqa.selenium.testing.drivers.WebDriverBuilder;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import static org.junit.Assert.assertTrue;
import static org.openqa.selenium.remote.CapabilityType.PROXY;
import static org.openqa.selenium.remote.HttpRequest.Method.DELETE;
import static org.openqa.selenium.remote.HttpRequest.Method.GET;
import static org.openqa.selenium.remote.HttpRequest.Method.POST;
import static org.openqa.selenium.remote.HttpRequest.Method.PUT;
import static org.openqa.selenium.testing.Ignore.Driver.ANDROID;
import static org.openqa.selenium.testing.Ignore.Driver.IE;
import static org.openqa.selenium.testing.Ignore.Driver.IPHONE;
import static org.openqa.selenium.testing.Ignore.Driver.SELENESE;
@Ignore(value = {ANDROID, IE, IPHONE, SELENESE},
reason = "Not tested on these browsers yet.")
@RunWith(SeleniumTestRunner.class)
public class SetProxyTest {
private static BrowserMobProxyServer proxyServer;
private static Pages pages;
private ProxyInstance instance;
@BeforeClass
public static void startProxy() {
TestEnvironment environment = GlobalTestEnvironment.get(InProcessTestEnvironment.class);
pages = new Pages(environment.getAppServer());
proxyServer = new BrowserMobProxyServer();
}
@AfterClass
public static void detroyProxy() {
proxyServer.destroy();
}
@Before
public void newProxyInstance() {
instance = proxyServer.newInstance();
}
@After
public void deleteProxyInstance() {
instance.destroy();
}
@Test
public void shouldAllowProxyToBeSetViaTheCapabilities() {
Proxy proxy = instance.asProxy();
DesiredCapabilities caps = new DesiredCapabilities();
caps.setCapability(PROXY, proxy);
WebDriver driver = new WebDriverBuilder().setCapabilities(caps).get();
driver.get(pages.simpleTestPage);
driver.quit();
assertTrue(instance.hasBeenCalled());
}
@Test
public void shouldAllowProxyToBeConfiguredAsAPac() throws IOException {
String pac = String.format(
"function FindProxyForURL(url, host) {\n" +
" return 'PROXY http://%s:%d';\n" +
"}", new NetworkUtils().getPrivateLocalAddress(), instance.port);
File tempDir = new File(System.getProperty("java.io.tmpdir"));
TemporaryFilesystem tempFs = TemporaryFilesystem.getTmpFsBasedOn(tempDir);
File pacFile = new File(tempDir, "proxy.pac");
// Use the default platform charset because otherwise IE gets upset. Apparently.
Files.write(pac, pacFile, Charset.defaultCharset());
String autoConfUrl = pacFile.toURI().toString();
if (!autoConfUrl.startsWith("file:
autoConfUrl = autoConfUrl.replace("file:/", "file:
}
System.out.println("autoConfUrl = " + autoConfUrl);
Proxy proxy = new Proxy();
proxy.setProxyAutoconfigUrl(autoConfUrl);
DesiredCapabilities caps = new DesiredCapabilities();
caps.setCapability(PROXY, proxy);
WebDriver driver = new WebDriverBuilder().setCapabilities(caps).get();
driver.get(pages.simpleTestPage);
driver.quit();
tempFs.deleteTemporaryFiles();
assertTrue(instance.hasBeenCalled());
}
private static class BrowserMobProxyServer {
private CommandLine process;
private String proxyUrl;
public BrowserMobProxyServer() {
// We need to run out of process as the browsermob proxy has a dependency
// on the Selenium Proxy interface, which may change.
new Build().of("//third_party/java/browsermob_proxy:browsermob_proxy:uber").go();
String browserBinary = InProject.locate(
"build/third_party/java/browsermob_proxy/browsermob_proxy-standalone.jar")
.getAbsolutePath();
int port = PortProber.findFreePort();
process = new CommandLine("java", "-jar", browserBinary, "--port", String.valueOf(port));
process.copyOutputTo(System.err);
process.executeAsync();
PortProber.pollPort(port);
String address = new NetworkUtils().getPrivateLocalAddress();
proxyUrl = String.format("http://%s:%d", address, port);
}
public ProxyInstance newInstance() {
try {
HttpRequest request = new HttpRequest(POST, proxyUrl + "/proxy", null);
JSONObject proxyDetails = new JSONObject(request.getResponse());
int port = proxyDetails.getInt("port");
// Wait until the proxy starts and is listening
PortProber.pollPort(port);
// Start recording requests
new HttpRequest(PUT, String.format("%s/proxy/%d/har", proxyUrl, port), null);
return new ProxyInstance(proxyServer.proxyUrl, port);
} catch (Exception e) {
throw Throwables.propagate(e);
}
}
public void destroy() {
process.destroy();
}
}
private static class ProxyInstance {
private final String baseUrl;
private final int port;
public ProxyInstance(String baseUrl, int port) {
this.baseUrl = baseUrl;
this.port = port;
}
public boolean hasBeenCalled() {
String url = String.format("%s/proxy/%d/har", baseUrl, port);
HttpRequest request = new HttpRequest(GET, url, null);
String response = request.getResponse();
return response.length() > 0;
}
public void destroy() {
try {
String url = String.format("%s/proxy/%d", baseUrl, port);
new HttpRequest(DELETE, url, null);
} catch (Exception e) {
throw Throwables.propagate(e);
}
}
public Proxy asProxy() {
Proxy proxy = new Proxy();
String address = new NetworkUtils().getPrivateLocalAddress();
String format = String.format("%s:%d", address, port);
proxy.setHttpProxy(format);
return proxy;
}
}
}
|
package com.artemis.cli;
import java.io.File;
import java.security.ProtectionDomain;
import com.beust.jcommander.JCommander;
import com.beust.jcommander.Parameter;
import com.beust.jcommander.ParameterException;
public class CliApplication {
@Parameter(
names = {"-h", "--help"},
description= "Displays this help message.",
help = true)
private boolean help;
public static void main(String[] args) {
new CliApplication().parse(args);
}
private void parse(String[] args) {
MatrixCommand matrix = new MatrixCommand();
WeaveCommand weave = new WeaveCommand();
OptimizationCommand optimze = new OptimizationCommand();
EclipseProcessorCommand eclipse = new EclipseProcessorCommand();
JCommander parser = new JCommander(this);
parser.addCommand(MatrixCommand.COMMAND, matrix);
parser.addCommand(WeaveCommand.COMMAND, weave);
parser.addCommand(OptimizationCommand.COMMAND, optimze);
parser.addCommand(EclipseProcessorCommand.COMMAND, eclipse);
try {
parser.setProgramName(getJarName());
parser.parse(args);
if (help) {
parser.usage();
System.exit(0);
}
String command = parser.getParsedCommand();
if (MatrixCommand.COMMAND.equals(command)) {
matrix.execute();
} else if (WeaveCommand.COMMAND.equals(command)) {
weave.execute();
} else if (OptimizationCommand.COMMAND.equals(command)) {
optimze.execute();
} else if (EclipseProcessorCommand.COMMAND.equals(command)) {
eclipse.execute();
} else {
parser.usage();
System.exit(1);
}
} catch (ParameterException e) {
System.err.println(e.getMessage());
System.err.println();
parser.usage();
}
}
static String getJarName() {
ProtectionDomain domain = CliApplication.class.getProtectionDomain();
String path = domain.getCodeSource().getLocation().getPath();
return new File(path).getName();
}
}
|
package jeelab.model.dao;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TemporalType;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import jeelab.exception.ReservationUnavailableException;
import jeelab.model.builder.ReservationBuilder;
import jeelab.model.entity.BusinessHours;
import jeelab.model.entity.Reservation;
import jeelab.model.entity.SportsCentreFacility;
import jeelab.view.ReservationForm;
/**
* Rezervace
* @author Vaclav Dobes
*
*/
@Stateless
public class ReservationDao {
@Inject
private ReservationBuilder reservationBuilder;
@Inject
private BusinessHoursDao businessHoursDao;
@PersistenceContext(unitName = "jee")
private EntityManager manager;
private boolean isAvailable(Reservation reservation){
return isAvailable(reservation.getId(), reservation.getSportsCentreFacility(), reservation.getDate(), reservation.getFrom(), reservation.getTo());
}
private boolean isAvailable(Long id, SportsCentreFacility facility , Date date, Float from, Float to){
Query query = manager.createQuery("select count(reservation) from Reservation reservation "
+ "where reservation.sportsCentreFacility = :facility "
+ (id != null ? "and reservation.id <> :resId " : "")
+ "and reservation.date = :date "
+ "and reservation.from < :resEnd "
+ "and reservation.to > :resStart");
if(id != null){
query.setParameter("resId", id);
}
return ((Long) query
.setParameter("facility", facility)
.setParameter("date", date, TemporalType.DATE)
.setParameter("resStart", from)
.setParameter("resEnd", to)
.getSingleResult()
).equals(0L);
}
private boolean isOutOfHours(Reservation reservation){
return isOutOfHours(reservation.getId(), reservation.getSportsCentreFacility(), reservation.getDate(), reservation.getFrom(), reservation.getTo());
}
private boolean isOutOfHours(Long id, SportsCentreFacility facility , Date date, Float from, Float to){
Calendar c = Calendar.getInstance();
c.setTime(date);
BusinessHours hours = businessHoursDao.getFacilityHoursForDay(facility.getId(), c.get(Calendar.DAY_OF_WEEK));
if(hours == null){
return true;
}
return !(hours.getOpenTime() <= from && hours.getCloseTime() >= to);
}
public void save(Reservation reservation) throws ReservationUnavailableException {
if(!isAvailable(reservation) || isOutOfHours(reservation)){
throw new ReservationUnavailableException();
}
manager.persist(reservation);
manager.flush();
}
public void updateReservation(long id, ReservationForm form) throws ReservationUnavailableException {
Reservation reservation = manager.find(Reservation.class, id);
if(reservation != null){
if(!isAvailable(reservation.getId(), reservation.getSportsCentreFacility(), form.getDate(), form.getFrom(), form.getTo())
|| isOutOfHours(reservation.getId(), reservation.getSportsCentreFacility(), form.getDate(), form.getFrom(), form.getTo())){
throw new ReservationUnavailableException();
}
reservationBuilder
.date(form.getDate())
.from(form.getFrom())
.to(form.getTo())
.user(form.getUser())
.sportsCentreFacility(form.getCentreFacility())
.build(reservation);
}
}
public void deleteReservation(long id) {
Reservation reservation = manager.find(Reservation.class, id);
if (reservation != null){
manager.remove(reservation);
}
}
/**
* Get reservation by id
* @param id
* @return
*/
public Reservation getReservation(Long id){
return manager.find(Reservation.class, id);
}
/**
* Vsechny Rezervace
* @param userId
* @return
*/
public List<Reservation> getReservations(Long max, Long offset) {
CriteriaBuilder cb = manager.getCriteriaBuilder();
CriteriaQuery<Reservation> cq = cb.createQuery(Reservation.class);
Root<Reservation> root = cq.from(Reservation.class);
cq.orderBy(cb.desc(root.get("date")));
TypedQuery<Reservation> q = manager.createQuery(cq);
if(max != null && !max.equals(0L)) {
q.setMaxResults(max.intValue());
}
if(offset != null && !offset.equals(0L)) {
q.setFirstResult(offset.intValue());
}
return q.getResultList();
}
/**
* Total number of reservations
* @return
*/
public Long getReservationsCount(){
return (Long) manager.createQuery("select count(reservation) from Reservation reservation").getSingleResult();
}
/**
* Rezervace podle uzivatele
* @param userId
* @return
*/
public List<Reservation> getUserReservations(Long userId, Long max, Long offset) {
CriteriaBuilder cb = manager.getCriteriaBuilder();
CriteriaQuery<Reservation> cq = cb.createQuery(Reservation.class);
Root<Reservation> root = cq.from(Reservation.class);
cq.orderBy(cb.desc(root.get("date")));
cq.where(cb.equal(root.join("user").get("id"), userId));
TypedQuery<Reservation> q = manager.createQuery(cq);
if(max != null && !max.equals(0L)) {
q.setMaxResults(max.intValue());
}
if(offset != null && !offset.equals(0L)) {
q.setFirstResult(offset.intValue());
}
return q.getResultList();
}
/**
* Total number of reservation for user
* @param userId
* @return
*/
public Long getUserReservationsCount(Long userId){
return (Long) manager.createQuery("select count(reservation) from Reservation reservation where reservation.user.id = :userId")
.setParameter("userId", userId)
.getSingleResult();
}
}
|
package br.ufsc.lehmann;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.apache.commons.lang3.ArrayUtils;
import com.google.common.collect.Multimap;
import com.google.common.collect.MultimapBuilder;
import com.google.gson.Gson;
import com.google.gson.JsonIOException;
import com.google.gson.JsonSyntaxException;
import br.ufsc.core.IMeasureDistance;
import br.ufsc.core.trajectory.SemanticTrajectory;
import br.ufsc.core.trajectory.semantic.Move;
import br.ufsc.core.trajectory.semantic.Stop;
import br.ufsc.ftsm.base.TrajectorySimilarityCalculator;
import br.ufsc.lehmann.msm.artigo.classifiers.validation.AUC;
import br.ufsc.lehmann.msm.artigo.classifiers.validation.Validation;
import br.ufsc.lehmann.msm.artigo.problems.BasicSemantic;
import br.ufsc.lehmann.msm.artigo.problems.IDataReader;
import br.ufsc.lehmann.msm.artigo.problems.InvolvesDatabaseReader;
import br.ufsc.lehmann.testexecution.Dataset;
import br.ufsc.lehmann.testexecution.Datasets;
import br.ufsc.lehmann.testexecution.ExecutionPOJO;
import br.ufsc.lehmann.testexecution.Groundtruth;
import br.ufsc.lehmann.testexecution.Measure;
import br.ufsc.lehmann.testexecution.Measures;
import smile.math.Random;
public class InvolvesPrecision10 {
public static void main(String[] args) throws JsonSyntaxException, JsonIOException, FileNotFoundException {
// EnumProblem prob = EnumProblem.INVOLVES;
// Problem problem = prob.problem(new Random());
// List<SemanticTrajectory> data = problem.data();
// SemanticTrajectory[] allData = data.toArray(new SemanticTrajectory[data.size()]);
//// AbstractClassifierTest t = new UMSClassifierTest(prob);
// AbstractClassifierTest t = new SMSMEllipsesClassifierTest(prob);
// TrajectorySimilarityCalculator<SemanticTrajectory> classifier = (TrajectorySimilarityCalculator<SemanticTrajectory>) t.measurer(problem);
Random r = new Random();
ExecutionPOJO execution = new Gson().fromJson(new FileReader("./src/test/resources/executions/SMSM_precision@10.test"), ExecutionPOJO.class);
Dataset dataset = execution.getDataset();
Measure measure = execution.getMeasure();
Groundtruth groundtruth = execution.getGroundtruth();
IDataReader dataReader = Datasets.createDataset(dataset);
TrajectorySimilarityCalculator<SemanticTrajectory> similarityCalculator = Measures.createMeasure(measure);
List<SemanticTrajectory> data = dataReader.read();
BasicSemantic<Object> groundtruthSemantic = new BasicSemantic<>(groundtruth.getIndex().intValue());
SemanticTrajectory[] allData = data.toArray(new SemanticTrajectory[data.size()]);
Multimap<Integer, SemanticTrajectory> trajs = MultimapBuilder.hashKeys().arrayListValues().build();
for (int i = 0; i < allData.length; i++) {
trajs.put(InvolvesDatabaseReader.USER_ID.getData(allData[i], 0), allData[i]);
}
List<SemanticTrajectory> bestTrajectories = trajs.keySet().stream().map((key) -> trajs.get(key).stream().max(new Comparator<SemanticTrajectory>() {
@Override
public int compare(SemanticTrajectory o1, SemanticTrajectory o2) {
double proportionO1 = movesDuration(o1) / stopsDuration(o1);
double proportionO2 = movesDuration(o2) / stopsDuration(o2);
return Double.compare(proportionO1, proportionO2);
}
private double movesDuration(SemanticTrajectory o1) {
double ret = 0.0;
for (int i = 0; i < o1.length(); i++) {
Move move = InvolvesDatabaseReader.MOVE_TEMPORAL_DURATION_SEMANTIC.getData(o1, i);
if(move != null) {
ret += move.getEndTime() - move.getStartTime();
}
}
return ret;
}
private double stopsDuration(SemanticTrajectory o1) {
double ret = 0.0;
for (int i = 0; i < o1.length(); i++) {
Stop stop = InvolvesDatabaseReader.STOP_NAME_SEMANTIC.getData(o1, i);
if(stop != null) {
ret += stop.getEndTime() - stop.getStartTime();
}
}
return ret;
}
}).get()).collect(Collectors.toList());
Map<SemanticTrajectory, List<SemanticTrajectory>> mostSimilarTrajs =
bestTrajectories.stream()
.map((traj) -> new Object[] {traj, find10MostSimilar(traj, allData, similarityCalculator)})
.collect(Collectors.toMap((value) -> (SemanticTrajectory) value[0], value -> (List<SemanticTrajectory>) value[1]));
List<SemanticTrajectory> keys = mostSimilarTrajs.keySet().stream().sorted(new Comparator<Object>() {
@Override
public int compare(Object o1, Object o2) {
return Double.compare((double) o1, (double) o2);
}
}).collect(Collectors.toList());
for (SemanticTrajectory key : keys) {
List<SemanticTrajectory> entries = mostSimilarTrajs.get(key);
String msg = String.format("colab = %d, dimensao_data = %d: ",
InvolvesDatabaseReader.USER_ID.getData(key, 0),
InvolvesDatabaseReader.DIMENSAO_DATA.getData(key, 0));
System.out.println(msg);
for (SemanticTrajectory t : entries) {
System.out.printf("\tcolab = %d, dimensao_data = %d, distancia = %.4f\n",
InvolvesDatabaseReader.USER_ID.getData(t, 0),
InvolvesDatabaseReader.DIMENSAO_DATA.getData(t, 0),
1 - similarityCalculator.getSimilarity(key, t));
}
}
// Validation validation = new Validation(groundtruthSemantic, (IMeasureDistance<SemanticTrajectory>) similarityCalculator, r);
// double[] precisionAtRecall = validation.precisionAtRecall(similarityCalculator, allData, 10);
// System.out.printf("Precision@recall(%d): %s\n", 10, ArrayUtils.toString(precisionAtRecall, "0.0"));
// double auc = AUC.precisionAtRecall(precisionAtRecall);
// System.out.printf("AUC: %.4f\n", auc);
}
private static List<SemanticTrajectory> find10MostSimilar(SemanticTrajectory traj, SemanticTrajectory[] allData, TrajectorySimilarityCalculator<SemanticTrajectory> similarityCalculator) {
Map<SemanticTrajectory, Double> ret = new HashMap<>();
for (SemanticTrajectory trajectory : allData) {
double similarity = similarityCalculator.getSimilarity(traj, trajectory);
ret.put(trajectory, 1 - similarity);
}
return ret.entrySet()
.stream()
.sorted(Comparator.comparing(Map.Entry::getValue))
.limit(10)
.map((entry) -> entry.getKey())
.collect(Collectors.toList());
}
}
|
package org.atlasapi.system;
import java.util.Collection;
import javax.annotation.PostConstruct;
import org.atlasapi.AtlasPersistenceModule;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.codahale.metrics.MetricRegistry;
import com.google.common.collect.ImmutableList;
import com.metabroadcast.common.health.HealthProbe;
import com.metabroadcast.common.health.probes.MemoryInfoProbe;
import com.metabroadcast.common.persistence.cassandra.health.CassandraProbe;
import com.metabroadcast.common.webapp.health.HealthController;
import com.metabroadcast.common.webapp.health.probes.MetricsProbe;
@Configuration
public class HealthModule {
private static final MetricRegistry metrics = new MetricRegistry();
private @Autowired Collection<HealthProbe> probes;
private @Autowired HealthController healthController;
private @Autowired AtlasPersistenceModule persistenceModule;
public @Bean HealthController healthController() {
return new HealthController(ImmutableList.of(
new MemoryInfoProbe(),
new CassandraProbe(persistenceModule.persistenceModule().getSession())
));
}
public @Bean org.atlasapi.system.HealthController threadController() {
return new org.atlasapi.system.HealthController(null);
}
public @Bean HealthProbe metricsProbe() {
return new MetricsProbe("Metrics", metrics());
}
public @Bean MetricRegistry metrics() {
return metrics;
}
@PostConstruct
public void addProbes() {
healthController.addProbes(probes);
}
}
|
package com.axelor.data.csv;
import groovy.lang.Binding;
import groovy.lang.GroovyCodeSource;
import groovy.lang.GroovyShell;
import groovy.lang.Script;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Objects;
import com.google.common.base.Objects.ToStringHelper;
import com.google.common.base.Strings;
import com.google.common.collect.Collections2;
import com.google.common.collect.Lists;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamAsAttribute;
import com.thoughtworks.xstream.annotations.XStreamImplicit;
@XStreamAlias("bind")
public class CSVBinding {
@XStreamAsAttribute
private String column;
@XStreamAlias("to")
@XStreamAsAttribute
private String field;
@XStreamAsAttribute
private String type;
@XStreamAsAttribute
private String search;
@XStreamAsAttribute
private boolean update;
@XStreamAlias("eval")
@XStreamAsAttribute
private String expression;
@XStreamAlias("if")
@XStreamAsAttribute
private String condition;
@XStreamImplicit(itemFieldName = "bind")
private List<CSVBinding> bindings;
public String getColumn() {
return column;
}
public String getField() {
return field;
}
public String getType() {
return type;
}
public String getSearch() {
return search;
}
public boolean isUpdate() {
return update;
}
public String getExpression() {
return expression;
}
public String getCondition() {
return condition;
}
public List<CSVBinding> getBindings() {
return bindings;
}
public static CSVBinding getBinding(final String column, final String field, Set<String> cols) {
CSVBinding cb = new CSVBinding();
cb.field = field;
cb.column = column;
if (cols == null || cols.isEmpty()) {
if (cb.column == null)
cb.column = field;
return cb;
}
for(String col : cols) {
if (cb.bindings == null)
cb.bindings = Lists.newArrayList();
cb.bindings.add(CSVBinding.getBinding(field + "." + col, col, null));
}
cb.update = true;
cb.search = Joiner.on(" AND ").join(Collections2.transform(cols, new Function<String, String>(){
@Override
public String apply(String input) {
return String.format("self.%s = :%s_%s_", input, field, input);
}
}));
return cb;
}
private Script script;
private Object _eval(final String expr, Map<String, Object> context) {
if (script == null) {
GroovyCodeSource gcs = AccessController.doPrivileged(new PrivilegedAction<GroovyCodeSource>() {
public GroovyCodeSource run() {
return new GroovyCodeSource(expr, "T" + column, "/groovy/shell");
}
});
GroovyShell shell = new GroovyShell();
script = shell.parse(gcs);
}
script.setBinding(new Binding(context));
return script.run();
}
public Object eval(Map<String, Object> context) {
if (Strings.isNullOrEmpty(expression))
return context.get(column);
return _eval(expression, context);
}
public boolean validate(Map<String, Object> context) {
if (Strings.isNullOrEmpty(condition))
return true;
String expr = condition + " ? true : false";
return (Boolean) _eval(expr, context);
}
@Override
public String toString() {
ToStringHelper ts = Objects.toStringHelper(this);
if (column != null) ts.add("column", column);
if (field != null) ts.add("field", field);
if (type != null) ts.add("type", type);
if (bindings != null) ts.add("bindings", bindings).toString();
return ts.toString();
}
}
|
package com.board.gd.domain.user;
import com.board.gd.domain.company.CompanyService;
import com.board.gd.exception.UserException;
import com.board.gd.mail.MailMessage;
import com.board.gd.mail.MailService;
import com.board.gd.slack.SlackManager;
import com.board.gd.utils.DateUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.UUID;
import java.util.stream.Collectors;
@Transactional(readOnly = true)
@Service
public class UserService implements UserDetailsService {
private static final Date DEFAULT_ROLE_EXPIRED_DATE = new Date(4150537200000L); // 2099 12 31
@Value("${server.host}")
private String serverHost;
@Value("${charge.period}")
private int chargePeriod;
@Autowired
private UserRepository userRepository;
@Autowired
private UserRoleRepository userRoleRepository;
@Autowired
private MailService mailService;
@Autowired
private CompanyService companyService;
@Autowired
private SlackManager slackManager;
private static final BCryptPasswordEncoder bcryptEncoder = new BCryptPasswordEncoder();
public User findOne(Long id) {
return userRepository.findOne(id);
}
public User findByEmail(String email) {
return userRepository.findByEmail(email);
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
return findByEmail(username);
}
public List<GrantedAuthority> findRolesByUserId(Long userId) {
return userRoleRepository.findByUserId(userId).stream()
.filter(userRole -> !DateUtils.isExpired(userRole.getExpiredAt())) // role
.map(userRole -> userRole.getRole().name())
.map(SimpleGrantedAuthority::new)
.collect(Collectors.toList());
}
public List<UserRole> getUserRoles(Long userId) {
return userRoleRepository.findByUserId(userId).stream()
.filter(userRole -> !DateUtils.isExpired(userRole.getExpiredAt())) // role
.collect(Collectors.toList());
}
public List<Long> findRolesExpiredSoon() {
LocalDateTime expiredCriteriaLdt = LocalDateTime.now().plusDays(1);
Date expiredCriteriaDate = Date.from(expiredCriteriaLdt.atZone(ZoneId.systemDefault()).toInstant());
return userRoleRepository.findByExpiredAtBefore(expiredCriteriaDate).stream()
.map(userRole -> userRole.getUser().getId())
.collect(Collectors.toList());
}
@Transactional(readOnly = false)
public void upsertPaidRole(Long userId) {
User user = userRepository.findOne(userId);
UserRole paidRole = userRoleRepository.findByUserId(userId).stream()
.filter(userRole -> userRole.getRole() == UserRoleType.ROLE_PAID)
.findFirst().orElse(null);
LocalDateTime expiredLdt = LocalDateTime.now().plusDays(chargePeriod);
Date expiredDate = Date.from(expiredLdt.atZone(ZoneId.systemDefault()).toInstant());
if (!Objects.isNull(paidRole)) {
updateUserRole(paidRole, expiredDate);
} else {
createUserRole(user, UserRoleType.ROLE_PAID, expiredDate);
}
}
@Transactional(readOnly = false)
public UserRole createUserRole(User user, UserRoleType userRole, Date expiredAt) {
if (Objects.isNull(user)) {
throw new UserException("Fail createUserRole!");
}
return userRoleRepository.save(UserRole.builder()
.role(userRole)
.user(user)
.expiredAt(expiredAt)
.build());
}
@Transactional(readOnly = false)
public void updateUserRole(UserRole userRole, Date expiredAt) {
userRole.setExpiredAt(expiredAt);
userRoleRepository.save(userRole);
}
@Transactional(readOnly = false)
public User createUserEmail(UserDto userDto) {
User user = userRepository.findByEmail(userDto.getEmail());
companyService.getCompaniesByEmail(userDto.getEmail());
if (!Objects.isNull(user) && !user.getEnabled()) {
sendAuthEmail(user, "auth");
return user;
}
if (!Objects.isNull(user)) {
throw new UserException(" . .");
}
user = userRepository.save(User.builder()
.name("")
.email(userDto.getEmail())
.authUUID(UUID.randomUUID().toString())
.enabled(false)
.withdrawn(false)
.build());
sendAuthEmail(user, "auth");
slackManager.sendPaymentMessage("[ ] email: " + userDto.getEmail());
return user;
}
@Transactional(readOnly = false)
public User updateAuthInfo(UserDto userDto) {
User user = userRepository.findByEmail(userDto.getEmail());
if (Objects.isNull(user)) {
throw new UserException(" .");
}
user.setAuthUUID(UUID.randomUUID().toString());
user = userRepository.save(user);
sendAuthEmail(user, "password");
return user;
}
@Transactional(readOnly = false)
public User create(UserDto userDto) {
User user = userRepository.save(User.builder()
.name(userDto.getName())
.email(userDto.getEmail())
.password(bcryptEncoder.encode(userDto.getPassword()))
.profileImg(userDto.getProfileImg())
.authUUID(UUID.randomUUID().toString())
.enabled(false)
.withdrawn(false)
.build());
sendAuthEmail(user, "auth");
createUserRole(user, UserRoleType.ROLE_USER, DEFAULT_ROLE_EXPIRED_DATE);
return user;
}
@Transactional(readOnly = false)
public User update(UserDto userDto) {
User user = userRepository.findOne(userDto.getId());
if (!Objects.isNull(userDto.getName())) {
user.setName(userDto.getName());
}
if (!Objects.isNull(userDto.getPassword())) {
user.setPassword(bcryptEncoder.encode(userDto.getPassword()));
}
if (!Objects.isNull(userDto.getCompanyId())) {
user.setCompany(companyService.findOne(userDto.getCompanyId()));
}
return userRepository.save(user);
}
@Transactional(readOnly = false)
public User withdraw(Long userId) {
User user = userRepository.findOne(userId);
user.setEmail("withdraw." + user.getEmail());
user.setWithdrawn(true);
return userRepository.save(user);
}
@Transactional(readOnly = false)
public User updateUserData(UserDto userDto) {
if (!Objects.isNull(userDto.getName()) && userDto.getName().length() < 2) {
throw new UserException(" .(2 )");
}
if (!Objects.isNull(userDto.getPassword()) && userDto.getPassword().length() < 6) {
throw new UserException(" .(6 )");
}
User user = userRepository.findOne(userDto.getId());
if (!user.getAuthUUID().equals(userDto.getUuid())) {
throw new UserException(" .");
}
update(userDto);
createUserRole(user, UserRoleType.ROLE_USER, DEFAULT_ROLE_EXPIRED_DATE);
return userRepository.save(user);
}
public long count() {
return userRepository.count();
}
public List<User> findAll() {
return userRepository.findAll();
}
@Transactional(readOnly = false)
public void deleteAll() {
userRepository.deleteAll();
}
@Transactional(readOnly = false)
public User authUser(Long id, String uuid) {
User user = findOne(id);
if (Objects.isNull(user)) {
throw new UserException("User not exist!");
}
if (ObjectUtils.notEqual(user.getAuthUUID(), uuid)) {
throw new UserException("Invalid UUID!");
}
user.setEnabled(true);
user.setAuthUUID("expired");
userRepository.save(user);
return user;
}
public void setAuthentication(Authentication authentication) {
SecurityContextHolder.getContext().setAuthentication(authentication);
}
public User getCurrentUser() {
Object userDetail = SecurityContextHolder.getContext().getAuthentication().getDetails();
if (!(userDetail instanceof User)) {
throw new UserException("Not authenticated!");
}
User user = (User) userDetail;
return userRepository.findOne(user.getId());
}
public void clearAuthentication() {
SecurityContextHolder.clearContext();
}
public boolean matchPassword(String rawPassword, String encodedPassword) {
return bcryptEncoder.matches(rawPassword, encodedPassword);
}
public void sendAuthEmail(User user, String type) {
MailMessage mailMessage = new MailMessage();
mailMessage.setTo(user.getEmail());
StringBuilder sb = new StringBuilder();
if (type.equals("auth")) {
mailMessage.setSubject("[] .");
sb.append(" !\n");
}
if (type.equals("password")) {
mailMessage.setSubject("[] .");
sb.append(" !\n");
}
sb.append(serverHost);
sb.append("/users/");
sb.append(user.getId());
sb.append("/auth?type=");
sb.append(type);
sb.append("&uuid=");
sb.append(user.getAuthUUID());
mailMessage.setText(sb.toString());
mailService.send(mailMessage);
}
}
|
package com.yahoo.lang;
/**
* A mutable boolean
*
* @author bratseth
*/
public class MutableBoolean {
private boolean value;
public MutableBoolean(boolean value) {
this.value = value;
}
public boolean get() { return value; }
public void set(boolean value) { this.value = value; }
public void andSet(boolean value) { this.value &= value; }
public void orSet(boolean value) { this.value |= value; }
@Override
public String toString() { return Boolean.toString(value); }
}
|
package org.noear.weed;
import org.noear.weed.wrap.*;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
class DbContextMetaData {
protected String _schema;
protected String _catalog;
private transient Map<String, TableWrap> _tables = new HashMap<>();
private transient DbType _dbType = DbType.Unknown;
private transient DbAdapter _dbAdapter;
private transient DataSource __dataSource; //dataSourceSet
public DataSource dataSource() {
return __dataSource;
}
protected void dataSourceDoSet(DataSource ds) {
__dataSource = ds;
}
public Connection getConnection() throws SQLException {
return dataSource().getConnection();
}
public DbType dbType() {
initMetaData();
return _dbType;
}
public DbAdapter dbAdapter() {
initMetaData();
return _dbAdapter;
}
public void dbAdapterSet(DbAdapter adapter){
initMetaData();
_dbAdapter = adapter;
}
public Collection<TableWrap> dbTables() {
initMetaData();
return _tables.values();
}
public TableWrap dbTable(String tableName) {
initMetaData();
for (Map.Entry<String, TableWrap> kv : _tables.entrySet()) {
if (tableName.equalsIgnoreCase(kv.getKey())) {
return kv.getValue();
}
}
return null;
}
public String dbTablePk1(String tableName) {
TableWrap tw = dbTable(tableName);
return tw == null ? null : tw.getPk1();
}
public void refreshMeta(){
initMetaDataDo();
}
private void initMetaData() {
if (_dbAdapter != null) {
return;
}
initMetaDataDo();
}
private synchronized void initMetaDataDo() {
System.out.println("Weed3::Init metadata");
Connection conn = null;
try {
System.out.println("Weed3::Start testing database connectivity...");
conn = getConnection();
DatabaseMetaData md = conn.getMetaData();
System.out.println("Weed3::The connection is successful");
if (_dbAdapter == null) {
setDatabaseType(md.getDatabaseProductName());
setSchema(conn);
}
setTables(md);
} catch (Throwable ex) {
System.out.println("Weed3::The connection error");
ex.printStackTrace();
} finally {
if (conn != null) {
try {
conn.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
private void setDatabaseType(String driverName) {
if (driverName != null) {
String pn = driverName.toLowerCase().replace(" ", "");
if (pn.indexOf("mysql") >= 0) {
_dbType = DbType.MySQL;
_dbAdapter = new DbMySQLAdapter();
} else if (pn.indexOf("mariadb") >= 0) {
_dbType = DbType.MariaDB;
_dbAdapter = new DbMySQLAdapter();
} else if (pn.indexOf("sqlserver") >= 0) {
_dbType = DbType.SQLServer;
_dbAdapter = new DbSQLServerAdapter();
} else if (pn.indexOf("oracle") >= 0) {
_dbType = DbType.Oracle;
_dbAdapter = new DbOracleAdapter();
} else if (pn.indexOf("postgresql") >= 0) {
_dbType = DbType.PostgreSQL;
_dbAdapter = new DbPostgreSQLAdapter();
} else if (pn.indexOf("db2") >= 0) {
_dbType = DbType.DB2;
_dbAdapter = new DbDb2Adapter();
} else if (pn.indexOf("sqlite") >= 0) {
_dbType = DbType.SQLite;
_dbAdapter = new DbSQLiteAdapter();
} else if (pn.indexOf("h2") >= 0) {
_dbType = DbType.H2;
_dbAdapter = new DbH2Adapter();
} else {
_dbAdapter = new DbMySQLAdapter();
}
}
}
private void setSchema(Connection conn) throws SQLException {
try {
_catalog = conn.getCatalog();
} catch (Throwable e) {
e.printStackTrace();
}
if (_schema != null) {
return;
}
try {
_schema = conn.getSchema();
} catch (Throwable e) {
switch (_dbType) {
case PostgreSQL:
_schema = "public";
break;
case H2:
_schema = "PUBLIC";
break;
case SQLServer:
_schema = "dbo";
case Oracle:
_schema = conn.getMetaData().getUserName();
break;
}
}
}
private void setTables(DatabaseMetaData md) throws SQLException {
ResultSet rs = null;
rs = dbAdapter().getTables(md,_catalog,_schema);
while (rs.next()) {
String name = rs.getString("TABLE_NAME");
String remarks = rs.getString("REMARKS");
TableWrap tWrap = new TableWrap(name, remarks);
_tables.put(name, tWrap);
}
rs.close();
for (String key : _tables.keySet()) {
TableWrap tWrap = _tables.get(key);
rs = md.getColumns(_catalog, _schema, key, "%");
while (rs.next()) {
int digit = 0;
Object o = rs.getObject("DECIMAL_DIGITS");
if (o != null) {
digit = ((Number) o).intValue();
}
ColumnWrap cw = new ColumnWrap(
rs.getString("COLUMN_NAME"),
rs.getInt("DATA_TYPE"),
rs.getInt("COLUMN_SIZE"),
digit,
rs.getString("REMARKS")
);
tWrap.addColumn(cw);
}
rs.close();
rs = md.getPrimaryKeys(_catalog, _schema, key);
while (rs.next()) {
String idName = rs.getString("COLUMN_NAME");
tWrap.addPk(idName);
}
rs.close();
}
}
}
|
package io.github.lxgaming.lxquest;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.java.JavaPlugin;
public class LXQuest extends JavaPlugin {
@Override
public void onEnable() {
getLogger().info("LXQuest Has Started!");
}
@Override
public void onDisable() {
getLogger().info("LXQuest Has Stopped!");
}
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
Player player = (Player) sender;
if (cmd.getName().equalsIgnoreCase("Quest") && sender instanceof Player) {
player.sendRawMessage("List Of Commands");
player.sendRawMessage("1 This command");
return true;
}
return false;
}
}
|
package edu.utoledo.nlowe.postfix;
import edu.utoledo.nlowe.CustomDataTypes.CustomStack;
import edu.utoledo.nlowe.postfix.exception.PostfixArithmeticException;
import edu.utoledo.nlowe.postfix.exception.PostfixOverflowException;
import edu.utoledo.nlowe.postfix.exception.PostfixUnderflowException;
import java.util.Collections;
import java.util.HashMap;
import java.util.Set;
import java.util.regex.Pattern;
/**
* A math engine that accepts string expressions in postfix notation as an integer.
* <p>
* All literals must be integers, and all operations will be rounded to an integer.
* <p>
* The following binary operations are supported by default:
* <ul>
* <li>'<': Addition</li>
* <li>'-': Subtraction</li>
* <li>'*' or 'x': Multiplication</li>
* <li>'/': Division</li>
* <li>'%': Modulus</li>
* <li>'^': Exponentiation</li>
* <li>'<': Left Shift</li>
* <li>'>': Right Shift</li>
* </ul>
* <p>
* The following unary operators are supported by default:
* <ul>
* <li>'Q' Square Root</li>
* <li>'C' Cube Root</li>
* </ul>
* <p>
* Additional operators may be registered by calling <code>register()</code> and
* passing a lambda for either a <code>BinaryOperator</code> or a <code>UnaryOperator</code>
*/
public class PostfixEngine
{
/** A regular expression that matches a single integer (positive, or negative) */
public static final String NUMERIC_REGEX = "^(-)?[0-9]+$";
/** A regular expression that matches oen or more white-space characters. Used to split tokens in postfix notation */
public static final String TOKEN_SEPARATOR_REGEX = "\\s+";
/** A part of a regular expression that matches the preceding characters not immediately followed by a number, understore, or opening parenthesis*/
public static final String NOT_FOLLOWED_BY_NUMBER_OR_PARENTHESIS_REGEX = "(?![0-9\\(_])";
/** All operators registered with the engine */
private final HashMap<String, Operator> operators = new HashMap<>();
public PostfixEngine()
{
// Register default valid operators
register("+", (a, b) -> a + b);
register("-", (a, b) -> a - b);
register("x", (a, b) -> a * b);
register("*", (a, b) -> a * b);
register("/", (a, b) -> a / b);
register("%", (a, b) -> a % b);
register("^", (a, b) -> (long) Math.pow(a, b));
register("<", (a, b) -> a << b);
register(">", (a, b) -> a >> b);
register("Q", (a) -> (long) Math.sqrt(a));
register("C", (a) -> (long) Math.cbrt(a));
}
/**
* Converts the given expression from infix notation to postfix notation
* <p>
* A valid infix expression must meet all of the following requirements:
* <ul>
* <li>Is not empty</li>
* <li>All parenthesis must be matched</li>
* <li>All unary operators must have an operand or group immediately following them</li>
* <li>Must not contain invalid tokens (non-numeric non-parenthesis characters that are not registered operators)</li>
* </ul>
*
* @param expression a valid expression in infix notation
* @return The equivalent postfix expression
*/
public String convertInfixExpression(String expression)
{
// Validate and simplify the expression
// An exception will be thrown if the expression fails validation
String simplifiedExpression = validateAndSimplifyInfixExpression(expression);
// Create a buffer to hold the resulting postfix expression and a buffer for groups / operators
StringBuilder result = new StringBuilder();
CustomStack<String> buffer = new CustomStack<>();
int index = 0;
do
{
if (simplifiedExpression.charAt(index) == '_')
{
// An underscore indicates spacing for a mixed separator style
// Skip the underscore and move on
index++;
continue;
}
// Extract the next token and increment the index by its length
String token = extractInfixToken(simplifiedExpression, index);
index += token.length();
// Now that we've extracted the token, we can parse it
if (token.length() == 1 && isValidOperator(token))
{
// Convert everything this operator needs
while (buffer.size() > 0 && !buffer.peek().equals("("))
{
//Operator Precedence is ignored for this project
result.append(buffer.pop()).append(" ");
}
buffer.push(token);
}
else if (token.equals("("))
{
buffer.push(token);
}
else if (token.equals(")"))
{
// End of sub group
while (!buffer.peek().equals("("))
{
result.append(buffer.pop()).append(" ");
}
buffer.pop();
}
else
{
// Just a literal, append it
result.append(token).append(" ");
}
} while (index < simplifiedExpression.length());
// Append any extra operators left on the expression
while (buffer.size() > 0)
{
result.append(buffer.pop()).append(" ");
}
return result.toString().trim();
}
public String validateAndSimplifyInfixExpression(String expression){
if (expression == null || expression.length() == 0)
{
throw new IllegalArgumentException("Nothing to convert");
}
// Infix expressions must have matched parenthesis
int parenthesisCounter = 0;
for (char c : expression.toCharArray())
{
// Increment the counter for opening parenthesis, decrement the counter for closing parenthesis
parenthesisCounter += (c == '(' ? 1 : (c == ')' ? -1 : 0));
}
// If the counter is not at zero, then we have an unmatched parenthesis somewhere
if (parenthesisCounter != 0)
{
throw new IllegalArgumentException("Malformed infix expression (unmatched parenthesis): '" + expression + "'");
}
// Not all infix expressions are delimited by tabs or spaces
// Strip them out, replacing them with underscores to detect mixed separator styles
// Then, parse the expression character by character
String simplifiedExpression = expression.replaceAll(TOKEN_SEPARATOR_REGEX, "_");
// Unary operators in infix notation cannot come after their operands
// Build a regex looking for any unary operator that is not followed by a number or opening parenthesis
StringBuilder unaryValidator = new StringBuilder().append("[");
operators.keySet().stream().filter(o -> operators.get(o) instanceof UnaryOperator).forEach(unaryValidator::append);
unaryValidator.append("]").append(NOT_FOLLOWED_BY_NUMBER_OR_PARENTHESIS_REGEX);
// Test the simplified expression to validate unary operators
if (Pattern.compile(unaryValidator.toString()).matcher(simplifiedExpression).find())
{
throw new IllegalArgumentException("Malformed infix expression (missing operand for unary operator): '" + expression + "'");
}
return simplifiedExpression;
}
private String extractInfixToken(String expression, int offset){
if (expression.charAt(offset) == '(' ||
expression.charAt(offset) == ')' ||
isValidOperator(String.valueOf(expression.charAt(offset)))
)
{
// The token is just a parenthesis or operator
return String.valueOf(expression.charAt(offset));
}
else if (String.valueOf(expression.charAt(offset)).matches(NUMERIC_REGEX))
{
// The token is a number or the start of a number
StringBuilder currentToken = new StringBuilder(String.valueOf(expression.charAt(offset++)));
// While there are more numbers remaining, append them to the currentToken String Builder
boolean moreNumbers;
do
{
if (offset < expression.length() && String.valueOf(expression.charAt(offset)).matches(NUMERIC_REGEX))
{
currentToken.append(expression.charAt(offset++));
moreNumbers = true;
}
else
{
moreNumbers = false;
}
} while (moreNumbers);
// We've found the entire number
return currentToken.toString();
}
else
{
throw new IllegalArgumentException("Unrecognized token '" + expression.charAt(offset) + "'");
}
}
/**
* Registers the token <code>token</code> to the specified binary operator functional interface.
* <p>
* If the specified token is already assigned to an operator, it will be overwritten.
*
* @param token The token that denotes the operator
* @param operator The functional interface to apply tokens to when this operator is encountered
*/
public void register(String token, BinaryOperator operator)
{
operators.put(token, operator);
}
/**
* Registers the token <code>token</code> to the specified unary operator functional interface.
* <p>
* If the specified token is already assigned to an operator, it will be overwritten.
*
* @param token The token that denotes the operator
* @param operator The functional interface to apply tokens to when this operator is encountered
*/
public void register(String token, UnaryOperator operator)
{
operators.put(token, operator);
}
public long evaluate(String expression) throws IllegalArgumentException, PostfixArithmeticException
{
CustomStack<Long> buffer = new CustomStack<>();
// Split the expression into tokens by white space (one or more of either a space or a tab)
String[] parts = expression.trim().split(TOKEN_SEPARATOR_REGEX);
for (String token : parts)
{
if (isValidOperator(token))
{
// Try to evaluate the operator based on what is already on the stack
Operator op = getEvaluatorFunction(token);
if (op instanceof BinaryOperator)
{
// Binary operators need at least two operands on the stack
if (buffer.size() < 2)
{
throw new IllegalArgumentException("Malformed postfix expression (not enough literals): '" + expression + "'");
}
// Extract the arguments backwards because we're using a stack
long b = buffer.pop();
long a = buffer.pop();
// Push the result onto the stack
buffer.push(((BinaryOperator) op).evaluate(a, b));
}
else if (op instanceof UnaryOperator)
{
// Unary Operators need at least one operand on the stack
if (buffer.size() == 0)
{
throw new IllegalArgumentException("Malformed postfix expression (not enough literals): '" + expression + "'");
}
// Pop the operand off of the stack, and push the evaluated result onto the stack
buffer.push(((UnaryOperator) op).evaluate(buffer.pop()));
}
}
else if (token.matches(NUMERIC_REGEX))
{
// Just an integer, push it onto the stack
buffer.push(Long.parseLong(token));
}
else
{
// Not a valid operator or literal
throw new IllegalArgumentException("Malformed postfix expression (unrecognized token " + token + "): '" + expression + "'");
}
}
// If we're left with more than one item on the stack, then the expression has too many literals
if (buffer.size() != 1)
{
throw new IllegalArgumentException("Malformed postfix expression (too many literals): '" + expression + "'");
}
// The result is the only thing left on the stack
long result = buffer.pop();
// Check for overflow / underflow
if (result > Integer.MAX_VALUE)
{
throw new PostfixOverflowException(result, "Integer overflow while evaluating expression '" + expression + "'");
}
else if (result < Integer.MIN_VALUE)
{
throw new PostfixUnderflowException(result, "Integer underflow while evaluating expression '" + expression + "'");
}
else
{
return result;
}
}
/**
* Evaluates the specified infix expression by first converting to postfix and then evaluating the result
*
* @param expression A valid infix expression
* @return the integer result of the evaluated expression
*/
public long evaluateInfix(String expression)
{
return evaluate(convertInfixExpression(expression));
}
/**
* Gets the operator assigned to the specified token
*
* @param operator the token representing the operator
* @return the operator's functional interface that is registered to the token
*/
public Operator getEvaluatorFunction(String operator)
{
if (!isValidOperator(operator))
{
throw new IllegalArgumentException("Undefined postfix operator: " + operator);
}
return operators.get(operator);
}
/**
* @param operator the operator to check
* @return <code>true</code> if and only if the specified operator is registered
*/
public boolean isValidOperator(String operator)
{
return operators.keySet().contains(operator);
}
/**
* @return The unmodifiable set of all registered operator tokens
*/
public Set<String> getSupportedOperators()
{
return Collections.unmodifiableSet(operators.keySet());
}
}
|
package org.noear.weed;
import org.noear.weed.cache.CacheUsing;
import org.noear.weed.cache.ICacheController;
import org.noear.weed.cache.ICacheService;
import org.noear.weed.ext.Act1;
import org.noear.weed.ext.Act2;
import org.noear.weed.utils.StringUtils;
import org.noear.weed.wrap.DbType;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
public class DbTableQueryBase<T extends DbTableQueryBase> extends WhereBase<T> implements ICacheController<DbTableQueryBase> {
String _table_raw;
String _table;
SQLBuilder _builder_bef;
int _isLog=0;
public DbTableQueryBase(DbContext context) {
super(context);
_builder_bef = new SQLBuilder();
}
public T log(boolean isLog) {
_isLog = isLog ? 1 : -1;
return (T) this;
}
/**
* build
* */
@Deprecated
public T expre(Act1<T> action){
action.run((T)this);
return (T)this;
}
public T build(Act1<T> builder){
builder.run((T)this);
return (T)this;
}
protected T table(String table) { // from
if (table.startsWith("
_table = table.substring(1);
_table_raw = _table;
} else {
_table_raw = table;
if (table.indexOf('.') > 0) {
_table = table;
} else {
if (WeedConfig.isUsingSchemaPrefix && _context.schema() != null) {
_table = fmtObject(_context.schema() + "." + table);
} else {
_table = fmtObject(table); //"$." + table;
}
}
}
return (T) this;
}
/** SQL with
*
* db.table("user u")
* .with("a","select type num from group by type")
* .where("u.type in(select a.type) and u.type2 in (select a.type)")
* .select("u.*")
* .getMapList();
* */
public T with(String name, String code, Object... args) {
if (_builder_bef.length() < 6) {
_builder_bef.append(" WITH ");
}else{
_builder_bef.append("," );
}
_builder_bef.append(fmtColumn(name))
.append(" AS (")
.append(code, args)
.append(") ");
return (T) this;
}
public T with(String name, SelectQ select) {
if (_builder_bef.length() < 6) {
_builder_bef.append(" WITH ");
}else{
_builder_bef.append("," );
}
_builder_bef.append(fmtColumn(name))
.append(" AS (")
.append(select)
.append(") ");
return (T) this;
}
/** FROM */
public T from(String table){
_builder.append(" FROM ").append(fmtObject(table));
return (T)this;
}
private T join(String style, String table) {
if (table.startsWith("
_builder.append(style).append(table.substring(1));
} else {
if (WeedConfig.isUsingSchemaPrefix && _context.schema() != null) {
_builder.append(style).append(fmtObject(_context.schema() + "." + table));
} else {
_builder.append(style).append(fmtObject(table));
}
}
return (T) this;
}
/** SQL */
public T innerJoin(String table) {
return join(" INNER JOIN ",table);
}
/** SQL */
public T leftJoin(String table) {
return join(" LEFT JOIN ",table);
}
/** SQL */
public T rightJoin(String table) {
return join(" RIGHT JOIN ",table);
}
public T append(String code, Object... args){
_builder.append(code, args);
return (T)this;
}
public T on(String code) {
_builder.append(" ON ").append(code);
return (T)this;
}
public T onEq(String column1, String column2) {
_builder.append(" ON ").append(fmtColumn(column1)).append("=").append(fmtColumn(column2));
return (T) this;
}
/** dataBuilder */
public long insert(Act1<IDataItem> dataBuilder) throws SQLException
{
DataItem item = new DataItem();
dataBuilder.run(item);
return insert(item);
}
/** data */
public long insert(IDataItem data) throws SQLException {
if (data == null || data.count() == 0) {
return 0;
}
_builder.clear();
_context.dbDialect()
.insertItem(_context, _table, _builder, this::isSqlExpr, _usingNull, data);
return compile().insert();
}
public long insertBy(IDataItem data, String conditionFields) throws SQLException {
if (data == null || data.count() == 0) {
return 0;
}
String[] ff = conditionFields.split(",");
if (ff.length == 0) {
throw new RuntimeException("Please enter constraints");
}
if (dbType() == DbType.MySQL || dbType() == DbType.MariaDB) {
_builder.clear();
_context.dbDialect()
.insertItem(_context, _table, _builder, this::isSqlExpr, _usingNull, data);
_builder.insert(6," IGNORE ");
return compile().insert();
} else {
this.where("1=1");
for (String f : ff) {
this.andEq(f, data.get(f));
}
if (this.exists()) {
return 0;
}
return insert(data);
}
}
public boolean insertList(List<DataItem> valuesList) throws SQLException {
if (valuesList == null) {
return false;
}
return insertList(valuesList.get(0), valuesList);
}
/** dataBuilder */
public <T> boolean insertList(Collection<T> valuesList, Act2<T,DataItem> dataBuilder) throws SQLException {
List<DataItem> list2 = new ArrayList<>();
for (T values : valuesList) {
DataItem item = new DataItem();
dataBuilder.run(values, item);
list2.add(item);
}
if (list2.size() > 0) {
return insertList(list2.get(0), list2);
}else{
return false;
}
}
protected <T extends GetHandler> boolean insertList(IDataItem cols, Collection<T> valuesList)throws SQLException {
if (valuesList == null || valuesList.size() == 0) {
return false;
}
if (cols == null || cols.count() == 0) {
return false;
}
_context.dbDialect()
.insertList(_context, _table, _builder, this::isSqlExpr, cols, valuesList);
return compile().execute() > 0;
}
/** data,
*
* upsertBy
* */
@Deprecated
public void updateExt(IDataItem data, String conditionFields) throws SQLException {
upsertBy(data, conditionFields);
}
/** data,
*
* upsertBy
* */
@Deprecated
public long upsert(IDataItem data, String conditionFields) throws SQLException {
return upsertBy(data,conditionFields);
}
/**
* data,
* */
public long upsertBy(IDataItem data, String conditionFields) throws SQLException {
if (data == null || data.count() == 0) {
return 0;
}
String[] ff = conditionFields.split(",");
if (ff.length == 0) {
throw new RuntimeException("Please enter constraints");
}
if (dbType() == DbType.MySQL || dbType() == DbType.MySQL) {
_builder.clear();
_context.dbDialect()
.insertItem(_context, _table, _builder, this::isSqlExpr, _usingNull, data);
_builder.append("ON DUPLICATE KEY UPDATE ");
for (String f : ff) {
data.remove(f);
}
List<Object> args = new ArrayList<Object>();
StringBuilder sb = new StringBuilder();
updateItemsBuild0(data, sb, args);
_builder.append(sb.toString(), args.toArray());
return compile().insert();
} else {
this.where("1=1");
for (String f : ff) {
this.andEq(f, data.get(f));
}
if (this.exists()) {
for (String f : ff) {
data.remove(f);
}
return this.update(data);
} else {
return this.insert(data);
}
}
}
/** dataBuilder */
public int update(Act1<IDataItem> dataBuilder) throws SQLException
{
DataItem item = new DataItem();
dataBuilder.run(item);
return update(item);
}
/** set */
public int update(IDataItem data) throws SQLException{
if (data == null || data.count() == 0) {
return 0;
}
List<Object> args = new ArrayList<Object>();
StringBuilder sb = new StringBuilder();
sb.append("UPDATE ").append(_table).append(" SET ");
updateItemsBuild0(data, sb, args);
_builder.backup();
_builder.insert(sb.toString(), args.toArray());
if(WeedConfig.isUpdateMustConditional && _builder.indexOf(" WHERE ")<0){
throw new RuntimeException("Lack of update condition!!!");
}
int rst = compile().execute();
_builder.restore();
return rst;
}
private void updateItemsBuild0(IDataItem data, StringBuilder buf, List<Object> args) {
data.forEach((key, value) -> {
if (value == null) {
if (_usingNull) {
buf.append(fmtColumn(key)).append("=null,");
}
return;
}
if (value instanceof String) {
String val2 = (String) value;
if (isSqlExpr(val2)) {
buf.append(fmtColumn(key)).append("=").append(val2.substring(1)).append(",");
} else {
buf.append(fmtColumn(key)).append("=?,");
args.add(value);
}
} else {
buf.append(fmtColumn(key)).append("=?,");
args.add(value);
}
});
buf.deleteCharAt(buf.length() - 1);
}
public int delete() throws SQLException {
StringBuilder sb = StringUtils.borrowBuilder();
sb.append("DELETE ");
if(_builder.indexOf(" FROM ")<0){
sb.append(" FROM ").append(_table);
}else{
sb.append(_table);
}
_builder.insert(StringUtils.releaseBuilder(sb));
if(WeedConfig.isDeleteMustConditional && _builder.indexOf(" WHERE ")<0){
throw new RuntimeException("Lack of delete condition!!!");
}
return compile().execute();
}
protected int limit_start, limit_size;
/** SQL paging */
public T limit(int start, int size) {
limit_start = start;
limit_size = size;
//_builder.append(" LIMIT " + start + "," + rows + " ");
return (T)this;
}
protected int limit_top = 0;
/** SQL top */
public T limit(int size) {
limit_top = size;
//_builder.append(" LIMIT " + rows + " ");
return (T)this;
}
/** SQL paging */
public T paging(int start, int size) {
limit_start = start;
limit_size = size;
//_builder.append(" LIMIT " + start + "," + rows + " ");
return (T)this;
}
/** SQL top */
public T top(int size) {
limit_top = size;
//_builder.append(" LIMIT " + rows + " ");
return (T)this;
}
@Deprecated
public boolean exists() throws SQLException {
return selectExists();
}
String _hint = null;
public T hint(String hint){
_hint = hint;
return (T)this;
}
@Deprecated
public long count() throws SQLException{
return selectCount();
//return count("COUNT(*)");
}
@Deprecated
public long count(String code) throws SQLException{
return selectCount(code);
//return selectDo(code).getVariate().longValue(0l);
}
@Deprecated
public IQuery select(String columns) {
return selectDo(columns);
}
protected IQuery selectDo(String columns) {
select_do(columns, true);
DbQuery rst = compile();
if(_cache != null){
rst.cache(_cache);
}
_builder.restore();
return rst;
}
public boolean selectExists() throws SQLException {
int bak = limit_top;
limit(1);
select_do(" 1 ", false);
limit(bak);
DbQuery rst = compile();
if (_cache != null) {
rst.cache(_cache);
}
_builder.restore();
return rst.getValue() != null;
}
public long selectCount() throws SQLException{
return selectCount("COUNT(*)");
}
public long selectCount(String column) throws SQLException{
return selectDo(column).getVariate().longValue(0L);
}
public Object selectValue(String column) throws SQLException {
return selectDo(column).getValue();
}
public <T> T selectValue(String column, T def) throws SQLException {
return selectDo(column).getValue(def);
}
public <T> T selectItem(String columns, Class<T> clz) throws SQLException {
return selectDo(columns).getItem(clz);
}
public <T> List<T> selectList(String columns, Class<T> clz) throws SQLException {
return selectDo(columns).getList(clz);
}
public Map<String,Object> selectMap(String columns) throws SQLException{
return selectDo(columns).getMap();
}
public List<Map<String, Object>> selectMapList(String columns) throws SQLException{
return selectDo(columns).getMapList();
}
public <T> List<T> selectArray(String column) throws SQLException{
return selectDo(column).getArray();
}
public SelectQ selectQ(String columns) {
select_do(columns, true);
return new SelectQ(_builder);
}
private void select_do(String columns, boolean doFormat) {
_builder.backup();
//1. xxx... FROM table
StringBuilder sb = new StringBuilder(_builder.builder.length() + 100);
sb.append(" ");
if (doFormat) {
sb.append(fmtMutColumns(columns)).append(" FROM ").append(_table);
} else {
sb.append(columns).append(" FROM ").append(_table);
}
sb.append(_builder.builder);
_builder.builder = sb;
if (limit_top > 0) {
_context.dbDialect().selectTop(_context, _table_raw, _builder, _orderBy, limit_top);
} else if (limit_size > 0) {
_context.dbDialect().selectPage(_context, _table_raw, _builder, _orderBy, limit_start, limit_size);
} else {
_builder.insert(0, "SELECT ");
if (_orderBy != null) {
_builder.append(_orderBy);
}
}
//3.hint
if (_hint != null) {
sb.append(_hint);
_builder.insert(0, _hint);
}
//4.whith
if (_builder_bef.length() > 0) {
_builder.insert(_builder_bef);
}
}
protected DbTran _tran = null;
@Deprecated
public T tran(DbTran transaction)
{
_tran = transaction;
return (T)this;
}
@Deprecated
public T tran()
{
_tran = _context.tran();
return (T)this;
}
//DbQuery
private DbQuery compile() {
DbQuery temp = new DbQuery(_context).sql(_builder);
_builder.clear();
if(_tran!=null) {
temp.tran(_tran);
}
return temp.onCommandBuilt((cmd)->{
cmd.isLog = _isLog;
cmd.tag = _table;
});
}
private boolean _usingNull = WeedConfig.isUsingValueNull;
/** null */
public T usingNull(boolean isUsing){
_usingNull = isUsing;
return (T)this;
}
private boolean _usingExpression = WeedConfig.isUsingValueExpression;
/** $sql */
public T usingExpr(boolean isUsing){
_usingExpression = isUsing;
return (T)this;
}
private boolean isSqlExpr(String txt) {
if (_usingExpression == false) {
return false;
}
if (txt.startsWith("$")
&& txt.indexOf(" ") < 0
&& txt.length() < 100) { //100
return true;
} else {
return false;
}
}
protected CacheUsing _cache = null;
public T caching(ICacheService service)
{
_cache = new CacheUsing(service);
return (T)this;
}
public T usingCache (boolean isCache)
{
_cache.usingCache(isCache);
return (T)this;
}
public T usingCache (int seconds)
{
_cache.usingCache(seconds);
return (T)this;
}
public T cacheTag(String tag)
{
_cache.cacheTag(tag);
return (T)this;
}
}
|
package org.cache2k.jcache;
import org.cache2k.Cache;
import org.cache2k.impl.BaseCache;
import javax.cache.CacheManager;
import javax.cache.configuration.CacheEntryListenerConfiguration;
import javax.cache.configuration.CompleteConfiguration;
import javax.cache.configuration.Configuration;
import javax.cache.configuration.MutableConfiguration;
import javax.cache.integration.CompletionListener;
import javax.cache.processor.EntryProcessor;
import javax.cache.processor.EntryProcessorException;
import javax.cache.processor.EntryProcessorResult;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* @author Jens Wilke; created: 2015-03-28
*/
public class Cache2kCacheAdapter<K, V> implements javax.cache.Cache<K, V> {
Cache2kManagerAdapter manager;
Cache<K, V> cache;
BaseCache<?, K, V> cacheImpl;
boolean storeByValue;
boolean readThrough = false;
/** Null, if no complete configuration is effective */
CompleteConfiguration<K, V> completeConfiguration;
public Cache2kCacheAdapter(Cache2kManagerAdapter _manager, Cache<K, V> _cache, boolean _storeByvalue, CompleteConfiguration<K, V> _completeConfiguration) {
manager = _manager;
cache = _cache;
cacheImpl = (BaseCache<?, K, V>) _cache;
completeConfiguration = _completeConfiguration;
storeByValue = _storeByvalue;
}
@Override
public V get(K k) {
checkClosed();
if (readThrough) {
return cache.get(k);
}
return cache.peek(k);
}
@Override
public Map<K, V> getAll(Set<? extends K> _keys) {
checkClosed();
if (readThrough) {
return cache.getAll(_keys);
}
return cache.peekAll(_keys);
}
@Override
public boolean containsKey(K key) {
checkClosed();
return cache.contains(key);
}
@Override
public void loadAll(Set<? extends K> keys, boolean replaceExistingValues, CompletionListener completionListener) {
throw new UnsupportedOperationException("jsr107 loadAll() not supported");
}
@Override
public void put(K k, V v) {
checkClosed();
if (v == null) {
throw new NullPointerException("null value not allowed");
}
cache.put(k, v);
}
@Override
public V getAndPut(K key, V _value) {
checkClosed();
checkNullValue(_value);
return cache.peekAndPut(key, _value);
}
private void checkNullValue(V _value) {
if (_value == null) {
throw new NullPointerException("null value not supported");
}
}
@Override
public void putAll(Map<? extends K, ? extends V> map) {
checkClosed();
if (map == null) {
throw new NullPointerException("null map parameter");
}
for (Map.Entry<? extends K, ? extends V> e : map.entrySet()) {
V v = e.getValue();
checkNullValue(e.getValue());
if (e.getKey() == null) {
throw new NullPointerException("null key not allowed");
}
}
for (Map.Entry<? extends K, ? extends V> e : map.entrySet()) {
V v = e.getValue();
cache.put(e.getKey(), e.getValue());
}
}
@Override
public boolean putIfAbsent(K key, V _value) {
checkClosed();
checkNullValue(_value);
return cache.putIfAbsent(key, _value);
}
@Override
public boolean remove(K key) {
return cacheImpl.removeWithFlag(key);
}
@Override
public boolean remove(K key, V oldValue) {
throw new UnsupportedOperationException("jsr107 remove(key, old) not supported");
}
@Override
public V getAndRemove(K key) {
throw new UnsupportedOperationException("jsr107 getAndRemove(key) not supported");
}
@Override
public boolean replace(K key, V oldValue, V newValue) {
throw new UnsupportedOperationException("jsr107 replace(k, old, new) not supported");
}
@Override
public boolean replace(K key, V value) {
throw new UnsupportedOperationException("jsr107 replace(k, v) not supported");
}
@Override
public V getAndReplace(K key, V value) {
throw new UnsupportedOperationException("jsr107 getAndReplace() not supported");
}
@Override
public void removeAll(Set<? extends K> keys) {
throw new UnsupportedOperationException("jsr107 removeAll(keys) not supported");
}
@Override
public void removeAll() {
throw new UnsupportedOperationException("jsr107 removeAll() not supported");
}
@Override
public void clear() {
cache.clear();
}
@SuppressWarnings("unchecked")
@Override
public <C extends Configuration<K, V>> C getConfiguration(Class<C> _class) {
if (_class.isAssignableFrom(CompleteConfiguration.class)) {
if (completeConfiguration != null) {
return (C) completeConfiguration;
}
MutableConfiguration<K, V> cfg = new MutableConfiguration<K, V>();
cfg.setTypes((Class<K>) cacheImpl.getKeyType(), (Class<V>) cacheImpl.getValueType());
cfg.setStoreByValue(storeByValue);
return (C) cfg;
} else {
return (C) new Configuration<K, V>() {
@Override
public Class<K> getKeyType() {
return (Class<K>) cacheImpl.getKeyType();
}
@Override
public Class<V> getValueType() {
return (Class<V>) cacheImpl.getValueType();
}
@Override
public boolean isStoreByValue() {
return storeByValue;
}
};
}
}
@Override
public <T> T invoke(K key, EntryProcessor<K, V, T> entryProcessor, Object... arguments) throws EntryProcessorException {
throw new UnsupportedOperationException("jsr107 invoke() not supported");
}
@Override
public <T> Map<K, EntryProcessorResult<T>> invokeAll(Set<? extends K> keys, EntryProcessor<K, V, T> entryProcessor, Object... arguments) {
throw new UnsupportedOperationException("jsr107 invokeAll() not supported");
}
@Override
public String getName() {
return cache.getName();
}
@Override
public CacheManager getCacheManager() {
return manager;
}
@Override
public void close() {
cache.close();
}
@Override
public boolean isClosed() {
return cache.isClosed();
}
@Override
public <T> T unwrap(Class<T> clazz) {
throw new UnsupportedOperationException("jsr107 unwrap() not supported");
}
@Override
public void registerCacheEntryListener(CacheEntryListenerConfiguration<K, V> cacheEntryListenerConfiguration) {
throw new UnsupportedOperationException("jsr107 registerCacheEntryListener not supported");
}
@Override
public void deregisterCacheEntryListener(CacheEntryListenerConfiguration<K, V> cacheEntryListenerConfiguration) {
throw new UnsupportedOperationException("jsr107 deregisterCacheEntryListener not supported");
}
@Override
public Iterator<Entry<K, V>> iterator() {
throw new UnsupportedOperationException("jsr107 iterator not supported");
}
private void checkClosed() {
if (cache.isClosed()) {
throw new IllegalStateException("cache is closed");
}
}
}
|
package com.yuyakaido.android.cardstackview;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.content.Context;
import android.database.DataSetObserver;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.FrameLayout;
import android.widget.RelativeLayout;
import java.util.ArrayList;
import java.util.List;
public class CardStackView extends RelativeLayout {
private int topIndex = 0;
private int visibleCount = 4;
private float distanceBorder = 300F;
private ArrayAdapter<?> adapter;
private OnTouchListener onTouchListener;
private CardAnimator cardAnimator;
private List<ViewGroup> containers = new ArrayList<>();
private CardStackEventListener cardStackEventListener;
private boolean elevationEnabled = true;
private boolean swipeEnabled = true;
private DataSetObserver dataSetObserver = new DataSetObserver() {
@Override
public void onChanged() {
initialize(false);
}
};
public interface CardStackEventListener {
void onBeginSwipe(int index, Direction direction);
void onEndSwipe(Direction direction);
void onSwiping(float positionX);
void onDiscarded(int index, Direction direction);
void onTapUp(int index);
}
public CardStackView(Context context) {
this(context, null);
}
public CardStackView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public CardStackView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
private void initialize(boolean resetIndex) {
initializeIndex(resetIndex);
initializeContainerViews();
initializeAnimation();
initializeViews();
}
public void initializeIndex(boolean resetIndex) {
if (resetIndex) {
topIndex = 0;
}
}
private void initializeContainerViews() {
removeAllViews();
containers.clear();
for (int i = 0; i < visibleCount; i++) {
FrameLayout v = new FrameLayout(getContext());
containers.add(v);
addView(v);
}
}
public void initializeAnimation() {
cardAnimator = new CardAnimator(getContext(), containers, elevationEnabled);
cardAnimator.initCards(elevationEnabled);
final DragGestureDetector dragGestureDetector = new DragGestureDetector(getContext(),
new DragGestureDetector.DragListener() {
@Override
public void onBeginDrag(MotionEvent e1, MotionEvent e2) {
cardAnimator.drag(e1, e2, elevationEnabled);
if (cardStackEventListener != null) {
float oldX = e1.getRawX();
float oldY = e1.getRawY();
float newX = e2.getRawX();
float newY = e2.getRawY();
final Direction direction = CardUtil.getDirection(oldX, oldY, newX, newY);
cardStackEventListener.onBeginSwipe(topIndex, direction);
}
}
@Override
public void onDragging(MotionEvent e1, MotionEvent e2) {
cardAnimator.drag(e1, e2, elevationEnabled);
if (cardStackEventListener != null) {
float oldX = e1.getRawX();
float newX = e2.getRawX();
float posX = (newX - oldX);
if (distanceBorder < posX) {
posX = 1F;
} else if (distanceBorder < -posX) {
posX = -1f;
} else {
posX = posX / distanceBorder;
}
cardStackEventListener.onSwiping(posX);
}
}
@Override
public void onEndDrag(MotionEvent e1, MotionEvent e2) {
float oldX = e1.getRawX();
float oldY = e1.getRawY();
float newX = e2.getRawX();
float newY = e2.getRawY();
float distance = CardUtil.getDistance(oldX, oldY, newX, newY);
final Direction direction = CardUtil.getDirection(oldX, oldY, newX, newY);
if (cardStackEventListener != null) {
cardStackEventListener.onEndSwipe(direction);
}
if (distance < distanceBorder) {
cardAnimator.moveToOrigin();
} else {
discard(direction);
}
}
@Override
public void onTapUp() {
if (cardStackEventListener != null) {
cardStackEventListener.onTapUp(topIndex);
}
}
});
onTouchListener = new OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent event) {
if (swipeEnabled) {
dragGestureDetector.onTouchEvent(event);
}
return true;
}
};
containers.get(containers.size() - 1).setOnTouchListener(onTouchListener);
}
public void initializeViews() {
for (int i = visibleCount - 1; i >= 0; i
ViewGroup parent = containers.get(i);
int adapterIndex = (topIndex + visibleCount - 1) - i;
if (adapterIndex > adapter.getCount() - 1) {
parent.setVisibility(View.GONE);
} else {
View child = adapter.getView(adapterIndex, parent.getChildAt(0), this);
parent.addView(child);
parent.setVisibility(View.VISIBLE);
}
}
}
public void setAdapter(ArrayAdapter<?> adapter) {
if (this.adapter != null) {
this.adapter.unregisterDataSetObserver(dataSetObserver);
}
this.adapter = adapter;
this.adapter.registerDataSetObserver(dataSetObserver);
initialize(true);
}
public void setCardStackEventListener(CardStackEventListener listener) {
cardStackEventListener = listener;
}
public void loadNextView() {
ViewGroup parent = containers.get(0);
int lastIndex = (visibleCount - 1) + topIndex;
if (lastIndex > adapter.getCount() - 1) {
parent.setVisibility(View.GONE);
return;
}
View child = adapter.getView(lastIndex, parent.getChildAt(0), parent);
parent.removeAllViews();
parent.addView(child);
}
public void discard(final Direction direction) {
cardAnimator.discard(direction, new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator arg0) {
cardAnimator.initCards(elevationEnabled);
if (cardStackEventListener != null) {
cardStackEventListener.onDiscarded(topIndex, direction);
}
topIndex++;
loadNextView();
containers.get(0).setOnTouchListener(null);
containers.get(containers.size() - 1)
.setOnTouchListener(onTouchListener);
}
});
}
public int getTopIndex() {
return topIndex;
}
public ViewGroup getTopView() {
return cardAnimator.getTopView();
}
public void setElevationEnabled(boolean elevationEnabled) {
this.elevationEnabled = elevationEnabled;
if (adapter != null) {
initialize(false);
}
}
public void setSwipeEnabled(boolean swipeEnabled) {
this.swipeEnabled = swipeEnabled;
}
}
|
package net.java.sip.communicator.impl.gui.i18n;
import java.text.*;
import java.util.*;
/**
* The Messages class manages the access to the internationalization
* properties files.
* @author Yana Stamcheva
*/
public class Messages {
private static final String BUNDLE_NAME
= "resources.languages.impl.gui.resources";
private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle
.getBundle(BUNDLE_NAME);
/**
* Returns an internationalized string corresponding to the given key.
* @param key The key of the string.
* @return An internationalized string corresponding to the given key.
*/
public static I18NString getI18NString(String key) {
I18NString i18nString = new I18NString();
String resourceString;
try {
resourceString = RESOURCE_BUNDLE.getString(key);
int mnemonicIndex = resourceString.indexOf('&');
if(mnemonicIndex > -1) {
i18nString.setMnemonic(resourceString.charAt(mnemonicIndex + 1));
String firstPart = resourceString.substring(0, mnemonicIndex);
String secondPart = resourceString.substring(mnemonicIndex + 1);
resourceString = firstPart.concat(secondPart);
}
i18nString.setText(resourceString);
} catch (MissingResourceException e) {
i18nString.setText('!' + key + '!');
}
return i18nString;
}
/**
* Returns an internationalized string corresponding to the given key,
* by replacing all occurences of '?' with the given string param.
* @param key The key of the string.
* @param params the params, that should replace {1}, {2}, etc. in the
* string given by the key parameter
* @return An internationalized string corresponding to the given key,
* by replacing all occurences of '?' with the given string param.
*/
public static I18NString getI18NString(String key, String[] params) {
I18NString i18nString = new I18NString();
String resourceString;
try {
resourceString = RESOURCE_BUNDLE.getString(key);
resourceString = MessageFormat.format(
resourceString, (Object[]) params);
int mnemonicIndex = resourceString.indexOf('&');
if(mnemonicIndex > -1) {
i18nString.setMnemonic(resourceString.charAt(mnemonicIndex + 1));
String firstPart = resourceString.substring(0, mnemonicIndex);
String secondPart = resourceString.substring(mnemonicIndex + 1);
resourceString = firstPart.concat(secondPart);
}
i18nString.setText(resourceString);
} catch (MissingResourceException e) {
i18nString.setText('!' + key + '!');
}
return i18nString;
}
}
|
package com.ht.weibo.ui.activity;
import android.app.ActionBar;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.ht.weibo.Constants;
import com.ht.weibo.R;
import com.ht.weibo.ui.adapter.StatusContentListAdapter;
import com.ht.weibo.ui.widget.RoundProgressBar;
import com.ht.weibo.util.AccessTokenKeeper;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.exception.WeiboException;
import com.sina.weibo.sdk.net.RequestListener;
import com.sina.weibo.sdk.openapi.legacy.StatusesAPI;
import com.sina.weibo.sdk.openapi.models.Status;
import com.sina.weibo.sdk.openapi.models.StatusList;
import me.imid.swipebacklayout.lib.app.SwipeBackActivity;
import java.util.ArrayList;
public class WBSquareActivity extends SwipeBackActivity implements PullToRefreshBase.OnRefreshListener2<ListView>, Runnable {
private int currentPage = 1;
private Oauth2AccessToken token;
private PullToRefreshListView pullToRefreshListView;
private ArrayList<Status> statuses;
private StatusContentListAdapter statusContentListAdapter;
private StatusesAPI statusesAPI;
private RoundProgressBar roundProgressBar;
private boolean isRoundProgressBarShown = true;
//ListView
private int CURRENT_LISTVIEW_ITEM_POSITION = 0;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wbsquare);
roundProgressBar = (RoundProgressBar)findViewById(R.id.roundProgressBar);
roundProgressBar.setMax(100);
Thread thread = new Thread(this);
thread.start();
//actionbar
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
View myHead = LayoutInflater.from(this).inflate(R.layout.wbsquare_head, null);
pullToRefreshListView = (PullToRefreshListView) this.findViewById(R.id.wbsquare_listview);
pullToRefreshListView.getRefreshableView().addHeaderView(myHead, null, false);
pullToRefreshListView.setMode(PullToRefreshBase.Mode.PULL_FROM_END);
pullToRefreshListView.setOnRefreshListener(this);
//sharepreferenceid
token = AccessTokenKeeper.readAccessToken(this);
statusesAPI = new StatusesAPI(this, Constants.APP_KEY, token);
statusesAPI.publicTimeline(10, currentPage, false, new RequestListener() {
@Override
public void onComplete(String response) {
if (!TextUtils.isEmpty(response)) {
isRoundProgressBarShown = false;
roundProgressBar.setVisibility(View.GONE);
StatusList statusList = StatusList.parse(response);
if (statusList != null) {
statuses = statusList.statusList;
if (statuses != null) {
statusContentListAdapter = new StatusContentListAdapter(WBSquareActivity.this, statuses);
pullToRefreshListView.setAdapter(statusContentListAdapter);
}
}
}
}
@Override
public void onWeiboException(WeiboException e) {
}
});
pullToRefreshListView.getRefreshableView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
position = position - pullToRefreshListView.getRefreshableView().getHeaderViewsCount();
Intent intent = new Intent(WBSquareActivity.this, StatusActivity.class);
Log.d("111111111111111111111", "11111111111111");
//StatusActivity
Status status = statuses.get(position);
if (status != null) {
intent.putExtra("status", status);
}
startActivity(intent);
}
});
}
@Override
public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
}
@Override
public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
currentPage = currentPage + 1;
statusesAPI.publicTimeline(10, currentPage, false, new RequestListener() {
@Override
public void onComplete(String response) {
pullToRefreshListView.onRefreshComplete();
if (!TextUtils.isEmpty(response)) {
StatusList statusList = StatusList.parse(response);
if (statusList != null) {
List<Status> statuses1 = statusList.statusList;
if (statuses1 != null) {
statuses.addAll(statuses1);
statusContentListAdapter.notifyDataSetChanged();
} else
Toast.makeText(WBSquareActivity.this, "", Toast.LENGTH_LONG).show();
}
}
}
@Override
public void onWeiboException(WeiboException e) {
}
});
}
// @Override
// public boolean onCreateOptionsMenu(Menu menu) {
// getMenuInflater().inflate(R.menu.main, menu);
// return true;
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
switch (itemId) {
case android.R.id.home:
this.finish();
break;
}
return super.onContextItemSelected(item);
}
@Override
public void run() {
boolean running = true;
int i=1;
while(running){
i+=5;
if(i > 100){
i=1;
}
roundProgressBar.setProgress(i);
if(!isRoundProgressBarShown){
running = isRoundProgressBarShown;
}
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
@Override
public void onPause() {
super.onPause();
CURRENT_LISTVIEW_ITEM_POSITION = pullToRefreshListView.getRefreshableView().getFirstVisiblePosition();//ListView
Log.d("onPause", CURRENT_LISTVIEW_ITEM_POSITION + "");
}
@Override
public void onResume() {
super.onResume();
//listivew
//listView.setAdapter(statusContentListAdapter);
pullToRefreshListView.getRefreshableView().setSelection(CURRENT_LISTVIEW_ITEM_POSITION);
Log.d("", CURRENT_LISTVIEW_ITEM_POSITION + "");
}
}
|
package com.pauldavdesign.mineauz.minigames;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Color;
import org.bukkit.FireworkEffect;
import org.bukkit.GameMode;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.FireworkEffect.Type;
import org.bukkit.configuration.Configuration;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Firework;
import org.bukkit.entity.Player;
import org.bukkit.entity.Vehicle;
import org.bukkit.event.HandlerList;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.FireworkMeta;
import org.bukkit.potion.PotionEffect;
import com.pauldavdesign.mineauz.minigames.blockRecorder.RecorderData;
import com.pauldavdesign.mineauz.minigames.events.EndMinigameEvent;
import com.pauldavdesign.mineauz.minigames.events.JoinMinigameEvent;
import com.pauldavdesign.mineauz.minigames.events.QuitMinigameEvent;
import com.pauldavdesign.mineauz.minigames.events.RevertCheckpointEvent;
import com.pauldavdesign.mineauz.minigames.events.SpectateMinigameEvent;
import com.pauldavdesign.mineauz.minigames.events.StartMinigameEvent;
import com.pauldavdesign.mineauz.minigames.gametypes.MinigameType;
import com.pauldavdesign.mineauz.minigames.gametypes.MinigameTypeBase;
import com.pauldavdesign.mineauz.minigames.mechanics.GameMechanics;
import com.pauldavdesign.mineauz.minigames.minigame.Minigame;
import com.pauldavdesign.mineauz.minigames.minigame.Team;
import com.pauldavdesign.mineauz.minigames.minigame.modules.WeatherTimeModule;
import com.pauldavdesign.mineauz.minigames.minigame.modules.TeamsModule;
import com.pauldavdesign.mineauz.minigames.sql.SQLPlayer;
public class PlayerData {
private Map<String, MinigamePlayer> minigamePlayers = new HashMap<String, MinigamePlayer>();
private boolean partyMode = false;
private List<String> deniedCommands = new ArrayList<String>();
private static Minigames plugin = Minigames.plugin;
private MinigameData mdata = plugin.mdata;
public PlayerData(){}
public void joinMinigame(MinigamePlayer player, Minigame minigame, boolean isBetting, Double betAmount){
MinigameType type = minigame.getType();
JoinMinigameEvent event = new JoinMinigameEvent(player, minigame);
Bukkit.getServer().getPluginManager().callEvent(event);
if(!event.isCancelled()){
if((minigame.isEnabled() || player.getPlayer().hasPermission("minigame.join.disabled")) &&
!minigame.isRegenerating() && (!minigame.isNotWaitingForPlayers() || (minigame.canLateJoin() && minigame.getMpTimer().getPlayerWaitTimeLeft() == 0)) &&
(minigame.getStartLocations().size() > 0 ||
(minigame.isTeamGame() && TeamsModule.getMinigameModule(minigame).hasTeamStartLocations())) &&
minigame.getEndPosition() != null && minigame.getQuitPosition() != null &&
(minigame.getType() == MinigameType.SINGLEPLAYER || minigame.getLobbyPosition() != null) &&
((type == MinigameType.SINGLEPLAYER && !minigame.isSpMaxPlayers()) || minigame.getPlayers().size() < minigame.getMaxPlayers())){
//Do betting stuff
if(isBetting){
if(minigame.getMpBets() == null && (player.getPlayer().getItemInHand().getType() != Material.AIR || betAmount != 0)){
minigame.setMpBets(new MultiplayerBets());
}
MultiplayerBets pbet = minigame.getMpBets();
ItemStack item = player.getPlayer().getItemInHand().clone();
if(pbet != null &&
((betAmount != 0 && pbet.canBet(player, betAmount) && plugin.getEconomy().getBalance(player.getName()) >= betAmount) ||
(pbet.canBet(player, item) && item.getType() != Material.AIR && pbet.betValue(item.getType()) > 0))){
player.sendMessage(MinigameUtils.getLang("player.bet.plyMsg"), null);
if(betAmount == 0){
pbet.addBet(player, item);
}
else{
pbet.addBet(player, betAmount);
plugin.getEconomy().withdrawPlayer(player.getName(), betAmount);
}
player.getPlayer().getInventory().removeItem(new ItemStack(item.getType(), 1));
}
else if(item.getType() == Material.AIR && betAmount == 0){
player.sendMessage(MinigameUtils.getLang("player.bet.plyNoBet"), "error");
return;
}
else if(betAmount != 0 && !pbet.canBet(player, betAmount)){
player.sendMessage(MinigameUtils.getLang("player.bet.incorrectAmount"), "error");
player.sendMessage(MinigameUtils.formStr("player.bet.incorrectAmountInfo", minigame.getMpBets().getHighestMoneyBet()), "error");
return;
}
else if(betAmount != 0 && plugin.getEconomy().getBalance(player.getName()) < betAmount){
player.sendMessage(MinigameUtils.getLang("player.bet.notEnoughMoney"), "error");
player.sendMessage(MinigameUtils.formStr("player.bet.notEnoughMoneyInfo", minigame.getMpBets().getHighestMoneyBet()), "error");
return;
}
else{
player.sendMessage(MinigameUtils.getLang("player.bet.incorrectItem"), "error");
player.sendMessage(MinigameUtils.formStr("player.bet.incorrectItemInfo", 1, minigame.getMpBets().highestBetName()), "error");
return;
}
}
//Try teleport the player to their designated area.
boolean tpd = false;
if(type == MinigameType.SINGLEPLAYER){
tpd = player.teleport(minigame.getStartLocations().get(0));//TODO: Make random
if(plugin.getConfig().getBoolean("warnings") && player.getPlayer().getWorld() != minigame.getStartLocations().get(0).getWorld() &&
player.getPlayer().hasPermission("minigame.set.start")){
player.sendMessage(ChatColor.RED + "WARNING: " + ChatColor.WHITE +
"Join location is across worlds! This may cause some server performance issues!", "error");
}
if(tpd && minigame.isFlightEnabled())
player.getPlayer().setFlying(true);
}
else{
tpd = player.teleport(minigame.getLobbyPosition());
if(plugin.getConfig().getBoolean("warnings") && player.getPlayer().getWorld() != minigame.getLobbyPosition().getWorld() &&
player.getPlayer().hasPermission("minigame.set.lobby")){
player.sendMessage(ChatColor.RED + "WARNING: " + ChatColor.WHITE +
"Lobby location is across worlds! This may cause some server performance issues!", "error");
}
}
if(!tpd){
player.sendMessage(MinigameUtils.getLang("minigame.error.noTeleport"), "error");
return;
}
//Give them the game type name
if(minigame.getGametypeName() == null)
player.sendMessage(MinigameUtils.formStr("player.join.plyInfo", minigame.getType().getName()), "win");
else
player.sendMessage(MinigameUtils.formStr("player.join.plyInfo", minigame.getGametypeName()), "win");
//Give them the objective
if(minigame.getObjective() != null){
player.sendMessage(ChatColor.GREEN + "
player.sendMessage(ChatColor.AQUA.toString() + ChatColor.BOLD + MinigameUtils.formStr("player.join.objective",
ChatColor.RESET.toString() + ChatColor.WHITE + minigame.getObjective()));
player.sendMessage(ChatColor.GREEN + "
}
//Prepare regeneration region for rollback.
if(minigame.getBlockRecorder().hasRegenArea() && !minigame.getBlockRecorder().hasCreatedRegenBlocks()){
RecorderData d = minigame.getBlockRecorder();
d.setCreatedRegenBlocks(true);
Location cur = new Location(minigame.getRegenArea1().getWorld(), 0, 0, 0);
for(double y = d.getRegenMinY(); y <= d.getRegenMaxY(); y++){
cur.setY(y);
for(double x = d.getRegenMinX(); x <= d.getRegenMaxX(); x++){
cur.setX(x);
for(double z = d.getRegenMinZ(); z <= d.getRegenMaxZ(); z++){
cur.setZ(z);
d.addBlock(cur.getBlock(), null);
}
}
}
}
else if(minigame.hasRestoreBlocks() && !minigame.getBlockRecorder().hasCreatedRegenBlocks()){
minigame.getBlockRecorder().setCreatedRegenBlocks(true);
for(RestoreBlock block : minigame.getRestoreBlocks().values()){
minigame.getBlockRecorder().addBlock(block.getLocation().getBlock(), null);
}
}
//Standardize player
player.storePlayerData();
player.setMinigame(minigame);
minigame.addPlayer(player);
WeatherTimeModule.getMinigameModule(minigame).applyCustomTime(player);
WeatherTimeModule.getMinigameModule(minigame).applyCustomWeather(player);
player.setCheckpoint(player.getPlayer().getLocation());
player.getPlayer().setFallDistance(0);
player.getPlayer().setWalkSpeed(0.2f);
player.getPlayer().setAllowFlight(false);
player.setStartTime(Calendar.getInstance().getTimeInMillis());
player.setGamemode(minigame.getDefaultGamemode());
for(PotionEffect potion : player.getPlayer().getActivePotionEffects()){
player.getPlayer().removePotionEffect(potion.getType());
}
//Hide Spectators
for(MinigamePlayer pl : minigame.getSpectators()){
player.getPlayer().hidePlayer(pl.getPlayer());
}
if(minigame.getPlayers().size() == 1){
//Register regen recorder events
if(minigame.getBlockRecorder().hasRegenArea())
Bukkit.getServer().getPluginManager().registerEvents(minigame.getBlockRecorder(), plugin);
WeatherTimeModule.getMinigameModule(minigame).startTimeLoop(minigame);
}
//Call Type specific join
mdata.minigameType(type).joinMinigame(player, minigame);
//Send other players the join message.
mdata.sendMinigameMessage(minigame, MinigameUtils.formStr("player.join.plyMsg", player.getName(), minigame.getName(true)), null, player);
player.updateInventory();
}
else if(!minigame.isEnabled()){
player.sendMessage(MinigameUtils.getLang("minigame.error.notEnabled"), "error");
}
else if(minigame.isRegenerating()){
player.sendMessage(MinigameUtils.getLang("minigame.error.regenerating"), "error");
}
else if(minigame.isNotWaitingForPlayers() && !minigame.canLateJoin()){
player.sendMessage(MinigameUtils.getLang("minigame.started"), "error");
}
else if(minigame.isNotWaitingForPlayers() && minigame.canLateJoin() &&
minigame.getMpTimer().getPlayerWaitTimeLeft() == 0 && minigame.getPlayers().size() != minigame.getMaxPlayers()){
player.sendMessage(MinigameUtils.formStr("minigame.lateJoinWait", minigame.getMpTimer().getStartWaitTimeLeft()), null);
}
else if(minigame.getStartLocations().size() == 0 ||
(minigame.isTeamGame() && !TeamsModule.getMinigameModule(minigame).hasTeamStartLocations())){
player.sendMessage(MinigameUtils.getLang("minigame.error.noStart"), "error");
}
else if(minigame.getEndPosition() == null){
player.sendMessage(MinigameUtils.getLang("minigame.error.noEnd"), "error");
}
else if(minigame.getQuitPosition() == null){
player.sendMessage(MinigameUtils.getLang("minigame.error.noQuit"), "error");
}
else if(minigame.getLobbyPosition() == null){
player.sendMessage(MinigameUtils.getLang("minigame.error.noLobby"), "error");
}
else if(minigame.getPlayers().size() >= minigame.getMaxPlayers()){
player.sendMessage(MinigameUtils.getLang("minigame.full"), "error");
}
}
}
public void spectateMinigame(MinigamePlayer player, Minigame minigame) {
SpectateMinigameEvent event = new SpectateMinigameEvent(player, minigame);
Bukkit.getServer().getPluginManager().callEvent(event);
if(!event.isCancelled()){
boolean tpd = player.teleport(minigame.getStartLocations().get(0));
if(!tpd){
player.sendMessage(MinigameUtils.getLang("minigame.error.noTeleport"), "error");
return;
}
player.storePlayerData();
player.setMinigame(minigame);
player.getPlayer().setGameMode(GameMode.ADVENTURE);
minigame.addSpectator(player);
if(minigame.canSpectateFly()){
player.getPlayer().setAllowFlight(true);
}
for(MinigamePlayer pl : minigame.getPlayers()){
pl.getPlayer().hidePlayer(player.getPlayer());
}
player.getPlayer().setScoreboard(minigame.getScoreboardManager());
for(PotionEffect potion : player.getPlayer().getActivePotionEffects()){
player.getPlayer().removePotionEffect(potion.getType());
}
player.sendMessage(MinigameUtils.formStr("player.spectate.join.plyMsg", minigame.getName(false)) + "\n" +
MinigameUtils.formStr("player.spectate.join.plyHelp", "\"/minigame quit\""), null);
mdata.sendMinigameMessage(minigame, MinigameUtils.formStr("player.spectate.join.minigameMsg", player.getName(), minigame.getName(false)), null, player);
}
}
public void startMPMinigame(Minigame minigame, boolean teleport){
List<MinigamePlayer> players = new ArrayList<MinigamePlayer>();
players.addAll(minigame.getPlayers());
Collections.shuffle(players);
if(minigame.isTeamGame() && GameMechanics.getGameMechanic(minigame.getScoreType()) != null){
GameMechanics.getGameMechanic(minigame.getScoreType()).balanceTeam(players, minigame);
}
Location start = null;
int pos = 0;
Map<Team, Integer> tpos = new HashMap<Team, Integer>();
for(Team t : TeamsModule.getMinigameModule(minigame).getTeams()){
tpos.put(t, 0);
}
Bukkit.getServer().getPluginManager().callEvent(new StartMinigameEvent(players, minigame, teleport));
for(MinigamePlayer ply : players){
if(!minigame.isTeamGame()){
if(pos < minigame.getStartLocations().size()){
ply.setStartTime(Calendar.getInstance().getTimeInMillis());
if(teleport){
start = minigame.getStartLocations().get(pos);
}
}
else{
pos = 0;
if(!minigame.getStartLocations().isEmpty()){
if(teleport){
start = minigame.getStartLocations().get(0);
}
}
else {
ply.sendMessage(MinigameUtils.getLang("minigame.error.incorrectStart"), "error");
quitMinigame(ply, false);
}
}
ply.setCheckpoint(start);
}
else{
Team team = ply.getTeam();
if(TeamsModule.getMinigameModule(minigame).hasTeamStartLocations()){
if(tpos.get(team) <= team.getStartLocations().size()){
tpos.put(team, 0);
}
start = team.getStartLocations().get(tpos.get(team));
tpos.put(team, tpos.get(team) + 1);
}
else{
if(pos < minigame.getStartLocations().size()){
if(teleport){
start = minigame.getStartLocations().get(pos);
}
}
else{
pos = 0;
if(!minigame.getStartLocations().isEmpty()){
if(teleport){
start = minigame.getStartLocations().get(0);
}
}
else {
ply.sendMessage(MinigameUtils.getLang("minigame.error.incorrectStart"), "error");
quitMinigame(ply, false);
}
}
}
if(minigame.getLives() > 0){
ply.sendMessage(MinigameUtils.formStr("minigame.livesLeft", minigame.getLives()), null);
}
}
if(start != null){
if(teleport){
ply.teleport(start);
ply.setCheckpoint(start);
}
if(minigame.getMaxScore() != 0){
ply.sendMessage(MinigameUtils.formStr("minigame.scoreToWin", minigame.getMaxScorePerPlayer()), null);
}
}
pos++;
ply.getLoadout().equiptLoadout(ply);
ply.getPlayer().setScoreboard(minigame.getScoreboardManager());
minigame.setScore(ply, 1);
minigame.setScore(ply, 0);
if(minigame.isFlightEnabled())
ply.getPlayer().setFlying(true);
}
}
public void revertToCheckpoint(MinigamePlayer player) {
RevertCheckpointEvent event = new RevertCheckpointEvent(player);
Bukkit.getServer().getPluginManager().callEvent(event);
if(!event.isCancelled()){
player.teleport(player.getCheckpoint());
player.addRevert();
player.sendMessage(MinigameUtils.getLang("player.checkpoint.revert"), null);
}
}
public void quitMinigame(MinigamePlayer player, boolean forced){
Minigame minigame = player.getMinigame();
QuitMinigameEvent event = new QuitMinigameEvent(player, minigame, forced);
Bukkit.getServer().getPluginManager().callEvent(event);
if(!event.isCancelled()){
player.setEndTime(System.currentTimeMillis());
if(!minigame.isSpectator(player)){
//SQL stuff
if(plugin.getSQL() != null){
if(minigame.canSaveCheckpoint() == false){
plugin.addSQLToStore(new SQLPlayer(minigame.getName(false), player.getName(), player.getUUID().toString(), 0, 1,
player.getKills(), player.getDeaths(), player.getScore(), player.getReverts(),
player.getEndTime() - player.getStartTime() + player.getStoredTime()));
plugin.startSQLCompletionSaver();
}
}
//Call Types quit.
mdata.minigameType(minigame.getType()).quitMinigame(player, minigame, forced);
//Prepare player for quit
if(player.getPlayer().getVehicle() != null){
Vehicle vehicle = (Vehicle) player.getPlayer().getVehicle();
vehicle.eject();
}
player.getPlayer().closeInventory();
player.removeMinigame();
minigame.removePlayer(player);
for(PotionEffect potion : player.getPlayer().getActivePotionEffects()){
player.getPlayer().removePotionEffect(potion.getType());
}
player.getPlayer().setFallDistance(0);
player.getPlayer().setNoDamageTicks(60);
final MinigamePlayer fplayer = player;
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
fplayer.getPlayer().setFireTicks(0);
}
});
player.resetAllStats();
if(!player.isDead()){
player.restorePlayerData();
player.teleport(minigame.getQuitPosition());
}
else{
player.setQuitPos(minigame.getQuitPosition());
player.setRequiredQuit(true);
}
if(minigame.getType() != MinigameType.SINGLEPLAYER){
if(minigame.getPlayers().size() == 1 && minigame.isNotWaitingForPlayers() && !forced){
List<MinigamePlayer> w = new ArrayList<MinigamePlayer>();
w.add(minigame.getPlayers().get(0));
List<MinigamePlayer> l = new ArrayList<MinigamePlayer>();
endMinigame(minigame.getPlayers().get(0).getMinigame(), w, l);
if(minigame.getMpBets() != null){
minigame.setMpBets(null);
}
}
}
//Reset Minigame
if(minigame.getPlayers().size() == 0){
if(minigame.getMinigameTimer() != null){
minigame.getMinigameTimer().stopTimer();
minigame.setMinigameTimer(null);
}
if(minigame.getFloorDegenerator() != null){
minigame.getFloorDegenerator().stopDegenerator();
}
if(minigame.getBlockRecorder().hasData()){
minigame.getBlockRecorder().restoreBlocks();
minigame.getBlockRecorder().restoreEntities();
minigame.getBlockRecorder().setCreatedRegenBlocks(false);
}
if(minigame.getMpBets() != null){
minigame.setMpBets(null);
}
mdata.clearClaimedScore(minigame);
WeatherTimeModule.getMinigameModule(minigame).stopTimeLoop();
}
minigame.getScoreboardManager().resetScores(player.getName());
for(MinigamePlayer pl : minigame.getSpectators()){
player.getPlayer().showPlayer(pl.getPlayer());
}
if(minigame.getPlayers().size() == 0 && !minigame.isRegenerating()){
HandlerList.unregisterAll(minigame.getBlockRecorder());
}
//Send out messages
if(!forced){
mdata.sendMinigameMessage(minigame, MinigameUtils.formStr("player.quit.plyMsg", player.getName(), minigame.getName(true)), "error", player);
}
else{
mdata.sendMinigameMessage(minigame, MinigameUtils.formStr("player.quit.plyForcedMsg", player.getName(), minigame.getName(true)), "error", player);
}
plugin.getLogger().info(player.getName() + " quit " + minigame);
player.updateInventory();
}
else{
if(player.getPlayer().getVehicle() != null){
Vehicle vehicle = (Vehicle) player.getPlayer().getVehicle();
vehicle.eject();
}
player.getPlayer().setFallDistance(0);
player.getPlayer().setNoDamageTicks(60);
final Player fplayer = player.getPlayer();
for(PotionEffect potion : player.getPlayer().getActivePotionEffects()){
player.getPlayer().removePotionEffect(potion.getType());
}
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
fplayer.setFireTicks(0);
}
});
player.getPlayer().closeInventory();
if(!player.isDead()){
player.restorePlayerData();
}
player.teleport(minigame.getQuitPosition());
player.removeMinigame();
minigame.removeSpectator(player);
for(MinigamePlayer pl : minigame.getPlayers()){
pl.getPlayer().showPlayer(player.getPlayer());
}
player.sendMessage(MinigameUtils.formStr("player.spectate.quit.plyMsg", minigame.getName(true)), "error");
mdata.sendMinigameMessage(minigame, MinigameUtils.formStr("player.spectate.quit.minigameMsg", player.getName(), minigame.getName(true)), "error", player);
}
}
}
public void endMinigame(MinigamePlayer player){
List<MinigamePlayer> w = new ArrayList<MinigamePlayer>();
List<MinigamePlayer> l = new ArrayList<MinigamePlayer>();
w.add(player);
endMinigame(player.getMinigame(), w, l);
}
public void endMinigame(Minigame mgm, List<MinigamePlayer> winners, List<MinigamePlayer> losers){
EndMinigameEvent event = new EndMinigameEvent(winners, losers, mgm);
Bukkit.getServer().getPluginManager().callEvent(event);
if(!event.isCancelled()){
winners = event.getWinners();
losers = event.getLosers();
//Prepare split money
double bets = 0;
if(mgm.getMpBets() != null){
if(mgm.getMpBets().hasMoneyBets()){
List<MinigamePlayer> plys = new ArrayList<MinigamePlayer>();
plys.addAll(event.getWinners());
if(!plys.isEmpty()){
bets = mgm.getMpBets().claimMoneyBets() / (double) plys.size();
BigDecimal roundBets = new BigDecimal(bets);
roundBets = roundBets.setScale(2, BigDecimal.ROUND_HALF_UP);
bets = roundBets.doubleValue();
}
mgm.setMpBets(null);
}
}
//Broadcast Message
if(plugin.getConfig().getBoolean("broadcastCompletion") && mgm.isEnabled() && mgm.isEnabled()){
if(mgm.isTeamGame()){
Team team = winners.get(0).getTeam();
String score = "";
List<Team> teams = TeamsModule.getMinigameModule(mgm).getTeams();
for(Team t : teams){
score += t.getColor().getColor().toString() + t.getScore();
if(t != teams.get(teams.size() - 1)){
score += ChatColor.WHITE + " : ";
}
}
String nscore = ", " + MinigameUtils.formStr("player.end.team.score", score);
MinigameUtils.broadcast(MinigameUtils.formStr("player.end.team.win",
team.getChatColor() + team.getDisplayName() + ChatColor.WHITE, mgm.getName(true)) + nscore, mgm, ChatColor.GREEN);
}
else{
if(winners.size() == 1){
String score = "";
if(winners.get(0).getScore() != 0)
score = MinigameUtils.formStr("player.end.broadcastScore", winners.get(0).getScore());
MinigameUtils.broadcast(MinigameUtils.formStr("player.end.broadcastMsg", winners.get(0).getDisplayName(), mgm.getName(true)) + ". " + score, mgm, ChatColor.GREEN);
}
else if(winners.size() > 1){
String win = "";
Collections.sort(winners, new Comparator<MinigamePlayer>() {
@Override
public int compare(MinigamePlayer o1,
MinigamePlayer o2) {
return Integer.valueOf(o1.getScore()).compareTo(o2.getScore());
}
});
for(MinigamePlayer pl : winners){
if(winners.indexOf(pl) < 2){
win += pl.getDisplayName();
if(winners.indexOf(pl) + 2 >= winners.size()){
win += " and ";
}
else{
win += ", ";
}
}
else{
win += String.valueOf(winners.size() - 3) + " others";
}
}
MinigameUtils.broadcast(MinigameUtils.formStr("player.end.broadcastMsg", win, mgm.getName(true)) + ". ", mgm, ChatColor.GREEN);
}
else{
MinigameUtils.broadcast(MinigameUtils.formStr("player.end.broadcastNobodyWon", mgm.getName(true)), mgm, ChatColor.RED);
}
}
}
for(MinigamePlayer player : losers){
quitMinigame(player, true);
}
for(MinigamePlayer player : winners){
player.setEndTime(Calendar.getInstance().getTimeInMillis());
//Group money bets
if(bets != 0){
plugin.getEconomy().depositPlayer(player.getName(), bets);
player.sendMessage(MinigameUtils.formStr("player.bet.winMoney", bets), null);
}
//Restore Player
if(player.getPlayer().getVehicle() != null){
Vehicle vehicle = (Vehicle) player.getPlayer().getVehicle();
vehicle.eject();
}
player.getPlayer().setFireTicks(0);
player.getPlayer().resetPlayerTime();
player.getPlayer().setNoDamageTicks(60);
List<ItemStack> tempItems = new ArrayList<ItemStack>(player.getTempRewardItems());
player.resetAllStats();
for(PotionEffect potion : player.getPlayer().getActivePotionEffects()){
player.getPlayer().removePotionEffect(potion.getType());
}
player.getPlayer().closeInventory();
if(player.getPlayer().getWorld() != mgm.getEndPosition().getWorld() && player.getPlayer().hasPermission("minigame.set.end") && plugin.getConfig().getBoolean("warnings")){
player.sendMessage(ChatColor.RED + "WARNING: " + ChatColor.WHITE + "End location is across worlds! This may cause some server performance issues!", "error");
}
if(!player.isDead()){
player.restorePlayerData();
player.getPlayer().teleport(mgm.getEndPosition());
}
else{
player.setRequiredQuit(true);
player.setQuitPos(mgm.getEndPosition());
}
//Reward Player
boolean hascompleted = false;
Configuration completion = null;
if(plugin.getSQL() == null && mgm.isEnabled()){
completion = mdata.getConfigurationFile("completion");
hascompleted = completion.getStringList(mgm.getName(false)).contains(player.getUUID().toString().replace("-", "_"));
if(!hascompleted){
List<String> completionlist = completion.getStringList(mgm.getName(false));
completionlist.add(player.getUUID().toString().replace("-", "_"));
completion.set(mgm.getName(false), completionlist);
MinigameSave completionsave = new MinigameSave("completion");
completionsave.getConfig().set(mgm.getName(false), completionlist);
completionsave.saveConfig();
}
MinigameTypeBase.issuePlayerRewards(player, mgm, hascompleted);
}
else if(mgm.isEnabled()){
plugin.addSQLToStore(new SQLPlayer(mgm.getName(false), player.getName(), player.getUUID().toString(), 1, 0, player.getKills(), player.getDeaths(), player.getScore(), player.getReverts(), player.getEndTime() - player.getStartTime()));
plugin.startSQLCompletionSaver();
}
//Item Bets (for non groups)
if(mgm.getMpBets() != null){
if(mgm.getMpBets().hasBets()){
player.getPlayer().getInventory().addItem(mgm.getMpBets().claimBets());
mgm.setMpBets(null);
}
}
for(MinigamePlayer pl : mgm.getSpectators()){
player.getPlayer().showPlayer(pl.getPlayer());
}
if(!tempItems.isEmpty()){
for(ItemStack item : tempItems){
Map<Integer, ItemStack> m = player.getPlayer().getInventory().addItem(item);
if(!m.isEmpty()){
for(ItemStack i : m.values()){
player.getPlayer().getWorld().dropItemNaturally(player.getPlayer().getLocation(), i);
}
}
}
}
//Restore Minigame
player.removeMinigame();
mgm.removePlayer(player);
player.getPlayer().setFallDistance(0);
WeatherTimeModule.getMinigameModule(mgm).stopTimeLoop();
mgm.getScoreboardManager().resetScores(player.getName());
if(mgm.getMinigameTimer() != null){
mgm.getMinigameTimer().stopTimer();
mgm.setMinigameTimer(null);
}
if(mgm.getFloorDegenerator() != null && mgm.getPlayers().size() == 0){
mgm.getFloorDegenerator().stopDegenerator();
}
if(mgm.getBlockRecorder().hasData()){
if(mgm.getType() != MinigameType.SINGLEPLAYER || mgm.getPlayers().isEmpty()){
mgm.getBlockRecorder().restoreBlocks();
mgm.getBlockRecorder().restoreEntities();
mgm.getBlockRecorder().setCreatedRegenBlocks(false);
}
}
plugin.getLogger().info(MinigameUtils.formStr("player.end.consMsg", player.getName(), mgm.getName(false)));
player.sendMessage(MinigameUtils.formStr("player.end.plyMsg", mgm.getName(true)), "win");
if(mgm.getPlayers().size() == 0 && !mgm.isRegenerating()){
HandlerList.unregisterAll(mgm.getBlockRecorder());
}
player.updateInventory();
}
mdata.clearClaimedScore(mgm);
//Call Types End.
mdata.minigameType(mgm.getType()).endMinigame(winners, losers, mgm);
}
}
// public void endTeamMinigame(int teamnum, Minigame mgm){
// List<MinigamePlayer> losers = new ArrayList<MinigamePlayer>();
// List<MinigamePlayer> winners = new ArrayList<MinigamePlayer>();
// if(teamnum == 1){
// //Blue team
// for(OfflinePlayer ply : mgm.getRedTeam()){
// losers.add(getMinigamePlayer(ply.getName()));
// for(OfflinePlayer ply : mgm.getBlueTeam()){
// winners.add(getMinigamePlayer(ply.getName()));
// else{
// //Red team
// for(OfflinePlayer ply : mgm.getRedTeam()){
// winners.add(getMinigamePlayer(ply.getName()));
// for(OfflinePlayer ply : mgm.getBlueTeam()){
// losers.add(getMinigamePlayer(ply.getName()));
// EndTeamMinigameEvent event = new EndTeamMinigameEvent(losers, winners, mgm, teamnum);
// Bukkit.getServer().getPluginManager().callEvent(event);
// if(!event.isCancelled()){
// if(event.getWinningTeamInt() == 1){
// if(plugin.getConfig().getBoolean("multiplayer.broadcastwin") && mgm.isEnabled()){
// String score = "";
// if(mgm.getRedTeamScore() != 0 && mgm.getBlueTeamScore() != 0){
// score = ", " + MinigameUtils.formStr("player.end.team.score", ChatColor.BLUE.toString() + mgm.getBlueTeamScore() + ChatColor.WHITE, ChatColor.RED.toString() + mgm.getRedTeamScore());
// plugin.getServer().broadcastMessage(ChatColor.GREEN + "[Minigames] " + MinigameUtils.formStr("player.end.team.win", ChatColor.BLUE.toString() + "Blue Team" + ChatColor.WHITE, mgm.getName()) + score);
// else{
// if(plugin.getConfig().getBoolean("multiplayer.broadcastwin") && mgm.isEnabled()){
// String score = "";
// if(mgm.getRedTeamScore() != 0 && mgm.getBlueTeamScore() != 0){
// score = ", " + MinigameUtils.formStr("player.end.team.score", ChatColor.RED.toString() + mgm.getBlueTeamScore() + ChatColor.WHITE, ChatColor.BLUE.toString() + mgm.getRedTeamScore());
// plugin.getServer().broadcastMessage(ChatColor.GREEN + "[Minigames] " + MinigameUtils.formStr("player.end.team.win", ChatColor.RED + "Red Team" + ChatColor.WHITE, mgm.getName()) + score);
// mgm.setRedTeamScore(0);
// mgm.setBlueTeamScore(0);
// mgm.getMpTimer().setStartWaitTime(0);
// List<MinigamePlayer> winplayers = new ArrayList<MinigamePlayer>();
// winplayers.addAll(event.getWinnningPlayers());
// if(plugin.getSQL() != null && mgm.isEnabled()){
//// new SQLCompletionSaver(mgm.getName(), winplayers, mdata.minigameType(mgm.getType()), true);
// List<SQLPlayer> sqlplayers = new ArrayList<SQLPlayer>();
// for(MinigamePlayer ply : winplayers){
// ply.setEndTime(Calendar.getInstance().getTimeInMillis());
// sqlplayers.add(new SQLPlayer(mgm.getName(), ply.getName(), 1, 0, ply.getKills(), ply.getDeaths(), ply.getScore(), ply.getReverts(), ply.getEndTime() - ply.getStartTime()));
// plugin.addSQLToStore(sqlplayers);
// plugin.startSQLCompletionSaver();
// if(mgm.getMpBets() != null){
// if(mgm.getMpBets().hasMoneyBets()){
// List<MinigamePlayer> plys = new ArrayList<MinigamePlayer>();
// plys.addAll(event.getWinnningPlayers());
// if(!plys.isEmpty()){
// double bets = mgm.getMpBets().claimMoneyBets() / (double) plys.size();
// BigDecimal roundBets = new BigDecimal(bets);
// roundBets = roundBets.setScale(2, BigDecimal.ROUND_HALF_UP);
// bets = roundBets.doubleValue();
// for(MinigamePlayer ply : plys){
// plugin.getEconomy().depositPlayer(ply.getName(), bets);
// ply.sendMessage(MinigameUtils.formStr("player.bet.winMoney", bets), null);
// mgm.setMpBets(null);
// if(!event.getLosingPlayers().isEmpty()){
// List<MinigamePlayer> loseplayers = new ArrayList<MinigamePlayer>();
// loseplayers.addAll(event.getLosingPlayers());
// if(plugin.getSQL() != null && mgm.isEnabled()){
//// new SQLCompletionSaver(mgm.getName(), loseplayers, mdata.minigameType(mgm.getType()), false);
// List<SQLPlayer> sqlplayers = new ArrayList<SQLPlayer>();
// for(MinigamePlayer ply : loseplayers){
// ply.setEndTime(Calendar.getInstance().getTimeInMillis());
// sqlplayers.add(new SQLPlayer(mgm.getName(), ply.getName(), 0, 1, ply.getKills(), ply.getDeaths(), ply.getScore(), ply.getReverts(), ply.getEndTime() - ply.getStartTime()));
// plugin.addSQLToStore(sqlplayers);
// plugin.startSQLCompletionSaver();
// for(int i = 0; i < loseplayers.size(); i++){
// if(loseplayers.get(i) instanceof MinigamePlayer){
// final MinigamePlayer p = loseplayers.get(i);
//// Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
//// @Override
//// public void run() {
// p.sendMessage(MinigameUtils.getLang("player.quit.plyBeatenMsg"), "error");
// quitMinigame(p, true);
// else{
// loseplayers.remove(i);
// mgm.setMpTimer(null);
// for(MinigamePlayer pl : loseplayers){
// mgm.getPlayers().remove(pl);
// for(int i = 0; i < winplayers.size(); i++){
// if(winplayers.get(i) instanceof MinigamePlayer){
// final MinigamePlayer p = winplayers.get(i);
// Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
// @Override
// public void run() {
// endMinigame(p);
// else{
// winplayers.remove(i);
// mgm.setMpTimer(null);
@Deprecated
public boolean playerInMinigame(Player player){
return minigamePlayers.get(player.getName()).isInMinigame();
}
@Deprecated
public List<Player> playersInMinigame(){
List<Player> players = new ArrayList<Player>();
for(Player player : plugin.getServer().getOnlinePlayers()){
if(playerInMinigame(player)){
players.add(player);
}
}
return players;
}
public void addMinigamePlayer(Player player){
minigamePlayers.put(player.getName(), new MinigamePlayer(player));
}
public void removeMinigamePlayer(Player player){
if(minigamePlayers.containsKey(player.getName())){
minigamePlayers.remove(player.getName());
}
}
public MinigamePlayer getMinigamePlayer(Player player){
return minigamePlayers.get(player.getName());
}
public MinigamePlayer getMinigamePlayer(UUID uuid){
for(MinigamePlayer p : minigamePlayers.values()){
if(p.getUUID() == uuid)
return p;
}
return null;
}
public MinigamePlayer getMinigamePlayer(String player){
return minigamePlayers.get(player);
}
public Collection<MinigamePlayer> getAllMinigamePlayers(){
return minigamePlayers.values();
}
public boolean hasMinigamePlayer(String name){
return minigamePlayers.containsKey(name);
}
public boolean hasMinigamePlayer(UUID uuid){
for(MinigamePlayer p : minigamePlayers.values()){
if(p.getUUID() == uuid)
return true;
}
return false;
}
public List<String> checkRequiredFlags(MinigamePlayer player, String minigame){
List<String> checkpoints = new ArrayList<String>();
checkpoints.addAll(mdata.getMinigame(minigame).getFlags());
List<String> pchecks = player.getFlags();
if(!pchecks.isEmpty()){
checkpoints.removeAll(pchecks);
}
return checkpoints;
}
public boolean onPartyMode(){
return partyMode;
}
public void setPartyMode(boolean mode){
partyMode = mode;
}
public void partyMode(MinigamePlayer player){
if(onPartyMode()){
Location loc = player.getPlayer().getLocation();
Firework firework = (Firework) player.getPlayer().getWorld().spawnEntity(loc, EntityType.FIREWORK);
FireworkMeta fwm = firework.getFireworkMeta();
Random chance = new Random();
Type type = Type.BALL_LARGE;
if(chance.nextInt(100) < 50){
type = Type.BALL;
}
Color col = Color.fromRGB(chance.nextInt(255), chance.nextInt(255), chance.nextInt(255));
FireworkEffect effect = FireworkEffect.builder().with(type).withColor(col).flicker(chance.nextBoolean()).trail(chance.nextBoolean()).build();
fwm.addEffect(effect);
fwm.setPower(1);
firework.setFireworkMeta(fwm);
}
}
public void partyMode(MinigamePlayer player, int amount, long delay){
if(!onPartyMode()) return;
final int fcount = amount;
final MinigamePlayer fplayer = player;
final long fdelay = delay;
partyMode(fplayer);
if(amount == 1) return;
Bukkit.getScheduler().scheduleSyncDelayedTask(plugin, new Runnable() {
@Override
public void run() {
if(fplayer != null){
partyMode(fplayer, fcount - 1, fdelay);
}
}
}, delay);
}
public List<String> getDeniedCommands() {
return deniedCommands;
}
public void setDeniedCommands(List<String> deniedCommands) {
this.deniedCommands = deniedCommands;
}
public void addDeniedCommand(String command){
deniedCommands.add(command);
}
public void removeDeniedCommand(String command){
deniedCommands.remove(command);
}
public void saveDeniedCommands(){
plugin.getConfig().set("disabledCommands", deniedCommands);
plugin.saveConfig();
}
public void loadDeniedCommands(){
setDeniedCommands(plugin.getConfig().getStringList("disabledCommands"));
}
}
|
package com.handmark.pulltorefresh.library;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Interpolator;
import android.widget.LinearLayout;
import com.handmark.pulltorefresh.library.internal.LoadingLayout;
public abstract class PullToRefreshBase<T extends View> extends LinearLayout {
final class SmoothScrollRunnable implements Runnable {
static final int ANIMATION_DURATION_MS = 190;
static final int ANIMATION_FPS = 1000 / 60;
private final Interpolator interpolator;
private final int scrollToY;
private final int scrollFromY;
private final Handler handler;
private boolean continueRunning = true;
private long startTime = -1;
private int currentY = -1;
public SmoothScrollRunnable(Handler handler, int fromY, int toY) {
this.handler = handler;
this.scrollFromY = fromY;
this.scrollToY = toY;
this.interpolator = new AccelerateDecelerateInterpolator();
}
@Override
public void run() {
/**
* Only set startTime if this is the first time we're starting, else
* actually calculate the Y delta
*/
if (startTime == -1) {
startTime = System.currentTimeMillis();
} else {
/**
* We do do all calculations in long to reduce software float
* calculations. We use 1000 as it gives us good accuracy and
* small rounding errors
*/
long normalizedTime = (1000 * (System.currentTimeMillis() - startTime)) / ANIMATION_DURATION_MS;
normalizedTime = Math.max(Math.min(normalizedTime, 1000), 0);
final int deltaY = Math.round((scrollFromY - scrollToY)
* interpolator.getInterpolation(normalizedTime / 1000f));
this.currentY = scrollFromY - deltaY;
setHeaderScroll(currentY);
}
// If we're not at the target Y, keep going...
if (continueRunning && scrollToY != currentY) {
handler.postDelayed(this, ANIMATION_FPS);
}
}
public void stop() {
this.continueRunning = false;
this.handler.removeCallbacks(this);
}
};
// Constants
static final float FRICTION = 2.0f;
static final int PULL_TO_REFRESH = 0x0;
static final int RELEASE_TO_REFRESH = 0x1;
static final int REFRESHING = 0x2;
public static final int MODE_PULL_DOWN_TO_REFRESH = 0x1;
public static final int MODE_PULL_UP_TO_REFRESH = 0x2;
public static final int MODE_BOTH = 0x3;
// Fields
private int touchSlop;
private float initialMotionY;
private float lastMotionX;
private float lastMotionY;
private boolean isBeingDragged = false;
private int state = PULL_TO_REFRESH;
private int mode = MODE_PULL_DOWN_TO_REFRESH;
private int currentMode;
private boolean disableScrollingWhileRefreshing = true;
T refreshableView;
private boolean isPullToRefreshEnabled = true;
private LoadingLayout headerLayout;
private LoadingLayout footerLayout;
private int headerHeight;
private final Handler handler = new Handler();
private OnRefreshListener onRefreshListener;
private SmoothScrollRunnable currentSmoothScrollRunnable;
// Constructors
public PullToRefreshBase(Context context) {
this(context, null);
}
public PullToRefreshBase(Context context, int mode) {
this(context);
this.mode = mode;
}
public PullToRefreshBase(Context context, AttributeSet attrs) {
super(context, attrs);
init(context, attrs);
}
// Getter & Setter
/**
* Deprecated. Use {@link #getRefreshableView()} from now on.
*
* @deprecated
* @return The Refreshable View which is currently wrapped
*/
public final T getAdapterView() {
return refreshableView;
}
/**
* Get the Wrapped Refreshable View. Anything returned here has already been
* added to the content view.
*
* @return The View which is currently wrapped
*/
public final T getRefreshableView() {
return refreshableView;
}
/**
* Whether Pull-to-Refresh is enabled
*
* @return enabled
*/
public final boolean isPullToRefreshEnabled() {
return isPullToRefreshEnabled;
}
/**
* By default the Widget disabled scrolling on the Refreshable View while
* refreshing. This method can change this behaviour.
*
* @param disableScrollingWhileRefreshing
* - true if you want to disable scrolling while refreshing
*/
public void setDisableScrollingWhileRefreshing(boolean disableScrollingWhileRefreshing) {
this.disableScrollingWhileRefreshing = disableScrollingWhileRefreshing;
}
/**
* Mark the current Refresh as complete. Will Reset the UI and hide the
* Refreshing View
*/
public final void onRefreshComplete() {
if (state != PULL_TO_REFRESH) {
resetHeader();
}
}
/**
* Set OnRefreshListener for the Widget
*
* @param listener
* - Listener to be used when the Widget is set to Refresh
*/
public final void setOnRefreshListener(OnRefreshListener listener) {
onRefreshListener = listener;
}
/**
* A mutator to enable/disable Pull-to-Refresh for the current View
*
* @param enable
* Whether Pull-To-Refresh should be used
*/
public final void setPullToRefreshEnabled(boolean enable) {
this.isPullToRefreshEnabled = enable;
}
/**
* Set Text to show when the Widget is being pulled, and will refresh when
* released
*
* @param releaseLabel
* - String to display
*/
public final void setReleaseLabel(String releaseLabel) {
if (null != headerLayout) {
headerLayout.setReleaseLabel(releaseLabel);
}
if (null != footerLayout) {
footerLayout.setReleaseLabel(releaseLabel);
}
}
/**
* Set Text to show when the Widget is being Pulled
*
* @param pullLabel
* - String to display
*/
public final void setPullLabel(String pullLabel) {
if (null != headerLayout) {
headerLayout.setPullLabel(pullLabel);
}
if (null != footerLayout) {
footerLayout.setPullLabel(pullLabel);
}
}
/**
* Set Text to show when the Widget is refreshing
*
* @param refreshingLabel
* - String to display
*/
public final void setRefreshingLabel(String refreshingLabel) {
if (null != headerLayout) {
headerLayout.setRefreshingLabel(refreshingLabel);
}
if (null != footerLayout) {
footerLayout.setRefreshingLabel(refreshingLabel);
}
}
public void setRefreshing() {
this.setRefreshing(true);
}
/**
* Sets the Widget to be in the refresh state. The UI will be updated to
* show the 'Refreshing' view.
*
* @param doScroll
* - true if you want to force a scroll to the Refreshing view.
*/
public void setRefreshing(boolean doScroll) {
if (state == REFRESHING)
return;
state = REFRESHING;
switch (currentMode) {
case MODE_PULL_DOWN_TO_REFRESH:
if (doScroll)
smoothScrollTo(-headerHeight);
headerLayout.refreshing();
break;
case MODE_PULL_UP_TO_REFRESH:
if (doScroll)
smoothScrollTo(headerHeight);
footerLayout.refreshing();
break;
}
}
public final boolean hasPullFromTop() {
return currentMode != MODE_PULL_UP_TO_REFRESH;
}
// Methods for/from SuperClass/Interfaces
@Override
public final boolean onTouchEvent(MotionEvent event) {
if (!isPullToRefreshEnabled) {
return false;
}
if (state == REFRESHING && disableScrollingWhileRefreshing) {
return true;
}
if (event.getAction() == MotionEvent.ACTION_DOWN && event.getEdgeFlags() != 0) {
return false;
}
switch (event.getAction()) {
case MotionEvent.ACTION_MOVE: {
if (isBeingDragged) {
lastMotionY = event.getY();
this.pullEvent();
}
break;
}
case MotionEvent.ACTION_DOWN: {
if (isReadyForPull()) {
lastMotionY = initialMotionY = event.getY();
}
break;
}
case MotionEvent.ACTION_CANCEL: {
if (isBeingDragged) {
isBeingDragged = false;
if (state == RELEASE_TO_REFRESH && null != onRefreshListener) {
setRefreshing(true);
onRefreshListener.onRefresh();
} else {
smoothScrollTo(0);
}
}
break;
}
case MotionEvent.ACTION_UP: {
if (isBeingDragged) {
isBeingDragged = false;
if (state == RELEASE_TO_REFRESH && null != onRefreshListener) {
setRefreshing(true);
onRefreshListener.onRefresh();
} else {
smoothScrollTo(0);
}
}
break;
}
}
return true;
}
@Override
public final boolean onInterceptTouchEvent(MotionEvent event) {
if (!isPullToRefreshEnabled) {
return false;
}
if (state == REFRESHING && disableScrollingWhileRefreshing) {
return true;
}
final int action = event.getAction();
if (action == MotionEvent.ACTION_CANCEL || action == MotionEvent.ACTION_UP) {
isBeingDragged = false;
return false;
}
if (action != MotionEvent.ACTION_DOWN && isBeingDragged) {
return true;
}
switch (action) {
case MotionEvent.ACTION_MOVE: {
if (isReadyForPull()) {
final float y = event.getY();
final float dy = y - lastMotionY;
final float yDiff = Math.abs(dy);
final float xDiff = Math.abs(event.getX() - lastMotionX);
if (yDiff > touchSlop && yDiff > xDiff) {
if ((mode == MODE_PULL_DOWN_TO_REFRESH || mode == MODE_BOTH) && dy >= 0.0001f
&& isReadyForPullDown()) {
lastMotionY = y;
isBeingDragged = true;
if (mode == MODE_BOTH) {
currentMode = MODE_PULL_DOWN_TO_REFRESH;
}
} else if ((mode == MODE_PULL_UP_TO_REFRESH || mode == MODE_BOTH) && dy <= 0.0001f
&& isReadyForPullUp()) {
lastMotionY = y;
isBeingDragged = true;
if (mode == MODE_BOTH) {
currentMode = MODE_PULL_UP_TO_REFRESH;
}
}
}
}
break;
}
case MotionEvent.ACTION_DOWN: {
if (isReadyForPull()) {
lastMotionY = initialMotionY = event.getY();
lastMotionX = event.getX();
isBeingDragged = false;
}
break;
}
}
return isBeingDragged;
}
protected void addRefreshableView(Context context, T refreshableView) {
addView(refreshableView, new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, 0, 1.0f));
}
/**
* This is implemented by derived classes to return the created View. If you
* need to use a custom View (such as a custom ListView), override this
* method and return an instance of your custom class.
*
* Be sure to set the ID of the view in this method, especially if you're
* using a ListActivity or ListFragment.
*
* @param context
* @param attrs
* AttributeSet from wrapped class. Means that anything you
* include in the XML layout declaration will be routed to the
* created View
* @return New instance of the Refreshable View
*/
protected abstract T createRefreshableView(Context context, AttributeSet attrs);
/**
* Implemented by derived class to return whether the View is in a state
* where the user can Pull to Refresh by scrolling down.
*
* @return true if the View is currently the correct state (for example, top
* of a ListView)
*/
protected abstract boolean isReadyForPullDown();
/**
* Implemented by derived class to return whether the View is in a state
* where the user can Pull to Refresh by scrolling up.
*
* @return true if the View is currently in the correct state (for example,
* bottom of a ListView)
*/
protected abstract boolean isReadyForPullUp();
// Methods
protected final void resetHeader() {
state = PULL_TO_REFRESH;
isBeingDragged = false;
if (null != headerLayout) {
headerLayout.reset();
}
if (null != footerLayout) {
footerLayout.reset();
}
smoothScrollTo(0);
}
private void init(Context context, AttributeSet attrs) {
setOrientation(LinearLayout.VERTICAL);
touchSlop = ViewConfiguration.getTouchSlop();
// Styleables from XML
final TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.PullToRefresh);
mode = a.getInteger(R.styleable.PullToRefresh_mode, MODE_PULL_DOWN_TO_REFRESH);
// Refreshable View
// By passing the attrs, we can add ListView/GridView params via XML
refreshableView = this.createRefreshableView(context, attrs);
this.addRefreshableView(context, refreshableView);
// Loading View Strings
String pullLabel = context.getString(R.string.pull_to_refresh_pull_label);
String refreshingLabel = context.getString(R.string.pull_to_refresh_refreshing_label);
String releaseLabel = context.getString(R.string.pull_to_refresh_release_label);
// Add Loading Views
if (mode == MODE_PULL_DOWN_TO_REFRESH || mode == MODE_BOTH) {
headerLayout = new LoadingLayout(context, MODE_PULL_DOWN_TO_REFRESH, releaseLabel, pullLabel,
refreshingLabel);
addView(headerLayout, 0, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
measureView(headerLayout);
headerHeight = headerLayout.getMeasuredHeight();
}
if (mode == MODE_PULL_UP_TO_REFRESH || mode == MODE_BOTH) {
footerLayout = new LoadingLayout(context, MODE_PULL_UP_TO_REFRESH, releaseLabel, pullLabel, refreshingLabel);
addView(footerLayout, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT));
measureView(footerLayout);
headerHeight = footerLayout.getMeasuredHeight();
}
// Styleables from XML
if (a.hasValue(R.styleable.PullToRefresh_headerTextColor)) {
final int color = a.getColor(R.styleable.PullToRefresh_headerTextColor, Color.BLACK);
if (null != headerLayout) {
headerLayout.setTextColor(color);
}
if (null != footerLayout) {
footerLayout.setTextColor(color);
}
}
if (a.hasValue(R.styleable.PullToRefresh_headerBackground)) {
this.setBackgroundResource(a.getResourceId(R.styleable.PullToRefresh_headerBackground, Color.WHITE));
}
if (a.hasValue(R.styleable.PullToRefresh_adapterViewBackground)) {
refreshableView.setBackgroundResource(a.getResourceId(R.styleable.PullToRefresh_adapterViewBackground,
Color.WHITE));
}
a.recycle();
// Hide Loading Views
switch (mode) {
case MODE_BOTH:
setPadding(getPaddingLeft(), -headerHeight, getPaddingRight(), -headerHeight);
break;
case MODE_PULL_UP_TO_REFRESH:
setPadding(getPaddingLeft(), getPaddingTop(), getPaddingRight(), -headerHeight);
break;
case MODE_PULL_DOWN_TO_REFRESH:
default:
setPadding(getPaddingLeft(), -headerHeight, getPaddingRight(), getPaddingBottom());
break;
}
// If we're not using MODE_BOTH, then just set currentMode to current
// mode
if (mode != MODE_BOTH) {
currentMode = mode;
}
}
private void measureView(View child) {
ViewGroup.LayoutParams p = child.getLayoutParams();
if (p == null) {
p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
}
int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0 + 0, p.width);
int lpHeight = p.height;
int childHeightSpec;
if (lpHeight > 0) {
childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight, MeasureSpec.EXACTLY);
} else {
childHeightSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED);
}
child.measure(childWidthSpec, childHeightSpec);
}
private void pullEvent() {
final int height;
switch (currentMode) {
case MODE_PULL_UP_TO_REFRESH:
height = Math.round(Math.max(initialMotionY - lastMotionY, 0) / FRICTION);
break;
case MODE_PULL_DOWN_TO_REFRESH:
default:
height = Math.round(Math.min(initialMotionY - lastMotionY, 0) / FRICTION);
break;
}
setHeaderScroll(height);
if (state == PULL_TO_REFRESH && headerHeight < Math.abs(height)) {
state = RELEASE_TO_REFRESH;
switch (currentMode) {
case MODE_PULL_UP_TO_REFRESH:
footerLayout.releaseToRefresh();
break;
case MODE_PULL_DOWN_TO_REFRESH:
headerLayout.releaseToRefresh();
break;
}
} else if (state == RELEASE_TO_REFRESH && headerHeight >= Math.abs(height)) {
state = PULL_TO_REFRESH;
switch (currentMode) {
case MODE_PULL_UP_TO_REFRESH:
footerLayout.pullToRefresh();
break;
case MODE_PULL_DOWN_TO_REFRESH:
headerLayout.pullToRefresh();
break;
}
}
}
private void setHeaderScroll(int y) {
scrollTo(0, y);
}
private boolean isReadyForPull() {
switch (mode) {
case MODE_PULL_DOWN_TO_REFRESH:
return isReadyForPullDown();
case MODE_PULL_UP_TO_REFRESH:
return isReadyForPullUp();
case MODE_BOTH:
return isReadyForPullUp() || isReadyForPullDown();
}
return false;
}
private void smoothScrollTo(int y) {
if (null != currentSmoothScrollRunnable) {
currentSmoothScrollRunnable.stop();
}
this.currentSmoothScrollRunnable = new SmoothScrollRunnable(handler, getScrollY(), y);
handler.post(currentSmoothScrollRunnable);
}
// Inner and Anonymous Classes
public static interface OnRefreshListener {
public void onRefresh();
}
public static interface OnLastItemVisibleListener {
public void onLastItemVisible();
}
@Override
public void setLongClickable(boolean longClickable) {
getRefreshableView().setLongClickable(longClickable);
}
}
|
package org.timepedia.chronoscope.client.browser;
import org.timepedia.chronoscope.client.Chart;
import org.timepedia.chronoscope.client.Dataset;
import org.timepedia.chronoscope.client.Datasets;
import org.timepedia.chronoscope.client.XYPlot;
import org.timepedia.chronoscope.client.canvas.ViewReadyCallback;
import org.timepedia.chronoscope.client.data.tuple.Tuple2D;
import org.timepedia.chronoscope.client.gss.GssContext;
import org.timepedia.chronoscope.client.plot.DefaultXYPlot;
import org.timepedia.chronoscope.client.render.XYPlotRenderer;
import org.timepedia.chronoscope.client.util.ArgChecker;
import org.timepedia.chronoscope.client.util.Interval;
import org.timepedia.exporter.client.Export;
import org.timepedia.exporter.client.ExportPackage;
import org.timepedia.exporter.client.Exportable;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.RootPanel;
@ExportPackage("chronoscope")
public class ChartPanel extends Composite implements Exportable {
private Element domElement;
private PlotPanel plotPanel;
private Dataset[] datasets;
private ViewReadyCallback viewReadyCallback;
private int width = 400, height = 250;
private DefaultXYPlot plot;
private XYPlotRenderer plotRenderer;
public final void init() {
ArgChecker.isNotNull(this.datasets, "this.datasets");
ArgChecker.isNotNull(this.domElement, "this.domElement");
createPlot(datasets);
plotPanel = new PlotPanel(domElement, plot, width, height, viewReadyCallback);
initWidget(plotPanel);
}
public void setDimensions(int width, int height) {
this.width = width;
this.height = height;
}
/**
* Replace the datasets and redraw all the elements in the chart.
* It is similar to re-create the graph but the performance is better especially
* with flash canvas.
*
* @param datasets
* array of the new datasets
*/
@Export
public void replaceDatasets(Dataset[] datasets) {
this.datasets = datasets;
}
public void changeDatasets(Dataset[] datasets) {
this.datasets = datasets;
System.out.println("A");
plot.setDatasets(new Datasets<Tuple2D>(datasets));
System.out.println("B");
plot.init();
System.out.println("C");
plot.redraw();
System.out.println("D");
}
public void setDomElement(Element element) {
this.domElement = element;
}
public void setViewReadyCallback(ViewReadyCallback callback) {
setReadyListener(callback);
}
protected XYPlot createPlot(Dataset[] datasetArray) {
DefaultXYPlot plot = new DefaultXYPlot();
plot.setDatasets(new Datasets<Tuple2D>(datasetArray));
plot.setPlotRenderer(new XYPlotRenderer());
return plot;
}
public void attach() {
onAttach();
RootPanel.detachOnWindowClose(this);
}
@Export
public void detach() {
onDetach();
if (getElement() != null) {
try {
getElement().getParentElement().removeChild(getElement());
} catch (Exception e) {
GWT.log("Can't detach " + e, e);
}
}
}
@Export
public Chart getChart() {
return plotPanel.getChart();
}
public int getChartHeight() {
return plotPanel.getChartHeight();
}
public int getChartWidth() {
return plotPanel.getChartWidth();
}
public void setGssContext(GssContext gssContext) {
plotPanel.setGssContext(gssContext);
}
public void setReadyListener(ViewReadyCallback viewReadyCallback) {
if(plotPanel == null) {
this.viewReadyCallback = viewReadyCallback;
}
else {
plotPanel.setReadyListener(viewReadyCallback);
}
}
}
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package net.kirauks.pixelrunner.scene.base;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.Contact;
import com.badlogic.gdx.physics.box2d.ContactImpulse;
import com.badlogic.gdx.physics.box2d.ContactListener;
import com.badlogic.gdx.physics.box2d.Fixture;
import com.badlogic.gdx.physics.box2d.Manifold;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ConcurrentLinkedQueue;
import org.andengine.engine.camera.hud.HUD;
import org.andengine.engine.handler.timer.ITimerCallback;
import org.andengine.engine.handler.timer.TimerHandler;
import org.andengine.entity.IEntity;
import org.andengine.entity.modifier.IEntityModifier.IEntityModifierListener;
import org.andengine.entity.modifier.MoveModifier;
import org.andengine.entity.primitive.Rectangle;
import org.andengine.entity.scene.IOnSceneTouchListener;
import org.andengine.entity.scene.Scene;
import org.andengine.entity.scene.background.AutoParallaxBackground;
import org.andengine.entity.scene.background.ParallaxBackground;
import org.andengine.entity.shape.Shape;
import org.andengine.entity.sprite.Sprite;
import org.andengine.entity.text.Text;
import org.andengine.entity.text.TextOptions;
import org.andengine.extension.physics.box2d.FixedStepPhysicsWorld;
import org.andengine.extension.physics.box2d.PhysicsConnector;
import org.andengine.extension.physics.box2d.PhysicsFactory;
import org.andengine.extension.physics.box2d.PhysicsWorld;
import org.andengine.extension.physics.box2d.util.constants.PhysicsConstants;
import org.andengine.input.touch.TouchEvent;
import org.andengine.util.adt.align.HorizontalAlign;
import org.andengine.util.adt.color.Color;
import org.andengine.util.debug.Debug;
import org.andengine.util.modifier.IModifier;
import net.kirauks.pixelrunner.GameActivity;
import net.kirauks.pixelrunner.game.IPlayerListener;
import net.kirauks.pixelrunner.scene.base.BaseScene;
import net.kirauks.pixelrunner.game.descriptor.LevelDescriptor;
import net.kirauks.pixelrunner.game.element.background.BackgroundElement;
import net.kirauks.pixelrunner.game.element.level.LevelElement;
import net.kirauks.pixelrunner.game.Player;
import net.kirauks.pixelrunner.game.Trail;
import net.kirauks.pixelrunner.manager.AudioManager;
import net.kirauks.pixelrunner.manager.SceneManager;
import net.kirauks.pixelrunner.scene.base.utils.ease.EaseBroadcast;
/**
*
* @author Karl
*/
public abstract class BaseGameScene extends BaseScene implements IOnSceneTouchListener{
private final float RIGHT_SPAWN = 900;
private final float PLAYER_X = 250;
private final float GROUND_LEVEL = 50;
private final float GROUND_WIDTH = 1000;
private final float GROUND_THICKNESS = LevelElement.PLATFORM_THICKNESS;
private final float BROADCAST_LEVEL = 240;
private final float BROADCAST_LEFT = -100;
private final float BROADCAST_RIGHT = 1000;
public class BaseGamePlayerListener implements IPlayerListener{
@Override
public void onJump() {
BaseGameScene.this.activity.vibrate(30);
}
@Override
public void onRoll() {
BaseGameScene.this.activity.vibrate(30);
}
@Override
public void onRollBackJump() {
BaseGameScene.this.player.reset();
BaseGameScene.this.restart();
BaseGameScene.this.activity.vibrate(new long[]{100, 50, 100, 50, 100, 50, 100, 50, 100, 50, 100, 50, 100});
}
@Override
public void onBonus() {
BaseGameScene.this.activity.vibrate(30);
}
};
private boolean isPaused = false;
private boolean isStarted = false;
private boolean isWin = false;
//HUD
protected HUD hud;
//HUD Broadcast
private Text chrono3;
private Text chrono2;
private Text chrono1;
private Text chronoStart;
//HUD - Pause
private Text pause;
//HUD - Win
private Text win;
//Level
protected LevelDescriptor level;
private TimerHandler levelReaderHandler;
private ITimerCallback levelReaderAction;
private TimerHandler levelWinHandler;
//Background
private AutoParallaxBackground autoParallaxBackground;
private List<Sprite> backgroundParallaxLayers = new LinkedList<Sprite>();
private float parallaxFactor = 1f;
//Graphics
protected Player player;
protected Trail playerTrail;
private Rectangle ground;
//Physic
protected PhysicsWorld physicWorld;
private Body groundBody;
//Elements memory
private ConcurrentLinkedQueue<Shape> levelElements = new ConcurrentLinkedQueue<Shape>();
public BaseGameScene(LevelDescriptor level){
this.level = level;
this.createBackground();
this.createLevelSpwaner();
}
@Override
public void createScene() {
this.initPhysics();
this.createPlayer();
this.createGround();
this.createHUD();
this.setOnSceneTouchListener(this);
}
public void initPhysics(){
this.physicWorld = new FixedStepPhysicsWorld(60, new Vector2(0, -50), false);
this.physicWorld.setContactListener(new ContactListener(){
@Override
public void beginContact(Contact contact){
final Fixture xA = contact.getFixtureA();
final Fixture xB = contact.getFixtureB();
//Player contacts
if (xA.getBody().getUserData().equals("player") && xB.getBody().getUserData().equals("ground")
|| xB.getBody().getUserData().equals("player") && xA.getBody().getUserData().equals("ground")){
if(!BaseGameScene.this.player.isRolling()){
BaseGameScene.this.player.resetMovements();
}
}
if(xA.getBody().getUserData().equals("player") && xB.getBody().getUserData() instanceof LevelElement){
LevelElement element = (LevelElement)xB.getBody().getUserData();
if(element.isPlatform()){
float playerY = xA.getBody().getPosition().y * PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT - BaseGameScene.this.player.getHeight() / 2;
float elementY = xB.getBody().getPosition().y * PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT + LevelElement.PLATFORM_THICKNESS / 2;
if (playerY >= elementY && xA.getBody().getLinearVelocity().y < 0.5) {
element.doPlayerAction(BaseGameScene.this.player);
if(!BaseGameScene.this.player.isRolling()){
BaseGameScene.this.player.resetMovements();
}
}
}
}
if(xB.getBody().getUserData().equals("player") && xA.getBody().getUserData() instanceof LevelElement){
LevelElement element = (LevelElement)xB.getBody().getUserData();
if(element.isPlatform()){
float playerY = xB.getBody().getPosition().y * PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT - BaseGameScene.this.player.getHeight() / 2;
float elementY = xA.getBody().getPosition().y * PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT + LevelElement.PLATFORM_THICKNESS / 2;
if (playerY >= elementY && xB.getBody().getLinearVelocity().y < 0.5) {
element.doPlayerAction(BaseGameScene.this.player);
if(!BaseGameScene.this.player.isRolling()){
BaseGameScene.this.player.resetMovements();
}
}
}
}
}
@Override
public void endContact(Contact contact){
}
@Override
public void preSolve(Contact contact, Manifold oldManifold){
final Fixture xA = contact.getFixtureA();
final Fixture xB = contact.getFixtureB();
if(xA.getBody().getUserData().equals("player") && xB.getBody().getUserData() instanceof LevelElement){
if(BaseGameScene.this.isStarted){
LevelElement element = (LevelElement)xB.getBody().getUserData();
if(element.isPlatform()){
float playerY = xA.getBody().getPosition().y * PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT - BaseGameScene.this.player.getHeight() / 2;
float elementY = xB.getBody().getPosition().y * PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT + LevelElement.PLATFORM_THICKNESS / 2;
if (playerY < elementY) {
contact.setEnabled(false);
}
}
else{
contact.setEnabled(false);
element.doPlayerAction(BaseGameScene.this.player);
}
}
else{
contact.setEnabled(false);
}
if(xB.getBody().getUserData().equals("player") && xA.getBody().getUserData() instanceof LevelElement){
if(BaseGameScene.this.isStarted){
LevelElement element = (LevelElement)xA.getBody().getUserData();
if(element.isPlatform()){
float playerY = xB.getBody().getPosition().y * PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT - BaseGameScene.this.player.getHeight() / 2;
float elementY = xA.getBody().getPosition().y * PhysicsConstants.PIXEL_TO_METER_RATIO_DEFAULT + LevelElement.PLATFORM_THICKNESS / 2;
if (playerY < elementY) {
contact.setEnabled(false);
}
}
else{
contact.setEnabled(false);
element.doPlayerAction(BaseGameScene.this.player);
}
}
else{
contact.setEnabled(false);
}
}
}
}
@Override
public void postSolve(Contact contact, ContactImpulse impulse){
}
});
this.registerUpdateHandler(this.physicWorld);
/*
DebugRenderer debug = new DebugRenderer(this.physicWorld, this.vbom);
this.attachChild(debug);
*/
}
private void createBackground(){
this.autoParallaxBackground = new AutoParallaxBackground(0, 0, 0, 5){
@Override
public void onUpdate(final float pSecondsElapsed) {
super.onUpdate(pSecondsElapsed * BaseGameScene.this.parallaxFactor);
}
};
this.setBackground(this.autoParallaxBackground);
for(BackgroundElement layer : this.level.getBackgroundsElements()){
Sprite layerSprite = new Sprite(layer.x, GROUND_LEVEL + layer.y, this.resourcesManager.gameParallaxLayers.get(layer.getResourceName()), this.vbom);
layerSprite.setColor(new Color(0.4f, 0.4f, 0.4f));
this.backgroundParallaxLayers.add(layerSprite);
layerSprite.setOffsetCenter(-1.5f, -1.5f);
layerSprite.setScale(4f);
this.autoParallaxBackground.attachParallaxEntity(new ParallaxBackground.ParallaxEntity(-layer.speed, layerSprite));
}
}
private void createPlayer(){
this.player = new Player(PLAYER_X, GROUND_LEVEL + GROUND_THICKNESS/2 + 32, this.resourcesManager.player, this.vbom, this.physicWorld) {
@Override
protected void onUpdateColor(){
super.onUpdateColor();
if(BaseGameScene.this.playerTrail != null){
BaseGameScene.this.playerTrail.setColor(this.getColor());
}
}
};
this.player.getBody().setUserData("player");
this.player.registerPlayerListener(new BaseGamePlayerListener());
this.attachChild(this.player);
this.playerTrail = new Trail(36, 0, 0, 64, -340, -300, -2, 2, 25, 30, 50, Trail.ColorMode.NORMAL, this.resourcesManager.trail, this.vbom);
this.playerTrail.bind(this.player);
this.attachChild(this.playerTrail);
this.playerTrail.hide();
this.playerTrail.setZIndex(this.player.getZIndex() - 1);
this.sortChildren();
Body retention = PhysicsFactory.createBoxBody(this.physicWorld, PLAYER_X - this.player.getWidth()/2, 250, 1, 400, BodyDef.BodyType.StaticBody, PhysicsFactory.createFixtureDef(0, 0, 0));
retention.setUserData("retention");
}
private void createGround(){
this.ground = new Rectangle(400, GROUND_LEVEL, GROUND_WIDTH, GROUND_THICKNESS, this.vbom);
this.ground.setColor(LevelElement.COLOR_DEFAULT);
this.groundBody = PhysicsFactory.createBoxBody(this.physicWorld, this.ground, BodyDef.BodyType.StaticBody, PhysicsFactory.createFixtureDef(0, 0, 0));
this.groundBody.setUserData("ground");
this.attachChild(this.ground);
}
protected abstract void onWin();
private void createLevelSpwaner(){
//Level elements
this.levelWinHandler = new TimerHandler(3f, new ITimerCallback(){
@Override
public void onTimePassed(TimerHandler pTimerHandler) {
BaseGameScene.this.unregisterUpdateHandler(pTimerHandler);
BaseGameScene.this.isWin = true;
BaseGameScene.this.onWin();
Sprite player = BaseGameScene.this.player;
final PhysicsConnector physicsConnector = BaseGameScene.this.physicWorld.getPhysicsConnectorManager().findPhysicsConnectorByShape(player);
physicsConnector.getBody().applyForce(135, 0, 0, 0);
BaseGameScene.this.parallaxFactor = 2f;
BaseGameScene.this.registerUpdateHandler(new TimerHandler(2f, new ITimerCallback(){
@Override
public void onTimePassed(final TimerHandler pTimerHandler){
BaseGameScene.this.unregisterUpdateHandler(pTimerHandler);
physicsConnector.getBody().applyForce(-135, 0, 0, 0);
}
}));
BaseGameScene.this.win.setVisible(true);
AudioManager.getInstance().stop();
AudioManager.getInstance().play("mfx/", "win.xm");
BaseGameScene.this.playerTrail.setColorMode(Trail.ColorMode.MULTICOLOR);
}
});
this.levelReaderAction = new ITimerCallback(){
@Override
public void onTimePassed(final TimerHandler pTimerHandler){
if(!BaseGameScene.this.level.hasNext()){
BaseGameScene.this.unregisterUpdateHandler(pTimerHandler);
BaseGameScene.this.registerUpdateHandler(BaseGameScene.this.levelWinHandler);
}
else{
//Level elements spawn
final float baseY = GROUND_LEVEL + GROUND_THICKNESS/2;
final LevelElement[] elementsToSpawn = BaseGameScene.this.level.getNext();
BaseGameScene.this.engine.runOnUpdateThread(new Runnable(){
public void run(){
for(final LevelElement lvlElement : elementsToSpawn){
lvlElement.build(RIGHT_SPAWN, baseY, BaseGameScene.this.vbom, BaseGameScene.this.player, BaseGameScene.this.physicWorld);
BaseGameScene.this.attachChild(lvlElement.getBuildedShape());
lvlElement.getBuildedShape().setZIndex(BaseGameScene.this.player.getZIndex() - 2);
BaseGameScene.this.sortChildren();
BaseGameScene.this.levelElements.add(lvlElement.getBuildedShape());
lvlElement.getBuildedBody().setUserData(lvlElement);
lvlElement.getBuildedBody().setLinearVelocity(new Vector2(-15, 0));
BaseGameScene.this.registerUpdateHandler(new TimerHandler(6f, new ITimerCallback(){
@Override
public void onTimePassed(final TimerHandler pTimerHandler){
BaseGameScene.this.unregisterUpdateHandler(pTimerHandler);
BaseGameScene.this.disposeLevelElement(lvlElement.getBuildedShape());
}
}));
}
}
});
if(!BaseGameScene.this.level.hasNext()){
BaseGameScene.this.unregisterUpdateHandler(pTimerHandler);
BaseGameScene.this.registerUpdateHandler(BaseGameScene.this.levelWinHandler);
}
}
}
};
}
private void createHUD(){
this.hud = new HUD();
this.camera.setHUD(this.hud);
//Broadcast messages
this.chrono3 = new Text(0, 0, resourcesManager.fontPixel_200, "3", vbom);
this.chrono2 = new Text(0, 0, resourcesManager.fontPixel_200, "2", vbom);
this.chrono1 = new Text(0, 0, resourcesManager.fontPixel_200, "1", vbom);
this.chronoStart = new Text(0, 0, resourcesManager.fontPixel_200, "GO!", vbom);
this.chrono3.setVisible(false);
this.chrono2.setVisible(false);
this.chrono1.setVisible(false);
this.chronoStart.setVisible(false);
this.hud.attachChild(this.chrono3);
this.hud.attachChild(this.chrono2);
this.hud.attachChild(this.chrono1);
this.hud.attachChild(this.chronoStart);
//Pause message
this.pause = new Text(GameActivity.CAMERA_WIDTH/2, GameActivity.CAMERA_HEIGHT/2, resourcesManager.fontPixel_200, "PAUSE", vbom);
this.pause.setVisible(false);
this.hud.attachChild(this.pause);
//win message
this.win = new Text(GameActivity.CAMERA_WIDTH/2, GameActivity.CAMERA_HEIGHT/2 + 130, resourcesManager.fontPixel_200, "EPIC", new TextOptions(HorizontalAlign.CENTER), vbom);
this.win.setVisible(false);
Text winSub = new Text(this.win.getWidth()/2, -25f, resourcesManager.fontPixel_200, "WIN!", new TextOptions(HorizontalAlign.CENTER), vbom);
this.win.attachChild(winSub);
this.hud.attachChild(this.win);
}
private synchronized void restart(){
if(this.isStarted){
this.isStarted = false;
this.onRestartBegin();
this.unregisterUpdateHandler(this.levelWinHandler);
this.unregisterUpdateHandler(this.levelReaderHandler);
AudioManager.getInstance().stop();
this.player.resetBonus();
this.playerTrail.hide();
this.parallaxFactor = -10f;
final Shape[] elements = this.levelElements.toArray(new Shape[this.levelElements.size()]);
this.levelElements.clear();
this.engine.runOnUpdateThread(new Runnable() {
@Override
public void run() {
for(Shape element : elements){
PhysicsConnector physicsConnector = BaseGameScene.this.physicWorld.getPhysicsConnectorManager().findPhysicsConnectorByShape(element);
if (physicsConnector != null){
Body body = physicsConnector.getBody();
body.setActive(false);
// The body will be destoyed by the unspwaner later
//BaseGameScene.this.physicWorld.unregisterPhysicsConnector(physicsConnector);
//BaseGameScene.this.physicWorld.destroyBody(body);
}
element.detachSelf();
}
BaseGameScene.this.registerUpdateHandler(new TimerHandler(1f, new ITimerCallback(){
@Override
public void onTimePassed(final TimerHandler pTimerHandler){
BaseGameScene.this.engine.unregisterUpdateHandler(pTimerHandler);
BaseGameScene.this.parallaxFactor = 1f;
BaseGameScene.this.player.resetMovements();
BaseGameScene.this.onRestartEnd();
BaseGameScene.this.start();
}
}));
}
});
}
}
protected abstract void onRestartBegin();
protected abstract void onRestartEnd();
public synchronized void start(){
if(!BaseGameScene.this.isPaused){
this.level.init();
this.onStartBegin();
this.broadcast(this.chrono3, new IEntityModifierListener() {
@Override
public void onModifierStarted(IModifier<IEntity> pModifier, IEntity pItem) {
}
@Override
public void onModifierFinished(IModifier<IEntity> pModifier, IEntity pItem) {
BaseGameScene.this.broadcast(BaseGameScene.this.chrono2, new IEntityModifierListener() {
@Override
public void onModifierStarted(IModifier<IEntity> pModifier, IEntity pItem) {
}
@Override
public void onModifierFinished(IModifier<IEntity> pModifier, IEntity pItem) {
BaseGameScene.this.broadcast(BaseGameScene.this.chrono1, new IEntityModifierListener() {
@Override
public void onModifierStarted(IModifier<IEntity> pModifier, IEntity pItem) {
}
@Override
public void onModifierFinished(IModifier<IEntity> pModifier, IEntity pItem) {
BaseGameScene.this.broadcast(BaseGameScene.this.chronoStart, new IEntityModifierListener() {
@Override
public void onModifierStarted(IModifier<IEntity> pModifier, IEntity pItem) {
AudioManager.getInstance().play("mfx/", BaseGameScene.this.level.getMusic());
BaseGameScene.this.playerTrail.show();
BaseGameScene.this.registerUpdateHandler(BaseGameScene.this.levelReaderHandler = new TimerHandler(BaseGameScene.this.level.getSpawnTime(), true, BaseGameScene.this.levelReaderAction));
BaseGameScene.this.onStartEnd();
BaseGameScene.this.isStarted = true;
}
@Override
public void onModifierFinished(IModifier<IEntity> pModifier, IEntity pItem) {
}
});
}
});
}
});
}
});
}
}
protected abstract void onStartBegin();
protected abstract void onStartEnd();
private void broadcast(final IEntity entity, final IEntityModifierListener listener){
entity.registerEntityModifier(new MoveModifier(0.5f, BROADCAST_RIGHT, BROADCAST_LEVEL, BROADCAST_LEFT, BROADCAST_LEVEL, new IEntityModifierListener() {
@Override
public void onModifierStarted(IModifier<IEntity> pModifier, IEntity pItem) {
entity.setVisible(true);
listener.onModifierStarted(pModifier, pItem);
}
@Override
public void onModifierFinished(IModifier<IEntity> pModifier, IEntity pItem) {
entity.setVisible(false);
listener.onModifierFinished(pModifier, pItem);
}
}, EaseBroadcast.getInstance()));
}
@Override
public void onBackKeyPressed() {
AudioManager.getInstance().stop();
SceneManager.getInstance().unloadGameLevelScene();
}
@Override
public void onPause() {
if(!this.isWin){
this.pause();
}
else{
this.audioManager.pause();
}
}
public void pause(){
this.isPaused = true;
this.chrono1.clearEntityModifiers();
this.chrono2.clearEntityModifiers();
this.chrono3.clearEntityModifiers();
this.chronoStart.clearEntityModifiers();
this.chrono1.setVisible(false);
this.chrono2.setVisible(false);
this.chrono3.setVisible(false);
this.chronoStart.setVisible(false);
this.setIgnoreUpdate(true);
this.pause.setVisible(true);
this.audioManager.pause();
}
public void resume(){
this.isPaused = false;
if(this.isStarted){
this.broadcast(this.chrono3, new IEntityModifierListener() {
@Override
public void onModifierStarted(IModifier<IEntity> pModifier, IEntity pItem) {
BaseGameScene.this.pause.setVisible(false);
}
@Override
public void onModifierFinished(IModifier<IEntity> pModifier, IEntity pItem) {
BaseGameScene.this.broadcast(BaseGameScene.this.chrono2, new IEntityModifierListener() {
@Override
public void onModifierStarted(IModifier<IEntity> pModifier, IEntity pItem) {
}
@Override
public void onModifierFinished(IModifier<IEntity> pModifier, IEntity pItem) {
BaseGameScene.this.broadcast(BaseGameScene.this.chrono1, new IEntityModifierListener() {
@Override
public void onModifierStarted(IModifier<IEntity> pModifier, IEntity pItem) {
}
@Override
public void onModifierFinished(IModifier<IEntity> pModifier, IEntity pItem) {
BaseGameScene.this.setIgnoreUpdate(false);
BaseGameScene.this.audioManager.resume();
}
});
}
});
}
});
}
else{
this.pause.setVisible(false);
this.setIgnoreUpdate(false);
this.audioManager.resume();
this.start();
}
}
@Override
public void onResume() {
if(this.isWin){
this.audioManager.resume();
}
}
@Override
protected void onManagedUpdate(float pSecondsElapsed) {
super.onManagedUpdate(pSecondsElapsed * this.player.getSpeed());
}
@Override
public void disposeScene() {
this.clearUpdateHandlers();
this.destroyPhysicsWorld();
this.camera.setHUD(null);
this.chrono3.detachSelf();
this.chrono3.dispose();
this.chrono2.detachSelf();
this.chrono2.dispose();
this.chrono1.detachSelf();
this.chrono1.dispose();
this.pause.detachSelf();
this.pause.dispose();
this.win.detachSelf();
this.win.dispose();
this.chronoStart.detachSelf();
this.chronoStart.dispose();
this.ground.detachSelf();
this.ground.dispose();
this.playerTrail.detachSelf();
this.playerTrail.dispose();
this.player.detachSelf();
this.player.dispose();
for(Sprite layer : this.backgroundParallaxLayers){
layer.detachSelf();
layer.dispose();
}
this.detachSelf();
this.dispose();
}
private void destroyPhysicsWorld(){
this.levelElements.clear();
this.engine.runOnUpdateThread(new Runnable(){
public void run(){
PhysicsWorld world = BaseGameScene.this.physicWorld;
Iterator<Body> localIterator = BaseGameScene.this.physicWorld.getBodies();
while (true){
if (!localIterator.hasNext()){
world.clearForces();
world.clearPhysicsConnectors();
world.reset();
world.dispose();
System.gc();
return;
}
try{
final Body localBody = (Body) localIterator.next();
world.destroyBody(localBody);
}
catch (Exception localException){
Debug.e(localException);
}
}
}
});
}
private synchronized void disposeLevelElement(final Shape element){
if(this.levelElements.contains(element)){
this.levelElements.remove(element);
this.engine.runOnUpdateThread(new Runnable() {
@Override
public void run() {
final PhysicsConnector physicsConnector = BaseGameScene.this.physicWorld.getPhysicsConnectorManager().findPhysicsConnectorByShape(element);
if (physicsConnector != null){
Body body = physicsConnector.getBody();
body.setActive(false);
BaseGameScene.this.physicWorld.unregisterPhysicsConnector(physicsConnector);
BaseGameScene.this.physicWorld.destroyBody(body);
}
element.detachSelf();
}
});
}
}
public boolean onSceneTouchEvent(Scene pScene, TouchEvent pSceneTouchEvent) {
if (pSceneTouchEvent.isActionDown()){
if(this.isPaused){
this.resume();
}
else if(this.isWin){
this.onBackKeyPressed();
}
else{
if(pSceneTouchEvent.getY() >= 240){
//Jump
this.player.jump();
}
else if(pSceneTouchEvent.getY() < 240){
//Roll
this.player.roll();
}
}
}
return false;
}
}
|
package com.duan.musicoco.app;
import android.app.Application;
import com.duan.musicoco.preference.SettingPreference;
import com.duan.musicoco.setting.AutoSwitchThemeController;
public class App extends Application {
@Override
public void onCreate() {
super.onCreate();
checkAutoThemeSwitch();
}
private void checkAutoThemeSwitch() {
SettingPreference settingPreference = new SettingPreference(this);
AutoSwitchThemeController instance = AutoSwitchThemeController.getInstance(this);
if (settingPreference.autoSwitchNightTheme() && !instance.isSet()) {
instance.setAlarm();
} else {
instance.cancelAlarm();
}
}
}
|
package com.ironz.binaryprefs.files;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
/**
* Concrete file adapter which implements NIO file operations
*/
// TODO: 12/12/16 create benchmarks for MappedByteBuffer and plain direct ByteBuffer
public class NioFileAdapter implements FileAdapter {
private final File srcDir;
public NioFileAdapter(File srcDir) {
this.srcDir = srcDir;
}
@Override
public String[] names() {
return srcDir.list();
}
@Override
public byte[] fetch(String name) throws Exception {
FileChannel channel = null;
RandomAccessFile randomAccessFile = null;
try {
File file = new File(srcDir, name);
randomAccessFile = new RandomAccessFile(file, "r");
channel = randomAccessFile.getChannel();
int size = (int) randomAccessFile.length();
MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, size);
byte[] bytes = new byte[size];
buffer.get(bytes);
return bytes;
} finally {
try {
if (randomAccessFile != null) randomAccessFile.close();
if (channel != null) channel.close();
} catch (IOException ignored) {
}
}
}
@Override
public void save(String name, byte[] bytes) throws Exception {
FileChannel channel = null;
RandomAccessFile randomAccessFile = null;
try {
File file = new File(srcDir, name);
randomAccessFile = new RandomAccessFile(file, "rw");
channel = randomAccessFile.getChannel();
MappedByteBuffer byteBuffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, bytes.length);
byteBuffer.put(bytes);
channel.write(byteBuffer);
} finally {
try {
if (randomAccessFile != null) randomAccessFile.close();
if (channel != null) channel.close();
} catch (Exception ignored) {
}
}
}
@Override
public boolean clear() {
boolean allDeleted = true;
for (File file : srcDir.listFiles()) {
boolean deleted = file.delete();
if (!deleted) {
allDeleted = false;
}
}
return allDeleted;
}
@Override
public boolean remove(String name) {
File file = new File(srcDir, name);
return file.delete();
}
}
|
package algorithms.imageProcessing.matching;
import algorithms.QuickSort;
import algorithms.compGeometry.LinesAndAngles;
import algorithms.misc.Histogram;
import algorithms.misc.HistogramHolder;
import algorithms.misc.MiscMath;
import algorithms.util.Errors;
import algorithms.util.IntIntDouble;
import algorithms.util.PairInt;
import algorithms.util.PairIntArray;
import gnu.trove.iterator.TIntIterator;
import gnu.trove.list.TDoubleList;
import gnu.trove.list.TIntList;
import gnu.trove.list.array.TDoubleArrayList;
import gnu.trove.list.array.TIntArrayList;
import gnu.trove.map.TIntDoubleMap;
import gnu.trove.map.TIntIntMap;
import gnu.trove.map.TIntObjectMap;
import gnu.trove.map.hash.TIntIntHashMap;
import gnu.trove.map.hash.TIntObjectHashMap;
import gnu.trove.set.TIntSet;
import gnu.trove.set.hash.TIntHashSet;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
import java.util.logging.Logger;
import javax.swing.JScrollPane;
/**
NOTE: NOT READY FOR USE YET.
TODO: need to change read pattern of
difference sat, and optimization.
"Efficient Partial Shape Matching
of Outer Contours: by Donoser
- called IS-Match, integral shape match
- a silhouette of ordered points are sampled
making it an "order preserved assignment problem".
- a chord angle descriptor is local and global and
is invariant to similarity transformations.
- the method returns partial sub matches
so works with articulated data and occluded shapes
- uses an efficient integral image based matching algorithm
- the multi-objective optimization uses principles of
Paretto efficiency, defined with the fraction of the
total matched and the summed differences of angles.
- the final result returned is the sequences and
the total fraction matched and summed absolute differences,
instead of the Salukwadze distance of a Paretto frontier.
* point sampling:
(a) same number of points over each contour
- can handle similarity transforms, but not occlusion
(b) OR, equidistant points
- can handle occlusion, but not scale
** equidistant is used here.
NOTE: changes will be made soon to accomodate
search of remaining points when there are
unequal number of points.
The runtime complexity for building the integral
image is O(m*n) where n and m are the number of sampled
points on the input shapes.
The runtime complexity for the search of the
integral image of summed differences and analysis
will be added here:
*
* @author nichole
*/
public class PartialShapeMatcher {
/**
* in sampling the boundaries of the shapes, one can
* choose to use the same number for each (which can result
* in very different spacings for different sized curves)
* or one can choose a set distance between sampling
* points.
* dp is the set distance between sampling points.
The authors use 3 as an example.
*/
protected int dp = 5;
protected Logger log = Logger.getLogger(this.getClass().getName());
public void overrideSamplingDistance(int d) {
this.dp = d;
}
/**
* NOT READY FOR USE.
A shape is defined as the clockwise ordered sequence
of points P_1...P_N
and the shape to match has points Q_1...Q_N.
The spacings used within this method are equidistant
and the default is 5, so override that if a different number
is needed.
The fixed equidistant spacing is invariant to rotation
and translation, but not to scale, so if the user needs to solve
for scale, need to do so outside of this method, that is, apply
scale changes to the datasets before use of this method..
* @param p
* @param q
*/
public Sequences match(PairIntArray p, PairIntArray q) {
log.info("p.n=" + p.getN() + " q.n=" + q.getN());
int diffN = p.getN() - q.getN();
//md[0:n2-1][0:n1-1][0:n1-1]
float[][][] md;
int n1, n2;
if (diffN <= 0) {
n1 = p.getN();
n2 = q.getN();
md = createDifferenceMatrices(p, q);
} else {
n1 = q.getN();
n2 = p.getN();
md = createDifferenceMatrices(q, p);
}
log.info("p=" + p.toString());
log.info("q=" + q.toString());
/*
the matrices in md can be analyzed for best
global solution and/or separately for best local
solution.
This method will return results for a local
solution to create the point correspondence list.
Note that the local best could be two different
kinds of models, so might write two
different methods for the results.
(1) the assumption of same object but with some
amount of occlusion, hence gaps in correspondence.
(2) the assumption of same object but with
some parts being differently oriented, for
an example, the scissors opened versus closed.
*/
/*
need sum of differences in sequence and the fraction
of the whole.
paretto efficiency is that all are at a compromise of best state,
such that increasing the state of one did not worsen the
state of another.
prefer:
-- smaller total difference for largest fraction of whole
-- 2ndly, largest total coverage
Note that for the rigid model (excepting scale transformation)
one would want to maximize the 3nd point, coverage, first
with a consistent transformation.
The articulated model chooses the 2nd point, second to get
best fits of components first.
*/
/*
NOTE: this may change with more testing.
goal is to find the best chains of sequential
matches below a threshold and then use
multi-objective optimization to choose the
best consistent aggregation of chains as the
final correspondence list.
the rigid model allowing occlusion
(not yet implemented) will
likely be a better solution and is similar to
matching patterns elsewhere in this project.
focusing first on this articulated match to
look at the range of ability to identify a
whole object which may be occluded and which
may have parts which have separate rigid
rotation (such as the scissors opened bersus
closed) and which may include extended objects due
to the segmentation including a part of
the background.
caveats to the articulated match are that
greedy solutions built by fraction of whole
may have many different kinds of errors,
but composing sequences with the top k
fraction (at every aggregation of sequential
segments) quickly leads to an unfeasibly
large number of sequences to evaluate.
*/
List<Sequence> sequences = new ArrayList<Sequence>();
List<Sequence> discarded = new ArrayList<Sequence>();
int rMax = (int)Math.sqrt(n1);
if (rMax < 2) {
rMax = 2;
}
int rMin = 2;
//rMax = n1/4;
//rMin = rMax;
// build the matching sequential sequences by
// searching from block size 2 to size sqrt(n1)
extractSimilar(md, sequences, discarded, rMin, rMax);
//changed to form adjacent segments where wrap
// around is present, so assert format here
assert(assertNoWrapAround(sequences));
Sequences sequences0 = matchArticulated(
sequences, discarded, n1, n2);
assert(assertNoWrapAround(sequences));
//addFeasibleDiscarded(sequences0, discarded);
if (diffN <= 0) {
return sequences0;
}
transpose(sequences0, n1, n2);
return sequences0;
}
protected void extractSimilar(float[][][] md,
List<Sequence> sequences,
List<Sequence> discarded, int rMin, int rMax) {
//md[0:n2-1][0:n1-1][0:n1-1]
int n2 = md.length;
int n1 = md[0].length;
// 23 degrees is 0.4014
double thresh = 23. * Math.PI/180.;
MinDiffs mins = new MinDiffs(n1);
for (int r = rMin; r <= rMax; ++r) {
findMinDifferenceMatrix(md, r, thresh, mins);
}
// 10 degrees is 0.175
double tolerance = 0.25;//0.1;//0.25;
DiffMatrixResults equivBest = new DiffMatrixResults(n1);
for (int r = rMin; r <= rMax; ++r) {
findEquivalentBest(md, r, mins, thresh, tolerance,
n1, n2, equivBest);
}
equivBest.sortListIndexes();
int[] topOffsets = findTopOffsets(equivBest, n1, n2);
if (topOffsets != null) {
log.info("topOffsets=" + Arrays.toString(topOffsets));
}
/*
StringBuilder sb = new StringBuilder();
for (int i = 0; i < n1; ++i) {
IndexesAndDiff iad = equivBest.indexesAndDiff[i];
if (iad != null) {
LinkedList<IntIntDouble> list =
iad.list;
for (IntIntDouble iid : list) {
sb.append(String.format(
"i=%d j=%d offset=%d d=%.4f\n",
i, iid.getA(), iid.getB(),
iid.getC()));
}
}
log.info(sb.toString());
sb.delete(0, sb.length());
}*/
for (int idx1 = 0; idx1 < n1; ++idx1) {
IndexesAndDiff indexesAndDiff =
equivBest.indexesAndDiff[idx1];
if (indexesAndDiff == null) {
continue;
}
LinkedList<IntIntDouble> list =
indexesAndDiff.list;
double sumAbsDiff = 0;
for (IntIntDouble node : list) {
int idx2 = node.getA();
double diff = node.getC();
sumAbsDiff += Math.abs(diff);
int offset = node.getB();
Sequence s = new Sequence(n1, n2, offset);
s.startIdx1 = idx1;
s.startIdx2 = idx2;
s.stopIdx2 = idx2;
//search through higher index lists to aggregate
int nextLIdx = idx1 + 1;
while (nextLIdx < n1) {
IndexesAndDiff indexesAndDiff2 =
equivBest.indexesAndDiff[nextLIdx];
if (indexesAndDiff2 == null) {
break;
}
Map<PairInt, IntIntDouble> jLookupMap2 =
indexesAndDiff2.jLookupMap;
int idx3 = s.stopIdx2 + 1;
PairInt key2 = new PairInt(idx3, offset);
IntIntDouble node2 = jLookupMap2.get(key2);
if (node2 != null) {
s.stopIdx2 = idx3;
diff = node2.getC();
sumAbsDiff += Math.abs(diff);
LinkedList<IntIntDouble> list2
= indexesAndDiff2.list;
list2.remove(node2);
jLookupMap2.remove(key2);
} else {
break;
}
nextLIdx++;
}
int n = s.length();
s.fractionOfWhole = (float)n/(float)n1;
s.absAvgSumDiffs = (float)(sumAbsDiff/(float)n);
if (s.stopIdx2 - s.startIdx2 > 1) {
if (s.absAvgSumDiffs <= tolerance) {
sequences.add(s);
log.info(String.format(
"%d seq %d:%d to %d frac=%.4f avg diff=%.4f",
(sequences.size() - 1),
s.startIdx1, s.startIdx2, s.stopIdx2,
s.fractionOfWhole, s.absAvgSumDiffs));
} else if (s.absAvgSumDiffs <= 3*tolerance) {
discarded.add(s);
}
}
}
}
log.info(sequences.size() + " sequences");
}
protected Sequences matchArticulated(List<Sequence> sequences,
List<Sequence> higherErrorSequences, int n1, int n2) {
// (1) choose the topK from sequences sorted by fraction
// and then add to those
int topK = 10 * (1 + (Math.max(n1, n2))/250);
int end = (topK > sequences.size()) ? sequences.size() : topK;
Collections.sort(sequences, new SequenceComparator2());
List<Sequences> tracks = new ArrayList<Sequences>();
for (int i = 0; i < end; ++i) {
Sequence s = sequences.get(i);
Sequences track = new Sequences();
tracks.add(track);
track.getSequences().add(s.copy());
log.info("seed " + i + " : " + s);
}
return matchArticulated(sequences, higherErrorSequences,
tracks, n1, n2);
}
protected Sequences matchArticulated(List<Sequence> sequences,
List<Sequence> higherErrorSequences,
List<Sequences> seedTracks, int n1, int n2) {
print0(sequences, "S");
print0(higherErrorSequences, "DS");
print("sort0:", sequences);
// use histogram to find 2 highest peaks:
int[] top2Offsets = findOffsets(sequences, n1, n2);
if (top2Offsets != null) {
log.info("top offsets=" + Arrays.toString(top2Offsets)
+ " n1=" + n1 + " n2=" + n2);
}
// (1) combine seedTracks that have same offset
combineIfSameOffset(seedTracks);
Collections.sort(sequences, new SequenceComparator2());
// (2) put the sorted sequences into sets with keys
// being offsets
TreeMap<Integer, List<Sequence>> seqeuncesMap =
placeInMapByOffsets(sequences);
// (3) add to seedTracks, the best of same offset sequences.
for (int i = 0; i < seedTracks.size(); ++i) {
Sequences track = seedTracks.get(i);
int offset = track.getSequences().get(0).getOffset();
List<Sequence> sList = seqeuncesMap.get(Integer.valueOf(offset));
track.getSequences().addAll(sList);
Sequence.mergeSequences(track.getSequences());
}
// (4) add to seedTracks, the best of nearest offsets
// within a tolerance, if they don't intersect
// a current range
int maxDiffOffset = 5;
// -- if does not intersect existing range
// -- if is consistent clockwise
assert(assertNoWrapAround2(seedTracks));
for (int i = 0; i < seedTracks.size(); ++i) {
Sequences track = seedTracks.get(i);
log.info("pre-sorted track " + i + ": " + track.toString());
}
//filterForConsistentClockwise(tracks);
// calculate the stats for each track (== Sequences)
for (Sequences track : seedTracks) {
int sumLen = 0;
float sumFrac = 0;
double sumDiffs = 0;
for (Sequence s : track.getSequences()) {
int len = s.stopIdx2 - s.startIdx2 + 1;
float diff = s.absAvgSumDiffs * len;
sumLen += len;
sumDiffs += diff;
sumFrac += s.fractionOfWhole;
}
track.setAbsSumDiffs(sumDiffs);
track.setAvgSumDiffs((float)(sumDiffs/(float)sumLen));
track.setFractionOfWhole(sumFrac);
}
Collections.sort(seedTracks, new TrackComparator(n1));
for (int i = 0; i < seedTracks.size(); ++i) {
Sequences track = seedTracks.get(i);
log.info("track " + i + ": " + track.toString());
}
if (seedTracks.isEmpty()) {
return null;
}
return seedTracks.get(0);
}
protected double matchRigidWithOcclusion(List<Sequence> sequences,
int n1, int n2) {
// sort by desc fraction of whole
Collections.sort(sequences, new SequenceComparator2());
for (int i = 0; i < sequences.size(); ++i) {
log.info(String.format("FSORT %d %s", i, sequences.get(i).toString()));
}
// evaluate the topk items as a transformation
int topK = 10 * (1 + (Math.max(n1, n2))/250);
int end = (topK > sequences.size()) ? sequences.size() : topK;
for (int i = 0; i < sequences.size(); ++i) {
Sequence s = sequences.get(i);
}
throw new UnsupportedOperationException("not yet implemented");
}
/**
* create the matrices of differences between p
* and q. Note that the matrix differences are
* absolute differences.
* index0 is rotations of q, index1 is p.n, index2 is q.n
returns a[0:q.n-1][0:p.n-1][0:p.n-1]
*/
protected float[][][] createDifferenceMatrices(
PairIntArray p, PairIntArray q) {
if (p.getN() > q.getN()) {
throw new IllegalArgumentException(
"q.n must be >= p.n");
}
/*
| a_1_1...a_1_N |
| a_2_1...a_2_N |
| a_N_1...a_N_N |
elements on the diagonal are zero
to shift to different first point as reference,
can shift down k-1 rows and left k-1 columns.
*/
//log.fine("a1:");
float[][] a1 = createDescriptorMatrix(p, p.getN());
//log.fine("a2:");
float[][] a2 = createDescriptorMatrix(q, q.getN());
// TODO: look at histograms of angles.
/*
float binSz = (float)(Math.PI/8.f);
HistogramHolder hist1 = createHistogram(a1, binSz);
HistogramHolder hist2 = createHistogram(a2, binSz);
try {
hist1.plotHistogram("a1 hist", "a1_hist");
hist2.plotHistogram("a2 hist", "a2_hist");
} catch(Throwable t) {
}
*/
/*
MXM NXN
30 31 32 33
20 21 22 20 21 22 23
10 11 12 10 11 12 13
00 01 02 00 01 02 03 p_i_j - q_i_j
01 02 03 00
20 21 22 31 32 33 30
10 11 12 21 22 23 20
00 01 02 11 12 13 10 p_i_j - q_(i+1)_(j+1)
12 13 10 11
20 21 22 02 03 00 01
10 11 12 32 33 30 31
00 01 02 22 23 20 21 p_i_j - q_(i+2)_(j+2)
23 20 21 22
20 21 22 13 10 11 12
10 11 12 03 00 01 02
00 01 02 33 30 31 32 p_i_j - q_(i+3)_(j+3)
*/
int n1 = p.getN();
int n2 = q.getN();
float[][][] md = new float[n2][][];
float[][] prevA2Shifted = null;
for (int i = 0; i < n2; ++i) {
float[][] shifted2;
if (prevA2Shifted == null) {
shifted2 = copy(a2);
} else {
// shifts by 1 to left and up by 1
rotate(prevA2Shifted);
shifted2 = prevA2Shifted;
}
// NOTE: absolute values are stored.
//M_D^n = A_1(1:M,1:M) - A_2(n:n+M-1,n:n+M-1)
md[i] = subtract(a1, shifted2);
assert(md[i].length == n1);
assert(md[i][0].length == n1);
prevA2Shifted = shifted2;
}
for (int i = 0; i < md.length; ++i) {
applySummedAreaTableConversion(md[i]);
}
//printDiagonal(md[0], mdCoords[0]);
log.fine("md.length=" + md.length);
return md;
}
/**
given the shape points for p and q,
create a matrix of descriptors, describing the difference
in chord angles.
The chord descriptor is invariant to translation, rotation,
and scale:
- a chord is a line joining 2 region points
- uses the relative orientation between 2 chords
angle a_i_j is from chord P_i_P_j to reference
point P_i
to another sampled point and chord P_j_P_(j-d) and P_j
d is the number of points before j in the sequence of points P.
a_i_j is the angle between the 2 chords P_i_P_j and P_j_P_(j-d)
*/
protected float[][] createDescriptorMatrix(PairIntArray p,
int n) {
float[][] a = new float[n][];
for (int i = 0; i < n; ++i) {
a[i] = new float[n];
}
/*
P1 Pmid
P2
*/
log.fine("n=" + n);
for (int i1 = 0; i1 < n; ++i1) {
int start = i1 + 1 + dp;
for (int ii = start; ii < (start + n - 1 - dp); ++ii) {
int i2 = ii;
int imid = i2 - dp;
// wrap around
if (imid > (n - 1)) {
imid -= n;
}
// wrap around
if (i2 > (n - 1)) {
i2 -= n;
}
//log.fine("i1=" + i1 + " imid=" + imid + " i2=" + i2);
double angleA = LinesAndAngles.calcClockwiseAngle(
p.getX(i1), p.getY(i1),
p.getX(i2), p.getY(i2),
p.getX(imid), p.getY(imid)
);
/*
String str = String.format(
"[%d](%d,%d) [%d](%d,%d) [%d](%d,%d) a=%.4f",
i1, p.getX(i1), p.getY(i1),
i2, p.getX(i2), p.getY(i2),
imid, p.getX(imid), p.getY(imid),
(float) angleA * 180. / Math.PI);
log.fine(str);
*/
a[i1][i2] = (float)angleA;
}
}
return a;
}
protected int distanceSqEucl(int x1, int y1, int x2, int y2) {
int diffX = x1 - x2;
int diffY = y1 - y2;
return (diffX * diffX + diffY * diffY);
}
private float[][] copy(float[][] a) {
float[][] a2 = new float[a.length][];
for (int i = 0; i < a2.length; ++i) {
a2[i] = Arrays.copyOf(a[i], a[i].length);
}
return a2;
}
private void rotate(float[][] prevShifted) {
// shift x left by 1 first
for (int y = 0; y < prevShifted[0].length; ++y) {
float tmp0 = prevShifted[0][y];
for (int x = 0; x < (prevShifted.length- 1); ++x){
prevShifted[x][y] = prevShifted[x + 1][y];
}
prevShifted[prevShifted.length - 1][y] = tmp0;
}
// shift y down by 1
for (int x = 0; x < prevShifted.length; ++x) {
float tmp0 = prevShifted[x][0];
for (int y = 0; y < (prevShifted[x].length - 1); ++y){
prevShifted[x][y] = prevShifted[x][y + 1];
}
prevShifted[x][prevShifted[x].length - 1] = tmp0;
}
}
private float[][] subtract(float[][] a1, float[][] a2) {
/*
MXM NXN
20 21 22
10 11 10 11 12
00 01 00 01 02
01 02 00
10 11 21 22 20
00 01 11 12 10
12 10 11
10 11 02 00 01
00 01 22 20 21
subtracting only the MXM portion
*/
assert(a1.length == a1[0].length);
assert(a2.length == a2[0].length);
int n1 = a1.length;
int n2 = a2.length;
assert(n1 <= n2);
float[][] output = new float[n1][];
for (int i = 0; i < n1; ++i) {
output[i] = new float[n1];
for (int j = 0; j < n1; ++j) {
float v = a1[i][j] - a2[i][j];
if (v < 0) {
v *= -1;
}
output[i][j] = v;
}
}
return output;
}
private void print(String label, float[][] a) {
StringBuilder sb = new StringBuilder(label);
sb.append("\n");
for (int j = 0; j < a[0].length; ++j) {
sb.append(String.format("row: %3d", j));
for (int i = 0; i < a.length; ++i) {
sb.append(String.format(" %.4f,", a[i][j]));
}
log.fine(sb.toString());
sb.delete(0, sb.length());
}
}
protected void applySummedAreaTableConversion(float[][] mdI) {
for (int x = 0; x < mdI.length; ++x) {
for (int y = 0; y < mdI[x].length; ++y) {
if (x > 0 && y > 0) {
mdI[x][y] += (mdI[x - 1][y] + mdI[x][y - 1]
- mdI[x - 1][y - 1]);
} else if (x > 0) {
mdI[x][y] += mdI[x - 1][y];
} else if (y > 0) {
mdI[x][y] += mdI[x][y - 1];
}
}
}
}
private void filterForConsistentClockwise(
List<Sequences> tracks) {
TIntList rmList = new TIntArrayList();
for (int i = 0; i < tracks.size(); ++i) {
Sequences sequences = tracks.get(i);
if (!sequences.isConsistentClockwise()) {
rmList.add(i);
}
}
log.info("removing " + rmList.size()
+ " tracks from " + tracks.size());
for (int i = (rmList.size() - 1); i > -1; --i) {
int rmIdx = rmList.get(i);
tracks.remove(rmIdx);
}
}
private void transpose(Sequences sequences,
int n1, int n2) {
if (sequences == null) {
return;
}
float f = sequences.getFractionOfWhole();
f *= ((float)n1/(float)n2);
sequences.setFractionOfWhole(f);
List<Sequence> sqs = sequences.getSequences();
List<Sequence> tr = new ArrayList<Sequence>();
for (Sequence s : sqs) {
Sequence str = s.transpose();
tr.add(str);
}
sqs.clear();
sqs.addAll(tr);
}
protected int[] findTopOffsets(DiffMatrixResults equivBest,
int n1, int n2) {
int n = 0;
for (int i = 0; i < equivBest.indexesAndDiff.length; ++i) {
IndexesAndDiff iad = equivBest.indexesAndDiff[i];
if (iad == null) {
continue;
}
LinkedList<IntIntDouble> list = iad.list;
n += list.size();
}
float[] values = new float[n];
n = 0;
for (int i = 0; i < equivBest.indexesAndDiff.length; ++i) {
IndexesAndDiff iad = equivBest.indexesAndDiff[i];
if (iad == null) {
continue;
}
LinkedList<IntIntDouble> list = iad.list;
for (IntIntDouble iid : list) {
values[n] = iid.getB();
n++;
}
}
int[] offsets = findOffsetHistPeaks(values, n1, n2);
return offsets;
}
protected int[] findOffsetHistPeaks(float[] values,
int n1, int n2) {
if (values == null || values.length == 0) {
return null;
}
float binWidth = 6.f;
//int nBins = 10;
HistogramHolder hist =
Histogram.createSimpleHistogram(
binWidth,
//nBins,
values,
Errors.populateYErrorsBySqrt(values));
// to help wrap around, moving items in last bin
// into first bin. then offset of 0 +- binWidth/2
// should be present there
int limit = n2 - (int)Math.ceil((float)binWidth/2.f);
for (int i = (hist.getYHist().length - 1); i > -1; --i) {
float x = hist.getXHist()[i];
if (x < limit) {
break;
}
hist.getYHist()[0] += hist.getYHist()[i];
hist.getYHist()[i] = 0;
}
List<Integer> indexes =
MiscMath.findStrongPeakIndexesDescSort(
hist, 0.1f);
// also looking at last non zero
int idx = MiscMath.findLastNonZeroIndex(hist);
if (idx > -1) {
log.info("last non zero offset=" +
hist.getXHist()[idx]);
}
int[] offsets;
if (indexes.size() > 0) {
int end = (indexes.size() < 3) ? indexes.size() : 3;
offsets = new int[end];
for (int j = 0; j < end; ++j) {
offsets[j] = Math.round(hist.getXHist()
[indexes.get(j).intValue()]);
}
} else {
int yPeakIdx = MiscMath.findYMaxIndex(
hist.getYHistFloat());
if (yPeakIdx == -1) {
return null;
}
offsets = new int[]{
Math.round(hist.getXHist()[yPeakIdx])
};
}
try {
hist.plotHistogram("offsets", "offsets");
} catch (Throwable t) {
}
return offsets;
}
protected int[] findOffsets(List<Sequence> sequences,
int n1, int n2) {
// NOTE: if symmetry is present, might need
// a period analysis
int n = 0;
for (int i = 0; i < sequences.size(); ++i) {
n += sequences.get(i).length();
}
// histogram with bins 10 degrees in size
float[] values = new float[n];
n = 0;
for (int i = 0; i < sequences.size(); ++i) {
int offset = sequences.get(i).getOffset();
int len = sequences.get(i).length();
for (int j = 0; j < len; ++j) {
values[n] = offset;
n++;
}
}
int[] offsets = findOffsetHistPeaks(values, n1, n2);
return offsets;
}
private void print(String prefix, List<Sequence> sequences) {
for (int i = 0; i < sequences.size(); ++i) {
log.info(String.format("%d %s %s", i, prefix,
sequences.get(i)));
}
}
private void print0(List<Sequence> sequences,
String label) {
// startIdx1 and print
List<Sequence> copy = new ArrayList<Sequence>(sequences);
// desc sort by fraction
Collections.sort(copy, new SequenceComparator2());
float maxDiff = Float.MIN_VALUE;
for (int i = 0; i < copy.size(); ++i) {
log.info(String.format("%s FSORT %d %s", label, i, copy.get(i).toString()));
if (copy.get(i).absAvgSumDiffs > maxDiff) {
maxDiff = copy.get(i).absAvgSumDiffs;
}
}
Collections.sort(copy, new SequenceComparator3(maxDiff));
for (int i = 0; i < copy.size(); ++i) {
log.info(String.format("%s FDSORT %d %s", label, i,
copy.get(i).toString()));
}
}
private HistogramHolder createHistogram(float[][] a,
float binSz) {
float[] values = new float[a.length * a.length -
a.length];
int count = 0;
for (int i = 0; i < a.length; ++i) {
for (int j = 0; j < a[0].length; ++j) {
if (i == j) {
continue;
}
values[count] = Math.abs(a[i][j]);
count++;
}
}
HistogramHolder hist =
Histogram.createSimpleHistogram(binSz, values,
Errors.populateYErrorsBySqrt(values));
return hist;
}
protected boolean merge(List<Sequence> sequences) {
if (sequences.size() < 2) {
return false;
}
/*
0
1
2
3 --0
4 --
*/
boolean didMerge = false;
//TODO: the sequences data structure will
// be revised to keep the sequences in order.
LinkedHashSet<Sequence> results
= new LinkedHashSet<Sequence>();
for (int i = 1; i < sequences.size(); ++i) {
Sequence s0 = sequences.get(i - 1);
Sequence s = sequences.get(i);
Sequence[] merged = s0.merge(s);
if (merged == null) {
results.add(s0);
results.add(s);
} else {
for (Sequence st : merged) {
results.add(st);
didMerge = true;
}
}
}
if (didMerge) {
sequences.clear();
sequences.addAll(results);
}
return didMerge;
}
private boolean canAppend(List<Sequence> track,
Sequence testS, int n1) {
if (intersectsExistingRange(track, testS)) {
return false;
}
//TODO: could improve the datastructure
// to make this delete faster. logic in
// the code is still changing currently.
track.add(testS);
boolean isC = Sequences.isConsistentClockwise(track);
boolean rmvd = track.remove(testS);
assert(rmvd);
return isC;
}
/**
* assuming that seedTracks each have only one offset
* (expecting only one sequence, more specifically),
* combine the items in seedTracks that have the same
* offset. "Combine" means merge if adjacent or overlapping,
* else append.
* @param seedTracks
*/
private void combineIfSameOffset(List<Sequences> seedTracks) {
if (seedTracks.size() < 2) {
return;
}
TIntObjectMap<TIntSet> offsetIndexMap
= new TIntObjectHashMap<TIntSet>();
for (int i = 0; i < seedTracks.size(); ++i) {
Sequences track = seedTracks.get(i);
int offset = track.getSequences().get(0).getOffset();
TIntSet indexes = offsetIndexMap.get(offset);
if (indexes == null) {
indexes = new TIntHashSet();
offsetIndexMap.put(offset, indexes);
}
indexes.add(i);
}
TIntSet rmSet = new TIntHashSet();
for (int i = 0; i < seedTracks.size(); ++i) {
if (rmSet.contains(i)) {
continue;
}
Sequences track = seedTracks.get(i);
int offset = track.getSequences().get(0).getOffset();
TIntSet indexes = offsetIndexMap.get(offset);
TIntIterator iter = indexes.iterator();
while (iter.hasNext()) {
int oIdx = iter.next();
if (oIdx == i || rmSet.contains(oIdx)) {
continue;
}
rmSet.add(oIdx);
// merge all of track2 with track
Sequences track2 = seedTracks.get(oIdx);
track.getSequences().addAll(track2.getSequences());
Sequence.mergeSequences(track.getSequences());
}
if (!indexes.isEmpty()) {
// NOTE: stats not yet popualated, so not updating here
// clear indexes so no others are merged from it
indexes.clear();
}
}
if (!rmSet.isEmpty()) {
TIntList rmList = new TIntArrayList(rmSet);
rmList.sort();
for (int i = (rmList.size() - 1); i > -1; --i) {
int rmIdx = rmList.get(i);
seedTracks.remove(rmIdx);
}
}
}
/**
* create a map with key being offset of the Sequence,
* and value being a list of all Sequences in sequences
* which have that offset.
* each Sequence in a sequences item must have same
* offset already.
* @param sequences
* @return
*/
private TreeMap<Integer, List<Sequence>>
placeInMapByOffsets(List<Sequence> sequences) {
TreeMap<Integer, List<Sequence>> map =
new TreeMap<Integer, List<Sequence>>();
for (Sequence s : sequences) {
int offset = s.getOffset();
Integer key = Integer.valueOf(offset);
List<Sequence> list = map.get(key);
if (list == null) {
list = new ArrayList<Sequence>();
map.put(key, list);
}
list.add(s);
}
return map;
}
private class IndexesAndDiff {
private final LinkedList<IntIntDouble> list;
/**
* key = pairint of j, jOffset, value=list node
*/
private final Map<PairInt, IntIntDouble> jLookupMap;
public IndexesAndDiff() {
list = new LinkedList<IntIntDouble>();
jLookupMap = new HashMap<PairInt, IntIntDouble>();
}
public void add(int j, int jOffset, double diff) {
IntIntDouble node = new IntIntDouble(j, jOffset, diff);
PairInt key = new PairInt(j, jOffset);
IntIntDouble existing = jLookupMap.get(key);
if (existing != null) {
double diff0 = Math.abs(existing.getC());
if (diff0 > Math.abs(node.getC())) {
list.add(node);
jLookupMap.put(key, node);
}
} else {
list.add(node);
jLookupMap.put(key, node);
}
}
void sortByJ() {
if (list.size() > 1) {
IntIntDouble[] a
= list.toArray(new IntIntDouble[list.size()]);
QuickSort.sortByA(a);
list.clear();
for (IntIntDouble abc : a) {
list.add(abc);
}
}
rewriteJLookupMap();
}
private void rewriteJLookupMap() {
jLookupMap.clear();
for (IntIntDouble node : list) {
int j = node.getA();
int jOffset = node.getB();
PairInt key = new PairInt(j, jOffset);
jLookupMap.put(key, node);
}
}
}
private class DiffMatrixResults {
/**
index = i
value = linked list of j,jOffset, and diff
*/
private final IndexesAndDiff[] indexesAndDiff;
public DiffMatrixResults(int n) {
indexesAndDiff = new IndexesAndDiff[n];
}
public void add(int i, int j, int jOffset,
double diff) {
if (indexesAndDiff[i] == null) {
indexesAndDiff[i] = new IndexesAndDiff();
}
indexesAndDiff[i].add(j, jOffset, diff);
}
void sortListIndexes() {
for (IndexesAndDiff id : indexesAndDiff) {
if (id != null) {
id.sortByJ();
}
}
}
}
private class MinDiffs {
// first dimension index: md[*][][]
int[] idxs0;
// i is the index of this array and represents the index
// of point in p array
// j is i + idxs[0] and represents the index
// of point in q array
float[] mins;
public MinDiffs(int n) {
idxs0 = new int[n];
mins = new float[n];
Arrays.fill(idxs0, -1);
Arrays.fill(mins, Float.MAX_VALUE);
}
}
private class TrackComparator implements
Comparator<Sequences> {
final int maxNPoints;
public TrackComparator(int n1) {
this.maxNPoints = n1;
}
@Override
public int compare(Sequences o1, Sequences o2) {
// prefer high fraction of whole, then diff
if (o1.getFractionOfWhole() > o2.getFractionOfWhole()) {
return -1;
} else if (o1.getFractionOfWhole() < o2.getFractionOfWhole()) {
return 1;
}
// hard wiring a minimum size of 5 for segments
float ns = (float)(maxNPoints/5);
float ns1 = 1.f - ((float)o1.getSequences().size()/ns);
float ns2 = 1.f - ((float)o2.getSequences().size()/ns);
if (ns1 > ns2) {
return -1;
} else if (ns1 < ns2) {
return 1;
}
return 0;
}
public int compare2(Sequences o1, Sequences o2) {
// adding a term to prefer the larger
// fraction, but in a smaller number of
// larger segments.
// hard wiring a minimum size of 5 for segments
float ns = (float)(maxNPoints/5);
float ns1 = 1.f - ((float)o1.getSequences().size()/ns);
float ns2 = 1.f - ((float)o2.getSequences().size()/ns);
//NOTE: this may need to change for cases where,
// for example, have one very large segment that
// is the right answer and several smaller matches
// that are false due to occlusion... presumably
// other sequences have as many false matches, but
// this needs alot more testing.
float s1 = o1.getFractionOfWhole() * ns1;
float s2 = o2.getFractionOfWhole() * ns2;
if (s1 > s2) {
return -1;
} else if (s1 < s2) {
return 1;
}
if (o1.getFractionOfWhole() > o2.getFractionOfWhole()) {
return -1;
} else if (o1.getFractionOfWhole() < o2.getFractionOfWhole()) {
return 1;
}
if (o1.getAbsSumDiffs() < o2.getAbsSumDiffs()) {
return -1;
} else if (o1.getAbsSumDiffs() > o2.getAbsSumDiffs()) {
return 1;
}
return 0;
}
}
/**
* comparator for a preferring high fraction and low differences,
then descending sort of fraction,
* then diff, then startIdx
*/
private class SequenceComparator3 implements
Comparator<Sequence> {
private final float maxDiff;
public SequenceComparator3(float maxDiff) {
this.maxDiff = maxDiff;
}
@Override
public int compare(Sequence o1, Sequence o2) {
float d1 = 1.f - (o1.absAvgSumDiffs/maxDiff);
float d2 = 1.f - (o2.absAvgSumDiffs/maxDiff);
float s1 = o1.fractionOfWhole + d1;
float s2 = o2.fractionOfWhole + d2;
if (s1 > s2) {
return -1;
} else if (s1 < s2) {
return 1;
}
if (o1.fractionOfWhole > o2.fractionOfWhole) {
return -1;
} else if (o1.fractionOfWhole < o2.fractionOfWhole) {
return 1;
}
if (o1.absAvgSumDiffs < o2.absAvgSumDiffs) {
return -1;
} else if (o1.absAvgSumDiffs > o2.absAvgSumDiffs) {
return 1;
}
if (o1.startIdx1 < o2.startIdx1) {
return -1;
} else if (o1.startIdx1 > o2.startIdx1) {
return 1;
}
return 0;
}
}
/**
* comparator for descending sort of fraction,
* then diff, then startIdx
*/
private class SequenceComparator2 implements
Comparator<Sequence> {
@Override
public int compare(Sequence o1, Sequence o2) {
if (o1.fractionOfWhole > o2.fractionOfWhole) {
return -1;
} else if (o1.fractionOfWhole < o2.fractionOfWhole) {
return 1;
}
if (o1.absAvgSumDiffs < o2.absAvgSumDiffs) {
return -1;
} else if (o1.absAvgSumDiffs > o2.absAvgSumDiffs) {
return 1;
}
if (o1.startIdx1 < o2.startIdx1) {
return -1;
} else if (o1.startIdx1 > o2.startIdx1) {
return 1;
}
return 0;
}
}
/**
* comparator to sort by ascending startIdx, then
* descending fraction of whole
*/
private class SequenceComparator implements
Comparator<Sequence> {
@Override
public int compare(Sequence o1, Sequence o2) {
if (o1.startIdx1 < o2.startIdx1) {
return -1;
} else if (o1.startIdx1 > o2.startIdx1) {
return 1;
}
if (o1.fractionOfWhole > o2.fractionOfWhole) {
return -1;
} else if (o1.fractionOfWhole < o2.fractionOfWhole) {
return 1;
}
if (o1.startIdx2 < o2.startIdx2) {
return -1;
} else if (o1.startIdx2 > o2.startIdx2) {
return 1;
}
if (o1.absAvgSumDiffs < o2.absAvgSumDiffs) {
return -1;
} else if (o1.absAvgSumDiffs > o2.absAvgSumDiffs) {
return 1;
}
// should not arrive here
return 0;
}
}
/**
*
* @param md 3 dimensional array of difference matrices
* @param r block size
* @return
*/
private void findMinDifferenceMatrix(
float[][][] md, int r, double threshold,
MinDiffs output) {
if (r < 1) {
throw new IllegalArgumentException("r cannot be < 1");
}
double c = 1./(double)(r*r);
//md[0:n2-1][0:n1-1][0:n1-1]
int n1 = md[0].length;
int n2 = md.length;
int[] idxs0 = output.idxs0;
float[] mins = output.mins;
int count = 0;
for (int jOffset = 0; jOffset < md.length; jOffset++) {
log.fine(String.format("block=%d md[%d]", r, jOffset));
float[][] a = md[jOffset];
float sum = 0;
//for (int i = 0; i < a.length; i+=r) {
for (int i = (r - 1); i < a.length; i++) {
float s1;
if ((i - r) > -1) {
s1 = a[i][i] - a[i-r][i] - a[i][i-r] + a[i-r][i-r];
log.finest(
String.format(
" [%d,%d] %.4f, %.4f, %.4f, %.4f => %.4f",
i, i, a[i][i], a[i-r][i], a[i][i-r],
a[i-r][i-r], s1*c));
} else {
s1 = a[i][i];
log.finest(
String.format(" [%d,%d] %.4f => %.4f",
i, i, a[i][i], s1*c));
}
s1 *= c;
log.fine(String.format(" [%2d,%2d<-%2d] => %.4f",
i,
((i + jOffset) < n2) ?
i + jOffset : (i + jOffset) - n2,
((i + jOffset - r + 1) < n2) ?
i + jOffset - r + 1 : (i + jOffset - r + 1) - n2,
s1*c));
log.info("*CHECK: i=" + i + " j=" + (i + jOffset)
+ " jOffset=" + jOffset
+ " d=" + s1 + " r=" + r);
float absS1 = s1;
if (absS1 < 0) {
absS1 *= -1;
}
if (absS1 > threshold) {
continue;
}
// note, idx from q is i + jOffset
count++;
sum += absS1;
if (absS1 < Math.abs(mins[i])) {
int idx2 = i + jOffset;
if (idx2 >= n2) {
// idx2 - (n1-i) = offset
idx2 -= n1;
}
mins[i] = s1;
idxs0[i] = jOffset;
if (false)
// fill in the rest of the diagonal in this block
for (int k = (i-1); k > (i-r); k
if (k < 0) {
break;
}
int kOffset = n1 - (i - k);
if (kOffset < 0) {
continue;
}
if (absS1 < Math.abs(mins[k])) {
idx2 = k + jOffset;
if (idx2 >= n2) {
idx2 -= n1;
}
mins[k] = s1;
// for consistency between i and j, need an edited
// offset instead of jOffset:
idxs0[k] = kOffset;
log.fine("CHECK: i=" + i + " j=" + (i + jOffset)
+ " jOffset=" + jOffset + " k=" + k
+ " kOffset=" + kOffset + " d=" + s1 + " r=" + r);
}
}
}
}
if (count == 0) {
sum = Integer.MAX_VALUE;
}
log.fine(String.format(
"SUM=%.4f block=%d md[%d]", sum, r, jOffset));
}
{
for (int i = 0; i < idxs0.length; ++i) {
if (mins[i] == Float.MAX_VALUE) {
continue;
}
int j = i + idxs0[i];
if (j > n2) {
j -= n1;
}
System.out.println("i=" + i + " j="
+ j + " offset=" + idxs0[i] + " mind=" + mins[i]);
}
}
log.info("OFFSETS=" + Arrays.toString(idxs0));
log.info("mins=" + Arrays.toString(mins));
}
/**
*
* @param md
* @param r
* @param mins
* @param threshold
* @param tolerance
* @param n1
* @param n2
* @param output contains pairs of i and jOffset, where
* j is i + jOffset
*/
private void findEquivalentBest(float[][][] md, int r,
MinDiffs mins, double threshold, double tolerance,
int n1, int n2, DiffMatrixResults output) {
//md[0:n2-1][0:n1-1][0:n1-1]
assert(md.length == n2);
double c = 1./(double)(r*r);
// capture all "best" within mins[i] += tolerance
for (int jOffset = 0; jOffset < n2; jOffset++) {
float[][] a = md[jOffset];
for (int i = 0; i < n1; i+=r) {
if (mins.idxs0[i] == -1) {
// there is no best for this p index
continue;
}
// mins.mins[i] is the best for index i (== P_i)
// mins.idxs0[i] is jOffset of best
// j is index i + jOffset
float s1;
if ((i - r) > -1) {
s1 = a[i][i] - a[i-r][i] - a[i][i-r] + a[i-r][i-r];
} else {
s1 = a[i][i];
}
s1 *= c;
float absS1 = s1;
if (absS1 < 0) {
absS1 *= -1;
}
if (absS1 > threshold) {
continue;
}
double best = mins.mins[i];
if (Math.abs(s1 - best) > tolerance) {
continue;
}
int idx2 = jOffset + i;
if (idx2 >= n2) {
idx2 -= n1;
}
output.add(i, idx2, jOffset, s1);
if (false)
// fill in the rest of the diagonal in this block
for (int k = (i-1); k > (i-r); k
if (k < 0) {
break;
}
int kOffset = n1 - (i - k);
if (kOffset < 0) {
continue;
}
if ((k - r) > -1) {
s1 = a[k][k] - a[k-r][k] - a[k][k-r] +
a[k-r][k-r];
} else {
s1 = a[k][k];
}
s1 *= c;
absS1 = s1;
if (absS1 < 0) {
absS1 *= -1;
}
if (absS1 > threshold) {
continue;
}
if (Math.abs(s1 - best) > tolerance) {
continue;
}
idx2 = jOffset + k;
if (idx2 >= n2) {
idx2 -= n1;
}
log.fine("CHECK: i=" + i + " j=" + (i + jOffset)
+ " jOffset=" + jOffset + " k=" + k
+ " kOffset=" + kOffset + " r=" + r);
// for consistency between i and j, need an edited
// offset instead of jOffset:
output.add(k, idx2, kOffset, s1);
}
}
}
}
private float findMaxAvgDiff(List<Sequence> sequences) {
float max = Float.MIN_VALUE;
for (Sequence s : sequences) {
float d = s.absAvgSumDiffs;
if (d > max) {
max = d;
}
}
return max;
}
private boolean intersectsExistingRange(
List<Sequence> existingList, Sequence sTest) {
for (Sequence s : existingList) {
if (s.intersects(sTest)) {
return true;
}
}
return false;
}
private boolean assertNoWrapAround(List<Sequence> sequences) {
for (Sequence s : sequences) {
boolean valid = s.assertNoWrapAround();
if (!valid) {
return false;
}
}
return true;
}
private boolean assertNoWrapAround2(List<Sequences> sequences) {
for (Sequences seqs : sequences) {
boolean valid = assertNoWrapAround(seqs.getSequences());
if (!valid) {
return false;
}
}
return true;
}
}
|
package com.octoblu.droidblu;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.support.v4.widget.DrawerLayout;
import org.eclipse.paho.client.mqttv3.IMqttActionListener;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.IMqttToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
public class Main extends Activity
implements NavigationDrawerFragment.NavigationDrawerCallbacks , MqttCallback{
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
/**
* Used to store the last screen title. For use in {@link #restoreActionBar()}.
*/
private CharSequence mTitle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getFragmentManager().findFragmentById(R.id.navigation_drawer);
mTitle = getTitle();
// Set up the drawer.
mNavigationDrawerFragment.setUp(
R.id.navigation_drawer,
(DrawerLayout) findViewById(R.id.drawer_layout));
// MqttAndroidClient yourMom = new MqttAndroidClient(this.getApplicationContext(), "tcp://meshblu.octoblu.com:1883", "yourMom");
final MqttAndroidClient mqttAndroidClient = new MqttAndroidClient(this.getApplicationContext(), "tcp://192.168.112.128:1883", "yourMom");
mqttAndroidClient.setCallback(this);
try {
MqttConnectOptions options = new MqttConnectOptions();
options.setUserName("bce15650-2fc3-11e4-bb6b-0d33aad5b861"); // Meshblu UUID
options.setPassword("00zt29jsy4fp8n0zfr4nj987iecul3di".toCharArray()); // Meshblu Token
options.setCleanSession(true);
IMqttToken mqttToken = mqttAndroidClient.connect(options, "", new IMqttActionListener() {
@Override
public void onSuccess(IMqttToken iMqttToken) {
Log.d("mqtt", "Dudez, I'm connected!");
try {
mqttAndroidClient.subscribe("bce15650-2fc3-11e4-bb6b-0d33aad5b861", 0);
} catch (MqttException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(IMqttToken iMqttToken, Throwable throwable) {
throwable.printStackTrace();
Log.e("mqtt", "Dudez, we need to talk");
}
});
} catch (MqttException e) {
e.printStackTrace();
}
}
@Override
public void onNavigationDrawerItemSelected(int position) {
// update the main content by replacing fragments
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, PlaceholderFragment.newInstance(position + 1))
.commit();
}
public void onSectionAttached(int number) {
switch (number) {
case 1:
mTitle = getString(R.string.title_section1);
break;
case 2:
mTitle = getString(R.string.title_section2);
break;
case 3:
mTitle = getString(R.string.title_section3);
break;
}
}
public void restoreActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setTitle(mTitle);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
restoreActionBar();
return true;
}
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/// MESSAGE HANDLING
@Override
public void connectionLost(Throwable throwable) {
Log.e("mqtt", "connectionLost");
throwable.printStackTrace();
}
@Override
public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
Log.i("mqtt", mqttMessage.toString());
}
@Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
Log.i("mqtt", "deliverComplete");
}
// END MESSAGE HANDLING
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
/**
* The fragment argument representing the section number for this
* fragment.
*/
private static final String ARG_SECTION_NUMBER = "section_number";
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static PlaceholderFragment newInstance(int sectionNumber) {
PlaceholderFragment fragment = new PlaceholderFragment();
Bundle args = new Bundle();
args.putInt(ARG_SECTION_NUMBER, sectionNumber);
fragment.setArguments(args);
return fragment;
}
public PlaceholderFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((Main) activity).onSectionAttached(
getArguments().getInt(ARG_SECTION_NUMBER));
}
}
}
|
package org.apdplat.qa.util;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apdplat.qa.datasource.DataSource;
import org.apdplat.qa.datasource.FileDataSource;
import org.apdplat.qa.model.Evidence;
import org.apdplat.qa.model.Question;
import org.apdplat.qa.parser.WordParser;
import org.apdplat.word.segmentation.Word;
import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*
* @author
*/
public class Tools {
private static final Logger LOG = LoggerFactory.getLogger(Tools.class);
private static Map<String, Integer> map = new HashMap<>();
public static String getTimeDes(long ms) {
int ss = 1000;
int mi = ss * 60;
int hh = mi * 60;
int dd = hh * 24;
long day = ms / dd;
long hour = (ms - day * dd) / hh;
long minute = (ms - day * dd - hour * hh) / mi;
long second = (ms - day * dd - hour * hh - minute * mi) / ss;
long milliSecond = ms - day * dd - hour * hh - minute * mi - second * ss;
StringBuilder str = new StringBuilder();
if (day > 0) {
str.append(day).append(",");
}
if (hour > 0) {
str.append(hour).append(",");
}
if (minute > 0) {
str.append(minute).append(",");
}
if (second > 0) {
str.append(second).append(",");
}
if (milliSecond > 0) {
str.append(milliSecond).append(",");
}
if (str.length() > 0) {
str = str.deleteCharAt(str.length() - 1);
}
return str.toString();
}
public static <T> List<List<T>> getCom(List<T> list) {
List<List<T>> result = new ArrayList<>();
T[] data = (T[]) list.toArray();
long max = 1 << data.length;
for (int i = 1; i < max; i++) {
List<T> sub = new ArrayList<>();
for (int j = 0; j < data.length; j++) {
if ((i & (1 << j)) != 0) {
sub.add(data[j]);
}
}
result.add(sub);
}
return result;
}
public static void extractQuestions(String file) {
//materialquestions
DataSource dataSource = new FileDataSource(file);
List<Question> questions = dataSource.getQuestions();
for (Question question : questions) {
System.out.println(question.getQuestion().trim() + ":" + question.getExpectAnswer());
}
}
public static void extractPatterns(String file, String pattern) {
//materialquestions
DataSource dataSource = new FileDataSource(file);
List<Question> questions = dataSource.getQuestions();
for (Question question : questions) {
System.out.println(pattern + " " + question.getQuestion().trim());
}
}
public static int getIDF(String term) {
Integer idf = map.get(term);
if (idf == null) {
return 0;
}
LOG.info("idf " + term + ":" + idf);
return idf;
}
public static List<Map.Entry<String, Integer>> initIDF(List<Question> questions) {
map = new HashMap<>();
for (Question question : questions) {
List<Evidence> evidences = question.getEvidences();
for (Evidence evidence : evidences) {
Set<String> set = new HashSet<>();
List<Word> words = WordParser.parse(evidence.getTitle() + evidence.getSnippet());
for (Word word : words) {
set.add(word.getText());
}
for (String item : set) {
Integer doc = map.get(item);
if (doc == null) {
doc = 1;
} else {
doc++;
}
map.put(item, doc);
}
}
}
List<Map.Entry<String, Integer>> list = Tools.sortByIntegerValue(map);
for (Map.Entry<String, Integer> entry : list) {
LOG.debug(entry.getKey() + " " + entry.getValue());
}
return list;
}
public static String getHTMLContent(String url) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(new URL(url).openStream()));
StringBuilder html = new StringBuilder();
String line = reader.readLine();
while (line != null) {
html.append(line).append("\n");
line = reader.readLine();
}
String content = TextExtract.parse(html.toString());
return content;
} catch (Exception e) {
LOG.debug("URL" + url, e);
}
return null;
}
/**
*
*
* @param text
* @return
*/
public static List<Word> getWords(String text) {
List<Word> result = new ArrayList<>();
List<Word> words = WordParser.parse(text);
for (Word word : words) {
result.add(word);
}
return result;
}
/**
* textpattern
*
* @param text
* @param pattern
* @return
*/
public static int countsForSkipBigram(String text, String pattern) {
int count = 0;
Pattern p = Pattern.compile(pattern);
Matcher matcher = p.matcher(text);
while (matcher.find()) {
LOG.debug("" + matcher.group());
count++;
}
return count;
}
/**
* textpattern
*
* @param text
* @param pattern
* @return
*/
public static int countsForBigram(String text, String pattern) {
int count = 0;
int index = -1;
while (true) {
index = text.indexOf(pattern, index + 1);
if (index > -1) {
LOG.debug(": " + pattern + " " + index);
count++;
} else {
break;
}
}
return count;
}
/**
* MAPVALUE
*
* @param map
* @return
*/
public static <K> List<Map.Entry<K, Integer>> sortByIntegerValue(Map<K, Integer> map) {
List<Map.Entry<K, Integer>> orderList = new ArrayList<>(map.entrySet());
Collections.sort(orderList, new Comparator<Map.Entry<K, Integer>>() {
@Override
public int compare(Map.Entry<K, Integer> o1, Map.Entry<K, Integer> o2) {
return (o1.getValue() - o2.getValue());
}
});
return orderList;
}
/**
* MAPVALUE
*
* @param map
* @return
*/
public static <K> List<Map.Entry<K, Double>> sortByDoubleValue(Map<K, Double> map) {
List<Map.Entry<K, Double>> orderList = new ArrayList<>(map.entrySet());
Collections.sort(orderList, new Comparator<Map.Entry<K, Double>>() {
@Override
public int compare(Map.Entry<K, Double> o1, Map.Entry<K, Double> o2) {
double abs = o1.getValue() - o2.getValue();
if (abs < 0) {
return -1;
}
if (abs > 0) {
return 1;
}
return 0;
}
});
return orderList;
}
public static void createAndWriteFile(String path, String text) {
BufferedWriter writer = null;
try {
File file = new File(path);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
file.createNewFile();
writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "utf-8"));
writer.write(text);
} catch (Exception ex) {
LOG.error("", ex);
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException ex) {
LOG.error("", ex);
}
}
}
}
public static String getRewindEvidenceText(String question, String answer) {
String rewindEvidenceText = MySQLUtils.getRewindEvidenceText(question, answer);
if (rewindEvidenceText != null) {
LOG.info("" + question + " " + answer);
return rewindEvidenceText;
}
//2google
StringBuilder text = new StringBuilder();
String query = question + answer;
try {
query = URLEncoder.encode(query, "UTF-8");
} catch (UnsupportedEncodingException e) {
LOG.error("url", e);
return null;
}
query = "http://ajax.googleapis.com/ajax/services/search/web?start=0&rsz=large&v=1.0&q=" + query;
try {
HostConfiguration hcf = new HostConfiguration();
hcf.setProxy("127.0.0.1", 8087);
HttpClient httpClient = new HttpClient();
GetMethod getMethod = new GetMethod(query);
//httpClient.executeMethod(hcf, getMethod);
httpClient.executeMethod(getMethod);
getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler());
int statusCode = httpClient.executeMethod(getMethod);
if (statusCode != HttpStatus.SC_OK) {
LOG.error("Method failed: " + getMethod.getStatusLine());
}
byte[] responseBody = getMethod.getResponseBody();
String response = new String(responseBody, "UTF-8");
LOG.debug("" + response);
JSONObject json = new JSONObject(response);
String totalResult = json.getJSONObject("responseData").getJSONObject("cursor").getString("estimatedResultCount");
int totalResultCount = Integer.parseInt(totalResult);
LOG.info(" " + totalResultCount);
JSONArray results = json.getJSONObject("responseData").getJSONArray("results");
LOG.debug(" Results:");
for (int i = 0; i < results.length(); i++) {
JSONObject result = results.getJSONObject(i);
String title = result.getString("titleNoFormatting");
LOG.debug(title);
//URL
String url = result.get("url").toString();
String content = null;//Tools.getHTMLContent(url);
if (content == null) {
content = result.get("content").toString();
content = content.replaceAll("<b>", "");
content = content.replaceAll("</b>", "");
content = content.replaceAll("\\.\\.\\.", "");
}
LOG.debug(content);
text.append(title).append(content);
}
LOG.info("" + question + " " + answer + " MySQL");
MySQLUtils.saveRewindEvidenceText(question, answer, text.toString());
return text.toString();
} catch (Exception e) {
LOG.debug("", e);
}
return null;
}
public static byte[] readAll(InputStream in) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
byte[] buffer = new byte[1024];
for (int n; (n = in.read(buffer)) > 0;) {
out.write(buffer, 0, n);
}
} catch (IOException ex) {
LOG.error("", ex);
}
return out.toByteArray();
}
public static String getAppPath(Class cls) {
if (cls == null) {
throw new IllegalArgumentException("");
}
ClassLoader loader = cls.getClassLoader();
String clsName = cls.getName() + ".class";
Package pack = cls.getPackage();
String path = "";
if (pack != null) {
String packName = pack.getName();
// JavaJDK
if (packName.startsWith("java.") || packName.startsWith("javax.")) {
throw new IllegalArgumentException("");
}
clsName = clsName.substring(packName.length() + 1);
if (packName.indexOf(".") < 0) {
path = packName + "/";
} else {
int start = 0, end = 0;
end = packName.indexOf(".");
while (end != -1) {
path = path + packName.substring(start, end) + "/";
start = end + 1;
end = packName.indexOf(".", start);
}
path = path + packName.substring(start) + "/";
}
}
// ClassLoadergetResource
URL url = loader.getResource(path + clsName);
// URL
String realPath = url.getPath();
// "file:"
int pos = realPath.indexOf("file:");
if (pos > -1) {
realPath = realPath.substring(pos + 5);
}
pos = realPath.indexOf(path + clsName);
realPath = realPath.substring(0, pos - 1);
// JARJAR
if (realPath.endsWith("!")) {
realPath = realPath.substring(0, realPath.lastIndexOf("/"));
}
try {
realPath = URLDecoder.decode(realPath, "utf-8");
} catch (Exception e) {
throw new RuntimeException(e);
}
if(realPath.endsWith("/lib")){
realPath = realPath.replace("/lib", "/classes");
}
//mavenJAR
if(realPath.contains("/org/apdplat/deep-qa/")){
int index = realPath.lastIndexOf("/");
String version = realPath.substring(index+1);
String jar = realPath+"/deep-qa-"+version+".jar";
LOG.info("maven jar"+jar);
ZipUtils.unZip(jar, "dic", "deep-qa/dic", true);
ZipUtils.unZip(jar, "questionTypePatterns", "deep-qa/questionTypePatterns", true);
realPath = "deep-qa";
}
return realPath;
}
public static Set<String> getQuestions(String file) {
//Set
Set<String> result = new HashSet<>();
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(Tools.class.getResourceAsStream(file), "utf-8"));
String line;
while ((line = reader.readLine()) != null) {
line = line.trim().replace("?", "").replace("", "");
if (line.equals("") || line.startsWith("#") || line.indexOf("#") == 1 || line.length() < 3) {
continue;
}
result.add(line);
}
} catch (Exception e) {
LOG.error("", e);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
LOG.error("", e);
}
}
}
return result;
}
}
|
package owltools.mooncat;
import java.util.Set;
import org.junit.Test;
import org.semanticweb.owlapi.model.OWLAxiom;
import org.semanticweb.owlapi.model.OWLEntity;
import org.semanticweb.owlapi.model.OWLObject;
import org.semanticweb.owlapi.model.OWLOntology;
import owltools.OWLToolsTestBasics;
import owltools.graph.OWLGraphWrapper;
import owltools.io.ParserWrapper;
public class Mireot3Test extends OWLToolsTestBasics {
private static boolean RENDER_ONTOLOGY_FLAG = false;
@Test
public void testMireot() throws Exception {
ParserWrapper pw = new ParserWrapper();
// this test ontology has a class defined using a caro class, and imports caro_local
OWLGraphWrapper g =
pw.parseToOWLGraph(getResourceIRIString("caro_mireot_test.owl"));
g.mergeImportClosure();
g.getSourceOntology();
Mooncat m = new Mooncat(g);
g.addSupportOntologiesFromImportsClosure();
final Set<OWLOntology> referencedOntologies = m.getReferencedOntologies();
final Set<OWLEntity> externalReferencedEntities = m.getExternalReferencedEntities();
final Set<OWLObject> closureOfExternalReferencedEntities = m.getClosureOfExternalReferencedEntities();
final Set<OWLAxiom> closureAxiomsOfExternalReferencedEntities = m.getClosureAxiomsOfExternalReferencedEntities();
if (RENDER_ONTOLOGY_FLAG) {
for (OWLOntology o : referencedOntologies) {
System.out.println("ref="+o);
}
for (OWLEntity e : externalReferencedEntities) {
System.out.println("e="+e);
}
for (OWLObject e : closureOfExternalReferencedEntities) {
System.out.println("c="+e);
}
for (OWLAxiom ax : closureAxiomsOfExternalReferencedEntities) {
System.out.println("M_AX:"+ax);
}
}
}
}
|
package com.jme3.system.lwjgl;
import com.jme3.input.JoyInput;
import com.jme3.input.KeyInput;
import com.jme3.input.MouseInput;
import com.jme3.input.TouchInput;
import com.jme3.input.lwjgl.GlfwJoystickInput;
import com.jme3.input.lwjgl.GlfwKeyInput;
import com.jme3.input.lwjgl.GlfwMouseInput;
import com.jme3.math.Vector2f;
import com.jme3.system.AppSettings;
import com.jme3.system.JmeContext;
import com.jme3.system.JmeSystem;
import com.jme3.system.NanoTimer;
import com.jme3.util.BufferUtils;
import com.jme3.util.SafeArrayList;
import org.lwjgl.Version;
import org.lwjgl.glfw.GLFWErrorCallback;
import org.lwjgl.glfw.GLFWFramebufferSizeCallback;
import org.lwjgl.glfw.GLFWImage;
import org.lwjgl.glfw.GLFWVidMode;
import org.lwjgl.glfw.GLFWWindowFocusCallback;
import org.lwjgl.glfw.GLFWWindowSizeCallback;
import org.lwjgl.system.Platform;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.nio.ByteBuffer;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import java.util.logging.Logger;
import static org.lwjgl.glfw.GLFW.*;
import static org.lwjgl.opengl.GL11.GL_FALSE;
import static org.lwjgl.system.MemoryUtil.NULL;
/**
* A wrapper class over the GLFW framework in LWJGL 3.
*
* @author Daniel Johansson
*/
public abstract class LwjglWindow extends LwjglContext implements Runnable {
private static final Logger LOGGER = Logger.getLogger(LwjglWindow.class.getName());
private static final EnumSet<JmeContext.Type> SUPPORTED_TYPES = EnumSet.of(
JmeContext.Type.Display,
JmeContext.Type.Canvas,
JmeContext.Type.OffscreenSurface);
private static final Map<String, Runnable> RENDER_CONFIGS = new HashMap<>();
static {
RENDER_CONFIGS.put(AppSettings.LWJGL_OPENGL30, () -> {
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
});
RENDER_CONFIGS.put(AppSettings.LWJGL_OPENGL31, () -> {
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);
});
RENDER_CONFIGS.put(AppSettings.LWJGL_OPENGL32, () -> {
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
});
RENDER_CONFIGS.put(AppSettings.LWJGL_OPENGL33, () -> {
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
});
RENDER_CONFIGS.put(AppSettings.LWJGL_OPENGL40, () -> {
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
});
RENDER_CONFIGS.put(AppSettings.LWJGL_OPENGL41, () -> {
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);
});
RENDER_CONFIGS.put(AppSettings.LWJGL_OPENGL42, () -> {
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
});
RENDER_CONFIGS.put(AppSettings.LWJGL_OPENGL43, () -> {
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
});
RENDER_CONFIGS.put(AppSettings.LWJGL_OPENGL44, () -> {
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 4);
});
RENDER_CONFIGS.put(AppSettings.LWJGL_OPENGL45, () -> {
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 5);
});
}
protected final AtomicBoolean needClose = new AtomicBoolean(false);
protected final AtomicBoolean needRestart = new AtomicBoolean(false);
private final JmeContext.Type type;
private final SafeArrayList<WindowSizeListener> windowSizeListeners = new SafeArrayList<>(WindowSizeListener.class);
private GLFWErrorCallback errorCallback;
private GLFWWindowSizeCallback windowSizeCallback;
private GLFWFramebufferSizeCallback framebufferSizeCallback;
private GLFWWindowFocusCallback windowFocusCallback;
private Thread mainThread;
private long window = NULL;
private int frameRateLimit = -1;
protected boolean wasActive = false;
protected boolean autoFlush = true;
protected boolean allowSwapBuffers = false;
public LwjglWindow(final JmeContext.Type type) {
if (!SUPPORTED_TYPES.contains(type)) {
throw new IllegalArgumentException("Unsupported type '" + type.name() + "' provided");
}
this.type = type;
}
/**
* Registers the specified listener to get notified when window size changes.
*
* @param listener The WindowSizeListener to register.
*/
public void registerWindowSizeListener(WindowSizeListener listener) {
windowSizeListeners.add(listener);
}
/**
* Removes the specified listener from the listeners list.
*
* @param listener The WindowSizeListener to remove.
*/
public void removeWindowSizeListener(WindowSizeListener listener) {
windowSizeListeners.remove(listener);
}
/**
* @return Type.Display or Type.Canvas
*/
@Override
public JmeContext.Type getType() {
return type;
}
/**
* Set the title if it's a windowed display
*
* @param title the title to set
*/
@Override
public void setTitle(final String title) {
if (created.get() && window != NULL) {
glfwSetWindowTitle(window, title);
}
}
/**
* Restart if it's a windowed or full-screen display.
*/
@Override
public void restart() {
if (created.get()) {
needRestart.set(true);
} else {
LOGGER.warning("Display is not created, cannot restart window.");
}
}
/**
* Apply the settings, changing resolution, etc.
*
* @param settings the settings to apply when creating the context.
*/
protected void createContext(final AppSettings settings) {
glfwSetErrorCallback(errorCallback = new GLFWErrorCallback() {
@Override
public void invoke(int error, long description) {
final String message = GLFWErrorCallback.getDescription(description);
listener.handleError(message, new Exception(message));
}
});
if (!glfwInit()) {
throw new IllegalStateException("Unable to initialize GLFW");
}
glfwDefaultWindowHints();
final String renderer = settings.getRenderer();
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_TRUE);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
RENDER_CONFIGS.computeIfAbsent(renderer, s -> () -> {
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GLFW_FALSE);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_ANY_PROFILE);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);
}).run();
if (settings.getBoolean("RendererDebug")) {
glfwWindowHint(GLFW_OPENGL_DEBUG_CONTEXT, GLFW_TRUE);
}
if (settings.isGammaCorrection()) {
glfwWindowHint(GLFW_SRGB_CAPABLE, GLFW_TRUE);
}
glfwWindowHint(GLFW_VISIBLE, GL_FALSE);
glfwWindowHint(GLFW_RESIZABLE, settings.isResizable() ? GLFW_TRUE : GLFW_FALSE);
glfwWindowHint(GLFW_DEPTH_BITS, settings.getDepthBits());
glfwWindowHint(GLFW_STENCIL_BITS, settings.getStencilBits());
glfwWindowHint(GLFW_SAMPLES, settings.getSamples());
glfwWindowHint(GLFW_STEREO, settings.useStereo3D() ? GLFW_TRUE : GLFW_FALSE);
glfwWindowHint(GLFW_REFRESH_RATE, settings.getFrequency()<=0?GLFW_DONT_CARE:settings.getFrequency());
glfwWindowHint(GLFW_COCOA_RETINA_FRAMEBUFFER, settings.isUseRetinaFrameBuffer() ? GLFW_TRUE : GLFW_FALSE);
if (settings.getBitsPerPixel() == 24) {
glfwWindowHint(GLFW_RED_BITS, 8);
glfwWindowHint(GLFW_GREEN_BITS, 8);
glfwWindowHint(GLFW_BLUE_BITS, 8);
} else if (settings.getBitsPerPixel() == 16) {
glfwWindowHint(GLFW_RED_BITS, 5);
glfwWindowHint(GLFW_GREEN_BITS, 6);
glfwWindowHint(GLFW_BLUE_BITS, 5);
}
glfwWindowHint(GLFW_ALPHA_BITS, settings.getAlphaBits());
// TODO: Add support for monitor selection
long monitor = NULL;
if (settings.isFullscreen()) {
monitor = glfwGetPrimaryMonitor();
}
final GLFWVidMode videoMode = glfwGetVideoMode(glfwGetPrimaryMonitor());
if (settings.getWidth() <= 0 || settings.getHeight() <= 0) {
settings.setResolution(videoMode.width(), videoMode.height());
}
window = glfwCreateWindow(settings.getWidth(), settings.getHeight(), settings.getTitle(), monitor, NULL);
if (window == NULL) {
throw new RuntimeException("Failed to create the GLFW window");
}
glfwSetWindowFocusCallback(window, windowFocusCallback = new GLFWWindowFocusCallback() {
@Override
public void invoke(final long window, final boolean focus) {
if (wasActive != focus) {
if (!wasActive) {
listener.gainFocus();
timer.reset();
} else {
listener.loseFocus();
}
wasActive = !wasActive;
}
}
});
if (!settings.isFullscreen()) {
if (settings.getCenterWindow()) {
// Center the window
glfwSetWindowPos(window,
(videoMode.width() - settings.getWidth()) / 2,
(videoMode.height() - settings.getHeight()) / 2);
} else {
glfwSetWindowPos(window,
settings.getWindowXPosition(),
settings.getWindowYPosition());
}
}
// Make the OpenGL context current
glfwMakeContextCurrent(window);
// Enable vsync
if (settings.isVSync()) {
glfwSwapInterval(1);
} else {
glfwSwapInterval(0);
}
setWindowIcon(settings);
showWindow();
// Windows resize callback
glfwSetWindowSizeCallback(window, windowSizeCallback = new GLFWWindowSizeCallback() {
@Override
public void invoke(final long window, final int width, final int height) {
// This is the window size, never to passed to any pixel based stuff!
// https://www.glfw.org/docs/latest/window_guide.html#window_size
onWindowSizeChanged(width, height);
// Notify listeners
for (WindowSizeListener listener : windowSizeListeners.getArray()) {
listener.onWindowSizeChanged(width, height);
}
}
});
// Add a framebuffer resize callback which delegates to the listener
glfwSetFramebufferSizeCallback(window, framebufferSizeCallback = new GLFWFramebufferSizeCallback() {
@Override
public void invoke(final long window, final int width, final int height) {
// https://www.glfw.org/docs/latest/window_guide.html#window_fbsize
listener.reshape(width, height);
}
});
allowSwapBuffers = settings.isSwapBuffers();
// Create OpenCL
if (settings.isOpenCLSupport()) {
initOpenCL(window);
}
framesAfterContextStarted = 0;
}
private void onWindowSizeChanged(final int width, final int height) {
settings.setResolution(width, height);
}
protected void showWindow() {
glfwShowWindow(window);
}
/**
* Set custom icons to the window of this application.
*
* @param settings settings for getting the icons
*/
protected void setWindowIcon(final AppSettings settings) {
final Object[] icons = settings.getIcons();
if (icons == null) return;
final GLFWImage[] images = imagesToGLFWImages(icons);
try (final GLFWImage.Buffer iconSet = GLFWImage.malloc(images.length)) {
for (int i = images.length - 1; i >= 0; i
final GLFWImage image = images[i];
iconSet.put(i, image);
}
glfwSetWindowIcon(window, iconSet);
}
}
/**
* Convert array of images to array of {@link GLFWImage}.
*/
private GLFWImage[] imagesToGLFWImages(final Object[] images) {
final GLFWImage[] out = new GLFWImage[images.length];
for (int i = 0; i < images.length; i++) {
final BufferedImage image = (BufferedImage) images[i];
out[i] = imageToGLFWImage(image);
}
return out;
}
/**
* Convert the {@link BufferedImage} to the {@link GLFWImage}.
*/
private GLFWImage imageToGLFWImage(BufferedImage image) {
if (image.getType() != BufferedImage.TYPE_INT_ARGB_PRE) {
final BufferedImage convertedImage = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_ARGB_PRE);
final Graphics2D graphics = convertedImage.createGraphics();
final int targetWidth = image.getWidth();
final int targetHeight = image.getHeight();
graphics.drawImage(image, 0, 0, targetWidth, targetHeight, null);
graphics.dispose();
image = convertedImage;
}
final ByteBuffer buffer = BufferUtils.createByteBuffer(image.getWidth() * image.getHeight() * 4);
for (int i = 0; i < image.getHeight(); i++) {
for (int j = 0; j < image.getWidth(); j++) {
int colorSpace = image.getRGB(j, i);
buffer.put((byte) ((colorSpace << 8) >> 24));
buffer.put((byte) ((colorSpace << 16) >> 24));
buffer.put((byte) ((colorSpace << 24) >> 24));
buffer.put((byte) (colorSpace >> 24));
}
}
buffer.flip();
final GLFWImage result = GLFWImage.create();
result.set(image.getWidth(), image.getHeight(), buffer);
return result;
}
/**
* Destroy the context.
*/
protected void destroyContext() {
try {
if (renderer != null) {
renderer.cleanup();
}
if (errorCallback != null) {
// We need to specifically set this to null as we might set a new callback before we reinit GLFW
glfwSetErrorCallback(null);
errorCallback.close();
errorCallback = null;
}
if (windowSizeCallback != null) {
windowSizeCallback.close();
windowSizeCallback = null;
}
if (framebufferSizeCallback != null) {
framebufferSizeCallback.close();
framebufferSizeCallback = null;
}
if (windowFocusCallback != null) {
windowFocusCallback.close();
windowFocusCallback = null;
}
if (window != NULL) {
glfwDestroyWindow(window);
window = NULL;
}
} catch (final Exception ex) {
listener.handleError("Failed to destroy context", ex);
}
}
@Override
public void create(boolean waitFor) {
if (created.get()) {
LOGGER.warning("create() called when display is already created!");
return;
}
if (Platform.get() == Platform.MACOSX) {
// NOTE: this is required for Mac OS X!
mainThread = Thread.currentThread();
mainThread.setName("jME3 Main");
if (waitFor) {
LOGGER.warning("create(true) is not supported for macOS!");
}
run();
} else {
mainThread = new Thread(this, "jME3 Main");
mainThread.start();
if (waitFor) {
waitFor(true);
}
}
}
/**
* Does LWJGL display initialization in the OpenGL thread
*
* @return returns {@code true} if the context initialization was successful
*/
protected boolean initInThread() {
try {
if (!JmeSystem.isLowPermissions()) {
// Enable uncaught exception handler only for current thread
Thread.currentThread().setUncaughtExceptionHandler((thread, thrown) -> {
listener.handleError("Uncaught exception thrown in " + thread.toString(), thrown);
if (needClose.get()) {
// listener.handleError() has requested the
// context to close. Satisfy request.
deinitInThread();
}
});
}
timer = new NanoTimer();
// For canvas, this will create a PBuffer,
// allowing us to query information.
// When the canvas context becomes available, it will
// be replaced seamlessly.
createContext(settings);
printContextInitInfo();
created.set(true);
super.internalCreate();
} catch (Exception ex) {
try {
if (window != NULL) {
glfwDestroyWindow(window);
window = NULL;
}
} catch (Exception ex2) {
LOGGER.log(Level.WARNING, null, ex2);
}
listener.handleError("Failed to create display", ex);
return false; // if we failed to create display, do not continue
}
listener.initialize();
return true;
}
private int framesAfterContextStarted = 0;
/**
* execute one iteration of the render loop in the OpenGL thread
*/
protected void runLoop() {
// If a restart is required, lets recreate the context.
if (needRestart.getAndSet(false)) {
restartContext();
}
if (!created.get()) {
throw new IllegalStateException();
}
// Update the frame buffer size from 2nd frame since the initial value
// of frame buffer size from glfw maybe incorrect when HiDPI display is in use
if (framesAfterContextStarted < 2) {
framesAfterContextStarted++;
if (framesAfterContextStarted == 2) {
int[] width = new int[1];
int[] height = new int[1];
glfwGetFramebufferSize(window, width, height);
if (settings.getWidth() != width[0] || settings.getHeight() != height[0]) {
listener.reshape(width[0], height[0]);
}
}
}
listener.update();
// All this does is call glfwSwapBuffers().
// If the canvas is not active, there's no need to waste time
// doing that.
if (renderable.get()) {
// calls swap buffers, etc.
try {
if (allowSwapBuffers && autoFlush) {
glfwSwapBuffers(window);
}
} catch (Throwable ex) {
listener.handleError("Error while swapping buffers", ex);
}
}
// Subclasses just call GLObjectManager. Clean up objects here.
// It is safe ... for now.
if (renderer != null) {
renderer.postFrame();
}
if (autoFlush) {
if (frameRateLimit != getSettings().getFrameRate()) {
setFrameRateLimit(getSettings().getFrameRate());
}
} else if (frameRateLimit != 20) {
setFrameRateLimit(20);
}
Sync.sync(frameRateLimit);
glfwPollEvents();
}
private void restartContext() {
try {
destroyContext();
createContext(settings);
} catch (Exception ex) {
LOGGER.log(Level.SEVERE, "Failed to set display settings!", ex);
}
// Reinitialize context flags and such
reinitContext();
// We need to reinit the mouse and keyboard input as they are tied to a window handle
if (keyInput != null && keyInput.isInitialized()) {
keyInput.resetContext();
}
if (mouseInput != null && mouseInput.isInitialized()) {
mouseInput.resetContext();
}
LOGGER.fine("Display restarted.");
}
private void setFrameRateLimit(int frameRateLimit) {
this.frameRateLimit = frameRateLimit;
}
/**
* De-initialize in the OpenGL thread.
*/
protected void deinitInThread() {
listener.destroy();
destroyContext();
super.internalDestroy();
glfwTerminate();
LOGGER.fine("Display destroyed.");
}
@Override
public void run() {
if (listener == null) {
throw new IllegalStateException("SystemListener is not set on context!"
+ "Must set with JmeContext.setSystemListener().");
}
LOGGER.log(Level.FINE, "Using LWJGL {0}", Version.getVersion());
if (!initInThread()) {
LOGGER.log(Level.SEVERE, "Display initialization failed. Cannot continue.");
return;
}
while (true) {
runLoop();
if (needClose.get()) {
break;
}
if (glfwWindowShouldClose(window)) {
listener.requestClose(false);
}
}
deinitInThread();
}
@Override
public JoyInput getJoyInput() {
if (joyInput == null) {
joyInput = new GlfwJoystickInput();
}
return joyInput;
}
@Override
public MouseInput getMouseInput() {
if (mouseInput == null) {
mouseInput = new GlfwMouseInput(this);
}
return mouseInput;
}
@Override
public KeyInput getKeyInput() {
if (keyInput == null) {
keyInput = new GlfwKeyInput(this);
}
return keyInput;
}
@Override
public TouchInput getTouchInput() {
return null;
}
@Override
public void setAutoFlushFrames(boolean enabled) {
this.autoFlush = enabled;
}
@Override
public void destroy(boolean waitFor) {
needClose.set(true);
if (mainThread == Thread.currentThread()) {
// Ignore waitFor.
return;
}
if (waitFor) {
waitFor(false);
}
}
public long getWindowHandle() {
return window;
}
public Vector2f getWindowContentScale(Vector2f store) {
float[] xScale = new float[1];
float[] yScale = new float[1];
glfwGetWindowContentScale(window, xScale, yScale);
if (store != null) {
return store.set(xScale[0], yScale[0]);
}
return new Vector2f(xScale[0], yScale[0]);
}
}
|
package com.restfb.types.webhook;
import com.restfb.JsonMapper;
import com.restfb.json.JsonObject;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Factory to convert the value field of the change into a class with special fields
*/
public class ChangeValueFactory {
private String field;
private JsonObject value;
private final Logger LOGGER = Logger.getLogger(getClass().getName());
public ChangeValueFactory setField(String field) {
this.field = field;
return this;
}
public ChangeValueFactory setValue(String value) {
this.value = new JsonObject(value);
return this;
}
public ChangeValue buildWithMapper(JsonMapper mapper) {
String classDefinition;
if (value != null && field != null) {
classDefinition = field.toUpperCase();
if (value.has("item")) {
classDefinition += "_" + value.getString("item").toUpperCase();
}
if (value.has("verb")) {
classDefinition += "_" + value.getString("verb").toUpperCase();
}
// System.out.println(classDefinition);
try {
ChangeValueEnumeration changeValueEnum = ChangeValueEnumeration.valueOf(classDefinition);
return mapper.toJavaObject(value.toString(), changeValueEnum.getValueClass());
} catch (IllegalArgumentException iae) {
if (LOGGER.isLoggable(Level.WARNING)) {
LOGGER.warning("undefined change value detected: " + classDefinition);
LOGGER.warning("please provide this information to the restfb team: " + value.toString());
}
return new FallBackChangeValue(value);
}
}
return null;
}
enum ChangeValueEnumeration {
FEED_COMMENT_ADD(FeedCommentValue.class),
FEED_COMMENT_EDITED(FeedCommentValue.class),
FEED_COMMENT_REMOVE(FeedCommentValue.class),
FEED_PHOTO_ADD(FeedPhotoAddValue.class),
FEED_PHOTO_REMOVE(FeedPhotoRemoveValue.class),
FEED_STATUS_ADD(FeedStatusValue.class),
FEED_STATUS_EDITED(FeedStatusValue.class),
FEED_STATUS_HIDE(FeedStatusValue.class),
FEED_POST_ADD(FeedPostValue.class),
FEED_POST_EDITED(FeedPostValue.class),
FEED_POST_REMOVE(FeedPostValue.class),
FEED_SHARE_ADD(FeedShareValue.class),
FEED_SHARE_EDITED(FeedShareValue.class),
FEED_SHARE_REMOVE(FeedShareValue.class),
FEED_LIKE_ADD(FeedLikeValue.class),
FEED_LIKE_REMOVE(FeedLikeValue.class),
RATINGS_RATING_ADD(RatingsRatingValue.class),
RATINGS_RATING_REMOVE(RatingsRatingValue.class),
RATINGS_COMMENT_ADD(RatingsCommentValue.class),
RATINGS_COMMENT_EDITED(RatingsCommentValue.class),
RATINGS_COMMENT_REMOVE(RatingsCommentValue.class),
RATINGS_LIKE_ADD(RatingsLikeValue.class),
RATINGS_LIKE_REMOVE(RatingsLikeValue.class),
CONVERSATIONS(PageConversation.class);
private Class<ChangeValue> valueClass;
ChangeValueEnumeration(Class valueClass) {
this.valueClass = valueClass;
}
public Class<ChangeValue> getValueClass() {
return valueClass;
}
}
}
|
package org.jevon.cordova.parse.pushplugin;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import com.parse.Parse;
import com.parse.ParseInstallation;
public class ParsePushPlugin extends CordovaPlugin {
public static final String ACTION_INITIALIZE = "initialize";
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
if (action.equals(ACTION_INITIALIZE)) {
this.initialize(callbackContext, args);
return true;
}
// TODO more actions...
return false; // false == NoSuchMethod
}
private void initialize(final CallbackContext context, final JSONArray args) throws JSONException {
if (args.length() >= 1) {
final String appId = args.getString(0);
final String clientKey = args.getString(1);
// "exec() to initialize blocked the main thread; Plugin should use CordovaInterface.getThreadPool()"
cordova.getThreadPool().execute(new Runnable() {
@Override
public void run() {
Parse.initialize(cordova.getActivity(), appId, clientKey);
// "Also, save the current installation to Parse"
ParseInstallation.getCurrentInstallation().saveInBackground();
context.success();
}
});
} else {
context.error("Expected two arguments");
}
}
}
|
package com.tlongdev.bktf;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.LayerDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.preference.PreferenceManager;
import android.util.Log;
import com.tlongdev.bktf.enums.Quality;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* Utility class (static only).
*/
public class Utility {
public static final String LOG_TAG = Utility.class.getSimpleName();
public static final String CURRENCY_USD = "usd";
public static final String CURRENCY_METAL = "metal";
public static final String CURRENCY_KEY = "keys";
public static final String CURRENCY_BUD = "earbuds";
/**
* Convenient method for getting the steamId (or vanity user name) of the user.
*/
public static String getSteamId(Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
String steamId = prefs.getString(context.getString(R.string.pref_steam_id), null);
if (steamId != null && steamId.equals("")){
return null;
}
return steamId;
}
/**
* Convenient method for getting the steamId of the user.
*/
public static String getResolvedSteamId(Context context) {
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
return prefs.getString(context.getString(R.string.pref_resolved_steam_id), null);
}
/**
* Properly formats the item name according to its properties.
*/
public static String formatItemName(String name, int tradable, int craftable, int quality, int index) {
String formattedName = "";
if (tradable == 0) {
formattedName += "Non-Tradable ";
}
if (craftable == 0) {
formattedName += "Non-Craftable ";
}
//Convert the quality int to enum for better readability
Quality q = Quality.values()[quality];
switch (q) {
case NORMAL:
formattedName += "Normal ";
break;
case GENUINE:
formattedName += "Genuine ";
break;
case VINTAGE:
formattedName += "Vintage ";
break;
case UNIQUE:
if (index > 0) //A unique item with a number
name = name + " #" + index;
break;
case UNUSUAL:
formattedName += getUnusualEffectName(index) + " ";
break;
case COMMUNITY:
formattedName += "Community ";
break;
case VALVE:
formattedName += "Valve ";
break;
case SELF_MADE:
formattedName += "Self-made ";
break;
case STRANGE:
formattedName += "Strange ";
break;
case HAUNTED:
formattedName += "Haunted ";
break;
case COLLECTORS:
formattedName += "Collector's ";
break;
}
return formattedName + name;
}
public static String formatSimpleItemName(String name, int quality, int index, boolean isProper) {
String formattedName = "";
//Convert the quality int to enum for better readability
Quality q = Quality.values()[quality];
switch (q) {
case NORMAL:
formattedName += "Normal ";
break;
case GENUINE:
formattedName += "Genuine ";
break;
case VINTAGE:
formattedName += "Vintage ";
break;
case UNIQUE:
if (index > 0) //A unique item with a number
name = name + " #" + index;
if (isProper){
name = "The " + name;
}
break;
case UNUSUAL:
formattedName += "Unusual ";
break;
case COMMUNITY:
formattedName += "Community ";
break;
case VALVE:
formattedName += "Valve ";
break;
case SELF_MADE:
formattedName += "Self-made ";
break;
case STRANGE:
formattedName += "Strange ";
break;
case HAUNTED:
formattedName += "Haunted ";
break;
case COLLECTORS:
formattedName += "Collector's ";
break;
}
return formattedName + name;
}
/**
* Get the proper name of the unusual effect
*/
public static String getUnusualEffectName(int index) {
switch (index) {
case 4:
return "Community Sparkle";
case 5:
return "Holy Glow";
case 6:
return "Green Confetti";
case 7:
return "Purple Confetti";
case 8:
return "Haunted Ghosts";
case 9:
return "Green Energy";
case 10:
return "Purple Energy";
case 11:
return "Circling TF Logo";
case 12:
return "Massed Flies";
case 13:
return "Burning Flames";
case 14:
return "Scorching Flames";
case 15:
return "Searing Plasma";
case 16:
return "Vivid Plasma";
case 17:
return "Sunbeams";
case 18:
return "Circling Peace Sign";
case 19:
return "Circling Heart";
case 29:
return "Stormy Storm";
case 30:
return "Blizzardy Storm";
case 31:
return "Nuts n' Bolts";
case 32:
return "Orbiting Planets";
case 33:
return "Orbiting Fire";
case 34:
return "Bubbling";
case 35:
return "Smoking";
case 36:
return "Steaming";
case 37:
return "Flaming Lantern";
case 38:
return "Cloudy Moon";
case 39:
return "Cauldron Bubbles";
case 40:
return "Eerie Orbiting Fire";
case 43:
return "Knifestorm";
case 44:
return "Misty Skull";
case 45:
return "Harvest Moon";
case 46:
return "It's A Secret To Everybody";
case 47:
return "Stormy 13th Hour";
case 56:
return "Kill-a-Watt";
case 57:
return "Terror-Watt";
case 58:
return "Cloud 9";
case 59:
return "Aces High";
case 60:
return "Dead Presidents";
case 61:
return "Miami Nights";
case 62:
return "Disco Beat Down";
case 63:
return "Phosphorous";
case 64:
return "Sulphurous";
case 65:
return "Memory Leak";
case 66:
return "Overclocked";
case 67:
return "Electrostatic";
case 68:
return "Power Surge";
case 69:
return "Anti-Freeze";
case 70:
return "Time Warp";
case 71:
return "Green Black Hole";
case 72:
return "Roboactive";
case 73:
return "Arcana";
case 74:
return "Spellbound";
case 75:
return "Chiroptera Venenata";
case 76:
return "Poisoned Shadows";
case 77:
return "Something Burning This Way Comes";
case 78:
return "Hellfire";
case 79:
return "Darkblaze";
case 80:
return "Demonflame";
case 81:
return "Bonzo The All-Gnawing";
case 82:
return "Amaranthine";
case 83:
return "Stare From Beyond";
case 84:
return "The Ooze";
case 85:
return "Ghastly Ghosts Jr";
case 86:
return "Haunted Phantasm Jr";
case 87:
return "Frostbite";
case 88:
return "Molten Mallard";
case 89:
return "Morning Glory";
case 90:
return "Death at Dusk";
case 3001:
return "Showstopper";
case 3003:
return "Holy Grail";
case 3004:
return "'72";
case 3005:
return "Fountain of Delight";
case 3006:
return "Screaming Tiger";
case 3007:
return "Skill Gotten Gains";
case 3008:
return "Midnight Whirlwind";
case 3009:
return "Silver Cyclone";
case 3010:
return "Mega Strike";
case 3011:
return "Haunted Phantasm";
case 3012:
return "Ghastly Ghosts";
default:
return "";
}
}
/**
* Returns a drawable based on the item's properties to use asa background
*/
public static LayerDrawable getItemBackground(Context context, int quality, int tradable, int craftable) {
//Convert the quality int to enum for better readability
Quality q = Quality.values()[quality];
Drawable itemFrame;
Drawable craftableFrame;
Drawable tradableFrame;
switch (q) {
case GENUINE:
itemFrame = context.getResources().getDrawable(R.drawable.item_background_genuine);
break;
case VINTAGE:
itemFrame = context.getResources().getDrawable(R.drawable.item_background_vintage);
break;
case UNUSUAL:
itemFrame = context.getResources().getDrawable(R.drawable.item_background_unusual);
break;
case UNIQUE:
itemFrame = context.getResources().getDrawable(R.drawable.item_background_unique);
break;
case COMMUNITY:
itemFrame = context.getResources().getDrawable(R.drawable.item_background_community);
break;
case VALVE:
itemFrame = context.getResources().getDrawable(R.drawable.item_background_valve);
break;
case SELF_MADE:
itemFrame = context.getResources().getDrawable(R.drawable.item_background_community);
break;
case STRANGE:
itemFrame = context.getResources().getDrawable(R.drawable.item_background_strange);
break;
case HAUNTED:
itemFrame = context.getResources().getDrawable(R.drawable.item_background_haunted);
break;
case COLLECTORS:
itemFrame = context.getResources().getDrawable(R.drawable.item_background_collectors);
break;
default:
itemFrame = context.getResources().getDrawable(R.drawable.item_background_normal);
break;
}
if (craftable == 0){
craftableFrame = context.getResources().getDrawable(R.drawable.non_craftable_border);
}
else {
//Easier to use an empty drawable instead of resizing the layer drawable
craftableFrame = context.getResources().getDrawable(R.drawable.empty_drawable);
}
if (tradable == 0){
tradableFrame = context.getResources().getDrawable(R.drawable.non_tradable_border);
}
else {
//Easier to use an empty drawable instead of resizing the layer drawable
tradableFrame = context.getResources().getDrawable(R.drawable.empty_drawable);
}
return new LayerDrawable(new Drawable[] {itemFrame, craftableFrame, tradableFrame});
}
/**
* Formats the given price and converts it to the desired currency.
*/
public static String formatPrice(Context context, double low, double high, String originalCurrency, String targetCurrency, boolean twoLines) throws Throwable {
//Initial string
String product = "";
//Convert the prices first
low = convertPrice(context, low, originalCurrency, targetCurrency);
if (high > 0.0)
high = convertPrice(context, high, originalCurrency, targetCurrency);
//Check if the price is an int
if ((int)low == low)
product += (int)low;
//Check if the double has fraction smaller than 0.01, if so we need to format the double
else if (("" + low).substring(("" + low).indexOf('.') + 1).length() > 2)
product += new DecimalFormat("#0.00").format(low);
else
product += low;
if (high > 0.0){
//Check if the price is an int
if ((int)high == high)
product += "-" + (int)high;
//Check if the double has fraction smaller than 0.01, if so we need to format the double
else if (("" + high).substring(("" + high).indexOf('.') + 1).length() > 2)
product += "-" + new DecimalFormat("#0.00").format(high);
else
product += "-" + high;
}
//If the price needs to be in two lines, the currency will be in a seperate line.
if (twoLines) {
product += "\n";
}
//Append the string with the proper currency
switch(targetCurrency) {
case CURRENCY_BUD:
if (low == 1.0 && high == 0.0)
return product + " bud";
else
return product + " buds";
case CURRENCY_METAL:
return product + " ref";
case CURRENCY_KEY:
if (low == 1.0 && high == 0.0)
return product + " key";
else
return product + " keys";
case CURRENCY_USD:
return "$" + product;
default:
//App should never reach this code
if (isDebugging(context))
Log.e(LOG_TAG, "Error formatting price");
throw new Throwable("Error while formatting price");
}
}
/**
* Converts the price to that desired currency.
*/
public static double convertPrice(Context context, double price, String originalCurrency, String targetCurrency) throws Throwable {
if (originalCurrency.equals(targetCurrency))
//The target currency equals the original currency, nothing to do.
return price;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
//Magic converter block
switch(originalCurrency){
case CURRENCY_BUD:
switch(targetCurrency){
case CURRENCY_KEY:
return price * (getDouble(prefs, context.getString(R.string.pref_buds_raw), 1)
/ getDouble(prefs, context.getString(R.string.pref_key_raw), 1));
case CURRENCY_METAL:
return price * getDouble(prefs, context.getString(R.string.pref_buds_raw), 1);
case CURRENCY_USD:
return price * (getDouble(prefs, context.getString(R.string.pref_buds_raw), 1)
* getDouble(prefs, context.getString(R.string.pref_metal_raw_usd), 1));
}
case CURRENCY_METAL:
switch(targetCurrency){
case CURRENCY_KEY:
return price / getDouble(prefs, context.getString(R.string.pref_key_raw), 1);
case CURRENCY_BUD:
return price / getDouble(prefs, context.getString(R.string.pref_buds_raw), 1);
case CURRENCY_USD:
return price * getDouble(prefs, context.getString(R.string.pref_metal_raw_usd), 1);
}
case CURRENCY_KEY:
switch(targetCurrency){
case CURRENCY_METAL:
return price * getDouble(prefs, context.getString(R.string.pref_key_raw), 1);
case CURRENCY_BUD:
return price * (getDouble(prefs, context.getString(R.string.pref_key_raw), 1)
/ getDouble(prefs, context.getString(R.string.pref_buds_raw), 1));
case CURRENCY_USD:
return price * getDouble(prefs, context.getString(R.string.pref_key_raw), 1)
* getDouble(prefs, context.getString(R.string.pref_metal_raw_usd), 1);
}
case CURRENCY_USD:
switch(targetCurrency){
case CURRENCY_METAL:
return price / getDouble(prefs, context.getString(R.string.pref_metal_raw_usd), 1);
case CURRENCY_BUD:
return price / getDouble(prefs, context.getString(R.string.pref_metal_raw_usd), 1)
/ getDouble(prefs, context.getString(R.string.pref_buds_raw), 1);
case CURRENCY_KEY:
return price * getDouble(prefs, context.getString(R.string.pref_metal_raw_usd), 1)
/ getDouble(prefs, context.getString(R.string.pref_key_raw), 1);
}
default:
String error = "Unknown currency: " + originalCurrency + " - " + targetCurrency;
if (isDebugging(context))
Log.e(LOG_TAG, error);
throw new Throwable(error);
}
}
/**
* Check if the given steamId is a 64bit steamId using Regex.
*/
public static boolean isSteamId(String id) {
return id.matches("7656119[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]");
}
/**
* Format the unix timestamp the a user readable string.
*/
public static String formatUnixTimeStamp(long unixSeconds){
Date date = new Date(unixSeconds*1000L); // *1000 is to convert seconds to milliseconds
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return sdf.format(date);
}
/**
* Format the timestamp to a user friendly string that is the same as on steam profile pages.
*/
public static String formatLastOnlineTime(long time) {
//If the time is longer than 2 days tho format is X days.
if (time >= 172800000L) {
long days = time / 86400000;
return "" + days + " days ago";
}
//If the time is longer than an hour, the format is X hour(s) Y minute(s)
if (time >= 3600000L) {
long hours = time / 3600000;
if (time % 3600000L == 0) {
if (hours == 1)
return "" + hours + " hour ago";
else {
return "" + hours + " hours ago";
}
}
else {
long minutes = (time % 3600000L) / 60000;
if (hours == 1)
if (minutes == 1)
return "" + hours + " hour " + minutes + " minute ago";
else
return "" + hours + " hour " + minutes + " minutes ago";
else {
if (minutes == 1)
return "" + hours + " hours " + minutes + " minute ago";
else
return "" + hours + " hours " + minutes + " minutes ago";
}
}
}
//Else it was less than an hour ago, the format is X minute(s).
else {
long minutes = time / 60000;
if (minutes == 0){
return "Just now";
} else if (minutes == 1){
return "1 minute ago";
} else {
return "" + minutes + " minutes ago";
}
}
}
/**
* Retrieves the steamId from a properly formatted JSON.
*/
public static String parseSteamIdFromVanityJson(String userJsonStr) throws JSONException {
final String OWM_RESPONSE = "response";
final String OWM_SUCCESS = "success";
final String OWM_STEAM_ID = "steamid";
final String OWM_MESSAGE = "message";
JSONObject jsonObject = new JSONObject(userJsonStr);
JSONObject response = jsonObject.getJSONObject(OWM_RESPONSE);
if (response.getInt(OWM_SUCCESS) != 1){
//Return the error message if unsuccessful.
return response.getString(OWM_MESSAGE);
}
return response.getString(OWM_STEAM_ID);
}
/**
* Retrieves the user name from a properly formatted JSON.
*/
public static String parseUserNameFromJson(String jsonString) throws JSONException {
final String OWM_RESPONSE = "response";
final String OWM_PLAYERS = "players";
final String OWM_NAME = "personaname";
JSONObject jsonObject = new JSONObject(jsonString);
JSONObject response = jsonObject.getJSONObject(OWM_RESPONSE);
JSONArray players = response.getJSONArray(OWM_PLAYERS);
JSONObject player = players.getJSONObject(0);
return player.getString(OWM_NAME);
}
/**
* Retrieves the url for the user avatar from a proerly formatted JSON.
*/
public static String parseAvatarUrlFromJson(String jsonString) throws JSONException {
final String OWM_RESPONSE = "response";
final String OWM_PLAYERS = "players";
final String OWM_AVATAR = "avatarfull";
JSONObject jsonObject = new JSONObject(jsonString);
JSONObject response = jsonObject.getJSONObject(OWM_RESPONSE);
JSONArray players = response.getJSONArray(OWM_PLAYERS);
JSONObject player = players.getJSONObject(0);
return player.getString(OWM_AVATAR);
}
/**
* Check whether the user if connected to the internet.
*/
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager
= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
/**
* Convenient method for storing double values in shared preferences.
*/
public static SharedPreferences.Editor putDouble(final SharedPreferences.Editor edit, final String key, final double value) {
return edit.putLong(key, Double.doubleToRawLongBits(value));
}
/**
* Convenient method for getting double values from shared preferences.
*/
public static double getDouble(final SharedPreferences prefs, final String key, final double defaultValue) {
return Double.longBitsToDouble(prefs.getLong(key, Double.doubleToLongBits(defaultValue)));
}
/**
* Whether we should log or not
*/
public static boolean isDebugging(Context context){
return PreferenceManager.getDefaultSharedPreferences(context).getBoolean(context.getString(R.string.pref_debug), false);
}
/**
* Check whether the given timestamp is older than 3 months
*/
public static boolean isPriceOld(int unixTimeStamp){
return System.currentTimeMillis() - unixTimeStamp*1000L > 7884000000L;
}
/**
* Rounds the given double
*/
public static double roundDouble(double value, int places) {
if (places < 0) throw new IllegalArgumentException();
BigDecimal bd = new BigDecimal(value);
bd = bd.setScale(places, RoundingMode.HALF_UP);
return bd.doubleValue();
}
public static double getRawMetal(int rawRef, int rawRec, int rawScraps) {
return (1.0/9.0 * rawScraps) + (1.0/3.0 * rawRec) + rawRef;
}
public static String getPaintName(int index){
switch (index){
case 7511618: return "Indubitably Green";
case 4345659: return "Zepheniah's Greed";
case 5322826: return "Noble Hatter's Violet";
case 14204632: return "Color No. 216-190-216";
case 8208497: return "Deep Commitment to Purple";
case 13595446: return "Mann Co. Orange";
case 10843461: return "Muskelmannbraun";
case 12955537: return "Peculiarly Drab Tincture";
case 6901050: return "Radigan Conagher Brown";
case 8154199: return "Ye Olde Rustic Color";
case 15185211: return "Australium Gold";
case 8289918: return "Aged Moustache Grey";
case 15132390: return "An Extraordinary Abundance of Tinge";
case 1315860: return "A Distinctive Lack of Hue";
case 16738740: return "Pink as Hell";
case 3100495: return "Color Similar to Slate";
case 8421376: return "Drably Olive";
case 3329330: return "The Bitter Taste of Defeat and Lime";
case 15787660: return "The Color of a Gentlemann's Business Pants";
case 15308410: return "Salmon Injustice";
case 12073019: return "Team Spirit";
case 4732984: return "Operator's Overalls";
case 11049612: return "Waterlogged Lab Coat";
case 3874595: return "Balaclava's Are Forever";
case 6637376: return "Air of Debonair";
case 8400928: return "The Value of Teamwork";
case 12807213: return "Cream Spirit";
case 2960676: return "After Eight";
case 12377523: return "A Mann's Mint";
default: return null;
}
}
public static boolean isPaint(int index){
switch (index){
case 7511618: return true;
case 4345659: return true;
case 5322826: return true;
case 14204632: return true;
case 8208497: return true;
case 13595446: return true;
case 10843461: return true;
case 12955537: return true;
case 6901050: return true;
case 8154199: return true;
case 15185211: return true;
case 8289918: return true;
case 15132390: return true;
case 1315860: return true;
case 16738740: return true;
case 3100495: return true;
case 8421376: return true;
case 3329330: return true;
case 15787660: return true;
case 15308410: return true;
case 12073019: return true;
case 4732984: return true;
case 11049612: return true;
case 3874595: return true;
case 6637376: return true;
case 8400928: return true;
case 12807213: return true;
case 2960676: return true;
case 12377523: return true;
default: return false;
}
}
public static boolean canHaveEffects(int defindex, int quality){
if (quality == 5 || quality == 7 || quality == 9) {
return defindex != 267 && defindex != 266;
} else if (defindex == 1899 || defindex == 125){
return true;
}
return false;
}
public static int fixDefindex(int defindex) {
//Check if the defindex is of a duplicate defindex to provide the proper price for it.
/*if (defindex >= 9 && defindex <= 12) { //duplicate shotguns
defindex = 9;
} else if (defindex == 23) {//duplicate pistol
defindex = 22;
} else if (defindex == 28) {//duplicate destruction tool
defindex = 26;
} else if (defindex >= 190 && defindex <= 199) { //duplicate stock weapons
defindex -= 190;
} else if (defindex >= 200 && defindex <= 209) {
defindex -= 187;
} else if (defindex == 210) {
defindex -= 186;
} else if (defindex == 211 || defindex == 212) {
defindex -= 182;
} else if (defindex == 736) { //duplicate sapper
defindex = 735;
} else if (defindex == 737) { //duplicate construction pda
defindex = 25;
} else if (defindex == 5041 || defindex == 5045) { //duplicate crates
defindex = 5022;
} else if (defindex == 5735 || defindex == 5742 //duplicate munitions
|| defindex == 5752 || defindex == 5781 || defindex == 5802) {
defindex = 5734;
}*/
switch (defindex){
case 9: case 10: case 11: case 12: //duplicate shotguns
return 9;
case 23: //duplicate pistol
return 22;
case 28: //duplicate destruction tool
return 26;
case 190: case 191: case 192: case 193: case 194: //duplicate stock weapons
case 195: case 196: case 197: case 198: case 199:
return defindex - 190;
case 200: case 201: case 202: case 203: case 204: //duplicate stock weapons
case 205: case 206: case 207: case 208: case 209:
return defindex - 187;
case 210:
return defindex - 186;
case 211: case 212:
return defindex - 182;
case 736: //duplicate sapper
return 735;
case 737: //duplicate construction pda
return 25;
case 5041: case 5045: //duplicate crates
return 5022;
case 5735: case 5742: case 5752: case 5781: case 5802: //duplicate munitions
return 5734;
default:
return defindex;
}
}
public static int getIconIndex(int defindex) {
//Check if the defindex is of a duplicate defindex to provide the proper price for it.
switch (defindex){
case 9: case 10: case 11: case 12: //duplicate shotguns
return 9;
case 23: //duplicate pistol
return 22;
case 28: //duplicate destruction tool
return 26;
case 190: case 191: case 192: case 193: case 194: //duplicate stock weapons
case 195: case 196: case 197: case 198: case 199:
return defindex - 190;
case 200: case 201: case 202: case 203: case 204: //duplicate stock weapons
case 205: case 206: case 207: case 208: case 209:
return defindex - 187;
case 210:
return defindex - 186;
case 211: case 212:
return defindex - 182;
case 294: //lugermorph
return 160;
case 422: //companion cube pin
return 299;
case 736: //duplicate sapper
return 735;
case 737: //duplicate construction pda
return 25;
case 2103: //Deus Ex arm
return 524;
case 5041: case 5045: //duplicate crates
return 5022;
case 5735: case 5742: case 5752: case 5781: case 5802: //duplicate munitions
return 5734;
case 8223: //duplicate soldier medal
return 121;
default:
return defindex;
}
}
public static class IntegerPair{
int x;
int y;
public IntegerPair(){
this(0);
}
public IntegerPair(int x) {
this(x, 0);
}
public IntegerPair(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
}
}
|
package com.metroveu.metroveu;
import android.support.test.espresso.assertion.ViewAssertions;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import com.metroveu.metroveu.activities.MainActivity;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static android.support.test.espresso.Espresso.onData;
import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.action.ViewActions.pressBack;
import static android.support.test.espresso.action.ViewActions.swipeLeft;
import static android.support.test.espresso.action.ViewActions.swipeRight;
import static android.support.test.espresso.action.ViewActions.swipeUp;
import static android.support.test.espresso.assertion.PositionAssertions.isBelow;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static org.hamcrest.Matchers.anything;
@RunWith(AndroidJUnit4.class)
public class MainActivityTest {
@Rule
public final ActivityTestRule<MainActivity> main = new ActivityTestRule<>(MainActivity.class);
@Test public void onAppStartedHomePageAppears() {
onView(withText(R.string.home))
.check(ViewAssertions.matches(isDisplayed()));
}
@Test public void onLinesButtonClickedLinesAppear() {
onView(withId(R.id.show_lines_button))
.perform(click());
onView(withId(R.id.liniesListView))
.check(ViewAssertions.matches(isDisplayed()));
}
@Test public void allLinesAreShown() {
onView(withId(R.id.show_lines_button))
.perform(click());
onView(withText("L1")).check(ViewAssertions.matches(isDisplayed()));
onView(withText("L2")).check(ViewAssertions.matches(isDisplayed()));
onView(withText("L9")).check(ViewAssertions.matches(isDisplayed()));
onView(withText("L10")).check(ViewAssertions.matches(isDisplayed()));
onView(withText("L11")).check(ViewAssertions.matches(isDisplayed()));
}
@Test public void fromLinesReturnToMain() {
onView(withId(R.id.show_lines_button))
.perform(click());
onView(withId(R.id.liniesListView))
.perform(pressBack());
onView(withText(R.string.home))
.check(ViewAssertions.matches(isDisplayed()));
}
/**
* Test per comprovar que prement una linia de la llista ens apareix el fragment de parades
*/
@Test public void onLineClickGoToStops() {
onView(withId(R.id.show_lines_button))
.perform(click());
onView(withText("L3"))
.perform(click());
onView(withId(R.id.paradesListView))
.check(ViewAssertions.matches(isDisplayed()));
}
@Test public void onLineClickShowStops() {
onView(withId(R.id.show_lines_button))
.perform(click());
onView(withText("L3"))
.perform(click());
onView(withText("Zona Universitària"))
.check(ViewAssertions.matches(isDisplayed()));
onData(anything()).inAdapterView(withId(R.id.paradesListView))
.atPosition(0)
//.perform(click());
.check(ViewAssertions.matches(isDisplayed()));
//TODO: Es pot ampliar el test
}
@Test public void fromStopsReturnToLines() {
onView(withId(R.id.show_lines_button))
.perform(click());
onView(withText("L2"))
.perform(click());
onView(withId(R.id.paradesListView))
.perform(pressBack());
onView(withId(R.id.liniesListView))
.check(ViewAssertions.matches(isDisplayed()));
}
/**
* Test per comprovar que prement una parada de la llista ens apareix el fragment dels detalls de la parada
*/
@Test public void onStopClickGoToDetails() {
onView(withId(R.id.show_lines_button))
.perform(click());
onView(withText("L4"))
.perform(click());
onView(withText("Maragall"))
.perform(click());
onView(withId(R.id.nomParada))
.check(ViewAssertions.matches(isDisplayed()));
}
/**
* Test per comprovar que prement una parada de la llista ens apareixen els detalls amb el seu nom
*/
@Test public void onStopClickShowDetailsName() {
onView(withId(R.id.show_lines_button))
.perform(click());
onView(withText("L4"))
.perform(click());
onView(withText("Maragall"))
.perform(click());
onView(withText("Maragall"))
.check(ViewAssertions.matches(isDisplayed()));
}
/**
* Test per comprovar que prement enrere als detalls d'una parada tornem a la llista de parades
*/
@Test public void fromDetailsReturnToStops() {
onView(withId(R.id.show_lines_button))
.perform(click());
onView(withText("L4"))
.perform(click());
onView(withText("Maragall"))
.perform(click());
onView(withId(R.id.nomParada))
.perform(pressBack());
onView(withId(R.id.paradesListView))
.check(ViewAssertions.matches(isDisplayed()));
}
/**
* Test per comprovar que lliscant amb el dit a l'esquerra es canvia de parada a l'anterior
*/
@Test public void fromStopChangeStopToLeft() {
onView(withId(R.id.show_lines_button))
.perform(click());
onView(withText("L5"))
.perform(click());
onView(withText("Collblanc"))
.perform(click());
onView(withId(R.id.nomParada))
.perform(swipeLeft());
onView(withText("Badal"))
.check(ViewAssertions.matches(isDisplayed()));
}
@Test public void fromStopChangeStopToRight() {
onView(withId(R.id.show_lines_button))
.perform(click());
onView(withText("L5"))
.perform(click());
onView(withText("Collblanc"))
.perform(click());
onView(withId(R.id.nomParada))
.perform(swipeRight());
onView(withText("Pubilla Cases"))
.check(ViewAssertions.matches(isDisplayed()));
}
@Test public void fromStopChangeStopAndDetails() {
onView(withId(R.id.show_lines_button))
.perform(click());
onView(withText("L5"))
.perform(click());
onView(withText("Collblanc"))
.perform(click());
onView(withId(R.id.nomParada))
.perform(swipeRight());
onView(withText("Pubilla Cases"))
.perform(click());
onView(withId(R.id.nomParada))
.check(ViewAssertions.matches(isDisplayed()));
}
/**
* Test per comprovar que des d'una parada lliscant amb el dit a l'esquerra es canvia de parada a l'anterior i si tornem a lliscar surt l'anterior d'aquesta
*/
@Test public void fromStopChangeStopToLeft2() {
onView(withId(R.id.show_lines_button))
.perform(click());
onView(withText("L5"))
.perform(click());
onView(withText("Collblanc"))
.perform(click());
onView(withId(R.id.nomParada))
.perform(swipeLeft());
onView(withText("Badal"))
.perform(click());
onView(withId(R.id.nomParada))
.perform(swipeLeft());
onView(withText("Plaça de Sants"))
.check(ViewAssertions.matches(isDisplayed()));
}
@Test public void fromStopChangeStopToRight2() {
onView(withId(R.id.show_lines_button))
.perform(click());
onView(withText("L5"))
.perform(click());
onView(withText("Collblanc"))
.perform(click());
onView(withId(R.id.nomParada))
.perform(swipeRight());
onView(withText("Pubilla Cases"))
.perform(click());
onView(withId(R.id.nomParada))
.perform(swipeRight());
onView(withText("Can Vidalet"))
.check(ViewAssertions.matches(isDisplayed()));
}
/**
* Test per comprovar que des d'una parada lliscant amb el dit a l'esquerra es canvia de parada
* a l'anterior i si llavors llisquem a la dreta tornem a la parada inicial
*/
@Test public void fromStopChangeStopToLeftAndRight() {
onView(withId(R.id.show_lines_button))
.perform(click());
onView(withText("L5"))
.perform(click());
onView(withText("Collblanc"))
.perform(click());
onView(withId(R.id.nomParada))
.perform(swipeLeft());
onView(withText("Badal"))
.perform(click());
onView(withId(R.id.nomParada))
.perform(swipeRight());
onView(withText("Collblanc"))
.check(ViewAssertions.matches(isDisplayed()));
}
/**
* Test per comprovar que des d'una parada lliscant amb el dit a la dreta es canvia de parada a
* seguent i si llavors llisquem a l'esquerra tornem a la parada inicial
*/
@Test public void fromStopChangeStopToRightAndLeft() {
onView(withId(R.id.show_lines_button))
.perform(click());
onView(withText("L5"))
.perform(click());
onView(withText("Collblanc"))
.perform(click());
onView(withId(R.id.nomParada))
.perform(swipeRight());
onView(withText("Pubilla Cases"))
.perform(click());
onView(withId(R.id.nomParada))
.perform(swipeLeft());
onView(withText("Collblanc"))
.check(ViewAssertions.matches(isDisplayed()));
}
/**
* Test per comprovar que les linies estan ordenades
*/
@Test public void orderedLines() {
onView(withId(R.id.show_lines_button))
.perform(click());
onView(withText("L2")).check(isBelow(withText("L1")));
onView(withText("L3")).check(isBelow(withText("L2")));
onView(withText("L4")).check(isBelow(withText("L3")));
onView(withText("L5")).check(isBelow(withText("L4")));
onView(withText("L9")).check(isBelow(withText("L5")));
onView(withText("L10")).check(isBelow(withText("L9")));
onView(withText("L11")).check(isBelow(withText("L10")));
onView(withText("TRAMVIA BLAU")).check(isBelow(withText("L11")));
onView(withText("FUNICULAR DE MONTJUÏC")).check(isBelow(withText("TRAMVIA BLAU")));
}
/**
* Test per comprovar que les parades estan ordenades
*/
@Test public void ordereStations() {
onView(withId(R.id.show_lines_button))
.perform(click());
onView(withText("L3"))
.perform(click());
onView(withText("Palau Reial")).check(isBelow(withText("Zona Universitària")));
onView(withText("Maria Cristina")).check(isBelow(withText("Palau Reial")));
onView(withText("Les Corts")).check(isBelow(withText("Maria Cristina")));
onView(withText("Plaça del Centre")).check(isBelow(withText("Les Corts")));
}
/**
* Test per comprovar que surt la accessibilitat correcta que tenen les parades
*/
@Test public void checkAdaptadaNoAdaptada() {
onView(withId(R.id.show_lines_button))
.perform(click());
onView(withText("L4"))
.perform(click());
onView(withText("Verdaguer"))
.perform(click());
onView(withText("No adaptada"))
.check(ViewAssertions.matches(isDisplayed()))
.perform(pressBack());
onView(withText("Joanic"))
.perform(click());
onView(withText("Adaptada"))
.check(ViewAssertions.matches(isDisplayed()))
.perform(pressBack());
onView(withText("Maragall"))
.perform(click());
onView(withText("No adaptada"))
.check(ViewAssertions.matches(isDisplayed()));
}
@Test public void checkSwipeAdaptadaNoAdaptada() {
onView(withId(R.id.show_lines_button))
.perform(click());
onView(withText("L4"))
.perform(click());
onView(withText("Verdaguer"))
.perform(click());
onView(withText("No adaptada"))
.check(ViewAssertions.matches(isDisplayed()))
.perform(swipeLeft());
onView(withText("Girona"))
.check(ViewAssertions.matches(isDisplayed()));
onView(withText("Adaptada"))
.check(ViewAssertions.matches(isDisplayed()))
.perform(swipeLeft());
onView(withText("Passeig de Gràcia"))
.check(ViewAssertions.matches(isDisplayed()));
onView(withText("Adaptada"))
.check(ViewAssertions.matches(isDisplayed()))
.perform(swipeLeft());
onView(withText("Urquinaona"))
.check(ViewAssertions.matches(isDisplayed()));
onView(withText("No adaptada"))
.check(ViewAssertions.matches(isDisplayed()));
}
@Test public void checkFinalDeLinia() {
onView(withId(R.id.show_lines_button))
.perform(click());
onView(withText("L4"))
.perform(click());
onView(withText("Trinitat Nova"))
.perform(click());
onView(withText("Final de línia"))
.check(ViewAssertions.matches(isDisplayed()))
.perform(pressBack());
onView(withId(R.id.paradesListView))
.perform(swipeUp())
.perform(swipeUp());
onView(withText("La Pau"))
.check(ViewAssertions.matches(isDisplayed()))
.perform(click());
onView(withText("Final de línia"))
.check(ViewAssertions.matches(isDisplayed()));
}
@Test public void checkFinalDeLiniaNavegant() {
onView(withId(R.id.show_lines_button))
.perform(click());
onView(withText("L9"))
.perform(click());
onView(withText("Onze de Setembre"))
.perform(click());
onView(withText("Onze de Setembre"))
.check(ViewAssertions.matches(isDisplayed()))
.perform(swipeRight());
onView(withText("Final de línia"))
.check(ViewAssertions.matches(isDisplayed()))
.perform(swipeRight());
onView(withText("Final de línia"))
.check(ViewAssertions.matches(isDisplayed()))
.perform(swipeLeft());
onView(withText("Onze de Setembre"))
.perform(swipeLeft());
onView(withText("Bon Pastor"))
.perform(swipeLeft());
onView(withText("Can Peixauet"))
.perform(swipeLeft());
onView(withText("Fondo"))
.perform(swipeLeft());
onView(withText("Església Major"))
.perform(swipeLeft());
onView(withText("Singuerlín"))
.perform(swipeLeft());
onView(withText("Final de línia"))
.check(ViewAssertions.matches(isDisplayed()))
.perform(swipeLeft());
onView(withText("Final de línia"))
.check(ViewAssertions.matches(isDisplayed()));
}
@Test public void checkCreateRoute() {
onView(withId(R.id.show_lines_button))
.perform(click());
onView(withText("L5"))
.perform(click());
onView(withText("Badal"))
.perform(click());
onView(withText("Començar ruta"))
.perform(click());
onView(withText("Badal"))
.perform(swipeLeft());
onView(withText("Plaça de Sants"))
.perform(swipeLeft());
onView(withText("Sants Estació"))
.perform(swipeLeft());
onView(withText("Entença"))
.perform(swipeLeft());
onView(withText("Hospital Clínic"))
.check(ViewAssertions.matches(isDisplayed()));
onView(withText("Finalitzar ruta"))
.perform(click());
onView(withText("Començar ruta"))
.check(ViewAssertions.matches(isDisplayed()));
}
@Test public void checkRouteCreated() {
onView(withId(R.id.show_routes_button))
.perform(click());
onView(withText("De L5-Badal a L5-Hospital Clínic"))
.check(ViewAssertions.matches(isDisplayed()))
.perform(click());
onView(withText("L5-Badal"))
.check(ViewAssertions.matches(isDisplayed()));
onView(withText("L5-Plaça de Sants"))
.check(ViewAssertions.matches(isDisplayed()));
onView(withText("L5-Sants Estació"))
.check(ViewAssertions.matches(isDisplayed()));
onView(withText("L5-Entença"))
.check(ViewAssertions.matches(isDisplayed()));
onView(withText("L5-Hospital Clínic"))
.check(ViewAssertions.matches(isDisplayed()))
.perform(pressBack());
onView(withText("De L5-Badal a L5-Hospital Clínic"))
.check(ViewAssertions.matches(isDisplayed()));
}
@Test public void checkCreateRouteDeletingLastStation() {
onView(withId(R.id.show_lines_button))
.perform(click());
onView(withText("L3"))
.perform(click());
onView(withText("Palau Reial"))
.perform(click());
onView(withText("Començar ruta"))
.perform(click());
onView(withText("Palau Reial"))
.perform(swipeLeft());
onView(withText("Maria Cristina"))
.perform(swipeLeft());
onView(withText("Les Corts"))
.perform(swipeLeft());
onView(withText("Plaça del Centre"))
.check(ViewAssertions.matches(isDisplayed()));
onView(withText("Eliminar ultima parada afegida"))
.check(ViewAssertions.matches(isDisplayed()))
.perform(click());
onView(withText("Finalitzar ruta"))
.perform(click());
onView(withText("Plaça del Centre"))
.check(ViewAssertions.matches(isDisplayed()))
.perform(pressBack());
onView(withText("L3"))
.perform(pressBack())
.perform(pressBack());
onView(withId(R.id.show_routes_button))
.perform(click());
onView(withText("De L3-Palau Reial a L3-Les Corts"))
.check(ViewAssertions.matches(isDisplayed()))
.perform(click());
onView(withText("L3-Palau Reial"))
.check(ViewAssertions.matches(isDisplayed()));
onView(withText("L3-Maria Cristina"))
.check(ViewAssertions.matches(isDisplayed()));
onView(withText("L3-Les Corts"))
.check(ViewAssertions.matches(isDisplayed()))
.perform(pressBack());
onView(withText("De L3-Palau Reial a L3-Les Corts"))
.check(ViewAssertions.matches(isDisplayed()));
}
}
|
package com.lorentzos.flingswipe;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.graphics.PointF;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.OvershootInterpolator;
public class FlingCardListener implements View.OnTouchListener {
private final float objectX;
private final float objectY;
private final int objectH;
private final int objectW;
private final int parentWidth;
private final FlingListener mFlingListener;
private final Object dataObject;
private final float halfWidth;
private float BASE_ROTATION_DEGREES;
private float aPosX;
private float aPosY;
private float aDownTouchX;
private float aDownTouchY;
private static final int INVALID_POINTER_ID = -1;
// The active pointer is the one currently moving our object.
private int mActivePointerId = INVALID_POINTER_ID;
private View frame = null;
private final int TOUCH_ABOVE = 0;
private final int TOUCH_BELOW = 1;
private int touchPosition;
private final Object obj = new Object();
private boolean isAnimationRunning = false;
private float MAX_COS = (float) Math.cos(Math.toRadians(45));
public FlingCardListener(View frame, Object itemAtPosition, FlingListener flingListener) {
this(frame,itemAtPosition, 15f, flingListener);
}
public FlingCardListener(View frame, Object itemAtPosition, float rotation_degrees, FlingListener flingListener) {
super();
this.frame = frame;
this.objectX = frame.getX();
this.objectY = frame.getY();
this.objectH = frame.getHeight();
this.objectW = frame.getWidth();
this.halfWidth = objectW/2f;
this.dataObject = itemAtPosition;
this.parentWidth = ((ViewGroup) frame.getParent()).getWidth();
this.BASE_ROTATION_DEGREES = rotation_degrees;
this.mFlingListener = flingListener;
}
public boolean onTouch(View view, MotionEvent event) {
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
// Save the ID of this pointer
mActivePointerId = event.getPointerId(0);
float x = 0;
float y = 0;
boolean success = false;
try {
y = event.getY(mActivePointerId);
x = event.getX(mActivePointerId);
success = true;
} catch (IllegalArgumentException e) {
Log.e(getClass().getSimpleName(), "Exception in onTouch(view, event) : " + mActivePointerId);
}
if (success) {
// Remember where we started
aDownTouchX = x;
aDownTouchY = y;
//to prevent an initial jump of the magnifier, aposX and aPosY must
//have the values from the magnifier frame
if (aPosX == 0) {
aPosX = frame.getX();
}
if (aPosY == 0) {
aPosY = frame.getY();
}
if (y < objectH / 2) {
touchPosition = TOUCH_ABOVE;
} else {
touchPosition = TOUCH_BELOW;
}
}
break;
case MotionEvent.ACTION_UP:
mActivePointerId = INVALID_POINTER_ID;
resetCardViewOnStack();
break;
case MotionEvent.ACTION_POINTER_DOWN:
break;
case MotionEvent.ACTION_POINTER_UP:
// Extract the index of the pointer that left the touch sensor
final int pointerIndex = (event.getAction() &
MotionEvent.ACTION_POINTER_INDEX_MASK) >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
final int pointerId = event.getPointerId(pointerIndex);
if (pointerId == mActivePointerId) {
// This was our active pointer going up. Choose a new
// active pointer and adjust accordingly.
final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
mActivePointerId = event.getPointerId(newPointerIndex);
}
break;
case MotionEvent.ACTION_MOVE:
// Find the index of the active pointer and fetch its position
final int pointerIndexMove = event.findPointerIndex(mActivePointerId);
final float xMove = event.getX(pointerIndexMove);
final float yMove = event.getY(pointerIndexMove);
// Calculate the distance moved
final float dx = xMove - aDownTouchX;
final float dy = yMove - aDownTouchY;
// Move the frame
aPosX += dx;
aPosY += dy;
// calculate the rotation degrees
float distobjectX = aPosX - objectX;
float rotation = BASE_ROTATION_DEGREES * 2.f * distobjectX / parentWidth;
if (touchPosition == TOUCH_BELOW) {
rotation = -rotation;
}
//in this area would be code for doing something with the view as the frame moves.
frame.setX(aPosX);
frame.setY(aPosY);
frame.setRotation(rotation);
mFlingListener.onScroll(getScrollProgressPercent());
break;
case MotionEvent.ACTION_CANCEL: {
mActivePointerId = INVALID_POINTER_ID;
break;
}
}
return true;
}
private float getScrollProgressPercent() {
if (movedBeyondLeftBorder()) {
return -1f;
} else if (movedBeyondRightBorder()) {
return 1f;
} else {
float zeroToOneValue = (aPosX + halfWidth - leftBorder()) / (rightBorder() - leftBorder());
return zeroToOneValue * 2f - 1f;
}
}
private boolean resetCardViewOnStack() {
if(movedBeyondLeftBorder()){
// Left Swipe
onSelected(true, getExitPoint(-objectW), 100 );
mFlingListener.onScroll(-1.0f);
}else if(movedBeyondRightBorder()) {
// Right Swipe
onSelected(false, getExitPoint(parentWidth), 100 );
mFlingListener.onScroll(1.0f);
}else {
float abslMoveDistance = Math.abs(aPosX-objectX);
aPosX = 0;
aPosY = 0;
aDownTouchX = 0;
aDownTouchY = 0;
frame.animate()
.setDuration(200)
.setInterpolator(new OvershootInterpolator(1.5f))
.x(objectX)
.y(objectY)
.rotation(0);
mFlingListener.onScroll(0.0f);
if(abslMoveDistance<4.0){
mFlingListener.onClick(dataObject);
}
}
return false;
}
private boolean movedBeyondLeftBorder() {
return aPosX+halfWidth < leftBorder();
}
private boolean movedBeyondRightBorder() {
return aPosX+halfWidth > rightBorder();
}
public float leftBorder(){
return parentWidth/4.f;
}
public float rightBorder(){
return 3*parentWidth/4.f;
}
public void onSelected(final boolean isLeft,
float exitY, long duration){
isAnimationRunning = true;
float exitX;
if(isLeft) {
exitX = -objectW-getRotationWidthOffset();
}else {
exitX = parentWidth+getRotationWidthOffset();
}
this.frame.animate()
.setDuration(duration)
.setInterpolator(new AccelerateInterpolator())
.x(exitX)
.y(exitY)
.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
if (isLeft) {
mFlingListener.onCardExited();
mFlingListener.leftExit(dataObject);
} else {
mFlingListener.onCardExited();
mFlingListener.rightExit(dataObject);
}
isAnimationRunning = false;
}
})
.rotation(getExitRotation(isLeft));
}
/**
* Starts a default left exit animation.
*/
public void selectLeft(){
if(!isAnimationRunning)
onSelected(true, objectY, 200);
}
/**
* Starts a default right exit animation.
*/
public void selectRight(){
if(!isAnimationRunning)
onSelected(false, objectY, 200);
}
private float getExitPoint(int exitXPoint) {
float[] x = new float[2];
x[0] = objectX;
x[1] = aPosX;
float[] y = new float[2];
y[0] = objectY;
y[1] = aPosY;
LinearRegression regression =new LinearRegression(x,y);
//Your typical y = ax+b linear regression
return (float) regression.slope() * exitXPoint + (float) regression.intercept();
}
private float getExitRotation(boolean isLeft){
float rotation= BASE_ROTATION_DEGREES * 2.f * (parentWidth - objectX)/parentWidth;
if (touchPosition == TOUCH_BELOW) {
rotation = -rotation;
}
if(isLeft){
rotation = -rotation;
}
return rotation;
}
/**
* When the object rotates it's width becomes bigger.
* The maximum width is at 45 degrees.
*
* The below method calculates the width offset of the rotation.
*
*/
private float getRotationWidthOffset() {
return objectW/MAX_COS - objectW;
}
public void setRotationDegrees(float degrees) {
this.BASE_ROTATION_DEGREES = degrees;
}
public boolean isTouching() {
return this.mActivePointerId != INVALID_POINTER_ID;
}
public PointF getLastPoint() {
return new PointF(this.aPosX, this.aPosY);
}
protected interface FlingListener {
public void onCardExited();
public void leftExit(Object dataObject);
public void rightExit(Object dataObject);
public void onClick(Object dataObject);
public void onScroll(float scrollProgressPercent);
}
}
|
package wingset;
import org.wings.SBoxLayout;
import org.wings.SButton;
import org.wings.SCheckBox;
import org.wings.SComboBox;
import org.wings.SComponent;
import org.wings.SConstants;
import org.wings.SDefaultListCellRenderer;
import org.wings.SDimension;
import org.wings.SFont;
import org.wings.SGridBagLayout;
import org.wings.SLabel;
import org.wings.SPanel;
import org.wings.STextField;
import org.wings.SToolBar;
import org.wings.border.*;
import org.wings.session.SessionManager;
import org.wings.style.CSSProperty;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Arrays;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeEvent;
/**
* A visual control used in many WingSet demos.
*
* @author hengels
*/
public class ComponentControls extends SPanel {
protected static final Object[] BORDERS = new Object[] {
new Object[] { "default", SDefaultBorder.INSTANCE },
new Object[] { "none", null },
new Object[] { "raised", new SBevelBorder(SBevelBorder.RAISED) },
new Object[] { "lowered", new SBevelBorder(SBevelBorder.LOWERED) },
new Object[] { "line", new SLineBorder(2) },
new Object[] { "grooved", new SEtchedBorder(SEtchedBorder.LOWERED) },
new Object[] { "ridged", new SEtchedBorder(SEtchedBorder.RAISED) },
new Object[] { "empty", new SEmptyBorder(5,5,5,5)}
};
protected static final Object[] COLORS = new Object[] {
new Object[] { "none", null },
new Object[] { "gray", Color.GRAY},
new Object[] { "yellow", new Color(255, 255, 100) },
new Object[] { "red", new Color(255, 100, 100) },
new Object[] { "green", new Color(100, 255, 100) },
new Object[] { "blue", new Color(100, 100, 255) },
};
protected static final Object[] FONTS = new Object[] {
new Object[] { "default font", null },
new Object[] { "serif italic bold", new SFont("Times,Times New Roman,serif", SFont.ITALIC | SFont.BOLD, 10)},
new Object[] { "serif", new SFont("Times,Times New Roman,serif", SFont.PLAIN, SFont.DEFAULT_SIZE) },
new Object[] { "16 sans bold", new SFont("Arial,sans-serif", SFont.BOLD, 16)},
new Object[] { "24 fantasy italic", new SFont("Comic,Comic Sans MS,fantasy", SFont.ITALIC, 24) }
};
protected final List components = new LinkedList();
protected final SToolBar globalControls = new SToolBar();
protected final SToolBar localControls = new SToolBar();
protected final SCheckBox ajaxCheckBox = new SCheckBox("AJAX");
protected final STextField widthTextField = new STextField();
protected final STextField heightTextField = new STextField();
protected final STextField insetsTextField = new STextField();
protected final SComboBox borderStyleComboBox = new SComboBox(BORDERS);
protected final SComboBox borderColorComboBox = new SComboBox(COLORS);
protected final STextField borderThicknessTextField = new STextField();
protected final SComboBox backgroundComboBox = new SComboBox(COLORS);
protected final SComboBox foregroundComboBox = new SComboBox(COLORS);
protected final SComboBox fontComboBox = new SComboBox(FONTS);
protected final SCheckBox formComponentCheckBox = new SCheckBox("as form");
private SLabel placeHolder = new SLabel("<html> ");
public ComponentControls() {
super(new SGridBagLayout());
setBackground(new Color(240,240,240));
setPreferredSize(SDimension.FULLWIDTH);
SBorder border = new SLineBorder(1, new Insets(0, 3, 0, 6));
border.setColor(new Color(255, 255, 255), SConstants.TOP);
border.setColor(new Color(255, 255, 255), SConstants.LEFT);
border.setColor(new Color(190, 190, 190), SConstants.RIGHT);
border.setColor(new Color(190, 190, 190), SConstants.BOTTOM);
globalControls.setBorder(border);
globalControls.setHorizontalAlignment(SConstants.LEFT_ALIGN);
((SBoxLayout)globalControls.getLayout()).setHgap(3);
((SBoxLayout)globalControls.getLayout()).setVgap(4);
border = new SLineBorder(1, new Insets(0, 3, 0, 6));
border.setColor(new Color(255, 255, 255), SConstants.TOP);
border.setColor(new Color(255, 255, 255), SConstants.LEFT);
border.setColor(new Color(190, 190, 190), SConstants.RIGHT);
border.setColor(new Color(190, 190, 190), SConstants.BOTTOM);
localControls.setBorder(border);
localControls.setHorizontalAlignment(SConstants.LEFT_ALIGN);
((SBoxLayout)localControls.getLayout()).setHgap(6);
((SBoxLayout)localControls.getLayout()).setVgap(4);
GridBagConstraints c = new GridBagConstraints();
c.gridwidth = GridBagConstraints.RELATIVE;
c.gridwidth = GridBagConstraints.REMAINDER;
c.gridheight = 1;
add(globalControls, c);
add(localControls, c);
ajaxCheckBox.setSelected(SessionManager.getSession().getRootFrame().isUpdateEnabled());
widthTextField.setColumns(3);
widthTextField.setToolTipText("length with unit (example: '200px')");
heightTextField.setColumns(3);
heightTextField.setToolTipText("length with unit (example: '200px')");
insetsTextField.setColumns(1);
insetsTextField.setToolTipText("length only (example: '8')\n(applies to the border!)");
borderThicknessTextField.setColumns(1);
borderThicknessTextField.setToolTipText("length only (example: '2')");
borderStyleComboBox.setRenderer(new ObjectPairCellRenderer());
borderColorComboBox.setRenderer(new ObjectPairCellRenderer());
backgroundComboBox.setRenderer(new ObjectPairCellRenderer());
foregroundComboBox.setRenderer(new ObjectPairCellRenderer());
fontComboBox.setRenderer(new ObjectPairCellRenderer());
formComponentCheckBox.setToolTipText("show as form component .. i.e. trigger form submission");
globalControls.add(ajaxCheckBox);
globalControls.addSeparator();
globalControls.add(new SLabel("width"));
globalControls.add(widthTextField);
globalControls.add(new SLabel("height"));
globalControls.add(heightTextField);
globalControls.add(new SLabel("border"));
globalControls.add(borderThicknessTextField);
globalControls.add(borderStyleComboBox);
globalControls.add(borderColorComboBox);
globalControls.add(new SLabel("insets"));
globalControls.add(insetsTextField);
globalControls.add(new SLabel("color"));
globalControls.add(foregroundComboBox);
globalControls.add(backgroundComboBox);
globalControls.add(new SLabel("font"));
globalControls.add(fontComboBox);
globalControls.add(new SLabel(""));
globalControls.add(formComponentCheckBox);
localControls.add(placeHolder);
ActionListener ajaxListener = new ActionListener() {
public void actionPerformed(ActionEvent event) {
ajax();
}
};
ajaxCheckBox.addActionListener(ajaxListener);
ActionListener preferredSizeListener = new ActionListener() {
public void actionPerformed(ActionEvent event) {
preferredSize();
}
};
widthTextField.addActionListener(preferredSizeListener);
heightTextField.addActionListener(preferredSizeListener);
ActionListener borderListener = new ActionListener() {
public void actionPerformed(ActionEvent event) {
border();
}
};
borderThicknessTextField.addActionListener(borderListener);
borderStyleComboBox.addActionListener(borderListener);
borderColorComboBox.addActionListener(borderListener);
insetsTextField.addActionListener(borderListener);
ActionListener foregroundListener = new ActionListener() {
public void actionPerformed(ActionEvent event) {
foreground();
}
};
foregroundComboBox.addActionListener(foregroundListener);
ActionListener backgroundListener = new ActionListener() {
public void actionPerformed(ActionEvent event) {
background();
}
};
backgroundComboBox.addActionListener(backgroundListener);
ActionListener fontListener = new ActionListener() {
public void actionPerformed(ActionEvent event) {
font();
}
};
fontComboBox.addActionListener(fontListener);
ActionListener showAsFormComponentListener = new ActionListener() {
public void actionPerformed(ActionEvent event) {
showAsFormComponent();
}
};
formComponentCheckBox.addActionListener(showAsFormComponentListener);
SessionManager.getSession().addPropertyChangeListener("ajax", new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent evt) {
ajaxCheckBox.setSelected((Boolean)evt.getNewValue());
}
});
}
void ajax() {
SessionManager.getSession().getRootFrame().setUpdateEnabled(ajaxCheckBox.isSelected());
SessionManager.getSession().setProperty("ajax", ajaxCheckBox.isSelected());
}
void preferredSize() {
for (Iterator iterator = components.iterator(); iterator.hasNext();) {
SComponent component = (SComponent) iterator.next();
SDimension preferredSize = new SDimension();
preferredSize.setWidth(widthTextField.getText());
preferredSize.setHeight(heightTextField.getText());
component.setPreferredSize(preferredSize);
}
}
void border() {
int insets = 0;
try {
insets = Integer.parseInt(insetsTextField.getText());
}
catch (NumberFormatException e) {}
int borderThickness = 1;
try {
borderThickness = Integer.parseInt(borderThicknessTextField.getText());
}
catch (NumberFormatException e) {}
SAbstractBorder border = (SAbstractBorder) getSelectedObject(borderStyleComboBox);
if (border != null && border != SDefaultBorder.INSTANCE) {
border.setColor((Color)getSelectedObject(borderColorComboBox));
border.setInsets(new Insets(insets, insets, insets, insets));
border.setThickness(borderThickness);
}
for (Iterator iterator = components.iterator(); iterator.hasNext();) {
SComponent component = (SComponent) iterator.next();
component.setBorder(border != null ? (SBorder)border.clone() : null);
}
}
void background() {
for (Iterator iterator = components.iterator(); iterator.hasNext();) {
SComponent component = (SComponent) iterator.next();
component.setBackground((Color)getSelectedObject(backgroundComboBox));
}
}
void foreground() {
for (Iterator iterator = components.iterator(); iterator.hasNext();) {
SComponent component = (SComponent) iterator.next();
component.setForeground((Color)getSelectedObject(foregroundComboBox));
}
}
void font() {
for (Iterator iterator = components.iterator(); iterator.hasNext();) {
SComponent component = (SComponent) iterator.next();
component.setFont((SFont) getSelectedObject(fontComboBox));
}
}
void showAsFormComponent() {
for (Iterator iterator = components.iterator(); iterator.hasNext();) {
SComponent component = (SComponent) iterator.next();
component.setShowAsFormComponent(formComponentCheckBox.isSelected());
}
}
protected Object getSelectedObject(SComboBox combo) {
return combo.getSelectedIndex() != -1 ? ((Object[])combo.getSelectedItem())[1] : null;
}
public void removeGlobalControl(SComponent control) {
int index = Arrays.asList(globalControls.getComponents()).indexOf(control);
if (index >= 0) {
globalControls.remove(index); // comp
if (globalControls.getComponent(index - 1) instanceof SLabel)
globalControls.remove(index-1); // label
}
}
public void addControl(SComponent component) {
if (localControls.getComponent(0) == placeHolder)
localControls.removeAll();
localControls.add(component);
}
public void addControllable(SComponent component) {
components.add(component);
}
public List getControllables() {
return components;
}
/**
* Renderer which expects <code>Object[]</code> values and returns the first value
*/
protected static class ObjectPairCellRenderer extends SDefaultListCellRenderer {
public SComponent getListCellRendererComponent(SComponent list, Object value, boolean selected, int row) {
Object[] objects = (Object[])value;
value = objects[0];
return super.getListCellRendererComponent(list, value, selected, row);
}
}
}
/*
SButton switchDebugViewButton = new SButton("Toggle AJAX debug view");
switchStyleButton.setShowAsFormComponent(false);
switchDebugViewButton.addScriptListener(new JavaScriptListener(
JavaScriptEvent.ON_CLICK,
"wingS.ajax.toggleDebugView(); return false;"
));
*/
|
package io.burt.jmespath.node;
import java.util.ArrayList;
import java.util.List;
import io.burt.jmespath.Adapter;
public class SliceNode<T> extends Node<T> {
private final int start;
private final int stop;
private final int step;
private final int limit;
public SliceNode(Adapter<T> runtime, Integer start, Integer stop, Integer step, Node<T> source) {
super(runtime, source);
this.step = (step == null) ? 1 : step;
this.limit = (this.step < 0) ? -1 : 0;
this.start = (start == null) ? this.limit : start;
this.stop = (stop == null) ? ((this.step < 0) ? Integer.MIN_VALUE : Integer.MAX_VALUE) : stop;
}
@Override
public T searchOne(T projectionElement) {
List<T> elements = runtime.toList(projectionElement);
int begin = (start < 0) ? Math.max(elements.size() + start, 0) : Math.min(start, elements.size());
int end = (stop < 0) ? Math.max(elements.size() + stop, limit) : Math.min(stop, elements.size());
List<T> output = new ArrayList<>(Math.max(0, (end - begin) / step));
for (int i = begin; i != end; i += step) {
output.add(elements.get(i));
}
return runtime.createArray(output);
}
@Override
protected String internalToString() {
return String.format("%d, %d, %d", start, stop, step);
}
@Override
protected boolean internalEquals(Object o) {
SliceNode other = (SliceNode) o;
return start == other.start && stop == other.stop && step == other.step;
}
@Override
protected int internalHashCode() {
int h = 1;
h = h * 31 + start;
h = h * 31 + stop;
h = h * 31 + step;
return h;
}
}
|
package org.opencms.ade.contenteditor.client;
import com.alkacon.acacia.client.EditorBase;
import com.alkacon.acacia.shared.ValidationResult;
import com.alkacon.vie.client.Vie;
import com.alkacon.vie.shared.I_Entity;
import org.opencms.ade.contenteditor.shared.CmsContentDefinition;
import org.opencms.ade.contenteditor.shared.rpc.I_CmsContentServiceAsync;
import org.opencms.ade.contenteditor.widgetregistry.client.WidgetRegistry;
import org.opencms.gwt.client.CmsCoreProvider;
import org.opencms.gwt.client.rpc.CmsRpcAction;
import org.opencms.gwt.client.util.I_CmsSimpleCallback;
import org.opencms.gwt.shared.rpc.I_CmsCoreServiceAsync;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import com.google.gwt.dom.client.Element;
import com.google.gwt.user.client.Command;
/**
* The content editor base.<p>
*/
public class CmsEditorBase extends EditorBase {
/** The core RPC service instance. */
private I_CmsCoreServiceAsync m_coreSvc;
/** The content service. */
private I_CmsContentServiceAsync m_service;
/**
* Constructor.<p>
*
* @param service the content service
*/
public CmsEditorBase(I_CmsContentServiceAsync service) {
super(service);
m_service = service;
getWidgetService().setWidgetFactories(WidgetRegistry.getInstance().getWidgetFactories());
}
/**
* Returns if the given element or it's descendants are inline editable.<p>
*
* @param element the element
*
* @return <code>true</code> if the element has editable descendants
*/
public static boolean hasEditable(Element element) {
List<Element> children = Vie.getInstance().find("[property^=\"opencms://\"]", element);
return (children != null) && !children.isEmpty();
}
/**
* Sets all annotated child elements editable.<p>
*
* @param element the element
* @param editable <code>true</code> to enable editing
*
* @return <code>true</code> if the element had editable elements
*/
public static boolean setEditable(Element element, boolean editable) {
List<Element> children = Vie.getInstance().select("[property^=\"opencms://\"]", element);
if (children.size() > 0) {
for (Element child : children) {
if (editable) {
child.setAttribute("contentEditable", "true");
} else {
child.removeAttribute("contentEditable");
}
}
return true;
}
return false;
}
/**
* @see com.alkacon.acacia.client.EditorBase#getService()
*/
@Override
public I_CmsContentServiceAsync getService() {
return m_service;
}
/**
* Loads the content definition for the given entity and executes the callback on success.<p>
*
* @param entityId the entity id
* @param callback the callback
*/
public void loadDefinition(final String entityId, final I_CmsSimpleCallback<CmsContentDefinition> callback) {
CmsRpcAction<CmsContentDefinition> action = new CmsRpcAction<CmsContentDefinition>() {
@Override
public void execute() {
start(0, true);
getService().loadDefinition(entityId, this);
}
@Override
protected void onResponse(final CmsContentDefinition result) {
registerContentDefinition(result);
WidgetRegistry.getInstance().registerExternalWidgets(
result.getExternalWidgetConfigurations(),
new Command() {
public void execute() {
stop(false);
callback.execute(result);
}
});
}
};
action.execute();
}
/**
* Loads the content definition for the given entity and executes the callback on success.<p>
*
* @param entityId the entity id
* @param callback the callback
*/
public void loadNewDefinition(final String entityId, final I_CmsSimpleCallback<CmsContentDefinition> callback) {
CmsRpcAction<CmsContentDefinition> action = new CmsRpcAction<CmsContentDefinition>() {
@Override
public void execute() {
getService().loadNewDefinition(entityId, this);
}
@Override
protected void onResponse(final CmsContentDefinition result) {
registerContentDefinition(result);
WidgetRegistry.getInstance().registerExternalWidgets(
result.getExternalWidgetConfigurations(),
new Command() {
public void execute() {
stop(false);
callback.execute(result);
}
});
}
};
action.execute();
}
/**
* Registers a deep copy of the source entity with the given target entity id.<p>
*
* @param sourceEntityId the source entity id
* @param targetEntityId the target entity id
*/
public void registerClonedEntity(String sourceEntityId, String targetEntityId) {
Vie.getInstance().getEntity(sourceEntityId).createDeepCopy(targetEntityId);
}
/**
* Saves the given entities.<p>
*
* @param entities the entities to save
* @param deletedEntites the deleted entity id's
* @param clearOnSuccess <code>true</code> to clear the VIE instance on success
* @param callback the call back command
*/
public void saveAndDeleteEntities(
final List<com.alkacon.acacia.shared.Entity> entities,
final List<String> deletedEntites,
final boolean clearOnSuccess,
final Command callback) {
CmsRpcAction<ValidationResult> asyncCallback = new CmsRpcAction<ValidationResult>() {
@Override
public void execute() {
start(200, true);
getService().saveAndDeleteEntities(entities, deletedEntites, this);
}
@Override
protected void onResponse(ValidationResult result) {
stop(false);
callback.execute();
if (clearOnSuccess) {
destroyFrom(true);
}
}
};
asyncCallback.execute();
}
/**
* Saves the given entities.<p>
*
* @param entities the entities to save
* @param deletedEntites the deleted entity id's
* @param clearOnSuccess <code>true</code> to clear the VIE instance on success
* @param callback the call back command
*/
public void saveAndDeleteEntities(
final Set<String> entities,
final Set<String> deletedEntites,
final boolean clearOnSuccess,
final Command callback) {
List<com.alkacon.acacia.shared.Entity> changedEntites = new ArrayList<com.alkacon.acacia.shared.Entity>();
for (String entityId : entities) {
I_Entity entity = m_vie.getEntity(entityId);
if (entity != null) {
changedEntites.add(com.alkacon.acacia.shared.Entity.serializeEntity(entity));
}
}
saveAndDeleteEntities(changedEntites, new ArrayList<String>(deletedEntites), clearOnSuccess, callback);
}
/**
* Saves the given entity.<p>
*
* @param entity the entity
* @param clearOnSuccess <code>true</code> to clear all entities from VIE on success
* @param callback the callback executed on success
*/
@Override
public void saveEntity(final I_Entity entity, final boolean clearOnSuccess, final Command callback) {
CmsRpcAction<ValidationResult> action = new CmsRpcAction<ValidationResult>() {
@Override
public void execute() {
start(0, true);
getService().saveEntity(com.alkacon.acacia.shared.Entity.serializeEntity(entity), this);
}
@Override
protected void onResponse(ValidationResult result) {
callback.execute();
if (clearOnSuccess) {
destroyFrom(true);
}
stop(true);
}
};
action.execute();
}
/**
* Sets the show editor help flag to the user session.<p>
*
* @param show the show editor help flag
*/
public void setShowEditorHelp(final boolean show) {
CmsRpcAction<Void> action = new CmsRpcAction<Void>() {
/**
* @see org.opencms.gwt.client.rpc.CmsRpcAction#execute()
*/
@Override
public void execute() {
getCoreService().setShowEditorHelp(show, this);
}
/**
* @see org.opencms.gwt.client.rpc.CmsRpcAction#onResponse(java.lang.Object)
*/
@Override
protected void onResponse(Void result) {
//nothing to do
}
};
action.execute();
}
/**
* Removes the given entity from the entity VIE store.<p>
*
* @param entityId the entity id
*/
public void unregistereEntity(String entityId) {
Vie.getInstance().removeEntity(entityId);
}
/**
* Returns the core RPC service.<p>
*
* @return the core service
*/
protected I_CmsCoreServiceAsync getCoreService() {
if (m_coreSvc == null) {
m_coreSvc = CmsCoreProvider.getService();
}
return m_coreSvc;
}
}
|
package org.deri.any23.extractor.html;
import java.io.IOException;
import java.util.Arrays;
import org.deri.any23.extractor.ExtractionException;
import org.deri.any23.extractor.ExtractionResult;
import org.deri.any23.extractor.ExtractorDescription;
import org.deri.any23.extractor.ExtractorFactory;
import org.deri.any23.extractor.SimpleExtractorFactory;
import org.deri.any23.extractor.Extractor.TagSoupDOMExtractor;
import org.deri.any23.rdf.Any23ValueFactoryWrapper;
import org.deri.any23.rdf.PopularPrefixes;
import org.deri.any23.vocab.FOAF;
import org.deri.any23.vocab.XFN;
import org.openrdf.model.BNode;
import org.openrdf.model.URI;
import org.openrdf.model.ValueFactory;
import org.openrdf.model.impl.ValueFactoryImpl;
import org.openrdf.model.vocabulary.RDF;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
public class XFNExtractor implements TagSoupDOMExtractor {
private final static ValueFactory vf = new Any23ValueFactoryWrapper(ValueFactoryImpl.getInstance());
private HTMLDocument document;
private ExtractionResult out;
public void run(Document in, URI documentURI, ExtractionResult out) throws IOException,
ExtractionException {
document = new HTMLDocument(in);
this.out = out;
BNode subject = vf.createBNode();
boolean foundAnyXFN = false;
for (Node link: document.findAll("//A[@rel][@href]")) {
foundAnyXFN |= extractLink(link, subject, documentURI);
}
if (!foundAnyXFN) return;
out.writeTriple(subject, RDF.TYPE, FOAF.Person);
out.writeTriple(subject, XFN.mePage, documentURI);
}
private boolean extractLink(Node firstLink, BNode subject, URI documentURI) throws ExtractionException {
String href = firstLink.getAttributes().getNamedItem("href").getNodeValue();
String rel = firstLink.getAttributes().getNamedItem("rel").getNodeValue();
String[] rels = rel.split("\\s+");
URI link = document.resolveURI(href);
if (containsRelMe(rels)) {
if (containsXFNRelExceptMe(rels)) {
return false; // "me" cannot be combined with any other XFN values
}
out.writeTriple(subject, XFN.mePage, link);
out.writeTriple(documentURI, XFN.getExtendedProperty("me"), link);
} else {
BNode person2 = vf.createBNode();
boolean foundAnyXFNRel = false;
for (String aRel : rels) {
foundAnyXFNRel |= extractRel(aRel, subject, documentURI, person2, link);
}
if (!foundAnyXFNRel) {
return false;
}
out.writeTriple(person2, RDF.TYPE, FOAF.Person);
out.writeTriple(person2, XFN.mePage, link);
}
return true;
}
private boolean containsRelMe(String[] rels) {
for (String rel : rels) {
if ("me".equals(rel.toLowerCase())) {
return true;
}
}
return false;
}
private boolean containsXFNRelExceptMe(String[] rels) {
for (String rel : rels) {
if (!"me".equals(rel.toLowerCase()) && XFN.isXFNLocalName(rel)) {
return true;
}
}
return false;
}
private boolean extractRel(String rel, BNode person1, URI uri1, BNode person2, URI uri2) {
URI peopleProp = XFN.getPropertyByLocalName(rel);
URI hyperlinkProp = XFN.getExtendedProperty(rel);
if (peopleProp == null) {
return false;
}
out.writeTriple(person1, peopleProp, person2);
out.writeTriple(uri1, hyperlinkProp, uri2);
return true;
}
public ExtractorDescription getDescription() {
return factory;
}
public final static ExtractorFactory<XFNExtractor> factory =
SimpleExtractorFactory.create(
"html-mf-xfn",
PopularPrefixes.createSubset("rdf", "foaf", "xfn"),
Arrays.asList("text/html;q=0.1", "application/xhtml+xml;q=0.1"),
null,
XFNExtractor.class);
}
|
package org.commcare.android.view;
import java.util.Collections;
import java.util.Comparator;
import java.util.Vector;
import org.achartengine.ChartFactory;
import org.achartengine.chart.PointStyle;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.model.XYSeries;
import org.achartengine.model.XYValueSeries;
import org.achartengine.renderer.XYMultipleSeriesRenderer;
import org.achartengine.renderer.XYSeriesRenderer;
import org.commcare.dalvik.R;
import org.commcare.suite.model.graph.AnnotationData;
import org.commcare.suite.model.graph.BubblePointData;
import org.commcare.suite.model.graph.Graph;
import org.commcare.suite.model.graph.GraphData;
import org.commcare.suite.model.graph.SeriesData;
import org.commcare.suite.model.graph.XYPointData;
import android.content.Context;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;
import android.widget.LinearLayout;
/*
* View containing a graph. Note that this does not derive from View; call renderView to get a view for adding to other views, etc.
* @author jschweers
*/
public class GraphView {
private static final int TEXT_SIZE = 21;
private Context mContext;
private GraphData mData;
private XYMultipleSeriesDataset mDataset;
private XYMultipleSeriesRenderer mRenderer;
public GraphView(Context context) {
mContext = context;
mDataset = new XYMultipleSeriesDataset();
mRenderer = new XYMultipleSeriesRenderer();
}
/*
* Set title of graph, and adjust spacing accordingly. Caller should re-render afterwards.
*/
public void setTitle(String title) {
mRenderer.setChartTitle(title);
mRenderer.setChartTitleTextSize(TEXT_SIZE);
}
/*
* Set margins.
*/
private void setMargins() {
int textAllowance = (int) mContext.getResources().getDimension(R.dimen.graph_text_margin);
int topMargin = (int) mContext.getResources().getDimension(R.dimen.graph_y_margin);
if (!mRenderer.getChartTitle().equals("")) {
topMargin += textAllowance;
}
int rightMargin = (int) mContext.getResources().getDimension(R.dimen.graph_x_margin);
int leftMargin = (int) mContext.getResources().getDimension(R.dimen.graph_x_margin);
if (!mRenderer.getYTitle().equals("")) {
leftMargin += textAllowance;
}
int bottomMargin = (int) mContext.getResources().getDimension(R.dimen.graph_y_margin);
if (!mRenderer.getXTitle().equals("")) {
bottomMargin += textAllowance;
}
mRenderer.setMargins(new int[]{topMargin, leftMargin, bottomMargin, rightMargin});
}
/*
* Get a View object that will display this graph. This should be called after making
* any changes to graph's configuration, title, etc.
*/
public View renderView(GraphData data) {
mData = data;
mRenderer.setInScroll(true);
for (SeriesData s : data.getSeries()) {
renderSeries(s);
}
renderAnnotations();
configure();
setMargins();
// Graph will not render correctly unless it has data.
// Add a dummy series to guarantee this.
// Do this after adding any real data and after configuring
// so that get_AxisMin functions return correct values.
SeriesData s = new SeriesData();
double minX = mRenderer.getXAxisMin();
double minY = mRenderer.getYAxisMin();
if (mData.getType().equals(Graph.TYPE_BUBBLE)) {
s.addPoint(new BubblePointData(minX, minY, 0.0));
}
else {
s.addPoint(new XYPointData(minX, minY));
}
s.setConfiguration("line-color", "#00000000");
s.setConfiguration("point-style", "none");
renderSeries(s);
if (mData.getType().equals(Graph.TYPE_BUBBLE)) {
return ChartFactory.getBubbleChartView(mContext, mDataset, mRenderer);
}
return ChartFactory.getLineChartView(mContext, mDataset, mRenderer);
}
/*
* Set up a single series.
*/
private void renderSeries(SeriesData s) {
XYSeriesRenderer currentRenderer = new XYSeriesRenderer();
mRenderer.addSeriesRenderer(currentRenderer);
configureSeries(s, currentRenderer);
XYSeries series;
if (mData.getType().equals(Graph.TYPE_BUBBLE)) {
series = new RangeXYValueSeries("");
if (s.getConfiguration("radius-max") != null) {
((RangeXYValueSeries) series).setMaxValue(Double.valueOf(s.getConfiguration("radius-max")));
}
}
else {
series = new XYSeries("");
}
mDataset.addSeries(series);
// Bubble charts will throw an index out of bounds exception if given points out of order
Vector<XYPointData> sortedPoints = new Vector<XYPointData>(s.size());
for (XYPointData d : s.getPoints()) {
sortedPoints.add(d);
}
Collections.sort(sortedPoints, new PointComparator());
for (XYPointData p : sortedPoints) {
if (mData.getType().equals(Graph.TYPE_BUBBLE)) {
BubblePointData b = (BubblePointData) p;
((RangeXYValueSeries) series).add(b.getX(), b.getY(), b.getRadius());
}
else {
series.add(p.getX(), p.getY());
}
}
}
/*
* Get layout params for this graph, which assume that graph will fill parent
* unless dimensions have been provided via setWidth and/or setHeight.
*/
public LinearLayout.LayoutParams getLayoutParams() {
return new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT);
}
/*
* Set up any annotations.
*/
private void renderAnnotations() {
Vector<AnnotationData> annotations = mData.getAnnotations();
if (!annotations.isEmpty()) {
// Create a fake series for the annotations
XYSeries series = new XYSeries("");
for (AnnotationData a : annotations) {
series.addAnnotation(a.getAnnotation(), a.getX(), a.getY());
}
// Annotations won't display unless the series has some data in it
series.add(0.0, 0.0);
mDataset.addSeries(series);
XYSeriesRenderer currentRenderer = new XYSeriesRenderer();
currentRenderer.setAnnotationsTextSize(TEXT_SIZE);
currentRenderer.setAnnotationsColor(mContext.getResources().getColor(R.drawable.black));
mRenderer.addSeriesRenderer(currentRenderer);
}
}
/*
* Apply any user-requested look and feel changes to graph.
*/
private void configureSeries(SeriesData s, XYSeriesRenderer currentRenderer) {
// Default to circular points, but allow Xs or no points at all
String pointStyle = s.getConfiguration("point-style", "circle").toLowerCase();
if (!pointStyle.equals("none")) {
PointStyle style = null;
if (pointStyle.equals("circle")) {
style = PointStyle.CIRCLE;
}
else if (pointStyle.equals("x")) {
style = PointStyle.X;
}
currentRenderer.setPointStyle(style);
currentRenderer.setFillPoints(true);
}
String lineColor = s.getConfiguration("line-color", "#ff000000");
currentRenderer.setColor(Color.parseColor(lineColor));
fillOutsideLine(s, currentRenderer, "fill-above", XYSeriesRenderer.FillOutsideLine.Type.ABOVE);
fillOutsideLine(s, currentRenderer, "fill-below", XYSeriesRenderer.FillOutsideLine.Type.BELOW);
}
/*
* Helper function for setting up color fills above or below a series.
*/
private void fillOutsideLine(SeriesData s, XYSeriesRenderer currentRenderer, String property, XYSeriesRenderer.FillOutsideLine.Type type) {
property = s.getConfiguration(property);
if (property != null) {
XYSeriesRenderer.FillOutsideLine fill = new XYSeriesRenderer.FillOutsideLine(type);
fill.setColor(Color.parseColor(property));
currentRenderer.addFillOutsideLine(fill);
}
}
/*
* Configure graph's look and feel based on default assumptions and user-requested configuration.
*/
private void configure() {
// Default options
mRenderer.setBackgroundColor(mContext.getResources().getColor(R.drawable.white));
mRenderer.setMarginsColor(mContext.getResources().getColor(R.drawable.white));
mRenderer.setLabelsColor(mContext.getResources().getColor(R.drawable.black));
mRenderer.setXLabelsColor(mContext.getResources().getColor(R.drawable.black));
mRenderer.setYLabelsColor(0, mContext.getResources().getColor(R.drawable.black));
mRenderer.setXLabelsAlign(Paint.Align.CENTER);
mRenderer.setYLabelsAlign(Paint.Align.RIGHT);
mRenderer.setYLabelsPadding(10);
mRenderer.setAxesColor(mContext.getResources().getColor(R.drawable.black));
mRenderer.setLabelsTextSize(TEXT_SIZE);
mRenderer.setAxisTitleTextSize(TEXT_SIZE);
mRenderer.setShowLabels(true);
mRenderer.setApplyBackgroundColor(true);
mRenderer.setShowLegend(false);
mRenderer.setShowGrid(true);
boolean panAndZoom = Boolean.valueOf(mData.getConfiguration("zoom", "false")).equals(Boolean.TRUE);
mRenderer.setPanEnabled(panAndZoom);
mRenderer.setZoomEnabled(panAndZoom);
mRenderer.setZoomButtonsVisible(panAndZoom);
// User-configurable options
mRenderer.setXTitle(mData.getConfiguration("x-axis-title", ""));
mRenderer.setYTitle(mData.getConfiguration("y-axis-title", ""));
if (mData.getConfiguration("x-axis-min") != null) {
mRenderer.setXAxisMin(Double.valueOf(mData.getConfiguration("x-axis-min")));
}
if (mData.getConfiguration("y-axis-min") != null) {
mRenderer.setYAxisMin(Double.valueOf(mData.getConfiguration("y-axis-min")));
}
if (mData.getConfiguration("x-axis-max") != null) {
mRenderer.setXAxisMax(Double.valueOf(mData.getConfiguration("x-axis-max")));
}
if (mData.getConfiguration("y-axis-max") != null) {
mRenderer.setYAxisMax(Double.valueOf(mData.getConfiguration("y-axis-max")));
}
String showGrid = mData.getConfiguration("show-grid", "true");
if (Boolean.valueOf(showGrid).equals(Boolean.FALSE)) {
mRenderer.setShowGridX(false);
mRenderer.setShowGridY(false);
}
String showAxes = mData.getConfiguration("show-axes", "true");
if (Boolean.valueOf(showAxes).equals(Boolean.FALSE)) {
mRenderer.setShowAxes(false);
}
Integer xLabelCount = mData.getConfiguration("x-label-count") == null ? null : new Integer(mData.getConfiguration("x-label-count"));
Integer yLabelCount = mData.getConfiguration("y-label-count") == null ? null : new Integer(mData.getConfiguration("y-label-count"));
if (xLabelCount == 0 && yLabelCount == 0) {
mRenderer.setShowLabels(false);
}
else {
if (xLabelCount != null) {
mRenderer.setXLabels(Integer.valueOf(xLabelCount));
}
if (yLabelCount != null) {
mRenderer.setYLabels(Integer.valueOf(yLabelCount));
}
}
}
/**
* Comparator to sort PointData objects by x value.
* @author jschweers
*/
private class PointComparator implements Comparator<XYPointData> {
@Override
public int compare(XYPointData lhs, XYPointData rhs) {
if (lhs.getX() > rhs.getX()) {
return 1;
}
if (lhs.getX() < rhs.getX()) {
return -1;
}
return 0;
}
}
/*
* Subclass of XYValueSeries allowing user to set a maximum radius.
* Useful when creating multiple bubble charts (or series on the same chart)
* and wanting their bubbles to be on the same scale.
*/
private class RangeXYValueSeries extends XYValueSeries {
private Double max = null;
public RangeXYValueSeries(String title) {
super(title);
}
/*
* (non-Javadoc)
* @see org.achartengine.model.XYValueSeries#getMaxValue()
*/
@Override
public double getMaxValue() {
return max == null ? super.getMaxValue() : max;
}
/*
* Set largest desired radius. No guarantees on what happens if the data
* actually contains a larger value.
*/
public void setMaxValue(double value) {
max = value;
}
}
}
|
package tech.tablesaw.plotly.components;
import com.mitchellbosecke.pebble.PebbleEngine;
import com.mitchellbosecke.pebble.error.PebbleException;
import com.mitchellbosecke.pebble.template.PebbleTemplate;
import tech.tablesaw.plotly.components.threeD.Scene;
import java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
public class Layout {
private static final int DEFAULT_HEIGHT = 600;
private static final int DEFAULT_WIDTH = 800;
private final static String DEFAULT_TITLE = "";
private final static String DEFAULT_PAPER_BG_COLOR = "#fff";
private final static String DEFAULT_PLOT_BG_COLOR = "#fff";
private final static String DEFAULT_DECIMAL_SEPARATOR = ".";
private final static String DEFAULT_THOUSANDS_SEPARATOR = ",";
private final static boolean DEFAULT_AUTO_SIZE = false;
private final static boolean DEFAULT_SHOW_LEGEND = true;
private final static HoverMode DEFAULT_HOVER_MODE = HoverMode.FALSE;
private final static DragMode DEFAULT_DRAG_MODE = DragMode.ZOOM;
private final static int DEFAULT_HOVER_DISTANCE = 20;
private final static BarMode DEFAULT_BAR_MODE = BarMode.GROUP;
private final static Font DEFAULT_TITLE_FONT = Font.builder().build();
private final static Font DEFAULT_FONT = Font.builder().build();
private final PebbleEngine engine = TemplateUtils.getNewEngine();
private final Scene scene;
/**
* Determines the mode of hover interactions.
*/
public enum HoverMode {
X("x"),
Y("y"),
CLOSEST("closest"),
FALSE("false");
private final String value;
HoverMode(String value) {
this.value = value;
}
@Override
public String toString() {
return value;
}
}
/**
* Determines the display mode for bars when you have multiple bar traces. This also applies to histogram bars.
* Group is the default.
*
* With "stack", the bars are stacked on top of one another.
* With "relative", the bars are stacked on top of one another, but with negative values below the axis,
* positive values above.
* With "group", the bars are plotted next to one another centered around the shared location.
* With "overlay", the bars are plotted over one another, provide an "opacity" to see through the overlaid bars.
*/
public enum BarMode {
STACK("stack"),
GROUP("group"),
OVERLAY("overlay"),
RELATIVE("relative");
private final String value;
BarMode(String value) {
this.value = value;
}
@Override
public String toString() {
return value;
}
}
/**
* Determines the mode of drag interactions.
* "select" and "lasso" apply only to scatter traces with markers or text.
* "orbit" and "turntable" apply only to 3D scenes.
*/
public enum DragMode {
ZOOM("zoom"),
PAN("pan"),
SELECT("select"),
LASSO("lasso"),
ORBIT("orbit"),
TURNTABLE("turntable");
private final String value;
DragMode(String value) {
this.value = value;
}
@Override
public String toString() {
return value;
}
}
/**
* The global font
*/
private final Font font;
/*
* The plot title
*/
private final String title;
/**
* Sets the title font
*/
private final Font titleFont;
/**
* Determines whether or not a layout width or height that has been left undefined by the user
* is initialized on each relayout. Note that, regardless of this attribute, an undefined layout width or height
* is always initialized on the first call to plot.
*/
private final boolean autoSize;
/**
* The width of the plot in pixels
*/
private final int width;
/**
* The height of the plot in pixels
*/
private final int height;
/**
* Sets the margins around the plot
*/
private final Margin margin;
/**
* Sets the color of paper where the graph is drawn.
*/
private final String paperBgColor;
/**
* Sets the color of plotting area in-between x and y axes.
*/
private final String plotBgColor;
/**
* Sets the decimal. For example, "." puts a '.' before decimals
*/
private final String decimalSeparator;
/**
* Sets the separator. For example, a " " puts a space between thousands.
*/
private final String thousandsSeparator;
/**
* Determines whether or not a legend is drawn.
*/
private final boolean showLegend;
/**
* Determines the mode of hover interactions.
*/
private final HoverMode hoverMode;
/**
* Determines the mode of drag interactions. "select" and "lasso" apply only to scatter traces with markers or text.
* "orbit" and "turntable" apply only to 3D scenes.
*/
private final DragMode dragMode;
/**
* Sets the default distance (in pixels) to look for data to add hover labels
* (-1 means no cutoff, 0 means no looking for data). This is only a real distance
* for hovering on point-like objects, like scatter points. For area-like objects (bars, scatter fills, etc)
* hovering is on inside the area and off outside, but these objects will not supersede hover on point-like
* objects in case of conflict.
*/
private final int hoverDistance;
private final Axis xAxis;
private final Axis yAxis;
private final Axis yAxis2;
private final Axis yAxis3;
private final Axis yAxis4;
private final Axis zAxis;
private final Grid grid;
private final BarMode barMode;
private Layout(LayoutBuilder builder) {
this.title = builder.title;
this.autoSize = builder.autoSize;
this.decimalSeparator = builder.decimalSeparator;
this.thousandsSeparator = builder.thousandsSeparator;
this.dragMode = builder.dragMode;
this.font = builder.font;
this.titleFont = builder.titleFont;
this.hoverDistance = builder.hoverDistance;
this.hoverMode = builder.hoverMode;
this.margin = builder.margin;
this.height = builder.height;
this.width = builder.width;
this.xAxis = builder.xAxis;
this.yAxis = builder.yAxis;
this.zAxis = builder.zAxis;
this.yAxis2 = builder.yAxis2;
this.yAxis3 = builder.yAxis3;
this.yAxis4 = builder.yAxis4;
this.paperBgColor = builder.paperBgColor;
this.plotBgColor = builder.plotBgColor;
this.showLegend = builder.showLegend;
this.barMode = builder.barMode;
this.scene = builder.scene;
this.grid = builder.grid;
}
public String getTitle() {
return title;
}
public String asJavascript() {
Writer writer = new StringWriter();
PebbleTemplate compiledTemplate;
try {
compiledTemplate = engine.getTemplate("layout_template.html");
compiledTemplate.evaluate(writer, getContext());
} catch (PebbleException | IOException e) {
e.printStackTrace();
}
return writer.toString();
}
protected Map<String, Object> getContext() {
Map<String, Object> context = new HashMap<>();
if (!title.equals(DEFAULT_TITLE)) context.put("title", title);
if(!titleFont.equals(DEFAULT_TITLE_FONT)) context.put("titlefont", titleFont);
context.put("width", width);
context.put("height", height);
if(!font.equals(DEFAULT_FONT)) context.put("font", font);
if(!autoSize == DEFAULT_AUTO_SIZE) context.put("autosize", autoSize);
if(hoverDistance != DEFAULT_HOVER_DISTANCE) context.put("hoverdistance", hoverDistance);
if (!hoverMode.equals(DEFAULT_HOVER_MODE)) context.put("hoverMode", hoverMode);
if (margin != null) {
context.put("margin", margin);
}
if (!decimalSeparator.equals(DEFAULT_DECIMAL_SEPARATOR)) context.put("decimalSeparator", decimalSeparator);
if (!thousandsSeparator.equals(DEFAULT_THOUSANDS_SEPARATOR)) context.put("thousandsSeparator", thousandsSeparator);
if(!dragMode.equals(DEFAULT_DRAG_MODE)) context.put("dragmode", dragMode);
if (!showLegend == DEFAULT_SHOW_LEGEND) context.put("showlegend", showLegend);
if (!plotBgColor.equals(DEFAULT_PLOT_BG_COLOR)) context.put("plotbgcolor", plotBgColor);
if (!paperBgColor.equals(DEFAULT_PAPER_BG_COLOR))context.put("paperbgcolor", paperBgColor);
if (!barMode.equals(DEFAULT_BAR_MODE)) context.put("barMode", barMode);
if (scene != null) context.put("scene", scene);
if (xAxis != null) {
context.put("xAxis", xAxis);
}
if (yAxis != null) {
context.put("yAxis", yAxis);
}
if (yAxis2 != null) {
context.put("yAxis2", yAxis2);
}
if (yAxis3 != null) {
context.put("yAxis3", yAxis3);
}
if (yAxis4 != null) {
context.put("yAxis4", yAxis4);
}
if (zAxis != null) { // TODO: remove? It's in scene for 3d scatters at least.
context.put("zAxis", zAxis);
}
if (grid != null) {
context.put("grid", grid);
}
return context;
}
public static LayoutBuilder builder() {
return new LayoutBuilder();
}
public static LayoutBuilder builder(String title) {
return Layout.builder()
.title(title)
.height(DEFAULT_HEIGHT)
.width(DEFAULT_WIDTH);
}
public static LayoutBuilder builder(String title, String xTitle) {
return Layout.builder(title)
.xAxis(Axis.builder()
.title(xTitle)
.build());
}
public static LayoutBuilder builder(String title, String xTitle, String yTitle) {
return Layout.builder(title, xTitle)
.yAxis(Axis.builder()
.title(yTitle)
.build());
}
public static class LayoutBuilder {
/**
* The global font
*/
private final Font font = DEFAULT_FONT;
/**
* The plot title
*/
private String title = "";
/**
* Sets the title font
*/
private Font titleFont = DEFAULT_TITLE_FONT;
/**
* Determines whether or not a layout width or height that has been left undefined by the user
* is initialized on each relayout. Note that, regardless of this attribute, an undefined layout width or height
* is always initialized on the first call to plot.
*/
private final boolean autoSize = false;
/**
* The width of the plot in pixels
*/
private int width = 700;
/**
* The height of the plot in pixels
*/
private int height = 450;
/**
* Sets the margins around the plot
*/
private Margin margin;
/**
* Sets the color of paper where the graph is drawn.
*/
private String paperBgColor = DEFAULT_PAPER_BG_COLOR;
/**
* Sets the color of plotting area in-between x and y axes.
*/
private String plotBgColor = DEFAULT_PLOT_BG_COLOR;
/**
* Sets the decimal. For example, "." puts a '.' before decimals
*/
private final String decimalSeparator = DEFAULT_DECIMAL_SEPARATOR;
/**
* Sets the separator. For example, a " " puts a space between thousands.
*/
private final String thousandsSeparator = DEFAULT_THOUSANDS_SEPARATOR;
/**
* Determines whether or not a legend is drawn.
*/
private boolean showLegend = DEFAULT_SHOW_LEGEND;
/**
* Determines the mode of hover interactions.
*/
private HoverMode hoverMode = DEFAULT_HOVER_MODE;
/**
* Determines the mode of drag interactions. "select" and "lasso" apply only to scatter traces with markers or text.
* "orbit" and "turntable" apply only to 3D scenes.
*/
private final DragMode dragMode = DEFAULT_DRAG_MODE;
/**
* Sets the default distance (in pixels) to look for data to add hover labels
* (-1 means no cutoff, 0 means no looking for data). This is only a real distance
* for hovering on point-like objects, like scatter points. For area-like objects (bars, scatter fills, etc)
* hovering is on inside the area and off outside, but these objects will not supersede hover on point-like
* objects in case of conflict.
*/
private int hoverDistance = DEFAULT_HOVER_DISTANCE; // greater than or equal to -1
private Axis xAxis;
private Axis yAxis;
private Axis yAxis2;
private Axis yAxis3;
private Axis yAxis4;
private Axis zAxis;
private BarMode barMode = DEFAULT_BAR_MODE;
private Scene scene;
/**
* Define grid to use when creating subplots
*/
private Grid grid;
public Layout build() {
return new Layout(this);
}
private LayoutBuilder() {}
public LayoutBuilder title(String title) {
this.title = title;
return this;
}
public LayoutBuilder titleFont(Font titleFont) {
this.titleFont = titleFont;
return this;
}
public LayoutBuilder barMode(BarMode barMode) {
this.barMode = barMode;
return this;
}
public LayoutBuilder margin(Margin margin) {
this.margin = margin;
return this;
}
public LayoutBuilder scene(Scene scene) {
this.scene = scene;
return this;
}
public LayoutBuilder hoverMode(HoverMode hoverMode) {
this.hoverMode = hoverMode;
return this;
}
public LayoutBuilder hoverDistance(int distance) {
this.hoverDistance = distance;
return this;
}
public LayoutBuilder showLegend(boolean showLegend) {
this.showLegend = showLegend;
return this;
}
public LayoutBuilder height(int height) {
this.height = height;
return this;
}
public LayoutBuilder width(int width) {
this.width = width;
return this;
}
public LayoutBuilder xAxis(Axis axis) {
this.xAxis = axis;
return this;
}
public LayoutBuilder yAxis(Axis axis) {
this.yAxis = axis;
return this;
}
public LayoutBuilder yAxis2(Axis axis) {
this.yAxis2 = axis;
return this;
}
public LayoutBuilder yAxis3(Axis axis) {
this.yAxis3 = axis;
return this;
}
public LayoutBuilder yAxis4(Axis axis) {
this.yAxis4 = axis;
return this;
}
public LayoutBuilder zAxis(Axis axis) {
this.zAxis = axis;
return this;
}
public LayoutBuilder plotBgColor(String color) {
this.plotBgColor = color;
return this;
}
public LayoutBuilder paperBgColor(String color) {
this.paperBgColor = color;
return this;
}
public LayoutBuilder grid(Grid grid) {
this.grid = grid;
return this;
}
}
}
|
package nars.inference;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.HashMap;
import nars.core.Events;
import nars.core.Memory;
import nars.core.Parameters;
import nars.entity.BudgetValue;
import nars.entity.Concept;
import nars.core.control.NAL;
import nars.entity.Sentence;
import nars.entity.Stamp;
import nars.entity.TLink;
import nars.entity.Task;
import nars.entity.TaskLink;
import nars.entity.TermLink;
import nars.entity.TruthValue;
import static nars.inference.TemporalRules.ORDER_CONCURRENT;
import static nars.inference.TemporalRules.ORDER_FORWARD;
import nars.io.Symbols;
import static nars.io.Symbols.VAR_DEPENDENT;
import static nars.io.Symbols.VAR_INDEPENDENT;
import static nars.io.Symbols.VAR_QUERY;
import nars.language.CompoundTerm;
import nars.language.Conjunction;
import nars.language.Disjunction;
import nars.language.Equivalence;
import nars.language.Implication;
import nars.language.Inheritance;
import nars.language.Negation;
import nars.language.SetExt;
import nars.language.SetInt;
import nars.language.Similarity;
import nars.language.Statement;
import nars.language.Term;
import static nars.language.Terms.equalSubTermsInRespectToImageAndProduct;
import nars.language.Variables;
import nars.plugin.input.PerceptionAccel;
/**
* Table of inference rules, indexed by the TermLinks for the task and the
* belief. Used in indirective processing of a task, to dispatch inference cases
* to the relevant inference rules.
*/
public class RuleTables {
/**
* Entry point of the inference engine
*
* @param tLink The selected TaskLink, which will provide a task
* @param bLink The selected TermLink, which may provide a belief
* @param memory Reference to the memory
*/
public static void reason(final TaskLink tLink, final TermLink bLink, final NAL nal) {
final Memory memory = nal.mem();
final Task task = nal.getCurrentTask();
final Sentence taskSentence = task.sentence;
final Term taskTerm = taskSentence.term; // cloning for substitution
final Term beliefTerm = bLink.target; // cloning for substitution
//CONTRAPOSITION //TODO: put into rule table
if ((taskTerm instanceof Implication) && taskSentence.isJudgment()) {
Concept d=memory.sampleNextConceptNovel(task.sentence);
if(d!=null && d.term.equals(taskSentence.term)) {
StructuralRules.contraposition((Statement)taskTerm, taskSentence, nal);
}
}
if(equalSubTermsInRespectToImageAndProduct(taskTerm,beliefTerm))
return;
final Concept currentConcept = nal.getCurrentConcept();
final Concept beliefConcept = memory.concept(beliefTerm);
Sentence belief = (beliefConcept != null) ? beliefConcept.getBelief(nal, task) : null;
nal.setCurrentBelief( belief ); // may be null
//only if the premise task is a =/>
//the following code is for:
//<(&/,<a --> b>,<b --> c>,<x --> y>,pick(a)) =/> <goal --> reached>>.
//(&/,<a --> b>,<b --> c>,<x --> y>). :|:
//<pick(a) =/> <goal --> reached>>. :|:
//<(&/,<a --> b>,<$1 --> c>,<x --> y>,pick(a)) =/> <$1 --> reached>>.
//(&/,<a --> b>,<goal --> c>,<x --> y>). :|:
//<pick(a) =/> <goal --> reached>>.
if(task.sentence.term instanceof Implication &&
(((Implication)task.sentence.term).getTemporalOrder()==ORDER_FORWARD ||
((Implication)task.sentence.term).getTemporalOrder()==ORDER_CONCURRENT)) {
Implication imp=(Implication)task.sentence.term;
if(imp.getSubject() instanceof Conjunction &&
((((Conjunction)imp.getSubject()).getTemporalOrder()==ORDER_FORWARD) ||
(((Conjunction)imp.getSubject()).getTemporalOrder()==ORDER_CONCURRENT))) {
Conjunction conj=(Conjunction)imp.getSubject();
for(int i=0;i<PerceptionAccel.PERCEPTION_DECISION_ACCEL_SAMPLES;i++) {
//prevent duplicate derivations
Set<Term> alreadyInducted = new HashSet();
Concept next=nal.memory.sampleNextConceptNovel(task.sentence);
if (next == null) continue;
Term t = next.getTerm();
Sentence s=null;
if(task.sentence.punctuation==Symbols.JUDGMENT_MARK && !next.beliefs.isEmpty()) {
s=next.beliefs.get(0);
}
if(task.sentence.punctuation==Symbols.GOAL_MARK && !next.desires.isEmpty()) {
s=next.desires.get(0);
}
if (s!=null && !alreadyInducted.contains(t) && (t instanceof Conjunction)) {
alreadyInducted.add(t);
Conjunction conj2=(Conjunction) t; //ok check if it is a right conjunction
if(conj.getTemporalOrder()==conj2.getTemporalOrder()) {
//conj2 conjunction has to be a minor of conj
//the case where its equal is already handled by other inference rule
if(conj2.term.length<conj.term.length) {
boolean equal=true;
HashMap<Term,Term> map=new HashMap<Term,Term>();
HashMap<Term,Term> map2=new HashMap<Term,Term>();
for(int j=0;j<conj2.term.length;j++) //ok now check if it is really a minor
{
if(!Variables.findSubstitute(VAR_INDEPENDENT, conj.term[j], conj2.term[j], map, map2)) {
equal=false;
break;
}
}
if(equal) {
//ok its a minor, we have to construct the residue implication now
///SPECIAL REASONING CONTEXT FOR TEMPORAL INDUCTION
Stamp SVSTamp=nal.getNewStamp();
Sentence SVBelief=nal.getCurrentBelief();
NAL.StampBuilder SVstampBuilder=nal.newStampBuilder;
//now set the current context:
nal.setCurrentBelief(s);
//END
Term[] residue=new Term[conj.term.length-conj2.term.length];
for(int k=0;k<residue.length;k++) {
residue[k]=conj.term[conj2.term.length+k];
}
Term C=Conjunction.make(residue,conj.getTemporalOrder());
Implication resImp=Implication.make(C, imp.getPredicate(), imp.getTemporalOrder());
if(resImp==null) {
continue;
}
resImp=(Implication) resImp.applySubstitute(map);
//todo add
Stamp st=new Stamp(task.sentence.stamp,nal.memory.time());
boolean eternalBelieve=nal.getCurrentBelief().isEternal();
boolean eternalTask=task.sentence.isEternal();
TruthValue BelieveTruth=nal.getCurrentBelief().truth;
TruthValue TaskTruth=task.sentence.truth;
if(eternalBelieve && !eternalTask) { //occurence time of task
st.setOccurrenceTime(task.sentence.getOccurenceTime());
}
if(!eternalBelieve && eternalTask) { //eternalize case
BelieveTruth=TruthFunctions.eternalize(BelieveTruth);
}
if(!eternalBelieve && !eternalTask) { //project believe to task
BelieveTruth=nal.getCurrentBelief().projectionTruth(task.sentence.getOccurenceTime(), memory.time());
}
//we also need to add one to stamp... time to think about redoing this for 1.6.3 in a more clever way..
ArrayList<Long> evBase=new ArrayList<Long>();
for(long l: st.evidentialBase) {
if(!evBase.contains(l)) {
evBase.add(l);
}
}
for(long l: nal.getCurrentBelief().stamp.evidentialBase) {
if(!evBase.contains(l)) {
evBase.add(l);
}
}
long[] evB=new long[evBase.size()];
int u=0;
for(long l : evBase) {
evB[i]=l;
u++;
}
st.evidentialBase=evB;
st.baseLength=evB.length;
TruthValue truth=TruthFunctions.deduction(BelieveTruth, TaskTruth);
Sentence S=new Sentence(resImp,s.punctuation,truth,st);
Task Tas=new Task(S,new BudgetValue(BudgetFunctions.forward(truth, nal)));
nal.derivedTask(Tas, false, false, null, null, true);
//RESTORE CONTEXT
nal.setNewStamp(SVSTamp);
nal.setCurrentBelief(SVBelief);
nal.newStampBuilder=SVstampBuilder; //also restore this one
}
}
}
}
}
}
}
//usual temporal induction between two events
for(int i=0;i<Parameters.TEMPORAL_INDUCTION_SAMPLES;i++) {
//prevent duplicate inductions
Set<Term> alreadyInducted = new HashSet();
Concept next=nal.memory.sampleNextConceptNovel(task.sentence);
if (next == null) continue;
Term t = next.getTerm();
if (!alreadyInducted.contains(t)) {
if (!next.beliefs.isEmpty()) {
Sentence s=next.beliefs.get(0);
///SPECIAL REASONING CONTEXT FOR TEMPORAL INDUCTION
Stamp SVSTamp=nal.getNewStamp();
Sentence SVBelief=nal.getCurrentBelief();
NAL.StampBuilder SVstampBuilder=nal.newStampBuilder;
//now set the current context:
nal.setCurrentBelief(s);
if(!taskSentence.isEternal() && !s.isEternal()) {
if(s.after(taskSentence, memory.param.duration.get())) {
nal.memory.proceedWithTemporalInduction(s,task.sentence,task,nal,false);
} else {
nal.memory.proceedWithTemporalInduction(task.sentence,s,task,nal,false);
}
}
//RESTORE OF SPECIAL REASONING CONTEXT
nal.setNewStamp(SVSTamp);
nal.setCurrentBelief(SVBelief);
nal.newStampBuilder=SVstampBuilder; //also restore this one
//END
alreadyInducted.add(t);
}
}
}
if (belief != null) {
nal.emit(Events.BeliefReason.class, belief, beliefTerm, taskTerm, nal);
//this is a new attempt/experiment to make nars effectively track temporal coherences
if(beliefTerm instanceof Implication &&
(beliefTerm.getTemporalOrder()==TemporalRules.ORDER_FORWARD || beliefTerm.getTemporalOrder()==TemporalRules.ORDER_CONCURRENT)) {
//prevent duplicate inductions
Set<Term> alreadyInducted = new HashSet();
for(int i=0;i<Parameters.TEMPORAL_INDUCTION_CHAIN_SAMPLES;i++) {
Concept next=nal.memory.concepts.sampleNextConcept();
if (next == null) continue;
Term t = next.getTerm();
if ((t instanceof Implication) && (!alreadyInducted.contains(t))) {
Implication implication=(Implication) t;
if (!next.beliefs.isEmpty() && (implication.isForward() || implication.isConcurrent())) {
///SPECIAL REASONING CONTEXT FOR TEMPORAL INDUCTION
Stamp SVSTamp=nal.getNewStamp();
Task SVTask=nal.getCurrentTask();
NAL.StampBuilder SVstampBuilder=nal.newStampBuilder;
//END
//now set the current context:
Sentence s=next.beliefs.get(0);
if(nal.memory.isNovelInRegardTo(s,belief.term)) {
nal.memory.setNotNovelAnymore(s,belief.term);
//this one needs an dummy task..
Task dummycur=new Task(s,new BudgetValue(Parameters.DEFAULT_JUDGMENT_PRIORITY,Parameters.DEFAULT_JUDGMENT_DURABILITY,s.truth));
nal.setCurrentTask(dummycur);
//its priority isnt needed at all, this just is for stamp completeness..
if(s.punctuation==belief.punctuation) {
TemporalRules.temporalInductionChain(s, belief, nal);
TemporalRules.temporalInductionChain(belief, s, nal);
}
}
alreadyInducted.add(t);
//RESTORE CONTEXT
nal.setNewStamp(SVSTamp);
nal.setCurrentTask(SVTask);
nal.newStampBuilder=SVstampBuilder; //also restore this one
//END
}
}
}
}
if (LocalRules.match(task, belief, nal)) {
//new tasks resulted from the match, so return
return;
}
}
// to be invoked by the corresponding links
if (CompositionalRules.dedSecondLayerVariableUnification(task, nal)) {
//unification ocurred, done reasoning in this cycle if it's judgment
if (taskSentence.isJudgment())
return;
}
//current belief and task may have changed, so set again:
nal.setCurrentBelief(belief);
nal.setCurrentTask(task);
/*if ((memory.getNewTaskCount() > 0) && taskSentence.isJudgment()) {
return;
}*/
CompositionalRules.dedConjunctionByQuestion(taskSentence, belief, nal);
final short tIndex = tLink.getIndex(0);
short bIndex = bLink.getIndex(0);
switch (tLink.type) { // dispatch first by TaskLink type
case TermLink.SELF:
switch (bLink.type) {
case TermLink.COMPONENT:
compoundAndSelf((CompoundTerm) taskTerm, beliefTerm, true, bIndex, nal);
break;
case TermLink.COMPOUND:
compoundAndSelf((CompoundTerm) beliefTerm, taskTerm, false, bIndex, nal);
break;
case TermLink.COMPONENT_STATEMENT:
if (belief != null) {
if (taskTerm instanceof Statement) {
SyllogisticRules.detachment(taskSentence, belief, bIndex, nal);
}
} else {
if(task.sentence.punctuation==Symbols.QUESTION_MARK && (taskTerm instanceof Implication || taskTerm instanceof Equivalence)) { //<a =/> b>? |- a!
Term goalterm=null;
if(taskTerm instanceof Implication) {
Implication imp=(Implication)taskTerm;
if(imp.getTemporalOrder()==TemporalRules.ORDER_FORWARD || imp.getTemporalOrder()==TemporalRules.ORDER_CONCURRENT) {
goalterm=imp.getSubject();
}
else
if(imp.getTemporalOrder()==TemporalRules.ORDER_BACKWARD) {
goalterm=imp.getPredicate();
}
}
else
if(taskTerm instanceof Equivalence) {
Equivalence qu=(Equivalence)taskTerm;
if(qu.getTemporalOrder()==TemporalRules.ORDER_FORWARD || qu.getTemporalOrder()==TemporalRules.ORDER_CONCURRENT) {
goalterm=qu.getSubject();
}
}
TruthValue truth=new TruthValue(1.0f,Parameters.DEFAULT_GOAL_CONFIDENCE);
Sentence sent=new Sentence(goalterm,Symbols.GOAL_MARK,truth,new Stamp(task.sentence.stamp,nal.memory.time()));
nal.singlePremiseTask(sent, new BudgetValue(Parameters.DEFAULT_GOAL_PRIORITY,Parameters.DEFAULT_GOAL_DURABILITY,BudgetFunctions.truthToQuality(truth)));
}
}
break;
case TermLink.COMPOUND_STATEMENT:
if (belief != null) {
SyllogisticRules.detachment(belief, taskSentence, bIndex, nal);
}
break;
case TermLink.COMPONENT_CONDITION:
if ((belief != null) && (taskTerm instanceof Implication)) {
bIndex = bLink.getIndex(1);
SyllogisticRules.conditionalDedInd((Implication) taskTerm, bIndex, beliefTerm, tIndex, nal);
}
break;
case TermLink.COMPOUND_CONDITION:
if ((belief != null) && (taskTerm instanceof Implication) && (beliefTerm instanceof Implication)) {
bIndex = bLink.getIndex(1);
SyllogisticRules.conditionalDedInd((Implication) beliefTerm, bIndex, taskTerm, tIndex, nal);
}
break;
}
break;
case TermLink.COMPOUND:
switch (bLink.type) {
case TermLink.COMPOUND:
compoundAndCompound((CompoundTerm) taskTerm, (CompoundTerm) beliefTerm, bIndex, nal);
break;
case TermLink.COMPOUND_STATEMENT:
compoundAndStatement((CompoundTerm) taskTerm, tIndex, (Statement) beliefTerm, bIndex, beliefTerm, nal);
break;
case TermLink.COMPOUND_CONDITION:
if (belief != null) {
if (beliefTerm instanceof Implication) {
Term[] u = new Term[] { beliefTerm, taskTerm };
if (Variables.unify(VAR_INDEPENDENT, ((Statement) beliefTerm).getSubject(), taskTerm, u)) {
Sentence newBelief = belief.clone(u[0]);
Sentence newTaskSentence = taskSentence.clone(u[1]);
detachmentWithVar(newBelief, newTaskSentence, bIndex, nal);
} else {
SyllogisticRules.conditionalDedInd((Implication) beliefTerm, bIndex, taskTerm, -1, nal);
}
} else if (beliefTerm instanceof Equivalence) {
SyllogisticRules.conditionalAna((Equivalence) beliefTerm, bIndex, taskTerm, -1, nal);
}
}
break;
}
break;
case TermLink.COMPOUND_STATEMENT:
switch (bLink.type) {
case TermLink.COMPONENT:
if (taskTerm instanceof Statement) {
componentAndStatement((CompoundTerm) nal.getCurrentTerm(), bIndex, (Statement) taskTerm, tIndex, nal);
}
break;
case TermLink.COMPOUND:
if (taskTerm instanceof Statement) {
compoundAndStatement((CompoundTerm) beliefTerm, bIndex, (Statement) taskTerm, tIndex, beliefTerm, nal);
}
break;
case TermLink.COMPOUND_STATEMENT:
if (belief != null) {
syllogisms(tLink, bLink, taskTerm, beliefTerm, nal);
}
break;
case TermLink.COMPOUND_CONDITION:
if (belief != null) {
bIndex = bLink.getIndex(1);
if ((taskTerm instanceof Statement) && (beliefTerm instanceof Implication)) {
conditionalDedIndWithVar((Implication) beliefTerm, bIndex, (Statement) taskTerm, tIndex, nal);
}
}
break;
}
break;
case TermLink.COMPOUND_CONDITION:
switch (bLink.type) {
case TermLink.COMPOUND:
if (belief != null) {
detachmentWithVar(taskSentence, belief, tIndex, nal);
}
break;
case TermLink.COMPOUND_STATEMENT:
if (belief != null) {
if (taskTerm instanceof Implication) // TODO maybe put instanceof test within conditionalDedIndWithVar()
{
Term subj = ((Statement) taskTerm).getSubject();
if (subj instanceof Negation) {
if (taskSentence.isJudgment()) {
componentAndStatement((CompoundTerm) subj, bIndex, (Statement) taskTerm, tIndex, nal);
} else {
componentAndStatement((CompoundTerm) subj, tIndex, (Statement) beliefTerm, bIndex, nal);
}
} else {
conditionalDedIndWithVar((Implication) taskTerm, tIndex, (Statement) beliefTerm, bIndex, nal);
}
}
break;
}
break;
}
}
}
/**
* Meta-table of syllogistic rules, indexed by the content classes of the
* taskSentence and the belief
*
* @param tLink The link to task
* @param bLink The link to belief
* @param taskTerm The content of task
* @param beliefTerm The content of belief
* @param nal Reference to the memory
*/
private static void syllogisms(TaskLink tLink, TermLink bLink, Term taskTerm, Term beliefTerm, NAL nal) {
Sentence taskSentence = nal.getCurrentTask().sentence;
Sentence belief = nal.getCurrentBelief();
int figure;
if (taskTerm instanceof Inheritance) {
if (beliefTerm instanceof Inheritance) {
figure = indexToFigure(tLink, bLink);
asymmetricAsymmetric(taskSentence, belief, figure, nal);
} else if (beliefTerm instanceof Similarity) {
figure = indexToFigure(tLink, bLink);
asymmetricSymmetric(taskSentence, belief, figure, nal);
} else {
detachmentWithVar(belief, taskSentence, bLink.getIndex(0), nal);
}
} else if (taskTerm instanceof Similarity) {
if (beliefTerm instanceof Inheritance) {
figure = indexToFigure(bLink, tLink);
asymmetricSymmetric(belief, taskSentence, figure, nal);
} else if (beliefTerm instanceof Similarity) {
figure = indexToFigure(bLink, tLink);
symmetricSymmetric(belief, taskSentence, figure, nal);
}
} else if (taskTerm instanceof Implication) {
if (beliefTerm instanceof Implication) {
figure = indexToFigure(tLink, bLink);
asymmetricAsymmetric(taskSentence, belief, figure, nal);
} else if (beliefTerm instanceof Equivalence) {
figure = indexToFigure(tLink, bLink);
asymmetricSymmetric(taskSentence, belief, figure, nal);
} else if (beliefTerm instanceof Inheritance) {
detachmentWithVar(taskSentence, belief, tLink.getIndex(0), nal);
}
} else if (taskTerm instanceof Equivalence) {
if (beliefTerm instanceof Implication) {
figure = indexToFigure(bLink, tLink);
asymmetricSymmetric(belief, taskSentence, figure, nal);
} else if (beliefTerm instanceof Equivalence) {
figure = indexToFigure(bLink, tLink);
symmetricSymmetric(belief, taskSentence, figure, nal);
} else if (beliefTerm instanceof Inheritance) {
detachmentWithVar(taskSentence, belief, tLink.getIndex(0), nal);
}
}
}
/**
* Decide the figure of syllogism according to the locations of the common
* term in the premises
*
* @param link1 The link to the first premise
* @param link2 The link to the second premise
* @return The figure of the syllogism, one of the four: 11, 12, 21, or 22
*/
private static final int indexToFigure(final TLink link1, final TLink link2) {
return (link1.getIndex(0) + 1) * 10 + (link2.getIndex(0) + 1);
}
/**
* Syllogistic rules whose both premises are on the same asymmetric relation
*
* @param taskSentence The taskSentence in the task
* @param belief The judgment in the belief
* @param figure The location of the shared term
* @param nal Reference to the memory
*/
private static void asymmetricAsymmetric(final Sentence taskSentence, final Sentence belief, int figure, final NAL nal) {
Statement taskStatement = (Statement) taskSentence.term;
Statement beliefStatement = (Statement) belief.term;
Term t1, t2;
Term[] u = new Term[] { taskStatement, beliefStatement };
switch (figure) {
case 11: // induction
if (Variables.unify(VAR_INDEPENDENT, taskStatement.getSubject(), beliefStatement.getSubject(), u)) {
taskStatement = (Statement) u[0];
beliefStatement = (Statement) u[1];
if (taskStatement.equals(beliefStatement)) {
return;
}
t1 = beliefStatement.getPredicate();
t2 = taskStatement.getPredicate();
SyllogisticRules.abdIndCom(t1, t2, taskSentence, belief, figure, nal);
CompositionalRules.composeCompound(taskStatement, beliefStatement, 0, nal);
//if(taskSentence.getOccurenceTime()==Stamp.ETERNAL && belief.getOccurenceTime()==Stamp.ETERNAL)
CompositionalRules.introVarOuter(taskStatement, beliefStatement, 0, nal);//introVarImage(taskContent, beliefContent, index, memory);
CompositionalRules.eliminateVariableOfConditionAbductive(figure,taskSentence,belief,nal);
}
break;
case 12: // deduction
if (Variables.unify(VAR_INDEPENDENT, taskStatement.getSubject(), beliefStatement.getPredicate(), u)) {
taskStatement = (Statement) u[0];
beliefStatement = (Statement) u[1];
if (taskStatement.equals(beliefStatement)) {
return;
}
t1 = beliefStatement.getSubject();
t2 = taskStatement.getPredicate();
if (Variables.unify(VAR_QUERY, t1, t2, new Term[] { taskStatement, beliefStatement })) {
LocalRules.matchReverse(nal);
} else {
SyllogisticRules.dedExe(t1, t2, taskSentence, belief, nal);
}
}
break;
case 21: // exemplification
if (Variables.unify(VAR_INDEPENDENT, taskStatement.getPredicate(), beliefStatement.getSubject(), u)) {
taskStatement = (Statement) u[0];
beliefStatement = (Statement) u[1];
if (taskStatement.equals(beliefStatement)) {
return;
}
t1 = taskStatement.getSubject();
t2 = beliefStatement.getPredicate();
if (Variables.unify(VAR_QUERY, t1, t2, new Term[] { taskStatement, beliefStatement })) {
LocalRules.matchReverse(nal);
} else {
SyllogisticRules.dedExe(t1, t2, taskSentence, belief, nal);
}
}
break;
case 22: // abduction
if (Variables.unify(VAR_INDEPENDENT, taskStatement.getPredicate(), beliefStatement.getPredicate(), u)) {
taskStatement = (Statement) u[0];
beliefStatement = (Statement) u[1];
if (taskStatement.equals(beliefStatement)) {
return;
}
t1 = taskStatement.getSubject();
t2 = beliefStatement.getSubject();
if (!SyllogisticRules.conditionalAbd(t1, t2, taskStatement, beliefStatement, nal)) { // if conditional abduction, skip the following
SyllogisticRules.abdIndCom(t1, t2, taskSentence, belief, figure, nal);
CompositionalRules.composeCompound(taskStatement, beliefStatement, 1, nal);
CompositionalRules.introVarOuter(taskStatement, beliefStatement, 1, nal);// introVarImage(taskContent, beliefContent, index, memory);
}
CompositionalRules.eliminateVariableOfConditionAbductive(figure,taskSentence,belief,nal);
}
break;
default:
}
}
/**
* Syllogistic rules whose first premise is on an asymmetric relation, and
* the second on a symmetric relation
*
* @param asym The asymmetric premise
* @param sym The symmetric premise
* @param figure The location of the shared term
* @param nal Reference to the memory
*/
private static void asymmetricSymmetric(final Sentence asym, final Sentence sym, final int figure, final NAL nal) {
Statement asymSt = (Statement) asym.term;
Statement symSt = (Statement) sym.term;
Term t1, t2;
Term[] u = new Term[] { asymSt, symSt };
switch (figure) {
case 11:
if (Variables.unify(VAR_INDEPENDENT, asymSt.getSubject(), symSt.getSubject(), u)) {
t1 = asymSt.getPredicate();
t2 = symSt.getPredicate();
if (Variables.unify(VAR_QUERY, t1, t2, u)) {
LocalRules.matchAsymSym(asym, sym, figure, nal);
} else {
SyllogisticRules.analogy(t2, t1, asym, sym, figure, nal);
}
}
break;
case 12:
if (Variables.unify(VAR_INDEPENDENT, asymSt.getSubject(), symSt.getPredicate(), u)) {
t1 = asymSt.getPredicate();
t2 = symSt.getSubject();
if (Variables.unify(VAR_QUERY, t1, t2, u)) {
LocalRules.matchAsymSym(asym, sym, figure, nal);
} else {
SyllogisticRules.analogy(t2, t1, asym, sym, figure, nal);
}
}
break;
case 21:
if (Variables.unify(VAR_INDEPENDENT, asymSt.getPredicate(), symSt.getSubject(), u)) {
t1 = asymSt.getSubject();
t2 = symSt.getPredicate();
if (Variables.unify(VAR_QUERY, t1, t2, u)) {
LocalRules.matchAsymSym(asym, sym, figure, nal);
} else {
SyllogisticRules.analogy(t1, t2, asym, sym, figure, nal);
}
}
break;
case 22:
if (Variables.unify(VAR_INDEPENDENT, asymSt.getPredicate(), symSt.getPredicate(), u)) {
t1 = asymSt.getSubject();
t2 = symSt.getSubject();
if (Variables.unify(VAR_QUERY, t1, t2, u)) {
LocalRules.matchAsymSym(asym, sym, figure, nal);
} else {
SyllogisticRules.analogy(t1, t2, asym, sym, figure, nal);
}
}
break;
}
}
/**
* Syllogistic rules whose both premises are on the same symmetric relation
*
* @param belief The premise that comes from a belief
* @param taskSentence The premise that comes from a task
* @param figure The location of the shared term
* @param nal Reference to the memory
*/
private static void symmetricSymmetric(final Sentence belief, final Sentence taskSentence, int figure, final NAL nal) {
Statement s1 = (Statement) belief.term;
Statement s2 = (Statement) taskSentence.term;
Term ut1, ut2; //parameters for unify()
Term rt1, rt2; //parameters for resemblance()
switch (figure) {
case 11:
ut1 = s1.getSubject();
ut2 = s2.getSubject();
rt1 = s1.getPredicate();
rt2 = s2.getPredicate();
break;
case 12:
ut1 = s1.getSubject();
ut2 = s2.getPredicate();
rt1 = s1.getPredicate();
rt2 = s2.getSubject();
break;
case 21:
ut1 = s1.getPredicate();
ut2 = s2.getSubject();
rt1 = s1.getSubject();
rt2 = s2.getPredicate();
break;
case 22:
ut1 = s1.getPredicate();
ut2 = s2.getPredicate();
rt1 = s1.getSubject();
rt2 = s2.getSubject();
break;
default:
throw new RuntimeException("Invalid figure: " + figure);
}
Term[] u = new Term[] { s1, s2 };
if (Variables.unify(VAR_INDEPENDENT, ut1, ut2, u)) {
//recalculate rt1, rt2 from above:
switch (figure) {
case 11: rt1 = s1.getPredicate(); rt2 = s2.getPredicate(); break;
case 12: rt1 = s1.getPredicate(); rt2 = s2.getSubject(); break;
case 21: rt1 = s1.getSubject(); rt2 = s2.getPredicate(); break;
case 22: rt1 = s1.getSubject(); rt2 = s2.getSubject(); break;
}
SyllogisticRules.resemblance(rt1, rt2, belief, taskSentence, figure, nal);
CompositionalRules.eliminateVariableOfConditionAbductive(
figure, taskSentence, belief, nal);
}
}
/**
* The detachment rule, with variable unification
*
* @param originalMainSentence The premise that is an Implication or
* Equivalence
* @param subSentence The premise that is the subject or predicate of the
* first one
* @param index The location of the second premise in the first
* @param nal Reference to the memory
*/
private static void detachmentWithVar(Sentence originalMainSentence, Sentence subSentence, int index, NAL nal) {
if(originalMainSentence==null) {
return;
}
Sentence mainSentence = originalMainSentence; // for substitution
if (!(mainSentence.term instanceof Statement))
return;
Statement statement = (Statement) mainSentence.term;
Term component = statement.term[index];
Term content = subSentence.term;
if (((component instanceof Inheritance) || (component instanceof Negation)) && (nal.getCurrentBelief() != null)) {
Term[] u = new Term[] { statement, content };
if (!component.hasVarIndep()) {
SyllogisticRules.detachment(mainSentence, subSentence, index, nal);
} else if (Variables.unify(VAR_INDEPENDENT, component, content, u)) {
mainSentence = mainSentence.clone(u[0]);
subSentence = subSentence.clone(u[1]);
SyllogisticRules.detachment(mainSentence, subSentence, index, nal);
} else if ((statement instanceof Implication) && (statement.getPredicate() instanceof Statement) && (nal.getCurrentTask().sentence.isJudgment())) {
Statement s2 = (Statement) statement.getPredicate();
if ((content instanceof Statement) && (s2.getSubject().equals(((Statement) content).getSubject()))) {
CompositionalRules.introVarInner((Statement) content, s2, statement, nal);
}
CompositionalRules.IntroVarSameSubjectOrPredicate(originalMainSentence,subSentence,component,content,index,nal);
} else if ((statement instanceof Equivalence) && (statement.getPredicate() instanceof Statement) && (nal.getCurrentTask().sentence.isJudgment())) {
CompositionalRules.IntroVarSameSubjectOrPredicate(originalMainSentence,subSentence,component,content,index,nal);
}
}
}
/**
* Conditional deduction or induction, with variable unification
*
* @param conditional The premise that is an Implication with a Conjunction
* as condition
* @param index The location of the shared term in the condition
* @param statement The second premise that is a statement
* @param side The location of the shared term in the statement
* @param nal Reference to the memory
*/
private static void conditionalDedIndWithVar(Implication conditional, short index, Statement statement, short side, NAL nal) {
if (!(conditional.getSubject() instanceof CompoundTerm))
return;
CompoundTerm condition = (CompoundTerm) conditional.getSubject();
Term component = condition.term[index];
Term component2 = null;
if (statement instanceof Inheritance) {
component2 = statement;
side = -1;
} else if (statement instanceof Implication) {
component2 = statement.term[side];
}
if (component2 != null) {
Term[] u = new Term[] { conditional, statement };
boolean unifiable = Variables.unify(VAR_INDEPENDENT, component, component2, u);
if (!unifiable) {
unifiable = Variables.unify(VAR_DEPENDENT, component, component2, u);
}
if (unifiable) {
conditional = (Implication) u[0];
statement = (Statement) u[1];
SyllogisticRules.conditionalDedInd(conditional, index, statement, side, nal);
}
}
}
/**
* Inference between a compound term and a component of it
*
* @param compound The compound term
* @param component The component term
* @param compoundTask Whether the compound comes from the task
* @param nal Reference to the memory
*/
private static void compoundAndSelf(CompoundTerm compound, Term component, boolean compoundTask, int index, NAL nal) {
if ((compound instanceof Conjunction) || (compound instanceof Disjunction)) {
if (nal.getCurrentBelief() != null) {
CompositionalRules.decomposeStatement(compound, component, compoundTask, index, nal);
} else if (compound.containsTerm(component)) {
StructuralRules.structuralCompound(compound, component, compoundTask, index, nal);
}
// } else if ((compound instanceof Negation) && !memory.getCurrentTask().isStructural()) {
} else if (compound instanceof Negation) {
if (compoundTask) {
if (compound.term[0] instanceof CompoundTerm)
StructuralRules.transformNegation((CompoundTerm)compound.term[0], nal);
} else {
StructuralRules.transformNegation(compound, nal);
}
}
}
/**
* Inference between two compound terms
*
* @param taskTerm The compound from the task
* @param beliefTerm The compound from the belief
* @param nal Reference to the memory
*/
private static void compoundAndCompound(CompoundTerm taskTerm, CompoundTerm beliefTerm, int index, NAL nal) {
if (taskTerm.getClass() == beliefTerm.getClass()) {
if (taskTerm.size() > beliefTerm.size()) {
compoundAndSelf(taskTerm, beliefTerm, true, index, nal);
} else if (taskTerm.size() < beliefTerm.size()) {
compoundAndSelf(beliefTerm, taskTerm, false, index, nal);
}
}
}
/**
* Inference between a compound term and a statement
*
* @param compound The compound term
* @param index The location of the current term in the compound
* @param statement The statement
* @param side The location of the current term in the statement
* @param beliefTerm The content of the belief
* @param nal Reference to the memory
*/
private static void compoundAndStatement(CompoundTerm compound, short index, Statement statement, short side, Term beliefTerm, NAL nal) {
if(index>compound.term.length) {
return;
}
Term component = compound.term[index];
Task task = nal.getCurrentTask();
if (component.getClass() == statement.getClass()) {
if ((compound instanceof Conjunction) && (nal.getCurrentBelief() != null)) {
Term[] u = new Term[] { compound, statement };
if (Variables.unify(VAR_DEPENDENT, component, statement, u)) {
compound = (CompoundTerm) u[0];
statement = (Statement) u[1];
SyllogisticRules.elimiVarDep(compound, component,
statement.equals(beliefTerm),
nal);
} else if (task.sentence.isJudgment()) { // && !compound.containsTerm(component)) {
CompositionalRules.introVarInner(statement, (Statement) component, compound, nal);
} else if (Variables.unify(VAR_QUERY, component, statement, u)) {
compound = (CompoundTerm) u[0];
statement = (Statement) u[1];
CompositionalRules.decomposeStatement(compound, component, true, index, nal);
}
}
} else {
if (task.sentence.isJudgment()) {
if (statement instanceof Inheritance) {
StructuralRules.structuralCompose1(compound, index, statement, nal);
if (!(compound instanceof SetExt || compound instanceof SetInt || compound instanceof Negation)) {
StructuralRules.structuralCompose2(compound, index, statement, side, nal);
} // {A --> B, A @ (A&C)} |- (A&C) --> (B&C)
} else if ((statement instanceof Similarity) && !(compound instanceof Conjunction)) {
StructuralRules.structuralCompose2(compound, index, statement, side, nal);
} // {A <-> B, A @ (A&C)} |- (A&C) <-> (B&C)
}
}
}
/**
* Inference between a component term (of the current term) and a statement
*
* @param compound The compound term
* @param index The location of the current term in the compound
* @param statement The statement
* @param side The location of the current term in the statement
* @param nal Reference to the memory
*/
private static void componentAndStatement(CompoundTerm compound, short index, Statement statement, short side, NAL nal) {
if (statement instanceof Inheritance) {
StructuralRules.structuralDecompose1(compound, index, statement, nal);
if (!(compound instanceof SetExt) && !(compound instanceof SetInt)) {
StructuralRules.structuralDecompose2(statement, index, nal); // {(C-B) --> (C-A), A @ (C-A)} |- A --> B
} else {
StructuralRules.transformSetRelation(compound, statement, side, nal);
}
} else if (statement instanceof Similarity) {
StructuralRules.structuralDecompose2(statement, index, nal); // {(C-B) --> (C-A), A @ (C-A)} |- A --> B
if ((compound instanceof SetExt) || (compound instanceof SetInt)) {
StructuralRules.transformSetRelation(compound, statement, side, nal);
}
}
/* else if ((statement instanceof Implication) && (compound instanceof Negation)) {
if (index == 0) {
StructuralRules.contraposition(statement, nal.getCurrentTask().sentence, nal);
} else {
StructuralRules.contraposition(statement, nal.getCurrentBelief(), nal);
}
}*/
}
/**
* The TaskLink is of type TRANSFORM, and the conclusion is an equivalent
* transformation
*
* @param tLink The task link
* @param nal Reference to the memory
*/
public static void transformTask(TaskLink tLink, NAL nal) {
CompoundTerm content = (CompoundTerm) nal.getCurrentTask().getTerm();
short[] indices = tLink.index;
Term inh = null;
if ((indices.length == 2) || (content instanceof Inheritance)) { // <(*, term,
inh = content;
} else if (indices.length == 3) { // <<(*, term,
inh = content.term[indices[0]];
} else if (indices.length == 4) { // <(&&, <(*, term,
Term component = content.term[indices[0]];
if ((component instanceof Conjunction) && (((content instanceof Implication) && (indices[0] == 0)) || (content instanceof Equivalence))) {
Term[] cterms = ((CompoundTerm) component).term;
if (indices[1] < cterms.length-1)
inh = cterms[indices[1]];
else
return;
} else {
return;
}
}
if (inh instanceof Inheritance) {
StructuralRules.transformProductImage((Inheritance) inh, content, indices, nal);
}
}
}
|
package com.airbnb.lottie.utils;
import android.animation.ValueAnimator;
import android.support.annotation.FloatRange;
import android.support.annotation.Nullable;
import android.support.annotation.VisibleForTesting;
import android.view.Choreographer;
import com.airbnb.lottie.LottieComposition;
/**
* This is a slightly modified {@link ValueAnimator} that allows us to update start and end values
* easily optimizing for the fact that we know that it's a value animator with 2 floats.
*/
public class LottieValueAnimator extends BaseLottieAnimator implements Choreographer.FrameCallback {
private float speed = 1f;
private long lastFrameTimeNs = 0;
private float frame = 0;
private int repeatCount = 0;
private float minFrame = Integer.MIN_VALUE;
private float maxFrame = Integer.MAX_VALUE;
@Nullable private LottieComposition composition;
@VisibleForTesting protected boolean isRunning = false;
public LottieValueAnimator() {
}
/**
* Returns a float representing the current value of the animation from 0 to 1
* regardless of the animation speed, direction, or min and max frames.
*/
@Override public Object getAnimatedValue() {
return getAnimatedValueAbsolute();
}
/**
* Returns the current value of the animation from 0 to 1 regardless
* of the animation speed, direction, or min and max frames.
*/
@FloatRange(from = 0f, to = 1f) public float getAnimatedValueAbsolute() {
if (composition == null) {
return 0;
}
return (frame - composition.getStartFrame()) / (composition.getEndFrame() - composition.getStartFrame());
}
/**
* Returns the current value of the currently playing animation taking into
* account direction, min and max frames.
*/
@Override @FloatRange(from = 0f, to = 1f) public float getAnimatedFraction() {
if (composition == null) {
return 0;
}
if (isReversed()) {
return (getMaxFrame() - frame) / (getMaxFrame() - getMinFrame());
} else {
return (frame - getMinFrame()) / (getMaxFrame() - getMinFrame());
}
}
@Override public long getDuration() {
return composition == null ? 0 : (long) composition.getDuration();
}
public float getFrame() {
return frame;
}
@Override public boolean isRunning() {
return isRunning;
}
@Override public void doFrame(long frameTimeNanos) {
postFrameCallback();
if (composition == null || !isRunning()) {
return;
}
long now = System.nanoTime();
long timeSinceFrame = now - lastFrameTimeNs;
float frameDuration = getFrameDurationNs();
float dFrames = timeSinceFrame / frameDuration;
frame += isReversed() ? -dFrames : dFrames;
boolean ended = !MiscUtils.contains(frame, getMinFrame(), getMaxFrame());
frame = MiscUtils.clamp(frame, getMinFrame(), getMaxFrame());
lastFrameTimeNs = now;
notifyUpdate();
if (ended) {
if (getRepeatCount() != INFINITE && repeatCount >= getRepeatCount()) {
frame = getMaxFrame();
notifyEnd(isReversed());
removeFrameCallback();
} else {
notifyRepeat();
repeatCount++;
if (getRepeatMode() == REVERSE) {
reverseAnimationSpeed();
} else {
frame = isReversed() ? getMaxFrame() : getMinFrame();
}
lastFrameTimeNs = now;
}
}
verifyFrame();
}
private float getFrameDurationNs() {
if (composition == null) {
return Float.MAX_VALUE;
}
return Utils.SECOND_IN_NANOS / composition.getFrameRate() / Math.abs(speed);
}
public void setComposition(LottieComposition composition) {
this.composition = composition;
setMinAndMaxFrames(
(int) Math.max(this.minFrame, composition.getStartFrame()),
(int) Math.min(this.maxFrame, composition.getEndFrame())
);
setFrame((int) frame);
lastFrameTimeNs = System.nanoTime();
}
public void setFrame(int frame) {
if (this.frame == frame) {
return;
}
this.frame = MiscUtils.clamp(frame, getMinFrame(), getMaxFrame());
lastFrameTimeNs = System.nanoTime();
notifyUpdate();
}
public void setMinFrame(int minFrame) {
setMinAndMaxFrames(minFrame, (int) maxFrame);
}
public void setMaxFrame(int maxFrame) {
setMinAndMaxFrames((int) minFrame, maxFrame);
}
public void setMinAndMaxFrames(int minFrame, int maxFrame) {
this.minFrame = minFrame;
this.maxFrame = maxFrame;
setFrame((int) MiscUtils.clamp(frame, minFrame, maxFrame));
}
public void reverseAnimationSpeed() {
setSpeed(-getSpeed());
}
public void setSpeed(float speed) {
this.speed = speed;
}
public float getSpeed() {
return speed;
}
public void playAnimation() {
notifyStart(isReversed());
setFrame((int) (isReversed() ? getMaxFrame() : getMinFrame()));
lastFrameTimeNs = System.nanoTime();
repeatCount = 0;
postFrameCallback();
}
public void endAnimation() {
removeFrameCallback();
notifyEnd(isReversed());
}
public void pauseAnimation() {
removeFrameCallback();
}
public void resumeAnimation() {
postFrameCallback();
lastFrameTimeNs = System.nanoTime();
if (isReversed() && getFrame() == getMinFrame()) {
frame = getMaxFrame();
} else if (!isReversed() && getFrame() == getMaxFrame()) {
frame = getMinFrame();
}
}
@Override public void cancel() {
notifyCancel();
removeFrameCallback();
}
private boolean isReversed() {
return speed < 0;
}
public float getMinFrame() {
if (composition == null) {
return 0;
}
return minFrame == Integer.MIN_VALUE ? composition.getStartFrame() : minFrame;
}
public float getMaxFrame() {
if (composition == null) {
return 0;
}
return maxFrame == Integer.MAX_VALUE ? composition.getEndFrame() : maxFrame;
}
protected void postFrameCallback() {
removeFrameCallback();
Choreographer.getInstance().postFrameCallback(this);
isRunning = true;
}
protected void removeFrameCallback() {
Choreographer.getInstance().removeFrameCallback(this);
isRunning = false;
}
private void verifyFrame() {
if (composition == null) {
return;
}
if (frame < minFrame || frame > maxFrame) {
throw new IllegalStateException(String.format("Frame must be [%f,%f]. It is %f", minFrame, maxFrame, frame));
}
}
}
|
package cerberus.view.gui.opengl.canvas.pathway;
import gleem.linalg.Vec3f;
import gleem.linalg.Vec4f;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Point;
import java.io.File;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import javax.media.opengl.GL;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.GLCanvas;
import javax.media.opengl.glu.GLU;
import org.eclipse.swt.layout.GridLayout;
import cerberus.data.collection.ISet;
import cerberus.data.collection.IStorage;
import cerberus.data.collection.StorageType;
import cerberus.data.collection.set.selection.ISetSelection;
import cerberus.data.mapping.GenomeMappingType;
import cerberus.data.pathway.Pathway;
import cerberus.data.pathway.element.APathwayEdge;
import cerberus.data.pathway.element.PathwayRelationEdge;
import cerberus.data.pathway.element.PathwayVertex;
import cerberus.data.pathway.element.PathwayVertexType;
import cerberus.data.pathway.element.APathwayEdge.EdgeType;
import cerberus.data.pathway.element.PathwayRelationEdge.EdgeRelationType;
import cerberus.data.view.camera.IViewCamera;
import cerberus.data.view.camera.ViewCameraBase;
import cerberus.data.view.rep.pathway.IPathwayVertexRep;
import cerberus.manager.IGeneralManager;
import cerberus.manager.ILoggerManager.LoggerType;
import cerberus.manager.data.IGenomeIdManager;
import cerberus.manager.type.ManagerObjectType;
import cerberus.util.colormapping.ColorMapping;
import cerberus.util.system.SystemTime;
//import cerberus.view.gui.awt.PickingTriggerMouseAdapter;
import cerberus.view.gui.jogl.PickingJoglMouseListener;
import cerberus.view.gui.jogl.IJoglMouseListener;
import cerberus.view.gui.opengl.GLCanvasStatics;
import cerberus.view.gui.opengl.IGLCanvasDirector;
import cerberus.view.gui.opengl.IGLCanvasUser;
import cerberus.view.gui.swt.jogl.SwtJoglGLCanvasViewRep;
import cerberus.view.gui.swt.pathway.APathwayGraphViewRep;
import cerberus.view.gui.swt.toolbar.Pathway3DToolbar;
import cerberus.view.gui.swt.widget.SWTEmbeddedGraphWidget;
import com.sun.opengl.util.BufferUtil;
import com.sun.opengl.util.GLUT;
import com.sun.opengl.util.texture.Texture;
import com.sun.opengl.util.texture.TextureIO;
/**
* @author Marc Streit
* @author Michael Kalkusch
*
*/
public abstract class AGLCanvasPathway3D
extends APathwayGraphViewRep
implements IGLCanvasUser, IJoglMouseListener {
//protected static long MOUSE_PICKING_IDLE_TIME = 3000; // 0.3s
protected IViewCamera refViewCamera;
protected float [][] viewingFrame;
protected float[][] fAspectRatio;
protected boolean bInitGLcanvawsWasCalled = false;
protected static final int X = GLCanvasStatics.X;
protected static final int Y = GLCanvasStatics.Y;
// private static final int Z = GLCanvasStatics.Z;
protected static final int MIN = GLCanvasStatics.MIN;
protected static final int MAX = GLCanvasStatics.MAX;
// private static final int OFFSET = GLCanvasStatics.OFFSET;
protected static final float SCALING_FACTOR_X = 0.0025f;
protected static final float SCALING_FACTOR_Y = 0.0025f;
protected int iVertexRepIndex = 0;
protected GLAutoDrawable canvas;
protected IGLCanvasDirector openGLCanvasDirector;
protected Vec3f origin;
protected Vec4f rotation;
protected GL gl;
protected float fZLayerValue = 0.0f;
//protected ArrayList<Integer> iArPathwayNodeDisplayListIDs;
protected ArrayList<Integer> iArPathwayEdgeDisplayListIDs;
protected int iEnzymeNodeDisplayListId = -1;
protected int iHighlightedEnzymeNodeDisplayListId = -1;
protected int iCompoundNodeDisplayListId = -1;
protected int iHighlightedCompoundNodeDisplayListId = -1;
protected float fPathwayNodeWidth = 0.0f;
protected float fPathwayNodeHeight = 0.0f;
protected float fCanvasXPos = 0.0f;
protected float fCanvasYPos = 0.0f;
protected float fPathwayTextureAspectRatio = 1.0f;
protected ArrayList<Integer> iArSelectionStorageNeighborDistance;
protected HashMap<Pathway, Float> refHashPathwayToZLayerValue;
/**
* Holds the pathways with the corresponding pathway textures.
*/
protected HashMap<Pathway, Texture> refHashPathwayToTexture;
/**
* Pathway that is currently under user interaction in the 2D pathway view.
*/
protected Pathway refPathwayUnderInteraction;
protected boolean bShowPathwayTexture = true;
// Picking relevant variables
protected static final int PICKING_BUFSIZE = 1024;
protected Point pickPoint;
protected int iUniqueObjectPickId = 0;
protected HashMap<Integer, IPathwayVertexRep> refHashPickID2VertexRep;
protected ArrayList<IPathwayVertexRep> iArHighlightedVertices;
protected HashMap<Integer, Pathway> refHashDisplayListNodeId2Pathway;
protected HashMap<Pathway, Integer> refHashPathway2DisplayListNodeId;
protected boolean bBlowUp = true;
protected float fHighlightedNodeBlowFactor = 1.0f;
protected boolean bAcordionDirection = false;
protected HashMap<Pathway, FloatBuffer> refHashPathway2ModelMatrix;
protected boolean bSelectionDataChanged = false;
protected PickingJoglMouseListener pickingTriggerMouseAdapter;
protected boolean bIsMouseOverPickingEvent = false;
protected float fLastMouseMovedTimeStamp = 0;
protected SystemTime systemTime = new SystemTime();
protected ArrayList<String> refInfoAreaCaption;
protected ArrayList<String> refInfoAreaContent;
protected ColorMapping expressionColorMapping;
/**
* Constructor
*
*/
public AGLCanvasPathway3D( final IGeneralManager refGeneralManager,
int iViewId,
int iParentContainerId,
String sLabel ) {
super(refGeneralManager, iViewId, iParentContainerId, "");
openGLCanvasDirector =
refGeneralManager.getSingelton().
getViewGLCanvasManager().getGLCanvasDirector( iParentContainerId );
refSWTContainer = ((SwtJoglGLCanvasViewRep)openGLCanvasDirector).getSWTContainer();
refSWTContainer.setLayout(new GridLayout(1, false));
new Pathway3DToolbar(refSWTContainer, this);
//FIXME: Is refEmbeddedFrameComposite variable really needed?
refEmbeddedFrameComposite = refSWTContainer;
this.canvas = openGLCanvasDirector.getGLCanvas();
pickingTriggerMouseAdapter = new PickingJoglMouseListener(this);
canvas.addMouseListener(pickingTriggerMouseAdapter);
canvas.addMouseMotionListener(pickingTriggerMouseAdapter);
viewingFrame = new float [2][2];
viewingFrame[X][MIN] = 0.0f;
viewingFrame[X][MAX] = 1.0f;
viewingFrame[Y][MIN] = 0.0f;
viewingFrame[Y][MAX] = 1.0f;
iArSelectionStorageNeighborDistance = new ArrayList<Integer>();
//iArPathwayNodeDisplayListIDs = new ArrayList<Integer>();
iArPathwayEdgeDisplayListIDs = new ArrayList<Integer>();
iArHighlightedVertices = new ArrayList<IPathwayVertexRep>();
refHashPathwayToZLayerValue = new HashMap<Pathway, Float>();
refHashPathwayToTexture = new HashMap<Pathway, Texture>();
refHashPickID2VertexRep = new HashMap<Integer, IPathwayVertexRep>();
refHashDisplayListNodeId2Pathway = new HashMap<Integer, Pathway>();
refHashPathway2DisplayListNodeId = new HashMap<Pathway, Integer>();
refHashPathway2ModelMatrix = new HashMap<Pathway, FloatBuffer>();
refInfoAreaCaption = new ArrayList<String>();
refInfoAreaContent = new ArrayList<String>();
refViewCamera = new ViewCameraBase();
expressionColorMapping = new ColorMapping(0, 65000);
expressionColorMapping.createLookupTable();
}
/*
* (non-Javadoc)
* @see cerberus.view.gui.opengl.IGLCanvasUser#init(javax.media.opengl.GLAutoDrawable)
*/
public void initGLCanvas( GLCanvas canvas ) {
//FIXME: derive from AGLCanvasUser !
System.err.println("Init called from " +this.getClass().getSimpleName());
this.gl = canvas.getGL();
// Clearing window and set background to WHITE
gl.glClearColor(1.0f, 1.0f, 1.0f, 1.0f);
//gl.glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);
gl.glEnable(GL.GL_DEPTH_TEST);
gl.glEnable(GL.GL_BLEND);
gl.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA);
gl.glDepthFunc(GL.GL_LEQUAL);
gl.glEnable(GL.GL_LINE_SMOOTH);
gl.glHint(GL.GL_LINE_SMOOTH_HINT, GL.GL_NICEST);
gl.glHint(GL.GL_PERSPECTIVE_CORRECTION_HINT, GL.GL_NICEST);
gl.glLineWidth(1.0f);
// float[] fMatSpecular = { 1.0f, 1.0f, 1.0f, 1.0f};
// float[] fMatShininess = {25.0f};
// float[] fLightPosition = {0.0f, 0.0f, 0.0f, 1.0f};
// float[] fWhiteLight = {1.0f, 1.0f, 1.0f, 1.0f};
float[] fModelAmbient = {0.6f, 0.6f, 0.6f, 1.0f};
// gl.glEnable(GL.GL_COLOR_MATERIAL);
gl.glEnable(GL.GL_COLOR_MATERIAL);
// gl.glColorMaterial(GL.GL_FRONT, GL.GL_DIFFUSE);
// gl.glMaterialfv(GL.GL_FRONT, GL.GL_SPECULAR, fMatSpecular, 0);
// gl.glMaterialfv(GL.GL_FRONT, GL.GL_SHININESS, fMatShininess, 0);
//gl.glLightfv(GL.GL_LIGHT0, GL.GL_POSITION, fLightPosition, 0);
// gl.glLightfv(GL.GL_LIGHT0, GL.GL_DIFFUSE, fWhiteLight, 0);
// gl.glLightfv(GL.GL_LIGHT0, GL.GL_SPECULAR, fWhiteLight, 0);
gl.glLightModelfv(GL.GL_LIGHT_MODEL_AMBIENT, fModelAmbient, 0);
gl.glEnable(GL.GL_LIGHTING);
gl.glEnable(GL.GL_LIGHT0);
// bCanvasInitialized = true;
gl.glHint(GL.GL_PERSPECTIVE_CORRECTION_HINT, GL.GL_NICEST);
gl.glEnable(GL.GL_TEXTURE_2D);
initPathwayData();
buildPathwayDisplayList();
setInitGLDone();
}
/**
* Initializing the zLayer value for the layered view
* and loading the overlay texture for each pathway.
*
*/
protected void initPathwayData() {
Pathway refTmpPathway = null;
// Load pathway storage
// Assumes that the set consists of only one storage
IStorage tmpStorage = alSetData.get(0).getStorageByDimAndIndex(0, 0);
int[] iArPathwayIDs = tmpStorage.getArrayInt();
for (int iPathwayIndex = 0; iPathwayIndex < tmpStorage.getSize(StorageType.INT);
iPathwayIndex++)
{
System.out.println("Create display list for new pathway");
refTmpPathway = (Pathway)refGeneralManager.getSingelton().getPathwayManager().
getItem(iArPathwayIDs[iPathwayIndex]);
// Do not load texture if pathway texture was already loaded before.
if (refHashPathwayToTexture.containsValue(refTmpPathway))
break;
if (bShowPathwayTexture)
loadBackgroundOverlayImage(refTmpPathway);
}
}
protected abstract void buildPathwayDisplayList();
protected void buildEnzymeNodeDisplayList() {
// Creating display list for node cube objects
iEnzymeNodeDisplayListId = gl.glGenLists(1);
fPathwayNodeWidth =
refRenderStyle.getEnzymeNodeWidth() / 2.0f * SCALING_FACTOR_X;
fPathwayNodeHeight =
refRenderStyle.getEnzymeNodeHeight() / 2.0f * SCALING_FACTOR_Y;
gl.glNewList(iEnzymeNodeDisplayListId, GL.GL_COMPILE);
fillNodeDisplayList();
gl.glEndList();
}
protected void buildHighlightedEnzymeNodeDisplayList() {
if (iHighlightedEnzymeNodeDisplayListId == -1)
{
// Creating display list for node cube objects
iHighlightedEnzymeNodeDisplayListId = gl.glGenLists(1);
}
fPathwayNodeWidth =
refRenderStyle.getEnzymeNodeWidth() / 2.0f * SCALING_FACTOR_X;
fPathwayNodeHeight =
refRenderStyle.getEnzymeNodeHeight() / 2.0f * SCALING_FACTOR_Y;
gl.glNewList(iHighlightedEnzymeNodeDisplayListId, GL.GL_COMPILE);
gl.glScaled(fHighlightedNodeBlowFactor,
fHighlightedNodeBlowFactor, fHighlightedNodeBlowFactor);
fillNodeDisplayList();
gl.glScaled(1.0f/fHighlightedNodeBlowFactor,
1.0f/fHighlightedNodeBlowFactor, 1.0f/fHighlightedNodeBlowFactor);
gl.glEndList();
}
protected void buildCompoundNodeDisplayList() {
// Creating display list for node cube objects
iCompoundNodeDisplayListId = gl.glGenLists(1);
fPathwayNodeWidth =
refRenderStyle.getCompoundNodeWidth() / 2.0f * SCALING_FACTOR_X;
fPathwayNodeHeight =
refRenderStyle.getCompoundNodeHeight() / 2.0f * SCALING_FACTOR_Y;
gl.glNewList(iCompoundNodeDisplayListId, GL.GL_COMPILE);
fillNodeDisplayList();
gl.glEndList();
}
protected void buildHighlightedCompoundNodeDisplayList() {
if (iHighlightedCompoundNodeDisplayListId == -1)
{
// Creating display list for node cube objects
iHighlightedCompoundNodeDisplayListId = gl.glGenLists(1);
}
fPathwayNodeWidth =
refRenderStyle.getCompoundNodeWidth() / 2.0f * SCALING_FACTOR_X;
fPathwayNodeHeight =
refRenderStyle.getCompoundNodeHeight() / 2.0f * SCALING_FACTOR_Y;
gl.glNewList(iHighlightedCompoundNodeDisplayListId, GL.GL_COMPILE);
gl.glScaled(fHighlightedNodeBlowFactor,
fHighlightedNodeBlowFactor, fHighlightedNodeBlowFactor);
fillNodeDisplayList();
gl.glScaled(1.0f/fHighlightedNodeBlowFactor,
1.0f/fHighlightedNodeBlowFactor, 1.0f/fHighlightedNodeBlowFactor);
gl.glEndList();
}
protected void fillNodeDisplayList() {
gl.glBegin(GL.GL_QUADS);
// FRONT FACE
gl.glNormal3f( 0.0f, 0.0f, 1.0f);
// Top Right Of The Quad (Front)
gl.glVertex3f(-fPathwayNodeWidth , -fPathwayNodeHeight, 0.015f);
// Top Left Of The Quad (Front)
gl.glVertex3f(fPathwayNodeWidth, -fPathwayNodeHeight, 0.015f);
// Bottom Left Of The Quad (Front)
gl.glVertex3f(fPathwayNodeWidth, fPathwayNodeHeight, 0.015f);
// Bottom Right Of The Quad (Front)
gl.glVertex3f(-fPathwayNodeWidth, fPathwayNodeHeight, 0.015f);
// BACK FACE
gl.glNormal3f( 0.0f, 0.0f,-1.0f);
// Bottom Left Of The Quad (Back)
gl.glVertex3f(fPathwayNodeWidth, -fPathwayNodeHeight,-0.015f);
// Bottom Right Of The Quad (Back)
gl.glVertex3f(-fPathwayNodeWidth, -fPathwayNodeHeight,-0.015f);
// Top Right Of The Quad (Back)
gl.glVertex3f(-fPathwayNodeWidth, fPathwayNodeHeight,-0.015f);
// Top Left Of The Quad (Back)
gl.glVertex3f(fPathwayNodeWidth, fPathwayNodeHeight,-0.015f);
// TOP FACE
gl.glNormal3f( 0.0f, 1.0f, 0.0f);
// Top Right Of The Quad (Top)
gl.glVertex3f(fPathwayNodeWidth, fPathwayNodeHeight,-0.015f);
// Top Left Of The Quad (Top)
gl.glVertex3f(-fPathwayNodeWidth, fPathwayNodeHeight,-0.015f);
// Bottom Left Of The Quad (Top)
gl.glVertex3f(-fPathwayNodeWidth, fPathwayNodeHeight, 0.015f);
// Bottom Right Of The Quad (Top)
gl.glVertex3f(fPathwayNodeWidth, fPathwayNodeHeight, 0.015f);
// BOTTOM FACE
gl.glNormal3f( 0.0f,-1.0f, 0.0f);
// Top Right Of The Quad (Bottom)
gl.glVertex3f(fPathwayNodeWidth, -fPathwayNodeHeight, 0.015f);
// Top Left Of The Quad (Bottom)
gl.glVertex3f(-fPathwayNodeWidth, -fPathwayNodeHeight, 0.015f);
// Bottom Left Of The Quad (Bottom)
gl.glVertex3f(-fPathwayNodeWidth, -fPathwayNodeHeight,-0.015f);
// Bottom Right Of The Quad (Bottom)
gl.glVertex3f(fPathwayNodeWidth, -fPathwayNodeHeight,-0.015f);
// RIGHT FACE
gl.glNormal3f( 1.0f, 0.0f, 0.0f);
// Top Right Of The Quad (Right)
gl.glVertex3f(fPathwayNodeWidth, fPathwayNodeHeight,-0.015f);
// Top Left Of The Quad (Right)
gl.glVertex3f(fPathwayNodeWidth, fPathwayNodeHeight, 0.015f);
// Bottom Left Of The Quad (Right)
gl.glVertex3f(fPathwayNodeWidth, -fPathwayNodeHeight, 0.015f);
// Bottom Right Of The Quad (Right)
gl.glVertex3f(fPathwayNodeWidth, -fPathwayNodeHeight,-0.015f);
// LEFT FACE
gl.glNormal3f(-1.0f, 0.0f, 0.0f);
// Top Right Of The Quad (Left)
gl.glVertex3f(-fPathwayNodeWidth, fPathwayNodeHeight, 0.015f);
// Top Left Of The Quad (Left)
gl.glVertex3f(-fPathwayNodeWidth, fPathwayNodeHeight,-0.015f);
// Bottom Left Of The Quad (Left)
gl.glVertex3f(-fPathwayNodeWidth, -fPathwayNodeHeight,-0.015f);
// Bottom Right Of The Quad (Left)
gl.glVertex3f(-fPathwayNodeWidth, -fPathwayNodeHeight, 0.015f);
gl.glEnd();
}
protected void fillHighlightedNodeDisplayList() {
int iGlowIterations = 15;
for (int iGlowIndex = 0; iGlowIndex < iGlowIterations; iGlowIndex++)
{
gl.glColor4f(1.0f, 1.0f, 0.0f, 0.3f / (float)iGlowIndex);
gl.glScalef(1.0f + (float)iGlowIndex / 20.0f, 1.0f + (float)iGlowIndex / 20.0f,
1.0f + (float)iGlowIndex / 20.0f);
gl.glBegin(GL.GL_QUADS);
// FRONT FACE
gl.glNormal3f( 0.0f, 0.0f, 1.0f);
// Top Right Of The Quad (Front)
gl.glVertex3f(-fPathwayNodeWidth , -fPathwayNodeHeight, 0.015f);
// Top Left Of The Quad (Front)
gl.glVertex3f(fPathwayNodeWidth, -fPathwayNodeHeight, 0.015f);
// Bottom Left Of The Quad (Front)
gl.glVertex3f(fPathwayNodeWidth, fPathwayNodeHeight, 0.015f);
// Bottom Right Of The Quad (Front)
gl.glVertex3f(-fPathwayNodeWidth, fPathwayNodeHeight, 0.015f);
// BACK FACE
gl.glNormal3f( 0.0f, 0.0f,-1.0f);
// Bottom Left Of The Quad (Back)
gl.glVertex3f(fPathwayNodeWidth, -fPathwayNodeHeight,-0.015f);
// Bottom Right Of The Quad (Back)
gl.glVertex3f(-fPathwayNodeWidth, -fPathwayNodeHeight,-0.015f);
// Top Right Of The Quad (Back)
gl.glVertex3f(-fPathwayNodeWidth, fPathwayNodeHeight,-0.015f);
// Top Left Of The Quad (Back)
gl.glVertex3f(fPathwayNodeWidth, fPathwayNodeHeight,-0.015f);
// TOP FACE
gl.glNormal3f( 0.0f, 1.0f, 0.0f);
// Top Right Of The Quad (Top)
gl.glVertex3f(fPathwayNodeWidth, fPathwayNodeHeight,-0.015f);
// Top Left Of The Quad (Top)
gl.glVertex3f(-fPathwayNodeWidth, fPathwayNodeHeight,-0.015f);
// Bottom Left Of The Quad (Top)
gl.glVertex3f(-fPathwayNodeWidth, fPathwayNodeHeight, 0.015f);
// Bottom Right Of The Quad (Top)
gl.glVertex3f(fPathwayNodeWidth, fPathwayNodeHeight, 0.015f);
// BOTTOM FACE
gl.glNormal3f( 0.0f,-1.0f, 0.0f);
// Top Right Of The Quad (Bottom)
gl.glVertex3f(fPathwayNodeWidth, -fPathwayNodeHeight, 0.015f);
// Top Left Of The Quad (Bottom)
gl.glVertex3f(-fPathwayNodeWidth, -fPathwayNodeHeight, 0.015f);
// Bottom Left Of The Quad (Bottom)
gl.glVertex3f(-fPathwayNodeWidth, -fPathwayNodeHeight,-0.015f);
// Bottom Right Of The Quad (Bottom)
gl.glVertex3f(fPathwayNodeWidth, -fPathwayNodeHeight,-0.015f);
// RIGHT FACE
gl.glNormal3f( 1.0f, 0.0f, 0.0f);
// Top Right Of The Quad (Right)
gl.glVertex3f(fPathwayNodeWidth, fPathwayNodeHeight,-0.015f);
// Top Left Of The Quad (Right)
gl.glVertex3f(fPathwayNodeWidth, fPathwayNodeHeight, 0.015f);
// Bottom Left Of The Quad (Right)
gl.glVertex3f(fPathwayNodeWidth, -fPathwayNodeHeight, 0.015f);
// Bottom Right Of The Quad (Right)
gl.glVertex3f(fPathwayNodeWidth, -fPathwayNodeHeight,-0.015f);
// LEFT FACE
gl.glNormal3f(-1.0f, 0.0f, 0.0f);
// Top Right Of The Quad (Left)
gl.glVertex3f(-fPathwayNodeWidth, fPathwayNodeHeight, 0.015f);
// Top Left Of The Quad (Left)
gl.glVertex3f(-fPathwayNodeWidth, fPathwayNodeHeight,-0.015f);
// Bottom Left Of The Quad (Left)
gl.glVertex3f(-fPathwayNodeWidth, -fPathwayNodeHeight,-0.015f);
// Bottom Right Of The Quad (Left)
gl.glVertex3f(-fPathwayNodeWidth, -fPathwayNodeHeight, 0.015f);
gl.glEnd();
gl.glScalef(1.0f / (1.0f + (float)iGlowIndex / 20.0f),
1.0f / (1.0f + (float)iGlowIndex / 20.0f),
1.0f / (1.0f + (float)iGlowIndex / 20.0f));
}
}
public final void render(GLAutoDrawable canvas) {
this.gl = canvas.getGL();
// isInitGLDone() == bInitGLcanvawsWasCalled
if ( ! bInitGLcanvawsWasCalled ) {
initGLCanvas( (GLCanvas) canvas);
System.err.println("INIT CALLED IN RENDER METHOD of " +this.getClass().getSimpleName());
}
if (bSelectionDataChanged)
{
buildPathwayDisplayList();
bSelectionDataChanged = false;
}
// Clear The Screen And The Depth Buffer
gl.glPushMatrix();
gl.glTranslatef( origin.x(), origin.y(), origin.z() );
gl.glRotatef( rotation.x(),
rotation.y(),
rotation.z(),
rotation.w() );
handlePicking();
renderPart(gl, GL.GL_RENDER);
//FIXME:
//fullscreen seetings
renderInfoArea(0.0f, 0.2f, 0.0f);
//split window settings
renderInfoArea(0.0f, -0.2f, 0.0f);
//gl.glFlush();
gl.glPopMatrix();
}
protected abstract void renderPart(GL gl, int iRenderMode);
protected abstract void renderPathway(final Pathway refTmpPathway,
int iDisplayListNodeId);
public void update(GLAutoDrawable canvas) {
}
public void destroyGLCanvas() {
System.err.println(" GLCanvasPathway2D.destroy(GLCanvas canvas)");
}
public void createVertex(IPathwayVertexRep vertexRep, Pathway refContainingPathway) {
boolean bHighlightVertex = false;
Color tmpNodeColor = null;
// refGeneralManager.getSingelton().logMsg(
// "OpenGL Pathway creating vertex for node " +vertexRep.getName(),
// LoggerType.VERBOSE);
fCanvasXPos = viewingFrame[X][MIN] +
(vertexRep.getXPosition() * SCALING_FACTOR_X);
fCanvasYPos = viewingFrame[Y][MIN] +
(vertexRep.getYPosition() * SCALING_FACTOR_Y);
fZLayerValue = refHashPathwayToZLayerValue.get(refContainingPathway);
// Init picking for this vertex
// if (bIsRefreshRendering == false)
iUniqueObjectPickId++;
gl.glPushName(iUniqueObjectPickId);
//gl.glLoadName(iUniqueObjectPickId);
refHashPickID2VertexRep.put(iUniqueObjectPickId, vertexRep);
if (iArHighlightedVertices.contains(vertexRep))
{
bHighlightVertex = true;
}
String sShapeType = vertexRep.getShapeType();
gl.glTranslatef(fCanvasXPos, fCanvasYPos, fZLayerValue);
// Pathway link
if (sShapeType.equals("roundrectangle"))
{
// renderText(vertexRep.getName(),
// fCanvasXPos - fCanvasWidth + 0.02f,
// fCanvasYPos + 0.02f,
// -0.001f);
// if vertex should be highlighted then the highlight color is taken.
// else the standard color for that node type is taken.
if (bHighlightVertex == true)
{
tmpNodeColor = refRenderStyle.getHighlightedNodeColor();
gl.glColor4f(tmpNodeColor.getRed(), tmpNodeColor.getGreen(), tmpNodeColor.getBlue(), 1.0f);
}
else
{
gl.glColor4f(131f/255f,111f/255f,1.0f, 1f);
}
fPathwayNodeWidth = vertexRep.getWidth() / 2.0f * SCALING_FACTOR_X;
fPathwayNodeHeight = vertexRep.getHeight() / 2.0f * SCALING_FACTOR_Y;
fillNodeDisplayList();
}
// Compounds
else if (sShapeType.equals("circle"))
{
// renderText(vertexRep.getName(),
// fCanvasXPos - 0.04f,
// fCanvasYPos - fCanvasHeight,
// -0.001f);
if (bHighlightVertex == true)
{
tmpNodeColor = refRenderStyle.getHighlightedNodeColor();
gl.glColor4f(tmpNodeColor.getRed(), tmpNodeColor.getGreen(), tmpNodeColor.getBlue(), 1.0f);
gl.glCallList(iHighlightedCompoundNodeDisplayListId);
}
else
{
gl.glColor4f(0.0f, 1.0f, 0.0f, 1.0f); // green
gl.glCallList(iCompoundNodeDisplayListId);
}
}
// Enzyme
else if (sShapeType.equals("rectangle"))
{
// renderText(vertexRep.getName(),
// fCanvasXPos - fCanvasWidth + 0.02f,
// fCanvasYPos + 0.02f,
// -0.001f);
if (bHighlightVertex == true)
{
tmpNodeColor = refRenderStyle.getHighlightedNodeColor();
gl.glColor4f(tmpNodeColor.getRed(), tmpNodeColor.getGreen(), tmpNodeColor.getBlue(), 1.0f);
gl.glCallList(iHighlightedEnzymeNodeDisplayListId);
}
else
{
tmpNodeColor = getMappingColor(vertexRep);
// Check if the mapping gave a valid color
if (!tmpNodeColor.equals(Color.BLACK))
{
gl.glColor4f(tmpNodeColor.getRed() / 255.0f,
tmpNodeColor.getGreen() / 255.0f,
tmpNodeColor.getBlue() / 255.0f, 1.0f);
}else
{
gl.glColor4f(0.53f, 0.81f, 1.0f, 1.0f); // ligth blue
}
gl.glCallList(iEnzymeNodeDisplayListId);
}
}
gl.glTranslatef(-fCanvasXPos, -fCanvasYPos, -fZLayerValue);
// if (bIsRefreshRendering == false)
gl.glPopName();
}
public void createEdge(
int iVertexId1,
int iVertexId2,
boolean bDrawArrow,
APathwayEdge refPathwayEdge) {
IPathwayVertexRep vertexRep1, vertexRep2;
PathwayVertex vertex1 =
refGeneralManager.getSingelton().getPathwayElementManager().
getVertexLUT().get(iVertexId1);
PathwayVertex vertex2 =
refGeneralManager.getSingelton().getPathwayElementManager().
getVertexLUT().get(iVertexId2);
vertexRep1 = vertex1.getVertexRepByIndex(iVertexRepIndex);
vertexRep2 = vertex2.getVertexRepByIndex(iVertexRepIndex);
float fCanvasXPos1 = viewingFrame[X][MIN] +
vertexRep1.getXPosition() * SCALING_FACTOR_X;
float fCanvasYPos1 = viewingFrame[Y][MIN] +
vertexRep1.getYPosition() * SCALING_FACTOR_Y;
float fCanvasXPos2 = viewingFrame[X][MIN] +
vertexRep2.getXPosition() * SCALING_FACTOR_X;
float fCanvasYPos2 = viewingFrame[Y][MIN] +
vertexRep2.getYPosition() * SCALING_FACTOR_Y;
Color tmpColor = new Color(1.0f, 1.0f, 1.0f, 1.0f);
// Differentiate between Relations and Reactions
if (refPathwayEdge.getEdgeType() == EdgeType.REACTION)
{
// edgeLineStyle = refRenderStyle.getReactionEdgeLineStyle();
// edgeArrowHeadStyle = refRenderStyle.getReactionEdgeArrowHeadStyle();
tmpColor = refRenderStyle.getReactionEdgeColor();
}
else if (refPathwayEdge.getEdgeType() == EdgeType.RELATION)
{
// In case when relations are maplinks
if (((PathwayRelationEdge)refPathwayEdge).getEdgeRelationType()
== EdgeRelationType.maplink)
{
// edgeLineStyle = refRenderStyle.getMaplinkEdgeLineStyle();
// edgeArrowHeadStyle = refRenderStyle.getMaplinkEdgeArrowHeadStyle();
tmpColor = refRenderStyle.getMaplinkEdgeColor();
}
else
{
// edgeLineStyle = refRenderStyle.getRelationEdgeLineStyle();
// edgeArrowHeadStyle = refRenderStyle.getRelationEdgeArrowHeadStyle();
tmpColor = refRenderStyle.getRelationEdgeColor();
}
}
gl.glColor4f(tmpColor.getRed(), tmpColor.getGreen(), tmpColor.getBlue(), 1.0f);
gl.glBegin(GL.GL_LINES);
gl.glVertex3f(fCanvasXPos1, fCanvasYPos1, fZLayerValue);
gl.glVertex3f(fCanvasXPos2, fCanvasYPos2, fZLayerValue);
gl.glEnd();
}
protected void replacePathway(Pathway refPathwayToReplace, int iNewPathwayId) {
refGeneralManager.getSingelton().logMsg(
this.getClass().getSimpleName() +
": replacePathway(): Replace pathway "+refPathwayToReplace.getPathwayID()
+" with " +iNewPathwayId,
LoggerType.MINOR_ERROR );
refGeneralManager.getSingelton().getPathwayManager().loadPathwayById(iNewPathwayId);
Pathway refNewPathway = (Pathway)refGeneralManager.getSingelton().
getPathwayManager().getItem(iNewPathwayId);
// Replace old pathway with new one in hash maps
FloatBuffer tmpModelMatrix = refHashPathway2ModelMatrix.get(refPathwayToReplace);
refHashPathway2ModelMatrix.remove(refPathwayToReplace);
refHashPathway2ModelMatrix.put(refNewPathway, tmpModelMatrix);
float fZLayer = refHashPathwayToZLayerValue.get(refPathwayToReplace);
refHashPathwayToZLayerValue.remove(refPathwayToReplace);
refHashPathwayToZLayerValue.put(refNewPathway, fZLayer);
Texture tmpTexture = refHashPathwayToTexture.get(refPathwayToReplace);
refHashPathwayToTexture.remove(refPathwayToReplace);
refHashPathwayToTexture.put(refNewPathway, tmpTexture);
int iTmpDisplayListNodeId = refHashPathway2DisplayListNodeId.get(refPathwayToReplace);
refHashPathway2DisplayListNodeId.remove(refPathwayToReplace);
refHashDisplayListNodeId2Pathway.remove(iTmpDisplayListNodeId);
iArHighlightedVertices.clear();
IStorage refTmpStorage = alSetData.get(0).getStorageByDimAndIndex(0, 0);
int[] iArPathwayIDs = refTmpStorage.getArrayInt();
//Replace old pathway ID with new ID
for (int index = 0; index < iArPathwayIDs.length; index++)
{
if (iArPathwayIDs[index] == refPathwayToReplace.getPathwayID())
{
iArPathwayIDs[index] = iNewPathwayId;
break;
}
}
refTmpStorage.setArrayInt(iArPathwayIDs);
if (bShowPathwayTexture)
loadBackgroundOverlayImage(refNewPathway);
createPathwayDisplayList(refNewPathway);
}
protected void createPathwayDisplayList(Pathway refTmpPathway) {
// Creating display list for pathways
int iVerticesDiplayListId = gl.glGenLists(1);
int iEdgeDisplayListId = gl.glGenLists(1);
//iArPathwayNodeDisplayListIDs.add(iVerticesDiplayListId);
iArPathwayEdgeDisplayListIDs.add(iEdgeDisplayListId);
refHashDisplayListNodeId2Pathway.put(iVerticesDiplayListId, refTmpPathway);
refHashPathway2DisplayListNodeId.put(refTmpPathway, iVerticesDiplayListId);
gl.glNewList(iVerticesDiplayListId, GL.GL_COMPILE);
extractVertices(refTmpPathway);
gl.glEndList();
gl.glNewList(iEdgeDisplayListId, GL.GL_COMPILE);
extractEdges(refTmpPathway);
gl.glEndList();
}
protected void connectVertices(IPathwayVertexRep refVertexRep1,
IPathwayVertexRep refVertexRep2) {
float fZLayerValue1 = 0.0f;
float fZLayerValue2 = 0.0f;
Pathway refTmpPathway = null;
Texture refPathwayTexture = null;
float fCanvasXPos1 = 0.0f;
float fCanvasYPos1 = 0.0f;
float fCanvasXPos2 = 0.0f;
float fCanvasYPos2 = 0.0f;
// Load pathway storage
// Assumes that the set consists of only one storage
IStorage tmpStorage = alSetData.get(0).getStorageByDimAndIndex(0, 0);
int[] iArPathwayIDs = tmpStorage.getArrayInt();
buildEnzymeNodeDisplayList();
buildHighlightedEnzymeNodeDisplayList();
buildCompoundNodeDisplayList();
buildHighlightedCompoundNodeDisplayList();
for (int iPathwayIndex = 0; iPathwayIndex < tmpStorage.getSize(StorageType.INT);
iPathwayIndex++)
{
refTmpPathway = (Pathway)refGeneralManager.getSingelton().getPathwayManager().
getItem(iArPathwayIDs[iPathwayIndex]);
// Recalculate scaling factor
refPathwayTexture = refHashPathwayToTexture.get(refTmpPathway);
fPathwayTextureAspectRatio =
(float)refPathwayTexture.getImageWidth() /
(float)refPathwayTexture.getImageHeight();
if(refTmpPathway.isVertexInPathway(refVertexRep1.getVertex()) == true)
{
//fZLayerValue1 = refHashPathwayToZLayerValue.get(refTmpPathway);
fZLayerValue1 = 0.0f;
fCanvasXPos1 = viewingFrame[X][MIN] +
refVertexRep1.getXPosition() * SCALING_FACTOR_X;
fCanvasYPos1 = viewingFrame[Y][MIN] +
refVertexRep1.getYPosition() * SCALING_FACTOR_Y;
}
if(refTmpPathway.isVertexInPathway(refVertexRep2.getVertex()) == true)
{
//fZLayerValue2 = refHashPathwayToZLayerValue.get(refTmpPathway);
fZLayerValue2 = 0.0f;
fCanvasXPos2 = viewingFrame[X][MIN] +
refVertexRep2.getXPosition() * SCALING_FACTOR_X;
fCanvasYPos2 = viewingFrame[Y][MIN] +
refVertexRep2.getYPosition() * SCALING_FACTOR_Y;
}
}
float[] tmpVec1 = {fCanvasXPos1, fCanvasYPos1, fZLayerValue1, 1.0f};
float[] tmpVec2 = {fCanvasXPos2, fCanvasYPos2, fZLayerValue2, 1.0f};
float[] resultVec1 = {1.0f, 1.0f, 1.0f, 1.0f};
float[] resultVec2 = {1.0f, 1.0f, 1.0f, 1.0f};
vecMatrixMult(tmpVec1, refHashPathway2ModelMatrix.get(refTmpPathway).array(), resultVec1);
vecMatrixMult(tmpVec2, refHashPathway2ModelMatrix.get(refTmpPathway).array(), resultVec2);
fCanvasXPos1 = resultVec1[0];
fCanvasYPos1 = resultVec1[1];
fZLayerValue1 = resultVec1[2];
fCanvasXPos2 = resultVec2[0];
fCanvasYPos2 = resultVec2[1];
fZLayerValue2 = resultVec2[2];
gl.glColor4f(1.0f, 1.0f, 0.0f, 1.0f);
gl.glLineWidth(3);
gl.glBegin(GL.GL_LINES);
gl.glVertex3f(fCanvasXPos1, fCanvasYPos1, fZLayerValue1);
gl.glVertex3f(fCanvasXPos2, fCanvasYPos2, fZLayerValue2);
gl.glEnd();
gl.glLineWidth(1);
}
public void renderInfoArea(float fx,
float fy,
float fz) {
float fHeight = 0.3f;
float fWidth = 5f;
gl.glPushMatrix();
gl.glLoadIdentity();
fx -= 1.2f;
fy += 0.3f;
gl.glTranslatef(0, 0, -6f);
gl.glDisable(GL.GL_LIGHTING);
for (int iLineNumber = 0; iLineNumber < refInfoAreaContent.size(); iLineNumber++)
{
renderText(refInfoAreaCaption.get(iLineNumber),
fx+0.05f,
fy + fHeight - 0.03f - 0.025f * iLineNumber,
fz);
renderText(refInfoAreaContent.get(iLineNumber),
fx+0.2f,
fy + fHeight -0.03f - 0.025f * iLineNumber,
fz);
}
// gl.glLineWidth(4);
// gl.glColor4f(0f, 0f, 1f, 1.0f);
// gl.glBegin(GL.GL_LINE);
// gl.glVertex3f(fx, fy, fz);
// gl.glVertex3f(fx+fWidth, fy, fz);
// gl.glVertex3f(fx-fWidth, fy-fHeight, fz);
// gl.glEnd();
gl.glColor4f(1f, 1f, 0f, 0.2f);
gl.glRectf(fx, fy, fx + fWidth, fy + fHeight);
gl.glEnable(GL.GL_LIGHTING);
gl.glPopMatrix();
}
/**
* Method for rendering text in OpenGL.
* TODO: Move method to some kind of GL Utility class.
*
* @param gl
* @param showText
* @param fx
* @param fy
* @param fz
*/
public void renderText(final String showText,
final float fx,
final float fy,
final float fz ) {
final float fFontSizeOffset = 0.02f;
GLUT glut = new GLUT();
// gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);
// gl.glLoadIdentity();
// gl.glTranslatef(0.0f,0.0f,-1.0f);
// Pulsing Colors Based On Text Position
gl.glColor3f(0.0f, 0.0f, 0.0f);
// Position The Text On The Screen...fullscreen goes much slower than
// the other
// way so this is kind of necessary to not just see a blur in smaller
// windows
// and even in the 640x480 method it will be a bit blurry...oh well you
// can
// set it if you would like :)
gl.glRasterPos3f(fx - fFontSizeOffset, fy - fFontSizeOffset, fz);
// Take a string and make it a bitmap, put it in the 'gl' passed over
// and pick
// the GLUT font, then provide the string to show
glut.glutBitmapString(GLUT.BITMAP_HELVETICA_10, showText);
}
/* (non-Javadoc)
* @see cerberus.view.gui.opengl.IGLCanvasUser#link2GLCanvasDirector(cerberus.view.gui.opengl.IGLCanvasDirector)
*/
public final void link2GLCanvasDirector(IGLCanvasDirector parentView) {
if ( openGLCanvasDirector == null ) {
openGLCanvasDirector = parentView;
}
parentView.addGLCanvasUser( this );
}
/* (non-Javadoc)
* @see cerberus.view.gui.opengl.IGLCanvasUser#getGLCanvasDirector()
*/
public final IGLCanvasDirector getGLCanvasDirector() {
return openGLCanvasDirector;
}
/* (non-Javadoc)
* @see cerberus.view.gui.opengl.IGLCanvasUser#getGLCanvas()
*/
public final GLAutoDrawable getGLCanvas() {
return canvas;
}
public final void setOriginRotation( final Vec3f origin,
final Vec4f rotation ) {
this.origin = origin;
this.rotation = rotation;
}
public void loadImageMapFromFile(String sImagePath) {
// TODO Auto-generated method stub
}
public void setNeighbourhoodDistance(int iNeighbourhoodDistance) {
// TODO Auto-generated method stub
}
public void zoomOrig() {
// TODO Auto-generated method stub
}
public void zoomIn() {
// TODO Auto-generated method stub
}
public void zoomOut() {
// TODO Auto-generated method stub
}
public void showOverviewMapInNewWindow(Dimension dim) {
// TODO Auto-generated method stub
}
public void showHideEdgesByType(boolean bShowEdges, EdgeType edgeType) {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
* @see cerberus.view.gui.swt.pathway.IPathwayGraphView#showBackgroundOverlay(boolean)
*/
public void showBackgroundOverlay(boolean bTurnOn) {
System.err.println("SHOW BACKGROUND OVERLAY: " + bTurnOn);
bShowPathwayTexture = bTurnOn;
buildPathwayDisplayList();
//getGLCanvas().display();
}
/*
* (non-Javadoc)
* @see cerberus.view.gui.swt.pathway.IPathwayGraphView#finishGraphBuilding()
*/
public void finishGraphBuilding() {
// Draw title
// renderText(refCurrentPathway.getTitle(), 0.0f, 0.0f, fZLayerValue);
}
/*
* (non-Javadoc)
* @see cerberus.view.gui.swt.pathway.IPathwayGraphView#loadBackgroundOverlayImage(java.lang.String)
*/
public void loadBackgroundOverlayImage(Pathway refTexturedPathway) {
int iPathwayId = refTexturedPathway.getPathwayID();
String sPathwayTexturePath = "";
Texture refPathwayTexture;
if (iPathwayId < 10)
{
sPathwayTexturePath = "map0000" + Integer.toString(iPathwayId);
}
else if (iPathwayId < 100 && iPathwayId >= 10)
{
sPathwayTexturePath = "map000" + Integer.toString(iPathwayId);
}
else if (iPathwayId < 1000 && iPathwayId >= 100)
{
sPathwayTexturePath = "map00" + Integer.toString(iPathwayId);
}
else if (iPathwayId < 10000 && iPathwayId >= 1000)
{
sPathwayTexturePath = "map0" + Integer.toString(iPathwayId);
}
sPathwayTexturePath = refGeneralManager.getSingelton().getPathwayManager().getPathwayImagePath()
+ sPathwayTexturePath +".gif";
try
{
refPathwayTexture = TextureIO.newTexture(new File(sPathwayTexturePath), false);
// refPathwayTexture.bind();
// refPathwayTexture.setTexParameteri(GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR);
// refPathwayTexture.setTexParameteri(GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR);
refHashPathwayToTexture.put(refTexturedPathway, refPathwayTexture);
refGeneralManager.getSingelton().logMsg(
this.getClass().getSimpleName() +
": loadBackgroundOverlay(): Loaded Texture for Pathway" +refTexturedPathway.getTitle(),
LoggerType.VERBOSE );
} catch (Exception e)
{
System.out.println("Error loading texture " + sPathwayTexturePath);
e.printStackTrace();
}
}
public void resetPathway() {
// TODO Auto-generated method stub
}
public void retrieveGUIContainer() {
SWTEmbeddedGraphWidget refSWTEmbeddedGraphWidget =
(SWTEmbeddedGraphWidget) refGeneralManager
.getSingelton().getSWTGUIManager().createWidget(
ManagerObjectType.GUI_SWT_EMBEDDED_JOGL_WIDGET,
refEmbeddedFrameComposite,
iWidth,
iHeight);
refSWTEmbeddedGraphWidget.createEmbeddedComposite();
refEmbeddedFrame = refSWTEmbeddedGraphWidget.getEmbeddedFrame();
}
public void initView() {
}
public void displayChanged(GLAutoDrawable drawable, final boolean modeChanged, final boolean deviceChanged) {
// TODO Auto-generated method stub
}
/*
* (non-Javadoc)
* @see cerberus.manager.event.mediator.IMediatorReceiver#updateReceiver(java.lang.Object, cerberus.data.collection.ISet)
*/
public void updateReceiver(Object eventTrigger, ISet updatedSet) {
ISetSelection refSetSelection = (ISetSelection)updatedSet;
refGeneralManager.getSingelton().logMsg(
"OpenGL Pathway update called by " + eventTrigger.getClass().getSimpleName(),
LoggerType.VERBOSE);
// Clear old selected vertices
iArHighlightedVertices.clear();
// Clear old neighborhood distances
iArSelectionStorageNeighborDistance.clear();
// Read selected vertex IDs
int[] iArSelectedElements = refSetSelection.getSelectionIdArray();
// Read neighbor data
int[] iArSelectionNeighborDistance = refSetSelection.getOptionalDataArray();
for (int iSelectedVertexIndex = 0;
iSelectedVertexIndex < ((IStorage)refSetSelection.getStorageByDimAndIndex(0, 0)).getSize(StorageType.INT);
iSelectedVertexIndex++)
{
iArHighlightedVertices.add(refGeneralManager.getSingelton().getPathwayElementManager().
getVertexLUT().get(iArSelectedElements[iSelectedVertexIndex]).getVertexRepByIndex(0));
//iArSelectionStorageNeighborDistance.add(iArSelectionNeighborDistance[iSelectedVertexIndex]);
}
bSelectionDataChanged = true;
}
public final boolean isInitGLDone()
{
return this.bInitGLcanvawsWasCalled;
}
public final void setInitGLDone()
{
if ( bInitGLcanvawsWasCalled ) {
System.err.println(" called setInitGLDone() for more than once! " +
this.getClass().getSimpleName() +
" " + this.getId());
}
else
{
System.out.println(" called setInitGLDone() " +
this.getClass().getSimpleName() +
" " + this.getId() );
}
bInitGLcanvawsWasCalled = true;
}
public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) {
//FIXME this is just a work around! derive from AGLCanvasUser or AGLCanvasUser_OriginRotation!
this.render( drawable );
}
protected void pickObjects(GL gl) {
int iArPickingBuffer[] = new int[PICKING_BUFSIZE];
IntBuffer pickingBuffer = BufferUtil.newIntBuffer(PICKING_BUFSIZE);
int iHitCount;
int viewport[] = new int[4];
// Deselect all highlighted nodes.
iArHighlightedVertices.clear();
// if (button != GLUT_LEFT_BUTTON || state != GLUT_DOWN) return;
gl.glGetIntegerv(GL.GL_VIEWPORT, viewport, 0);
gl.glSelectBuffer(PICKING_BUFSIZE, pickingBuffer);
gl.glRenderMode(GL.GL_SELECT);
gl.glInitNames();
//gl.glPushName(0);
gl.glMatrixMode(GL.GL_PROJECTION);
gl.glPushMatrix();
gl.glLoadIdentity();
/* create 5x5 pixel picking region near cursor location */
GLU glu = new GLU();
glu.gluPickMatrix((double) pickPoint.x,
(double) (viewport[3] - pickPoint.y),
5.0, 5.0, viewport, 0); // pick width and height is set to 10 (i.e. picking tolerance)
float h = (float) (float) (viewport[3]-viewport[1]) /
(float) (viewport[2]-viewport[0]);
gl.glFrustum(-1.0f, 1.0f, -h, h, 5.0f, 60.0f);
gl.glMatrixMode(GL.GL_MODELVIEW);
// System.out.println("Viewport: " +viewport[0] +" " +viewport[1] +" " +viewport[2] +" " +viewport[3]);
// System.out.println("Picked point: " +pickPoint.x +" " +pickPoint.y);
renderPart(gl, GL.GL_SELECT);
gl.glMatrixMode(GL.GL_PROJECTION);
gl.glPopMatrix();
gl.glMatrixMode(GL.GL_MODELVIEW);
iHitCount = gl.glRenderMode(GL.GL_RENDER);
pickingBuffer.get(iArPickingBuffer);
processHits(iHitCount, iArPickingBuffer);
// Reset picked point
pickPoint = null;
}
protected void processHits(int iHitCount, int iArPickingBuffer[]) {
//System.out.println("Number of hits: " +iHitCount);
IPathwayVertexRep refPickedVertexRep;
int iNames = 0;
int iPtr = 0;
int i = 0;
int iPickedPathwayDisplayListNodeId = 0;
for (i = 0; i < iHitCount; i++)
{
iNames = iArPickingBuffer[iPtr];
//System.out.println(" number of names for this hit = " + iNames);
iPtr++;
//System.out.println(" z1 is " + (float) iArPickingBuffer[iPtr] / 0x7fffffff);
iPtr++;
//System.out.println(" z2 is " + (float) iArPickingBuffer[iPtr] / 0x7fffffff);
iPtr++;
//System.out.println(" names are ");
if (iNames != 2)
return;
// for (int j = 0; j < iNames; j++)
//System.out.println("Pathway pick node ID:" + iArPickingBuffer[iPtr]);
iPickedPathwayDisplayListNodeId = iArPickingBuffer[iPtr];
iPtr++;
//System.out.println("Object pick ID: " + iArPickingBuffer[iPtr]);
refPickedVertexRep = refHashPickID2VertexRep.get(iArPickingBuffer[iPtr]);
if (refPickedVertexRep == null)
return;
fillInfoAreaContent(refPickedVertexRep);
// Perform real element picking
// That means the picked node will be highlighted.
// Otherwise the picking action was only mouse over.
if (!bIsMouseOverPickingEvent)
{
// Update the currently selected pathway
refPathwayUnderInteraction = refHashDisplayListNodeId2Pathway.get(
iPickedPathwayDisplayListNodeId);
// Check if the clicked node is a pathway
// If this is the case the current pathway will be replaced by the clicked one.
if(refPickedVertexRep.getVertex().getVertexType().equals(PathwayVertexType.map))
{
int iNewPathwayId = new Integer(refPickedVertexRep.getVertex().getElementTitle().substring(8));
//Check if picked pathway is alread displayed
if (!refHashPathway2DisplayListNodeId.containsKey(refGeneralManager.getSingelton().
getPathwayManager().getItem(iNewPathwayId)))
{
replacePathway(refPathwayUnderInteraction, iNewPathwayId);
return;
}
}
if (!iArHighlightedVertices.contains(refPickedVertexRep))
{
// Clear currently highlighted vertices when new node was selected
if(!iArHighlightedVertices.isEmpty())
{
iArHighlightedVertices.clear();
iArSelectionStorageNeighborDistance.clear();
}
iArHighlightedVertices.add(refPickedVertexRep);
// Convert to int[]
int[] iArTmp = new int[iArHighlightedVertices.size()];
for(int index = 0; index < iArHighlightedVertices.size(); index++)
iArTmp[index] = iArHighlightedVertices.get(index).getVertex().getElementId();
updateSelectionSet(iArTmp,
new int[0], new int[0]);
refGeneralManager.getSingelton().logMsg(
"OpenGL Pathway object selected: " +refPickedVertexRep.getName(),
LoggerType.VERBOSE);
}
else
{
iArHighlightedVertices.remove(refPickedVertexRep);
// // Remove identical nodes from unselected vertex
// iterIdenticalVertices = refGeneralManager.getSingelton().
// getPathwayElementManager().getPathwayVertexListByName(
// pickedVertexRep.getVertex().getElementTitle()).iterator();
// while(iterIdenticalVertices.hasNext())
// iArHighlightedVertices.remove(iterIdenticalVertices.next().
// getVertexRepByIndex(iVertexRepIndex));
refGeneralManager.getSingelton().logMsg(
"OpenGL Pathway object unselected: " +refPickedVertexRep.getName(),
LoggerType.VERBOSE);
}
//fillInfoAreaContent(refPickedVertexRep);
// FIXME: not very efficient
// All display lists are newly created
//iArPathwayNodeDisplayListIDs.clear();
iArPathwayEdgeDisplayListIDs.clear();
buildPathwayDisplayList();
// gl.glNewList(iPickedPathwayDisplayListNodeId, GL.GL_COMPILE);
// extractVertices(refPathwayUnderInteraction);
// gl.glEndList();
loadNodeInformationInBrowser(refPickedVertexRep.getVertex().getVertexLink());
}
}
}
protected void fillInfoAreaContent(IPathwayVertexRep refPickedVertexRep) {
// Do nothing if picked node is invalid.
if (refPickedVertexRep == null)
return;
refInfoAreaCaption.clear();
refInfoAreaContent.clear();
// Check if vertex is an pathway
if (refPickedVertexRep.getVertex().getVertexType().equals(PathwayVertexType.map))
{
refInfoAreaCaption.add("Pathway: ");
refInfoAreaContent.add(refPickedVertexRep.getVertex().getVertexReps()[0].getName());
}
// Check if vertex is an compound
else if (refPickedVertexRep.getVertex().getVertexType().equals(PathwayVertexType.compound))
{
refInfoAreaCaption.add("Compound: ");
refInfoAreaContent.add(refPickedVertexRep.getVertex().getVertexReps()[0].getName());
}
// Check if vertex is an enzyme.
else if (refPickedVertexRep.getVertex().getVertexType().
equals(PathwayVertexType.enzyme))
{
String sEnzymeCode = refPickedVertexRep.getVertex().getElementTitle().substring(3);
String sAccessionCode = "";
String sTmpGeneName = "";
String sMicroArrayCode = "";
int iAccessionID = 0;
int iGeneID = 0;
Collection<Integer> iArTmpAccessionId = null;
// FIXME: From where can we get the storage ID?
int iExpressionStorageId = 45301;
refInfoAreaCaption.add("Enzyme: ");
refInfoAreaContent.add(sEnzymeCode);
//Just for testing mapping!
IGenomeIdManager refGenomeIdManager =
refGeneralManager.getSingelton().getGenomeIdManager();
int iEnzymeID = refGenomeIdManager.getIdIntFromStringByMapping(sEnzymeCode,
GenomeMappingType.ENZYME_CODE_2_ENZYME);
if (iEnzymeID == -1)
return;
Collection<Integer> iTmpGeneId = refGenomeIdManager.getIdIntListByType(iEnzymeID,
GenomeMappingType.ENZYME_2_NCBI_GENEID);
if(iTmpGeneId == null)
return;
Iterator<Integer> iterTmpGeneId = iTmpGeneId.iterator();
Iterator<Integer> iterTmpAccessionId = null;
while (iterTmpGeneId.hasNext())
{
iGeneID = iterTmpGeneId.next();
String sNCBIGeneId = refGenomeIdManager.getIdStringFromIntByMapping(iGeneID,
GenomeMappingType.NCBI_GENEID_2_NCBI_GENEID_CODE);
refInfoAreaCaption.add("NCBI GeneID: ");
refInfoAreaContent.add(sNCBIGeneId);
iAccessionID = refGenomeIdManager.getIdIntFromIntByMapping(iGeneID,
GenomeMappingType.NCBI_GENEID_2_ACCESSION);
if (iAccessionID == -1)
break;
sAccessionCode = refGenomeIdManager.getIdStringFromIntByMapping(iAccessionID,
GenomeMappingType.ACCESSION_2_ACCESSION_CODE);
refInfoAreaCaption.add("Accession: ");
refInfoAreaContent.add(sAccessionCode);
sTmpGeneName = refGenomeIdManager.getIdStringFromIntByMapping(iAccessionID,
GenomeMappingType.ACCESSION_2_GENE_NAME);
refInfoAreaCaption.add("Gene name: ");
refInfoAreaContent.add(sTmpGeneName);
iArTmpAccessionId = refGenomeIdManager.getIdIntListByType(iAccessionID,
GenomeMappingType.ACCESSION_2_MICROARRAY);
if(iArTmpAccessionId == null)
continue;
iterTmpAccessionId = iArTmpAccessionId.iterator();
while (iterTmpAccessionId.hasNext())
{
int iMicroArrayId = iterTmpAccessionId.next();
sMicroArrayCode = refGenomeIdManager.getIdStringFromIntByMapping(iMicroArrayId,
GenomeMappingType.MICROARRAY_2_MICROARRAY_CODE);
refInfoAreaCaption.add("MicroArray: ");
refInfoAreaContent.add(sMicroArrayCode);
//Get expression value by MicroArrayID
IStorage refExpressionStorage = refGeneralManager.getSingelton().
getStorageManager().getItemStorage(iExpressionStorageId);
int iExpressionStorageIndex = refGenomeIdManager.getIdIntFromIntByMapping(
iMicroArrayId, GenomeMappingType.MICROARRAY_2_MICROARRAY_EXPRESSION);
// Get rid of 770 internal ID identifier
iExpressionStorageIndex = (int)(((float)iExpressionStorageIndex - 770.0f) / 1000.0f);
int iExpressionValue = (refExpressionStorage.getArrayInt())[iExpressionStorageIndex];
refInfoAreaCaption.add("Expression value: ");
refInfoAreaContent.add(new Integer(iExpressionValue).toString());
Color testColor = expressionColorMapping.colorMappingLookup(iExpressionValue);
System.out.println("Result color mapping: " +testColor.getRed() +","
+testColor.getGreen() +","+testColor.getBlue());
}
}
}
}
protected Color getMappingColor(IPathwayVertexRep refPickedVertexRep) {
int iCummulatedExpressionValue = 0;
int iNumberOfExpressionValues = 0;
// Do nothing if picked node is invalid.
if (refPickedVertexRep == null)
return Color.BLACK;
String sEnzymeCode = refPickedVertexRep.getVertex().getElementTitle().substring(3);
int iAccessionID = 0;
int iGeneID = 0;
Collection<Integer> iArTmpAccessionId = null;
// FIXME: From where can we get the storage ID?
int iExpressionStorageId = 45301;
//Just for testing mapping!
IGenomeIdManager refGenomeIdManager =
refGeneralManager.getSingelton().getGenomeIdManager();
int iEnzymeID = refGenomeIdManager.getIdIntFromStringByMapping(sEnzymeCode,
GenomeMappingType.ENZYME_CODE_2_ENZYME);
if (iEnzymeID == -1)
return Color.BLACK;
Collection<Integer> iTmpGeneId = refGenomeIdManager.getIdIntListByType(iEnzymeID,
GenomeMappingType.ENZYME_2_NCBI_GENEID);
if(iTmpGeneId == null)
return Color.BLACK;
Iterator<Integer> iterTmpGeneId = iTmpGeneId.iterator();
Iterator<Integer> iterTmpAccessionId = null;
while (iterTmpGeneId.hasNext())
{
iGeneID = iterTmpGeneId.next();
iAccessionID = refGenomeIdManager.getIdIntFromIntByMapping(iGeneID,
GenomeMappingType.NCBI_GENEID_2_ACCESSION);
if (iAccessionID == -1)
break;
iArTmpAccessionId = refGenomeIdManager.getIdIntListByType(iAccessionID,
GenomeMappingType.ACCESSION_2_MICROARRAY);
if(iArTmpAccessionId == null)
continue;
iterTmpAccessionId = iArTmpAccessionId.iterator();
while (iterTmpAccessionId.hasNext())
{
int iMicroArrayId = iterTmpAccessionId.next();
//Get expression value by MicroArrayID
IStorage refExpressionStorage = refGeneralManager.getSingelton().
getStorageManager().getItemStorage(iExpressionStorageId);
int iExpressionStorageIndex = refGenomeIdManager.getIdIntFromIntByMapping(
iMicroArrayId, GenomeMappingType.MICROARRAY_2_MICROARRAY_EXPRESSION);
// Get rid of 770 internal ID identifier
iExpressionStorageIndex = (int)(((float)iExpressionStorageIndex - 770.0f) / 1000.0f);
int iExpressionValue = (refExpressionStorage.getArrayInt())[iExpressionStorageIndex];
iCummulatedExpressionValue += iExpressionValue;
iNumberOfExpressionValues++;
}
}
if (iNumberOfExpressionValues != 0)
{
return(expressionColorMapping.colorMappingLookup(iCummulatedExpressionValue
/ iNumberOfExpressionValues));
}
return Color.BLACK;
}
// private void drawBezierCurve(GL gl) {
// final int nbCtrlPoints = 4;
// final int sizeCtrlPoints = nbCtrlPoints * 3;
// float a = 1.0f;
// float b = 0.f;
// float ctrlPoints[] =
// { -a, -a, 0f,
// -a/2, +a, 2f,
// +a, +2*a, 1f,
// +2*a, -a/4, -1f };
// if (ctrlPoints.length != sizeCtrlPoints)
// System.out.println("ERROR ctrlPoints\n");
// gl.glMap1f(GL.GL_MAP1_VERTEX_3, 0.0f, 1.0f, 3, 4, ctrlPoints, 0);
// gl.glEnable(GL.GL_MAP1_VERTEX_3);
// // Draw ctrlPoints.
// gl.glBegin(GL.GL_POINTS);
// for (int i = 0; i < sizeCtrlPoints; i += 3)
// gl.glVertex3f(ctrlPoints[i], ctrlPoints[i + 1],
// ctrlPoints[i + 2]);
// gl.glEnd();
// // Draw courve.
// gl.glBegin(GL.GL_LINE_STRIP);
// for (float v = 0; v <= 1; v += 0.01)
// gl.glEvalCoord1f(v);
// gl.glEnd();
protected abstract void highlightIdenticalNodes();
protected void vecMatrixMult(float[] vecIn, float[] matIn, float[] vecOut) {
vecOut[0] = (vecIn[0]*matIn[ 0]) + (vecIn[1]*matIn[ 1]) + (vecIn[2]*matIn[ 2]) + (vecIn[3]*matIn[ 3]);
vecOut[1] = (vecIn[0]*matIn[ 4]) + (vecIn[1]*matIn[ 5]) + (vecIn[2]*matIn[ 6]) + (vecIn[3]*matIn[ 7]);
vecOut[2] = (vecIn[0]*matIn[ 8]) + (vecIn[1]*matIn[ 9]) + (vecIn[2]*matIn[10]) + (vecIn[3]*matIn[11]);
vecOut[3] = (vecIn[0]*matIn[12]) + (vecIn[1]*matIn[13]) + (vecIn[2]*matIn[14]) + (vecIn[3]*matIn[15]);
vecOut[0] /= vecOut[3];
vecOut[1] /= vecOut[3];
vecOut[2] /= vecOut[3];
vecOut[3] = 1.0f;
}
protected void handlePicking() {
if (pickingTriggerMouseAdapter.wasMousePressed())
{
pickPoint = pickingTriggerMouseAdapter.getPickedPoint();
bIsMouseOverPickingEvent = false;
}
if (pickingTriggerMouseAdapter.wasMouseMoved())
{
// Restart timer
fLastMouseMovedTimeStamp = System.nanoTime();
bIsMouseOverPickingEvent = true;
}
else if (bIsMouseOverPickingEvent == true &&
System.nanoTime() - fLastMouseMovedTimeStamp >= 0.3 * 1e9)
{
pickPoint = pickingTriggerMouseAdapter.getPickedPoint();
fLastMouseMovedTimeStamp = System.nanoTime();
}
// Check if a object was picked
if (pickPoint != null)
{
pickObjects(gl);
bIsMouseOverPickingEvent = false;
}
//System.out.println("Picking idle time: " + ((System.nanoTime() - fLastMouseMovedTimeStamp)) * 1e-9);
}
/**
* @see cerberus.view.gui.jogl.IJoglMouseListener#getViewCamera()
*/
public final IViewCamera getViewCamera() {
return refViewCamera;
}
/**
* @see cerberus.view.gui.jogl.IJoglMouseListener#hasViewCameraChanged()
*/
public final boolean hasViewCameraChanged() {
return refViewCamera.hasViewCameraChanged();
}
/**
* @see cerberus.view.gui.jogl.IJoglMouseListener#setViewCamera(cerberus.data.view.camera.IViewCamera)
*/
public final void setViewCamera(IViewCamera set) {
refViewCamera = set;
}
}
|
package li.strolch.utils;
import static li.strolch.utils.helper.StringHelper.EMPTY;
import static li.strolch.utils.helper.StringHelper.isEmpty;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.CodeSource;
import java.util.*;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import li.strolch.utils.collections.MapOfMaps;
import li.strolch.utils.collections.TypedTuple;
import li.strolch.utils.dbc.DBC;
import li.strolch.utils.helper.StringHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class I18nMessage {
private static final Logger logger = LoggerFactory.getLogger(I18nMessage.class);
private static MapOfMaps<String, Locale, ResourceBundle> bundleMap;
private final String bundleName;
private final String key;
private final Properties values;
private final ResourceBundle bundle;
private String message;
public I18nMessage(ResourceBundle bundle, String key) {
DBC.INTERIM.assertNotNull("bundle may not be null!", bundle);
DBC.INTERIM.assertNotEmpty("key must be set!", key);
this.key = key;
this.values = new Properties();
this.bundle = bundle;
this.bundleName = bundle.getBaseBundleName();
}
public I18nMessage(String bundle, String key, Properties values, String message) {
DBC.INTERIM.assertNotNull("bundle must not be empty!", bundle);
DBC.INTERIM.assertNotEmpty("key must be set!", key);
DBC.INTERIM.assertNotEmpty("message must be set!", message);
this.key = key;
this.values = values == null ? new Properties() : values;
this.message = message;
this.bundle = findBundle(bundle);
this.bundleName = this.bundle == null ? bundle : this.bundle.getBaseBundleName();
}
public I18nMessage(I18nMessage other) {
this.key = other.key;
this.values = other.values;
this.bundle = other.bundle;
this.bundleName = other.bundleName;
this.message = other.message;
}
public String getKey() {
return this.key;
}
public String getBundle() {
return this.bundle.getBaseBundleName();
}
public Properties getValues() {
return this.values;
}
public Object getValue(String key) {
return this.values.get(key);
}
private ResourceBundle getBundle(Locale locale) {
if (this.bundle == null)
return null;
if (this.bundle.getLocale() == locale)
return this.bundle;
String baseName = this.bundle.getBaseBundleName();
try {
ClassLoader classLoader = this.bundle.getClass().getClassLoader();
if (classLoader == null)
return ResourceBundle.getBundle(baseName, locale);
return ResourceBundle.getBundle(baseName, locale, classLoader);
} catch (MissingResourceException e) {
logger.error("Failed to find resource bundle " + baseName + " " + locale.toLanguageTag()
+ ", returning current bundle " + this.bundle.getLocale().toLanguageTag());
return this.bundle;
}
}
public String getMessage(ResourceBundle bundle) {
DBC.INTERIM.assertNotNull("bundle may not be null!", bundle);
return formatMessage(bundle);
}
public String getMessage(Locale locale) {
ResourceBundle bundle = getBundle(locale);
if (bundle == null) {
if (isEmpty(this.bundleName))
return getMessage();
logger.warn("No bundle found for " + this.bundleName + " " + locale);
getBundleMap().forEach((s, map) -> {
logger.info(" " + s);
map.forEach((l, resourceBundle) -> logger.info(" " + l + ": " + map.keySet()));
});
return getMessage();
}
return formatMessage(bundle);
}
public String getMessage() {
return formatMessage();
}
public I18nMessage value(String key, Object value) {
DBC.INTERIM.assertNotEmpty("key must be set!", key);
this.values.setProperty(key, value == null ? "(null)" : value.toString());
return this;
}
public String formatMessage() {
if (this.message != null)
return this.message;
if (this.bundle == null) {
this.message = this.key;
return this.message;
}
this.message = formatMessage(this.bundle);
return this.message;
}
public String formatMessage(ResourceBundle bundle) {
try {
String string = bundle.getString(this.key);
return StringHelper.replacePropertiesIn(this.values, EMPTY, string);
} catch (MissingResourceException e) {
String baseName = bundle.getBaseBundleName();
String languageTag = bundle.getLocale().toLanguageTag();
logger.error("Key " + this.key + " is missing in bundle " + baseName + " for locale " + languageTag);
return this.key;
}
}
public <T> T accept(I18nMessageVisitor<T> visitor) {
return visitor.visit(this);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((this.key == null) ? 0 : this.key.hashCode());
result = prime * result + ((this.values == null) ? 0 : this.values.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
I18nMessage other = (I18nMessage) obj;
if (this.key == null) {
if (other.key != null)
return false;
} else if (!this.key.equals(other.key))
return false;
if (this.values == null) {
if (other.values != null)
return false;
} else if (!this.values.equals(other.values))
return false;
return true;
}
private ResourceBundle findBundle(String baseName) {
if (baseName.isEmpty())
return null;
Map<Locale, ResourceBundle> bundlesByLocale = getBundleMap().getMap(baseName);
if (bundlesByLocale == null || bundlesByLocale.isEmpty())
return null;
ResourceBundle bundle = bundlesByLocale.get(Locale.getDefault());
if (bundle != null)
return bundle;
return bundlesByLocale.values().iterator().next();
}
private static MapOfMaps<String, Locale, ResourceBundle> getBundleMap() {
if (bundleMap == null) {
synchronized (I18nMessage.class) {
bundleMap = findAllBundles();
}
}
return bundleMap;
}
private static MapOfMaps<String, Locale, ResourceBundle> findAllBundles() {
try {
CodeSource src = I18nMessage.class.getProtectionDomain().getCodeSource();
if (src == null) {
logger.error(
"Failed to find CodeSource for ProtectionDomain " + I18nMessage.class.getProtectionDomain());
return new MapOfMaps<>();
}
File jarLocationF = new File(src.getLocation().toURI());
if (!(jarLocationF.exists() && jarLocationF.getParentFile().isDirectory())) {
logger.info("Found JAR repository at " + jarLocationF.getParentFile());
return new MapOfMaps<>();
}
MapOfMaps<String, Locale, ResourceBundle> bundleMap = new MapOfMaps<>();
File jarD = jarLocationF.getParentFile();
File[] jarFiles = jarD.listFiles((dir, name) -> name.endsWith(".jar"));
if (jarFiles == null)
return new MapOfMaps<>();
for (File file : jarFiles) {
if (shouldIgnoreFile(file))
continue;
logger.info("Scanning JAR " + file.getName() + " for property files...");
try (JarFile jarFile = new JarFile(file)) {
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry je = entries.nextElement();
String entryName = je.getName();
if (entryName.startsWith("META-INF")
|| entryName.equals("componentVersion.properties")
|| entryName.equals("strolch_db_version.properties"))
continue;
if (!entryName.endsWith(".properties"))
continue;
String propertyName = entryName.replace('/', '.');
logger.info(" Found property file " + propertyName + " in JAR " + file.getName());
TypedTuple<String, Locale> tuple = parsePropertyName(entryName);
if (tuple == null)
continue;
String baseName = tuple.getFirst();
Locale locale = tuple.getSecond();
ResourceBundle bundle = ResourceBundle
.getBundle(baseName, locale, new CustomControl(jarFile.getInputStream(je)));
bundleMap.addElement(bundle.getBaseBundleName(), bundle.getLocale(), bundle);
logger.info(" Loaded bundle " + bundle.getBaseBundleName() + " " + bundle.getLocale());
}
}
}
File classesD = new File(jarD.getParentFile(), "classes");
if (classesD.isDirectory()) {
File[] propertyFiles = classesD.listFiles(
(dir, name) -> name.endsWith(".properties") && !(name.equals("appVersion.properties") || name
.equals("ENV.properties")));
if (propertyFiles != null && propertyFiles.length > 0) {
for (File propertyFile : propertyFiles) {
logger.info(" Found property file " + propertyFile.getName() + " in classes " + classesD
.getAbsolutePath());
TypedTuple<String, Locale> tuple = parsePropertyName(propertyFile.getName());
if (tuple == null)
continue;
String baseName = tuple.getFirst();
Locale locale = tuple.getSecond();
ResourceBundle bundle;
try (FileInputStream in = new FileInputStream(propertyFile)) {
bundle = ResourceBundle.getBundle(baseName, locale, new CustomControl(in));
}
bundleMap.addElement(bundle.getBaseBundleName(), bundle.getLocale(), bundle);
logger.info(" Loaded bundle " + bundle.getBaseBundleName() + " " + bundle.getLocale());
}
}
}
logger.info("Done.");
return bundleMap;
} catch (Exception e) {
logger.error("Failed to find all property files!", e);
return new MapOfMaps<>();
}
}
private static TypedTuple<String, Locale> parsePropertyName(String entryName) {
String propertyName = entryName.replace('/', '.');
String bundleName = propertyName.substring(0, propertyName.lastIndexOf("."));
String baseName;
Locale locale;
int i = bundleName.indexOf('_');
if (i > 0) {
baseName = bundleName.substring(0, i);
String localeS = bundleName.substring(i + 1);
String[] parts = localeS.split("_");
if (parts.length == 2) {
String language = parts[0];
String country = parts[1];
int languageI = Arrays.binarySearch(Locale.getISOLanguages(), language);
int countryI = Arrays.binarySearch(Locale.getISOCountries(), country);
if (languageI >= 0 && countryI >= 0)
locale = new Locale(language, country);
else {
logger.warn("Ignoring bad bundle locale for " + entryName);
return null;
}
} else {
int languageI = Arrays.binarySearch(Locale.getISOLanguages(), localeS);
if (languageI >= 0)
locale = new Locale(localeS);
else {
logger.warn("Ignoring bad bundle locale for " + entryName);
return null;
}
}
} else {
baseName = bundleName;
locale = Locale.getDefault();
}
return new TypedTuple<>(baseName, locale);
}
private static class CustomControl extends ResourceBundle.Control {
private final InputStream stream;
public CustomControl(InputStream stream) {
this.stream = stream;
}
@Override
public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader,
boolean reload) throws IOException {
return new PropertyResourceBundle(this.stream);
}
}
private static boolean shouldIgnoreFile(File file) {
return file.getName().contains("jaxb-core")
|| file.getName().contains("jaxrs-ri")
|| file.getName().contains("jaxb-impl")
|| file.getName().contains("jaxb-api")
|| file.getName().contains("jakarta")
|| file.getName().contains("cron")
|| file.getName().contains("sax")
|| file.getName().contains("aopalliance")
|| file.getName().contains("antlr")
|| file.getName().contains("ST4")
|| file.getName().contains("osgi")
|| file.getName().contains("gson")
|| file.getName().contains("logback")
|| file.getName().contains("slf4j")
|| file.getName().contains("postgresql")
|| file.getName().contains("commons-csv")
|| file.getName().contains("camel")
|| file.getName().contains("yasson")
|| file.getName().contains("tyrus")
|| file.getName().contains("jersey")
|| file.getName().contains("icu4j")
|| file.getName().contains("activation")
|| file.getName().contains("validation-api")
|| file.getName().contains("HikariCP")
|| file.getName().contains("javassist")
|| file.getName().contains("org.abego.treelayout")
|| file.getName().contains("hk2")
|| file.getName().contains("javax")
|| file.getName().contains("grizzly");
}
}
|
package com.gmail.jakekinsella.robot.pathing.socket;
import com.gmail.jakekinsella.robot.RobotControl;
import com.gmail.jakekinsella.robot.pathing.PaddedLine;
public class SocketFollower implements Follower {
private static final int PIXEL_TOLERANCE = 40;
private static final double ANGLE_TOLERANCE = 1;
private PaddedLine line;
private RobotControl robotControl;
private boolean finished;
private boolean shouldTurn = true;
private boolean shouldMove = false;
public SocketFollower(PaddedLine line, RobotControl robotControl) {
this.line = line;
this.robotControl = robotControl;
this.finished = false;
}
public boolean isFinished() {
return this.finished;
}
public void execute() {
if (this.shouldTurn) {
this.robotControl.turn(this.line.getAngle());
this.shouldTurn = false;
this.shouldMove = true;
}
if (this.shouldMove && this.line.checkIfAngleClose(this.robotControl.getAngle(), ANGLE_TOLERANCE)) {
this.robotControl.drive(0.5); // TODO: Change the robot speed
this.shouldMove = false;
}
this.finished = this.isRobotAtEnd();
if (this.finished) {
this.robotControl.drive(0);
}
}
private boolean isRobotAtEnd() {
boolean atEnd = Math.abs(this.robotControl.getRobotBounds().getCenterX() - this.line.getEndX()) < PIXEL_TOLERANCE;
atEnd = atEnd && Math.abs(this.robotControl.getRobotBounds().getCenterY() - this.line.getEndY()) < PIXEL_TOLERANCE;
atEnd = atEnd && this.line.checkIfAngleClose(this.robotControl.getAngle(), ANGLE_TOLERANCE);
atEnd = atEnd && !this.line.isPointOnLine(this.robotControl.getRobotBounds().getCenterX(), this.robotControl.getRobotBounds().getCenterY());
return atEnd;
}
}
|
package com.gmail.liamgomez75.parkourroll.listeners;
import com.gmail.liamgomez75.parkourroll.ParkourRoll;
import com.gmail.liamgomez75.parkourroll.experience.Experience;
import com.gmail.liamgomez75.parkourroll.localisation.Localisation;
import com.gmail.liamgomez75.parkourroll.localisation.LocalisationEntry;
import com.gmail.liamgomez75.parkourroll.utils.LevelConfigUtils;
import org.bukkit.World;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.EntityDamageEvent;
import org.bukkit.plugin.Plugin;
/**
* Damage Listener for Parkour Roll.
*
* @author Liam Gomez <liamgomez75.gmail.com>
* @author JamesHealey94 <jameshealey1994.gmail.com>
*/
public class DamageListener implements Listener {
/**
* Plugin used for customizable values and localisation.
*/
private ParkourRoll plugin;
/**
* Constructor - Initializes plugin.
*
* @param plugin plugin used to set config values and localisation
*/
public DamageListener(ParkourRoll plugin) {
this.plugin = plugin;
}
/**
* Performs parkour roll.
* If expected fall damage is below damage threshold, the player will perform a parkour roll to set damage to 0.
* Else, if player is not killed by the fall, they will perform a parkour roll to reduce the damage.
*
* @param e EntityDamageEvent triggered
*/
@EventHandler
public void onEntityDamageEvent(final EntityDamageEvent e) {
if (!(e.getEntity() instanceof Player)) {
return;
}
final Player p = (Player) e.getEntity();
int lvl = LevelConfigUtils.getPlayerLevel(p,p.getWorld(),plugin);
final Localisation localisation = plugin.getLocalisation();
if (e.getCause().equals(EntityDamageEvent.DamageCause.FALL)) {
if (p.isSneaking() && p.hasPermission("pkr.defaults")) {
if (e.getDamage() <= plugin.getConfig().getDouble("Level." + lvl +".Damage Threshold")) { // TODO better name than threshold maybe?
e.setDamage(0.0);
p.sendMessage(localisation.get(LocalisationEntry.MSG_SUCCESSFUL_ROLL));
} else {
e.setDamage(e.getDamage() * plugin.getConfig().getDouble("Level." + lvl + ".Damage Reduction"));
if (e.getDamage() < p.getHealth()) {
p.sendMessage(localisation.get(LocalisationEntry.MSG_INJURED_BUT_SUCCESSFUL_ROLL));
} else {
return;
}
}
int dmg = (int) e.getDamage();
int randomNum =(int) (Math.random() * dmg) + 1;
final int xpGained = Experience.getExpReward(plugin, p, randomNum);
Experience.addXP(plugin, p, p.getWorld(), xpGained);
}
}
}
}
|
package org.neo4j.management;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.neo4j.kernel.AbstractGraphDatabase;
import org.neo4j.kernel.EmbeddedGraphDatabase;
import org.neo4j.kernel.impl.transaction.xaframework.XaDataSource;
import org.neo4j.management.impl.XaManagerBean;
import org.neo4j.test.TargetDirectory;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
public class TestXaManagerBeans
{
private AbstractGraphDatabase graphDb;
private XaManager xaManager;
private TargetDirectory dir = TargetDirectory.forTest( getClass() );
@Before
public synchronized void startGraphDb()
{
graphDb = new EmbeddedGraphDatabase( dir.directory( "test" ).getAbsolutePath() );
xaManager = graphDb.getSingleManagementBean( XaManager.class );
}
@After
public synchronized void stopGraphDb()
{
if ( graphDb != null ) graphDb.shutdown();
graphDb = null;
}
@Test
public void canAccessXaManagerBean() throws Exception
{
assertNotNull( "no XA manager bean", xaManager );
assertTrue( "no XA resources", xaManager.getXaResources().length > 0 );
}
@Test
public void hasAllXaManagerBeans()
{
for ( XaDataSource xaDataSource : graphDb.getXaDataSourceManager().getAllRegisteredDataSources() )
{
XaResourceInfo info = getByName( xaDataSource.getName() );
assertEquals( "wrong branchid for XA data source " + xaDataSource.getName(),
XaManagerBean.toHexString( xaDataSource.getBranchId() ), info.getBranchId() );
assertEquals( "wrong log version for XA data source " + xaDataSource.getName(),
xaDataSource.getCurrentLogVersion(), info.getLogVersion() );
assertEquals( "wrong last tx ID for XA data source " + xaDataSource.getName(),
xaDataSource.getLastCommittedTxId(), info.getLastTxId() );
}
}
private XaResourceInfo getByName( String name )
{
for ( XaResourceInfo xaResourceInfo : xaManager.getXaResources() )
{
if ( name.equals( xaResourceInfo.getName() ) )
{
return xaResourceInfo;
}
}
fail( "no such XA resource: " + name );
return null;
}
}
|
package com.vaadin.terminal.gwt.server;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.portlet.MimeResponse;
import javax.portlet.PortletContext;
import javax.portlet.PortletRequest;
import javax.portlet.PortletResponse;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.portlet.ResourceResponse;
import javax.portlet.ResourceURL;
import com.vaadin.Application;
import com.vaadin.external.json.JSONException;
import com.vaadin.external.json.JSONObject;
import com.vaadin.terminal.DeploymentConfiguration;
import com.vaadin.terminal.PaintException;
import com.vaadin.terminal.StreamVariable;
import com.vaadin.terminal.WrappedRequest;
import com.vaadin.terminal.WrappedResponse;
import com.vaadin.terminal.gwt.client.Connector;
import com.vaadin.ui.Root;
/**
* TODO document me!
*
* @author peholmst
*
*/
@SuppressWarnings("serial")
public class PortletCommunicationManager extends AbstractCommunicationManager {
private transient MimeResponse currentMimeResponse;
public PortletCommunicationManager(Application application) {
super(application);
}
public void handleFileUpload(WrappedRequest request,
WrappedResponse response) throws IOException {
String contentType = request.getContentType();
String name = request.getParameter("name");
String ownerId = request.getParameter("rec-owner");
Connector owner = getConnector(getApplication(), ownerId);
StreamVariable streamVariable = ownerToNameToStreamVariable.get(owner)
.get(name);
if (contentType.contains("boundary")) {
doHandleSimpleMultipartFileUpload(request, response,
streamVariable, name, owner,
contentType.split("boundary=")[1]);
} else {
doHandleXhrFilePost(request, response, streamVariable, name, owner,
request.getContentLength());
}
}
@Override
protected void postPaint(Root root) {
super.postPaint(root);
Application application = root.getApplication();
if (ownerToNameToStreamVariable != null) {
Iterator<Connector> iterator = ownerToNameToStreamVariable.keySet()
.iterator();
while (iterator.hasNext()) {
Connector owner = iterator.next();
if (application.getConnector(owner.getConnectorId()) == null) {
// Owner is no longer attached to the application
iterator.remove();
}
}
}
}
@Override
protected boolean handleApplicationRequest(WrappedRequest request,
WrappedResponse response) throws IOException {
currentMimeResponse = (RenderResponse) ((WrappedPortletResponse) response)
.getPortletResponse();
try {
return super.handleApplicationRequest(request, response);
} finally {
currentMimeResponse = null;
}
}
@Override
public void handleUidlRequest(WrappedRequest request,
WrappedResponse response, Callback callback, Root root)
throws IOException, InvalidUIDLSecurityKeyException {
currentMimeResponse = (ResourceResponse) ((WrappedPortletResponse) response)
.getPortletResponse();
super.handleUidlRequest(request, response, callback, root);
currentMimeResponse = null;
}
private Map<Connector, Map<String, StreamVariable>> ownerToNameToStreamVariable;
@Override
String getStreamVariableTargetUrl(Connector owner, String name,
StreamVariable value) {
if (ownerToNameToStreamVariable == null) {
ownerToNameToStreamVariable = new HashMap<Connector, Map<String, StreamVariable>>();
}
Map<String, StreamVariable> nameToReceiver = ownerToNameToStreamVariable
.get(owner);
if (nameToReceiver == null) {
nameToReceiver = new HashMap<String, StreamVariable>();
ownerToNameToStreamVariable.put(owner, nameToReceiver);
}
nameToReceiver.put(name, value);
ResourceURL resurl = createResourceURL();
resurl.setResourceID("UPLOAD");
resurl.setParameter("name", name);
resurl.setParameter("rec-owner", owner.getConnectorId());
resurl.setProperty("name", name);
resurl.setProperty("rec-owner", owner.getConnectorId());
return resurl.toString();
}
private ResourceURL createResourceURL() {
if (currentMimeResponse == null) {
throw new RuntimeException(
"No reponse object available. Cannot create a resource URL");
}
return currentMimeResponse.createResourceURL();
}
@Override
protected void cleanStreamVariable(Connector owner, String name) {
Map<String, StreamVariable> map = ownerToNameToStreamVariable
.get(owner);
map.remove(name);
if (map.isEmpty()) {
ownerToNameToStreamVariable.remove(owner);
}
}
@Override
protected BootstrapHandler createBootstrapHandler() {
return new BootstrapHandler() {
@Override
public boolean handleRequest(Application application,
WrappedRequest request, WrappedResponse response)
throws IOException {
PortletRequest portletRequest = WrappedPortletRequest.cast(
request).getPortletRequest();
if (portletRequest instanceof RenderRequest) {
return super.handleRequest(application, request, response);
} else {
return false;
}
}
@Override
protected String getApplicationId(BootstrapContext context) {
PortletRequest portletRequest = WrappedPortletRequest.cast(
context.getRequest()).getPortletRequest();
/*
* We need to generate a unique ID because some portals already
* create a DIV with the portlet's Window ID as the DOM ID.
*/
return "v-" + portletRequest.getWindowID();
}
@Override
protected String getAppUri(BootstrapContext context) {
return getRenderResponse(context).createActionURL().toString();
}
private RenderResponse getRenderResponse(BootstrapContext context) {
PortletResponse response = ((WrappedPortletResponse) context
.getResponse()).getPortletResponse();
RenderResponse renderResponse = (RenderResponse) response;
return renderResponse;
}
@Override
protected JSONObject getDefaultParameters(BootstrapContext context)
throws JSONException {
/*
* We need this in order to get uploads to work. TODO this is
* not needed for uploads anymore, check if this is needed for
* some other things
*/
JSONObject defaults = super.getDefaultParameters(context);
defaults.put("usePortletURLs", true);
ResourceURL uidlUrlBase = getRenderResponse(context)
.createResourceURL();
uidlUrlBase.setResourceID("UIDL");
defaults.put("portletUidlURLBase", uidlUrlBase.toString());
defaults.put("pathInfo", "");
return defaults;
}
@Override
protected void writeMainScriptTagContents(BootstrapContext context)
throws JSONException, IOException {
// fixed base theme to use - all portal pages with Vaadin
// applications will load this exactly once
String portalTheme = WrappedPortletRequest
.cast(context.getRequest())
.getPortalProperty(
AbstractApplicationPortlet.PORTAL_PARAMETER_VAADIN_THEME);
if (portalTheme != null
&& !portalTheme.equals(context.getThemeName())) {
String portalThemeUri = getThemeUri(context, portalTheme);
// XSS safe - originates from portal properties
context.getWriter().write(
"vaadin.loadTheme('" + portalThemeUri + "');");
}
super.writeMainScriptTagContents(context);
}
@Override
protected String getMainDivStyle(BootstrapContext context) {
DeploymentConfiguration deploymentConfiguration = context
.getRequest().getDeploymentConfiguration();
return deploymentConfiguration.getApplicationOrSystemProperty(
AbstractApplicationPortlet.PORTLET_PARAMETER_STYLE,
null);
}
@Override
protected String getInitialUIDL(WrappedRequest request, Root root)
throws PaintException {
return PortletCommunicationManager.this.getInitialUIDL(request,
root);
}
@Override
protected JSONObject getApplicationParameters(
BootstrapContext context) throws JSONException,
PaintException {
JSONObject parameters = super.getApplicationParameters(context);
WrappedPortletResponse wrappedPortletResponse = (WrappedPortletResponse) context
.getResponse();
MimeResponse portletResponse = (MimeResponse) wrappedPortletResponse
.getPortletResponse();
ResourceURL resourceURL = portletResponse.createResourceURL();
resourceURL.setResourceID("browserDetails");
parameters.put("browserDetailsUrl", resourceURL.toString());
return parameters;
}
};
}
@Override
protected InputStream getThemeResourceAsStream(Root root, String themeName,
String resource) {
PortletApplicationContext2 context = (PortletApplicationContext2) root
.getApplication().getContext();
PortletContext portletContext = context.getPortletSession()
.getPortletContext();
return portletContext.getResourceAsStream("/"
+ AbstractApplicationPortlet.THEME_DIRECTORY_PATH + themeName
+ "/" + resource);
}
}
|
package com.valerysamovich.java.patric.day1.examples;
public class ExampleSwitch {
public static void main(String[] args) {
String j = "Two";
switch(j){
case "Zero":
System.out.println("Value is 0");
break;
case "One":
System.out.println("Value is 1");
break;
case "Two":
System.out.println("Value is 2");
break;
case "Three":
System.out.println("Value is 3");
break;
default:
System.out.println("No value");
break;
}
int num = 2;
switch(num){
case 1:
System.out.println("One");
break;
case 2:
System.out.println("Two");
break;
default:
System.out.println("No match found!");
}
}
}
|
package gjb.experimental;
import org.firstinspires.ftc.robotcore.external.ClassFactory;
import org.firstinspires.ftc.robotcore.external.navigation.VuMarkInstanceId;
import org.firstinspires.ftc.robotcore.external.navigation.VuforiaLocalizer;
import org.firstinspires.ftc.robotcore.external.navigation.VuforiaTrackable;
import org.firstinspires.ftc.robotcore.external.navigation.VuforiaTrackables;
import java.util.prefs.BackingStoreException;
import gjb.interfaces.LoggingInterface;
import gjb.interfaces.RuntimeSupportInterface;
import gjb.interfaces.SubSystemInterface;
public class SubSysVision implements SubSystemInterface {
enum CameraDirection {
FRONT,
BACK
};
// Vision configuration
public class Config {
public final CameraDirection cameraDirection;
public final boolean enableDisplay; // If true, will show camera view on screen.
public final String trackableAssetName; // Name of the asset that contains the trackables.
public final String []trackableIds; // EXPECTED IDs of trackables that will be tracked. This is just to make sure that we have the right
// set of trackables here.
// Future: Positions x, y, z, and rotation angles a1, a2, a3 for each trackable in field, and of camera on Robot.
// Consider placing this in an asset file. One can have multiple asset files for various field configurations.
public Config( CameraDirection cameraDirection, boolean enableDisplay, String trackableAssetName, String[]trackableIds) {
this.cameraDirection = cameraDirection;
this.enableDisplay = enableDisplay;
this.trackableAssetName = trackableAssetName;
this.trackableIds = trackableIds;
}
}
public class VisionInfo {
double timestamp; // In seconds, since start of OpMode (rt.getRuntime()). A negative value indicates no information.
String trackableId;
// Future: positions x, y, z and angles a1, a2, a3
}
// Returns true iff {vi} is not null an it was captured within {timeWindow}
// of the present.
boolean validVisionInfo(VisionInfo vi, double timeWindow) {
// Note that -ve timestamp indicates invalid tracking information.
return vi!= null && vi.timestamp >= 0 && vi.timestamp >= (rt.getRuntime() - timeWindow);
}
final String THIS_COMPONENT = "SS_VISION"; // // Replace EMPTY by short word identifying task
final public RuntimeSupportInterface rt;
final public LoggingInterface log;
// Place additional instance variables here - like hardware access objects
final Config cfg;
private boolean inited = false;
private boolean tracking = false;
/**
* {@link #vuforia} is the variable we will use to store our instance of the Vuforia
* localization engine.
*/
VuforiaLocalizer vuforia;
VuforiaTrackables trackableList;
VuforiaTrackable trackable;
// Modify this constructor to add any additional initialization parameters - see
// other subsystems for examples.
public SubSysVision(RuntimeSupportInterface rt, Config cfg) {
this.rt = rt;
this.log = rt.getRootLog().newLogger(THIS_COMPONENT); // Create a child log.
this.cfg = cfg;
}
public synchronized void startTracking() {
if (!tracking) {
trackableList.activate();
tracking = true;
} else {
log.loggedAssert(false, "Attempt to start tracking when tracking has already started");
}
}
public synchronized void stopTracking() {
if (tracking) {
trackableList.deactivate();
tracking = true;
} else {
log.loggedAssert(false, "Attempt to stop tracking when tracking has already stopped");
}
}
@Override
public void init() {
this.log.pri1(LoggingInterface.INIT_START, "");
// Any subsystem initialization code goes here.
VuforiaLocalizer.Parameters parameters;
if (cfg.enableDisplay) {
int cameraMonitorViewId = rt.getIdentifierFromPackage("cameraMonitorViewId", "id");
parameters = new VuforiaLocalizer.Parameters(cameraMonitorViewId);
} else {
parameters = new VuforiaLocalizer.Parameters();
}
parameters.cameraDirection = (cfg.cameraDirection == CameraDirection.FRONT)
? VuforiaLocalizer.CameraDirection.FRONT
: VuforiaLocalizer.CameraDirection.BACK;
;
this.vuforia = ClassFactory.createVuforiaLocalizer(parameters);
/**
* Load the data set containing the VuMarks for Relic Recovery. There's only one trackable
* in this data set: all three of the VuMarks in the game were created from this one template,
* but differ in their instance id information.
* @see VuMarkInstanceId
*/
trackableList = this.vuforia.loadTrackablesFromAsset(cfg.trackableAssetName);
trackable = trackableList.get(0);
trackable.setName(cfg.trackableAssetName); // can help in debugging; otherwise not necessary
this.log.pri1(LoggingInterface.INIT_END, "");
}
@Override
public void deinit() {
this.log.pri1(LoggingInterface.DEINIT_START, "");
// Place any shutdown/deinitialization code here - this is called ONCE
// after tasks & OpModes have stopped.
if (tracking) {
stopTracking();
}
trackable = null;
trackableList = null;
vuforia=null;
this.log.pri1(LoggingInterface.DEINIT_END, "");
}
// Place additional helper methods here.
}
|
package org.reldb.dbrowser.ui.monitors;
import java.util.Timer;
import java.util.TimerTask;
import org.eclipse.swt.widgets.Caret;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyleRange;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Point;
import org.eclipse.wb.swt.SWTResourceManager;
import org.reldb.dbrowser.ui.updates.UpdatesCheck;
import org.reldb.dbrowser.ui.updates.UpdatesCheckDialog;
import org.reldb.dbrowser.ui.updates.UpdatesCheck.SendStatus;
import org.reldb.dbrowser.utilities.FontSize;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.layout.GridData;
public class CheckForUpdates extends Composite {
private UpdatesCheck updateChecker;
private StyledText txtStatus;
private MouseAdapter mouseHandler = new MouseAdapter() {
@Override
public void mouseUp(MouseEvent event) {
UpdatesCheckDialog.launch(getShell());
}
};
private void makeRelItalic() {
StyleRange italic = new StyleRange();
italic.start = 0;
italic.length = 3;
italic.fontStyle = SWT.ITALIC;
txtStatus.setStyleRange(italic);
}
private void centreText() {
GC gc = new GC(txtStatus);
Point textExtent = gc.textExtent(txtStatus.getText());
txtStatus.setMargins(2, (CheckForUpdates.this.getSize().y - textExtent.y) / 2, 2, 0);
}
private void setText(String text) {
txtStatus.setText(text);
makeRelItalic();
centreText();
getParent().layout();
}
protected void completed(SendStatus sendStatus) {
try {
if (sendStatus.getResponse() != null && sendStatus.getResponse().startsWith("Success")) {
String updateURL = UpdatesCheck.getUpdateURL(sendStatus);
if (updateURL != null) {
System.out.println("CheckForUpdates: Rel update is available at " + updateURL);
setText("Rel update is available.");
txtStatus.setForeground(SWTResourceManager.getColor(SWT.COLOR_BLACK));
txtStatus.setBackground(SWTResourceManager.getColor(255, 200, 200));
} else {
System.out.println("CheckForUpdates: Rel is up to date.");
setText("Rel is up to date.");
txtStatus.setForeground(SWTResourceManager.getColor(SWT.COLOR_DARK_GREEN));
}
}
} catch (Exception e) {
System.out.println("CheckForUpdates: exception: " + e);
}
}
/**
* Create the composite.
* @param parent
* @param style
*/
public CheckForUpdates(Composite parent, int style) {
super(parent, style);
GridLayout gridLayout = new GridLayout(1, false);
gridLayout.marginHeight = 0;
gridLayout.marginWidth = 0;
gridLayout.verticalSpacing = 0;
gridLayout.horizontalSpacing = 0;
setLayout(gridLayout);
setVisible(false);
txtStatus = new StyledText(this, SWT.WRAP);
txtStatus.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true, 1, 1));
txtStatus.setEditable(false);
txtStatus.setForeground(SWTResourceManager.getColor(SWT.COLOR_BLACK));
txtStatus.setBackground(getBackground());
txtStatus.setFont(FontSize.getThisFontInNewSize(txtStatus.getFont(), 10, SWT.NORMAL));
txtStatus.addMouseListener(mouseHandler);
txtStatus.setCaret(new Caret(txtStatus, SWT.NONE));
setText("Rel updates?");
updateChecker = new UpdatesCheck(parent.getDisplay()) {
@Override
public void completed(SendStatus sendStatus) {
CheckForUpdates.this.completed(sendStatus);
}
};
TimerTask checkForUpdates = new TimerTask() {
@Override
public void run() {
getDisplay().asyncExec(new Runnable() {
@Override
public void run() {
if (CheckForUpdates.this.isDisposed())
return;
setVisible(true);
setText("Rel updates?");
System.out.println("CheckForUpdates: check for updates.");
updateChecker.doCancel();
updateChecker.doSend();
}
});
}
};
// Check for updates after 10 seconds, then every 12 hours
Timer checkTimer = new Timer();
checkTimer.schedule(checkForUpdates, 1000 * 5, 1000 * 60 * 60 * 12);
}
}
|
package de.fosd.jdime.matcher.ordered.mceSubtree;
import de.fosd.jdime.common.Artifact;
import de.fosd.jdime.common.MergeContext;
import de.fosd.jdime.matcher.Matcher;
import de.fosd.jdime.matcher.Matchings;
import de.fosd.jdime.matcher.NewMatching;
import de.fosd.jdime.matcher.ordered.OrderedMatcher;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* A <code>OrderedMatcher</code> that uses the <code>BalancedSequence</code> class to match <code>Artifact</code>s.
* Its {@link #match(MergeContext, Artifact, Artifact, int)} method assumes that the given <code>Artifact</code>s
* may be interpreted as ordered trees whose nodes are labeled via their {@link Artifact#matches(Artifact)} method.
*
* @param <T>
* the type of the <code>Artifact</code>s
*/
public class MCESubtreeMatcher<T extends Artifact<T>> extends OrderedMatcher<T> {
/**
* Constructs a new <code>OrderedMatcher</code>
*
* @param matcher
* matcher
*/
public MCESubtreeMatcher(Matcher<T> matcher) {
super(matcher);
}
@Override
public Matchings<T> match(MergeContext context, T left, T right, int lookAhead) {
Stream<T> leftPreOrder = preOrder(left).stream();
Stream<T> rightPreOrder = preOrder(right).stream();
List<BalancedSequence<T>> leftSeqs;
List<BalancedSequence<T>> rightSeqs;
if (lookAhead == MergeContext.LOOKAHEAD_FULL) {
leftSeqs = leftPreOrder.map(BalancedSequence<T>::new).collect(Collectors.toList());
rightSeqs = rightPreOrder.map(BalancedSequence<T>::new).collect(Collectors.toList());
} else {
leftSeqs = leftPreOrder.map(t -> new BalancedSequence<>(t, lookAhead)).collect(Collectors.toList());
rightSeqs = rightPreOrder.map(t -> new BalancedSequence<>(t, lookAhead)).collect(Collectors.toList());
}
Set<NewMatching<T>> matchings = getMatchings(leftSeqs, rightSeqs);
/*
* Now we filter out the BalancedSequences in rightSequences which were produced by a node that is
* already in the left tree.
*/
rightSeqs.removeIf(rightSeq -> leftSeqs.stream().anyMatch(leftSeq -> rightSeq.getRoot().matches(leftSeq.getRoot())));
matchings.addAll(getMatchings(rightSeqs, leftSeqs));
Matchings<T> result = new Matchings<>();
result.addAll(matchings);
return result;
}
/**
* Returns for every element of <code>left</code> a <code>NewMatching</code> with the element of
* <code>right</code> for which the <code>results</code> array contains the highest score.
*
* @param left
* the <code>BalancedSequence</code>s of the nodes of the left tree
* @param right
* the <code>BalancedSequence</code>s of the nodes of the right tree @return a <code>Set</code> of
* <code>NewMatching</code>s of the described format
*/
private Set<NewMatching<T>> getMatchings(List<BalancedSequence<T>> left, List<BalancedSequence<T>> right) {
Set<NewMatching<T>> matchings = new HashSet<>();
NewMatching<T> matching = null;
for (BalancedSequence<T> leftSequence : left) {
for (BalancedSequence<T> rightSequence : right) {
Integer res = BalancedSequence.lcs(leftSequence, rightSequence);
if (matching == null || matching.getScore() < res) {
matching = new NewMatching<>(leftSequence.getRoot(), rightSequence.getRoot(), res);
}
}
matchings.add(matching);
matching = null;
}
return matchings;
}
/**
* Returns the tree with root <code>root</code> in pre-order.
*
* @param root
* the root of the tree
*
* @return the tree in pre-order
*/
private List<T> preOrder(T root) {
List<T> nodes = new ArrayList<>();
Queue<T> waitQ = new LinkedList<>(Collections.singleton(root));
T node;
while (!waitQ.isEmpty()) {
node = waitQ.poll();
nodes.add(node);
waitQ.addAll(node.getChildren());
}
return nodes;
}
}
|
package de.lmu.ifi.dbs.preprocessing;
import de.lmu.ifi.dbs.data.RealVector;
import de.lmu.ifi.dbs.database.Database;
import de.lmu.ifi.dbs.distance.DoubleDistance;
import de.lmu.ifi.dbs.utilities.QueryResult;
import de.lmu.ifi.dbs.utilities.optionhandling.AttributeSettings;
import de.lmu.ifi.dbs.utilities.optionhandling.OptionHandler;
import de.lmu.ifi.dbs.utilities.optionhandling.ParameterException;
import de.lmu.ifi.dbs.utilities.optionhandling.WrongParameterValueException;
import java.util.ArrayList;
import java.util.List;
/**
* Computes the HiCO correlation dimension of objects of a certain database. The PCA
* is based on k nearest neighbor queries.
*
* @author Elke Achtert (<a
* href="mailto:achtert@dbs.ifi.lmu.de">achtert@dbs.ifi.lmu.de</a>)
*/
public class KnnQueryBasedHiCOPreprocessor extends HiCOPreprocessor {
/**
* Undefined value for k.
*/
public static final int UNDEFINED_K = -1;
/**
* Option string for parameter k.
*/
public static final String K_P = "k";
/**
* Description for parameter k.
*/
public static final String K_D = "<int>a positive integer specifying the number of "
+ "nearest neighbors considered in the PCA. "
+ "If this value is not defined, k ist set to three "
+ "times of the dimensionality of the database objects.";
/**
* The number of nearest neighbors considered in the PCA.
*/
private int k;
/**
* Provides a new Preprocessor that computes the correlation dimension of
* objects of a certain database based on a k nearest neighbor query.
*/
public KnnQueryBasedHiCOPreprocessor() {
super();
parameterToDescription.put(K_P + OptionHandler.EXPECTS_VALUE, K_D);
optionHandler = new OptionHandler(parameterToDescription, getClass().getName());
}
/**
* @see HiCOPreprocessor#objectIDsForPCA(Integer, Database,boolean, boolean)
*/
protected List<Integer> objectIDsForPCA(Integer id, Database<RealVector> database, boolean verbose, boolean time) {
if (k == UNDEFINED_K) {
RealVector obj = database.get(id);
k = 3 * obj.getDimensionality();
}
pcaDistanceFunction.setDatabase(database, verbose, time);
List<QueryResult<DoubleDistance>> knns = database.kNNQueryForID(id, k, pcaDistanceFunction);
List<Integer> ids = new ArrayList<Integer>(knns.size());
for (QueryResult knn : knns) {
ids.add(knn.getID());
}
return ids;
}
/**
* Sets the value for the parameter k. If k is not specified, the default
* value is used.
*
* @see de.lmu.ifi.dbs.utilities.optionhandling.Parameterizable#setParameters(String[])
*/
public String[] setParameters(String[] args) throws ParameterException {
String[] remainingParameters = super.setParameters(args);
if (optionHandler.isSet(K_P)) {
String kString = optionHandler.getOptionValue(K_P);
try {
k = Integer.parseInt(kString);
if (k <= 0) {
throw new WrongParameterValueException(K_P, kString, K_D);
}
}
catch (NumberFormatException e) {
throw new WrongParameterValueException(K_P, kString, K_D, e);
}
}
else {
k = UNDEFINED_K;
}
setParameters(args, remainingParameters);
return remainingParameters;
}
/**
* Returns the parameter setting of the attributes.
*
* @return the parameter setting of the attributes
*/
public List<AttributeSettings> getAttributeSettings() {
List<AttributeSettings> attributeSettings = super.getAttributeSettings();
AttributeSettings mySettings = attributeSettings.get(0);
mySettings.addSetting(K_P, Integer.toString(k));
return attributeSettings;
}
/**
* Returns a description of the class and the required parameters. <p/> This
* description should be suitable for a usage description.
*
* @return String a description of the class and the required parameters
*/
public String description() {
StringBuffer description = new StringBuffer();
description.append(KnnQueryBasedHiCOPreprocessor.class
.getName());
description
.append(" computes the correlation dimension of objects of a certain database.\n");
description.append("The PCA is based on k nearest neighbor queries.\n");
description.append(optionHandler.usage("", false));
return description.toString();
}
}
|
package edu.wpi.first.wpilibj.templates.subsystems;
import edu.wpi.first.wpilibj.Solenoid;
import edu.wpi.first.wpilibj.command.Subsystem;
import edu.wpi.first.wpilibj.templates.commands.RunShooterSolenoid;
import edu.wpi.first.wpilibj.templates.variablestores.VstM;
/**
*
* @author Robotics
*/
public class ShooterSolenoid extends Subsystem {
// Put methods for controlling this subsystem
// here. Call these from Commands.
private Solenoid shooterSolenoid = new Solenoid(VstM.Solenoids.SHOOTER_SOLENOID_PORT);
public void initDefaultCommand() {
setDefaultCommand(new RunShooterSolenoid());
}
public void extend() {
shooterSolenoid.set(true);
}
public void retract() {
shooterSolenoid.set(false);
}
public void stop() {
shooterSolenoid.set(false);
}
}
|
package gov.nih.nci.calab.service.submit;
import gov.nih.nci.calab.db.DataAccessProxy;
import gov.nih.nci.calab.db.IDataAccess;
import gov.nih.nci.calab.domain.Keyword;
import gov.nih.nci.calab.domain.nano.characterization.Characterization;
import gov.nih.nci.calab.domain.nano.characterization.physical.composition.CarbonNanotubeComposition;
import gov.nih.nci.calab.domain.nano.characterization.physical.composition.ComplexComposition;
import gov.nih.nci.calab.domain.nano.characterization.physical.composition.DendrimerComposition;
import gov.nih.nci.calab.domain.nano.characterization.physical.composition.EmulsionComposition;
import gov.nih.nci.calab.domain.nano.characterization.physical.composition.FullereneComposition;
import gov.nih.nci.calab.domain.nano.characterization.physical.composition.LiposomeComposition;
import gov.nih.nci.calab.domain.nano.characterization.physical.composition.MetalParticleComposition;
import gov.nih.nci.calab.domain.nano.characterization.physical.composition.PolymerComposition;
import gov.nih.nci.calab.domain.nano.characterization.physical.composition.QuantumDotComposition;
import gov.nih.nci.calab.domain.nano.particle.Nanoparticle;
import gov.nih.nci.calab.dto.characterization.composition.CarbonNanotubeBean;
import gov.nih.nci.calab.dto.characterization.composition.ComplexParticleBean;
import gov.nih.nci.calab.dto.characterization.composition.CompositionBean;
import gov.nih.nci.calab.dto.characterization.composition.DendrimerBean;
import gov.nih.nci.calab.dto.characterization.composition.EmulsionBean;
import gov.nih.nci.calab.dto.characterization.composition.FullereneBean;
import gov.nih.nci.calab.dto.characterization.composition.LiposomeBean;
import gov.nih.nci.calab.dto.characterization.composition.MetalParticleBean;
import gov.nih.nci.calab.dto.characterization.composition.PolymerBean;
import gov.nih.nci.calab.dto.characterization.composition.QuantumDotBean;
import gov.nih.nci.calab.dto.workflow.FileBean;
import gov.nih.nci.calab.exception.CalabException;
import gov.nih.nci.calab.service.security.UserService;
import gov.nih.nci.calab.service.util.CalabConstants;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
/**
* This class includes service calls involved in creating nanoparticles and
* adding functions and characterizations for nanoparticles.
*
* @author pansu
*
*/
public class SubmitNanoparticleService {
private static Logger logger = Logger
.getLogger(SubmitNanoparticleService.class);
/**
* Update keywords and visibilities for the particle with the given name and
* type
*
* @param particleType
* @param particleName
* @param keywords
* @param visibilities
* @throws Exception
*/
public void createNanoparticle(String particleType, String particleName,
String[] keywords, String[] visibilities) throws Exception {
// save nanoparticle to the database
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
// get the existing particle from database created during sample
// creation
List results = ida.search("from Nanoparticle where name='"
+ particleName + "' and type='" + particleType + "'");
Nanoparticle particle = null;
for (Object obj : results) {
particle = (Nanoparticle) obj;
}
if (particle == null) {
throw new CalabException("No such particle in the database");
}
particle.getKeywordCollection().clear();
if (keywords != null) {
for (String keyword : keywords) {
Keyword keywordObj = new Keyword();
keywordObj.setName(keyword);
particle.getKeywordCollection().add(keywordObj);
}
}
} catch (Exception e) {
ida.rollback();
logger
.error("Problem updating particle with name: "
+ particleName);
throw e;
} finally {
ida.close();
}
// remove existing visiblities for the nanoparticle
UserService userService = new UserService(CalabConstants.CSM_APP_NAME);
List<String> currentVisibilities = userService.getAccessibleGroups(
particleName, "R");
for (String visiblity : currentVisibilities) {
userService.removeAccessibleGroup(particleName, visiblity, "R");
}
// set new visibilities for the nanoparticle
for (String visibility : visibilities) {
// by default, always set visibility to NCL_PI and NCL_Researcher to
// be true
userService.secureObject(particleName, "NCL_PI", "R");
userService.secureObject(particleName, "NCL_Researcher", "R");
userService.secureObject(particleName, visibility, "R");
}
}
/**
* Saves the particle composition to the database
*
* @param particleType
* @param particleName
* @param composition
* @throws Exception
*/
public void addParticleComposition(String particleType,
String particleName, CompositionBean composition) throws Exception {
// if ID is not set save to the database otherwise update
Characterization doComp = null;
if (composition instanceof CarbonNanotubeBean) {
doComp = (CarbonNanotubeComposition) composition.getDomainObj();
} else if (composition instanceof ComplexParticleBean) {
doComp = (ComplexComposition) composition.getDomainObj();
} else if (composition instanceof DendrimerBean) {
doComp = (DendrimerComposition) composition.getDomainObj();
} else if (composition instanceof EmulsionBean) {
doComp = (EmulsionComposition) composition.getDomainObj();
} else if (composition instanceof FullereneBean) {
doComp = (FullereneComposition) composition.getDomainObj();
} else if (composition instanceof LiposomeBean) {
doComp = (LiposomeComposition) composition.getDomainObj();
} else if (composition instanceof QuantumDotBean) {
doComp = (QuantumDotComposition) composition.getDomainObj();
} else if (composition instanceof MetalParticleBean) {
doComp = (MetalParticleComposition) composition.getDomainObj();
} else if (composition instanceof PolymerBean) {
doComp = (PolymerComposition) composition.getDomainObj();
} else {
throw new CalabException(
"Can't save composition for the given particle type: "
+ composition.getClass().getName());
}
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
Nanoparticle particle = null;
int existingViewTitleCount = -1;
try {
ida.open();
// check if viewTitle is already used
String viewTitleQuery="";
if (doComp.getId()==null){
viewTitleQuery="select count(achar) from Characterization achar where achar.identificationName='"+ doComp.getIdentificationName()+"'";
}
else {
viewTitleQuery="select count(achar) from Characterization achar where achar.identificationName='"
+ doComp.getIdentificationName() + "' and achar.id!="+
doComp.getId();
}
List viewTitleResult = ida
.search(viewTitleQuery);
for (Object obj : viewTitleResult) {
existingViewTitleCount = ((Integer) (obj)).intValue();
}
if (existingViewTitleCount == 0) {
// if ID exists, do update
if (doComp.getId() != null) {
ida.store(doComp);
} else {// get the existing particle and compositions
// from database
// created
// during sample
// creation
List results = ida
.search("select particle from Nanoparticle particle left join fetch particle.characterizationCollection where particle.name='"
+ particleName
+ "' and particle.type='"
+ particleType + "'");
for (Object obj : results) {
particle = (Nanoparticle) obj;
}
if (particle != null) {
particle.getCharacterizationCollection().add(doComp);
}
}
}
} catch (Exception e) {
e.printStackTrace();
ida.rollback();
logger.error("Problem saving composition: ");
throw e;
} finally {
ida.close();
}
if (existingViewTitleCount > 0) {
throw new CalabException(
"The view title is already in use. Please enter a different one.");
}
}
public void saveAssayResult(String particleName, String fileName,
String title, String description, String comments, String[] keywords) {
}
public List<FileBean> getAllRunFiles(String particleName) {
List<FileBean> runFiles = new ArrayList<FileBean>();
// TODO fill in the database query code
FileBean file = new FileBean();
file.setId("1");
file.setShortFilename("NCL_3_distri.jpg");
runFiles.add(file);
return runFiles;
}
}
|
package gov.nih.nci.calab.service.submit;
import gov.nih.nci.calab.db.DataAccessProxy;
import gov.nih.nci.calab.db.HibernateDataAccess;
import gov.nih.nci.calab.db.IDataAccess;
import gov.nih.nci.calab.domain.Instrument;
import gov.nih.nci.calab.domain.InstrumentConfiguration;
import gov.nih.nci.calab.domain.Keyword;
import gov.nih.nci.calab.domain.LabFile;
import gov.nih.nci.calab.domain.LookupType;
import gov.nih.nci.calab.domain.MeasureUnit;
import gov.nih.nci.calab.domain.OutputFile;
import gov.nih.nci.calab.domain.nano.characterization.Characterization;
import gov.nih.nci.calab.domain.nano.characterization.CharacterizationFileType;
import gov.nih.nci.calab.domain.nano.characterization.DerivedBioAssayData;
import gov.nih.nci.calab.domain.nano.characterization.invitro.CFU_GM;
import gov.nih.nci.calab.domain.nano.characterization.invitro.Caspase3Activation;
import gov.nih.nci.calab.domain.nano.characterization.invitro.CellLineType;
import gov.nih.nci.calab.domain.nano.characterization.invitro.CellViability;
import gov.nih.nci.calab.domain.nano.characterization.invitro.Chemotaxis;
import gov.nih.nci.calab.domain.nano.characterization.invitro.Coagulation;
import gov.nih.nci.calab.domain.nano.characterization.invitro.ComplementActivation;
import gov.nih.nci.calab.domain.nano.characterization.invitro.CytokineInduction;
import gov.nih.nci.calab.domain.nano.characterization.invitro.EnzymeInduction;
import gov.nih.nci.calab.domain.nano.characterization.invitro.Hemolysis;
import gov.nih.nci.calab.domain.nano.characterization.invitro.LeukocyteProliferation;
import gov.nih.nci.calab.domain.nano.characterization.invitro.NKCellCytotoxicActivity;
import gov.nih.nci.calab.domain.nano.characterization.invitro.OxidativeBurst;
import gov.nih.nci.calab.domain.nano.characterization.invitro.OxidativeStress;
import gov.nih.nci.calab.domain.nano.characterization.invitro.Phagocytosis;
import gov.nih.nci.calab.domain.nano.characterization.invitro.PlasmaProteinBinding;
import gov.nih.nci.calab.domain.nano.characterization.invitro.PlateletAggregation;
import gov.nih.nci.calab.domain.nano.characterization.physical.MolecularWeight;
import gov.nih.nci.calab.domain.nano.characterization.physical.Morphology;
import gov.nih.nci.calab.domain.nano.characterization.physical.MorphologyType;
import gov.nih.nci.calab.domain.nano.characterization.physical.Purity;
import gov.nih.nci.calab.domain.nano.characterization.physical.Shape;
import gov.nih.nci.calab.domain.nano.characterization.physical.ShapeType;
import gov.nih.nci.calab.domain.nano.characterization.physical.Size;
import gov.nih.nci.calab.domain.nano.characterization.physical.Solubility;
import gov.nih.nci.calab.domain.nano.characterization.physical.SolventType;
import gov.nih.nci.calab.domain.nano.characterization.physical.Surface;
import gov.nih.nci.calab.domain.nano.characterization.physical.composition.ParticleComposition;
import gov.nih.nci.calab.domain.nano.function.Agent;
import gov.nih.nci.calab.domain.nano.function.AgentTarget;
import gov.nih.nci.calab.domain.nano.function.Function;
import gov.nih.nci.calab.domain.nano.function.Linkage;
import gov.nih.nci.calab.domain.nano.particle.Nanoparticle;
import gov.nih.nci.calab.dto.characterization.CharacterizationBean;
import gov.nih.nci.calab.dto.characterization.DerivedBioAssayDataBean;
import gov.nih.nci.calab.dto.characterization.composition.CompositionBean;
import gov.nih.nci.calab.dto.characterization.invitro.CytotoxicityBean;
import gov.nih.nci.calab.dto.characterization.physical.MorphologyBean;
import gov.nih.nci.calab.dto.characterization.physical.ShapeBean;
import gov.nih.nci.calab.dto.characterization.physical.SolubilityBean;
import gov.nih.nci.calab.dto.characterization.physical.SurfaceBean;
import gov.nih.nci.calab.dto.common.LabFileBean;
import gov.nih.nci.calab.dto.function.FunctionBean;
import gov.nih.nci.calab.exception.CalabException;
import gov.nih.nci.calab.service.common.FileService;
import gov.nih.nci.calab.service.security.UserService;
import gov.nih.nci.calab.service.util.CaNanoLabConstants;
import gov.nih.nci.calab.service.util.PropertyReader;
import gov.nih.nci.calab.service.util.StringUtils;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
/**
* This class includes service calls involved in creating nanoparticle general
* info and adding functions and characterizations for nanoparticles, as well as
* creating reports.
*
* @author pansu
*
*/
public class SubmitNanoparticleService {
private static Logger logger = Logger
.getLogger(SubmitNanoparticleService.class);
// remove existing visibilities for the data
private UserService userService;
public SubmitNanoparticleService() throws Exception {
userService = new UserService(CaNanoLabConstants.CSM_APP_NAME);
}
/**
* Update keywords and visibilities for the particle with the given name and
* type
*
* @param particleType
* @param particleName
* @param keywords
* @param visibilities
* @throws Exception
*/
public void addParticleGeneralInfo(String particleType,
String particleName, String[] keywords, String[] visibilities)
throws Exception {
// save nanoparticle to the database
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
// get the existing particle from database created during sample
// creation
List results = ida.search("from Nanoparticle where name='"
+ particleName + "' and type='" + particleType + "'");
Nanoparticle particle = null;
for (Object obj : results) {
particle = (Nanoparticle) obj;
}
if (particle == null) {
throw new CalabException("No such particle in the database");
}
particle.getKeywordCollection().clear();
if (keywords != null) {
for (String keyword : keywords) {
Keyword keywordObj = new Keyword();
keywordObj.setName(keyword);
particle.getKeywordCollection().add(keywordObj);
}
}
} catch (Exception e) {
ida.rollback();
logger
.error("Problem updating particle with name: "
+ particleName);
throw e;
} finally {
ida.close();
}
userService.setVisiblity(particleName, visibilities);
}
/**
* Save characterization to the database.
*
* @param particleType
* @param particleName
* @param achar
* @throws Exception
*/
private void addParticleCharacterization(String particleType,
String particleName, Characterization achar,
CharacterizationBean charBean) throws Exception {
// if ID is not set save to the database otherwise update
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
Nanoparticle particle = null;
int existingViewTitleCount = -1;
try {
ida.open();
// check if viewTitle is already used the same type of
// characterization for the same particle
boolean viewTitleUsed = isCharacterizationViewTitleUsed(ida,
particleType, particleName, achar);
if (!viewTitleUsed) {
if (achar.getInstrumentConfiguration() != null) {
addInstrumentConfig(achar.getInstrumentConfiguration(), ida);
}
// if ID exists, do update
if (achar.getId() != null) {
// check if ID is still valid
try {
Characterization storedChara = (Characterization) ida
.load(Characterization.class, achar.getId());
} catch (Exception e) {
throw new Exception(
"This characterization is no longer in the database. Please log in again to refresh.");
}
ida.store(achar);
} else {// get the existing particle and characterizations
// from database created during sample creation
List results = ida
.search("select particle from Nanoparticle particle left join fetch particle.characterizationCollection where particle.name='"
+ particleName
+ "' and particle.type='"
+ particleType + "'");
for (Object obj : results) {
particle = (Nanoparticle) obj;
}
if (particle != null) {
particle.getCharacterizationCollection().add(achar);
}
}
}
if (existingViewTitleCount > 0) {
throw new Exception(
"The view title is already in use. Please enter a different one.");
}
// add new characterization file type if necessary
if (!charBean.getDerivedBioAssayDataList().isEmpty()) {
for (DerivedBioAssayDataBean derivedBioAssayDataBean : charBean
.getDerivedBioAssayDataList()) {
if (derivedBioAssayDataBean.getType().length() > 0) {
CharacterizationFileType fileType = new CharacterizationFileType();
addLookupType(ida, fileType, derivedBioAssayDataBean
.getType());
}
}
}
} catch (Exception e) {
e.printStackTrace();
ida.rollback();
logger.error("Problem saving characterization: ");
throw e;
} finally {
ida.close();
}
// save file to the file system
// if this block of code is inside the db try catch block, hibernate
// doesn't persist derivedBioAssayData
if (!charBean.getDerivedBioAssayDataList().isEmpty()) {
for (DerivedBioAssayDataBean derivedBioAssayDataBean : charBean
.getDerivedBioAssayDataList()) {
saveCharacterizationFile(derivedBioAssayDataBean);
}
}
}
/*
* check if viewTitle is already used the same type of characterization for
* the same particle
*/
private boolean isCharacterizationViewTitleUsed(IDataAccess ida,
String particleType, String particleName, Characterization achar)
throws Exception {
String viewTitleQuery = "";
if (achar.getId() == null) {
viewTitleQuery = "select count(achar.identificationName) from Nanoparticle particle join particle.characterizationCollection achar where particle.name='"
+ particleName
+ "' and particle.type='"
+ particleType
+ "' and achar.identificationName='"
+ achar.getIdentificationName()
+ "' and achar.name='"
+ achar.getName() + "'";
} else {
viewTitleQuery = "select count(achar.identificationName) from Nanoparticle particle join particle.characterizationCollection achar where particle.name='"
+ particleName
+ "' and particle.type='"
+ particleType
+ "' and achar.identificationName='"
+ achar.getIdentificationName()
+ "' and achar.name='"
+ achar.getName() + "' and achar.id!=" + achar.getId();
}
List viewTitleResult = ida.search(viewTitleQuery);
int existingViewTitleCount = -1;
for (Object obj : viewTitleResult) {
existingViewTitleCount = ((Integer) (obj)).intValue();
}
if (existingViewTitleCount > 0) {
return true;
} else {
return false;
}
}
/**
* Save the file to the file system
*
* @param fileBean
*/
public void saveCharacterizationFile(DerivedBioAssayDataBean fileBean)
throws Exception {
byte[] fileContent = fileBean.getFileContent();
String rootPath = PropertyReader.getProperty(
CaNanoLabConstants.FILEUPLOAD_PROPERTY, "fileRepositoryDir");
if (fileContent != null) {
FileService fileService = new FileService();
fileService.writeFile(fileContent, rootPath + File.separator
+ fileBean.getUri());
}
userService.setVisiblity(fileBean.getId(), fileBean
.getVisibilityGroups());
}
private void addInstrumentConfig(InstrumentConfiguration instrumentConfig,
IDataAccess ida) throws Exception {
Instrument instrument = instrumentConfig.getInstrument();
// check if instrument is already in database
List instrumentResults = ida
.search("select instrument from Instrument instrument where instrument.type='"
+ instrument.getType()
+ "' and instrument.manufacturer='"
+ instrument.getManufacturer() + "'");
Instrument storedInstrument = null;
for (Object obj : instrumentResults) {
storedInstrument = (Instrument) obj;
}
if (storedInstrument != null) {
instrument.setId(storedInstrument.getId());
} else {
ida.createObject(instrument);
}
// if new instrumentConfig, save it
if (instrumentConfig.getId() == null) {
ida.createObject(instrumentConfig);
} else {
InstrumentConfiguration storedInstrumentConfig = (InstrumentConfiguration) ida
.load(InstrumentConfiguration.class, instrumentConfig
.getId());
storedInstrumentConfig.setDescription(instrumentConfig
.getDescription());
storedInstrumentConfig.setInstrument(instrument);
}
}
/**
* Saves the particle composition to the database
*
* @param particleType
* @param particleName
* @param composition
* @throws Exception
*/
public void addParticleComposition(String particleType,
String particleName, CompositionBean composition) throws Exception {
ParticleComposition doComp = composition.getDomainObj();
addParticleCharacterization(particleType, particleName, doComp,
composition);
}
/**
* O Saves the size characterization to the database
*
* @param particleType
* @param particleName
* @param size
* @throws Exception
*/
public void addParticleSize(String particleType, String particleName,
CharacterizationBean size) throws Exception {
Size doSize = new Size();
size.updateDomainObj(doSize);
addParticleCharacterization(particleType, particleName, doSize, size);
}
/**
* Saves the size characterization to the database
*
* @param particleType
* @param particleName
* @param surface
* @throws Exception
*/
public void addParticleSurface(String particleType, String particleName,
CharacterizationBean surface) throws Exception {
Surface doSurface = new Surface();
((SurfaceBean) surface).updateDomainObj(doSurface);
addParticleCharacterization(particleType, particleName, doSurface,
surface);
MeasureUnit measureUnit = new MeasureUnit();
addMeasureUnit(measureUnit, doSurface.getCharge().getUnitOfMeasurement(), CaNanoLabConstants.UNIT_TYPE_CHARGE);
addMeasureUnit(measureUnit, doSurface.getSurfaceArea().getUnitOfMeasurement(), CaNanoLabConstants.UNIT_TYPE_AREA);
addMeasureUnit(measureUnit, doSurface.getZetaPotential().getUnitOfMeasurement(), CaNanoLabConstants.UNIT_TYPE_ZETA_POTENTIAL);
}
private void addLookupType(IDataAccess ida, LookupType lookupType,
String type) throws Exception {
String className = lookupType.getClass().getSimpleName();
List results = ida.search("select count(distinct name) from "
+ className + " type where name='" + type + "'");
lookupType.setName(type);
int count = -1;
for (Object obj : results) {
count = ((Integer) (obj)).intValue();
}
if (count == 0) {
ida.createObject(lookupType);
}
}
private void addLookupType(LookupType lookupType, String type)
throws Exception {
// if ID is not set save to the database otherwise update
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
String className = lookupType.getClass().getSimpleName();
try {
ida.open();
List results = ida.search("select count(distinct name) from "
+ className + " type where name='" + type + "'");
lookupType.setName(type);
int count = -1;
for (Object obj : results) {
count = ((Integer) (obj)).intValue();
}
if (count == 0) {
ida.createObject(lookupType);
}
} catch (Exception e) {
e.printStackTrace();
ida.rollback();
logger.error("Problem saving look up type: " + type);
throw e;
} finally {
ida.close();
}
}
private void addMeasureUnit(MeasureUnit unitType, String unit, String type)
throws Exception {
// if ID is not set save to the database otherwise update
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
String className = unitType.getClass().getSimpleName();
try {
ida.open();
List results = ida.search("select count(distinct measureUnit.name) from "
+ className + " measureUnit where measureUnit.name='" + unit + "' and measureUnit.type='" + type + "'");
int count = -1;
for (Object obj : results) {
count = ((Integer) (obj)).intValue();
}
if (count == 0) {
unitType.setName(unit);
unitType.setType(type);
ida.createObject(unitType);
}
} catch (Exception e) {
e.printStackTrace();
ida.rollback();
logger.error("Problem saving look up type: " + type);
throw e;
} finally {
ida.close();
}
}
/**
* Saves the molecular weight characterization to the database
*
* @param particleType
* @param particleName
* @param molecularWeight
* @throws Exception
*/
public void addParticleMolecularWeight(String particleType,
String particleName, CharacterizationBean molecularWeight)
throws Exception {
MolecularWeight doMolecularWeight = new MolecularWeight();
molecularWeight.updateDomainObj(doMolecularWeight);
addParticleCharacterization(particleType, particleName,
doMolecularWeight, molecularWeight);
}
/**
* Saves the morphology characterization to the database
*
* @param particleType
* @param particleName
* @param morphology
* @throws Exception
*/
public void addParticleMorphology(String particleType, String particleName,
CharacterizationBean morphology) throws Exception {
Morphology doMorphology = new Morphology();
((MorphologyBean) morphology).updateDomainObj(doMorphology);
addParticleCharacterization(particleType, particleName, doMorphology,
morphology);
MorphologyType morphologyType = new MorphologyType();
addLookupType(morphologyType, doMorphology.getType());
}
/**
* Saves the shape characterization to the database
*
* @param particleType
* @param particleName
* @param shape
* @throws Exception
*/
public void addParticleShape(String particleType, String particleName,
CharacterizationBean shape) throws Exception {
Shape doShape = new Shape();
((ShapeBean) shape).updateDomainObj(doShape);
addParticleCharacterization(particleType, particleName, doShape, shape);
ShapeType shapeType = new ShapeType();
addLookupType(shapeType, doShape.getType());
}
/**
* Saves the purity characterization to the database
*
* @param particleType
* @param particleName
* @param purity
* @throws Exception
*/
public void addParticlePurity(String particleType, String particleName,
CharacterizationBean purity) throws Exception {
Purity doPurity = new Purity();
purity.updateDomainObj(doPurity);
// TODO think about how to deal with characterization file.
addParticleCharacterization(particleType, particleName, doPurity,
purity);
}
/**
* Saves the solubility characterization to the database
*
* @param particleType
* @param particleName
* @param solubility
* @throws Exception
*/
public void addParticleSolubility(String particleType, String particleName,
CharacterizationBean solubility) throws Exception {
Solubility doSolubility = new Solubility();
((SolubilityBean) solubility).updateDomainObj(doSolubility);
// TODO think about how to deal with characterization file.
addParticleCharacterization(particleType, particleName, doSolubility,
solubility);
SolventType solventType = new SolventType();
addLookupType(solventType, doSolubility.getSolvent());
MeasureUnit measureUnit = new MeasureUnit();
addMeasureUnit(measureUnit, doSolubility.getCriticalConcentration().getUnitOfMeasurement(), CaNanoLabConstants.UNIT_TYPE_CONCENTRATION);
}
/**
* Saves the invitro hemolysis characterization to the database
*
* @param particleType
* @param particleName
* @param hemolysis
* @throws Exception
*/
public void addHemolysis(String particleType, String particleName,
CharacterizationBean hemolysis) throws Exception {
Hemolysis doHemolysis = new Hemolysis();
hemolysis.updateDomainObj(doHemolysis);
// TODO think about how to deal with characterization file.
addParticleCharacterization(particleType, particleName, doHemolysis,
hemolysis);
}
/**
* Saves the invitro coagulation characterization to the database
*
* @param particleType
* @param particleName
* @param coagulation
* @throws Exception
*/
public void addCoagulation(String particleType, String particleName,
CharacterizationBean coagulation) throws Exception {
Coagulation doCoagulation = new Coagulation();
coagulation.updateDomainObj(doCoagulation);
addParticleCharacterization(particleType, particleName, doCoagulation,
coagulation);
}
/**
* Saves the invitro plate aggregation characterization to the database
*
* @param particleType
* @param particleName
* @param plateletAggregation
* @throws Exception
*/
public void addPlateletAggregation(String particleType,
String particleName, CharacterizationBean plateletAggregation)
throws Exception {
PlateletAggregation doPlateletAggregation = new PlateletAggregation();
plateletAggregation.updateDomainObj(doPlateletAggregation);
addParticleCharacterization(particleType, particleName,
doPlateletAggregation, plateletAggregation);
}
/**
* Saves the invitro Complement Activation characterization to the database
*
* @param particleType
* @param particleName
* @param complementActivation
* @throws Exception
*/
public void addComplementActivation(String particleType,
String particleName, CharacterizationBean complementActivation)
throws Exception {
ComplementActivation doComplementActivation = new ComplementActivation();
complementActivation.updateDomainObj(doComplementActivation);
addParticleCharacterization(particleType, particleName,
doComplementActivation, complementActivation);
}
/**
* Saves the invitro chemotaxis characterization to the database
*
* @param particleType
* @param particleName
* @param chemotaxis
* @throws Exception
*/
public void addChemotaxis(String particleType, String particleName,
CharacterizationBean chemotaxis) throws Exception {
Chemotaxis doChemotaxis = new Chemotaxis();
chemotaxis.updateDomainObj(doChemotaxis);
addParticleCharacterization(particleType, particleName, doChemotaxis,
chemotaxis);
}
/**
* Saves the invitro NKCellCytotoxicActivity characterization to the
* database
*
* @param particleType
* @param particleName
* @param nkCellCytotoxicActivity
* @throws Exception
*/
public void addNKCellCytotoxicActivity(String particleType,
String particleName, CharacterizationBean nkCellCytotoxicActivity)
throws Exception {
NKCellCytotoxicActivity doNKCellCytotoxicActivity = new NKCellCytotoxicActivity();
nkCellCytotoxicActivity.updateDomainObj(doNKCellCytotoxicActivity);
addParticleCharacterization(particleType, particleName,
doNKCellCytotoxicActivity, nkCellCytotoxicActivity);
}
/**
* Saves the invitro LeukocyteProliferation characterization to the database
*
* @param particleType
* @param particleName
* @param leukocyteProliferation
* @throws Exception
*/
public void addLeukocyteProliferation(String particleType,
String particleName, CharacterizationBean leukocyteProliferation)
throws Exception {
LeukocyteProliferation doLeukocyteProliferation = new LeukocyteProliferation();
leukocyteProliferation.updateDomainObj(doLeukocyteProliferation);
addParticleCharacterization(particleType, particleName,
doLeukocyteProliferation, leukocyteProliferation);
}
/**
* Saves the invitro CFU_GM characterization to the database
*
* @param particleType
* @param particleName
* @param cfu_gm
* @throws Exception
*/
public void addCFU_GM(String particleType, String particleName,
CharacterizationBean cfu_gm) throws Exception {
CFU_GM doCFU_GM = new CFU_GM();
cfu_gm.updateDomainObj(doCFU_GM);
addParticleCharacterization(particleType, particleName, doCFU_GM,
cfu_gm);
}
/**
* Saves the invitro OxidativeBurst characterization to the database
*
* @param particleType
* @param particleName
* @param oxidativeBurst
* @throws Exception
*/
public void addOxidativeBurst(String particleType, String particleName,
CharacterizationBean oxidativeBurst) throws Exception {
OxidativeBurst doOxidativeBurst = new OxidativeBurst();
oxidativeBurst.updateDomainObj(doOxidativeBurst);
addParticleCharacterization(particleType, particleName,
doOxidativeBurst, oxidativeBurst);
}
/**
* Saves the invitro Phagocytosis characterization to the database
*
* @param particleType
* @param particleName
* @param phagocytosis
* @throws Exception
*/
public void addPhagocytosis(String particleType, String particleName,
CharacterizationBean phagocytosis) throws Exception {
Phagocytosis doPhagocytosis = new Phagocytosis();
phagocytosis.updateDomainObj(doPhagocytosis);
addParticleCharacterization(particleType, particleName, doPhagocytosis,
phagocytosis);
}
/**
* Saves the invitro CytokineInduction characterization to the database
*
* @param particleType
* @param particleName
* @param cytokineInduction
* @throws Exception
*/
public void addCytokineInduction(String particleType, String particleName,
CharacterizationBean cytokineInduction) throws Exception {
CytokineInduction doCytokineInduction = new CytokineInduction();
cytokineInduction.updateDomainObj(doCytokineInduction);
addParticleCharacterization(particleType, particleName,
doCytokineInduction, cytokineInduction);
}
/**
* Saves the invitro plasma protein binding characterization to the database
*
* @param particleType
* @param particleName
* @param plasmaProteinBinding
* @throws Exception
*/
public void addProteinBinding(String particleType, String particleName,
CharacterizationBean plasmaProteinBinding) throws Exception {
PlasmaProteinBinding doProteinBinding = new PlasmaProteinBinding();
plasmaProteinBinding.updateDomainObj(doProteinBinding);
addParticleCharacterization(particleType, particleName,
doProteinBinding, plasmaProteinBinding);
}
/**
* Saves the invitro binding characterization to the database
*
* @param particleType
* @param particleName
* @param cellViability
* @throws Exception
*/
public void addCellViability(String particleType, String particleName,
CharacterizationBean cellViability) throws Exception {
CellViability doCellViability = new CellViability();
((CytotoxicityBean) cellViability).updateDomainObj(doCellViability);
addParticleCharacterization(particleType, particleName,
doCellViability, cellViability);
CellLineType cellLineType = new CellLineType();
addLookupType(cellLineType, doCellViability.getCellLine());
}
/**
* Saves the invitro EnzymeInduction binding characterization to the
* database
*
* @param particleType
* @param particleName
* @param enzymeInduction
* @throws Exception
*/
public void addEnzymeInduction(String particleType, String particleName,
CharacterizationBean enzymeInduction) throws Exception {
EnzymeInduction doEnzymeInduction = new EnzymeInduction();
enzymeInduction.updateDomainObj(doEnzymeInduction);
addParticleCharacterization(particleType, particleName,
doEnzymeInduction, enzymeInduction);
}
/**
* Saves the invitro OxidativeStress characterization to the database
*
* @param particleType
* @param particleName
* @param oxidativeStress
* @throws Exception
*/
public void addOxidativeStress(String particleType, String particleName,
CharacterizationBean oxidativeStress) throws Exception {
OxidativeStress doOxidativeStress = new OxidativeStress();
oxidativeStress.updateDomainObj(doOxidativeStress);
addParticleCharacterization(particleType, particleName,
doOxidativeStress, oxidativeStress);
}
/**
* Saves the invitro Caspase3Activation characterization to the database
*
* @param particleType
* @param particleName
* @param caspase3Activation
* @throws Exception
*/
public void addCaspase3Activation(String particleType, String particleName,
CharacterizationBean caspase3Activation) throws Exception {
Caspase3Activation doCaspase3Activation = new Caspase3Activation();
caspase3Activation.updateDomainObj(doCaspase3Activation);
addParticleCharacterization(particleType, particleName,
doCaspase3Activation, caspase3Activation);
CellLineType cellLineType = new CellLineType();
addLookupType(cellLineType, doCaspase3Activation.getCellLine());
}
public void setCharacterizationFile(String particleName,
String characterizationName, LabFileBean fileBean) {
}
public void addParticleFunction(String particleType, String particleName,
FunctionBean function) throws Exception {
Function doFunction = function.getDomainObj();
// if ID is not set save to the database otherwise update
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
Nanoparticle particle = null;
int existingViewTitleCount = -1;
try {
// Have to seperate this section out in a different hibernate
// session.
// check linkage id object type
ida.open();
if (doFunction.getId() != null
&& doFunction.getLinkageCollection() != null) {
for (Linkage linkage : doFunction.getLinkageCollection()) {
// check linkage id object type
if (linkage.getId() != null) {
List result = ida
.search("from Linkage linkage where linkage.id = "
+ linkage.getId());
if (result != null && result.size() > 0) {
Linkage existingObj = (Linkage) result.get(0);
// the the type is different,
if (existingObj.getClass() != linkage.getClass()) {
linkage.setId(null);
ida.removeObject(existingObj);
}
}
}
}
}
ida.close();
ida.open();
if (doFunction.getLinkageCollection() != null) {
for (Linkage linkage : doFunction.getLinkageCollection()) {
Agent agent = linkage.getAgent();
if (agent != null) {
for (AgentTarget agentTarget : agent
.getAgentTargetCollection()) {
ida.store(agentTarget);
}
ida.store(agent);
}
ida.store(linkage);
}
}
boolean viewTitleUsed = isFunctionViewTitleUsed(ida, particleType,
particleName, doFunction);
if (!viewTitleUsed) {
if (doFunction.getId() != null) {
ida.store(doFunction);
} else {// get the existing particle and compositions
// from database created during sample creation
List results = ida
.search("select particle from Nanoparticle particle left join fetch particle.functionCollection where particle.name='"
+ particleName
+ "' and particle.type='"
+ particleType + "'");
for (Object obj : results) {
particle = (Nanoparticle) obj;
}
if (particle != null) {
particle.getFunctionCollection().add(doFunction);
}
}
}
} catch (Exception e) {
e.printStackTrace();
ida.rollback();
logger.error("Problem saving characterization: ");
throw e;
} finally {
ida.close();
}
if (existingViewTitleCount > 0) {
throw new CalabException(
"The view title is already in use. Please enter a different one.");
}
}
/*
* check if viewTitle is already used the same type of function for the same
* particle
*/
private boolean isFunctionViewTitleUsed(IDataAccess ida,
String particleType, String particleName, Function function)
throws Exception {
// check if viewTitle is already used the same type of
// function for the same particle
String viewTitleQuery = "";
if (function.getId() == null) {
viewTitleQuery = "select count(function.identificationName) from Nanoparticle particle join particle.functionCollection function where particle.name='"
+ particleName
+ "' and particle.type='"
+ particleType
+ "' and function.identificationName='"
+ function.getIdentificationName()
+ "' and function.type='" + function.getType() + "'";
} else {
viewTitleQuery = "select count(function.identificationName) from Nanoparticle particle join particle.functionCollection function where particle.name='"
+ particleName
+ "' and particle.type='"
+ particleType
+ "' and function.identificationName='"
+ function.getIdentificationName()
+ "' and function.id!="
+ function.getId()
+ " and function.type='"
+ function.getType() + "'";
}
List viewTitleResult = ida.search(viewTitleQuery);
int existingViewTitleCount = -1;
for (Object obj : viewTitleResult) {
existingViewTitleCount = ((Integer) (obj)).intValue();
}
if (existingViewTitleCount > 0) {
return true;
} else {
return false;
}
}
/**
* Load the file for the given fileId from the database
*
* @param fileId
* @return
*/
public LabFileBean getFile(String fileId) throws Exception {
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
LabFileBean fileBean = null;
try {
ida.open();
LabFile file = (LabFile) ida.load(LabFile.class, StringUtils
.convertToLong(fileId));
fileBean = new LabFileBean(file);
} catch (Exception e) {
e.printStackTrace();
ida.rollback();
logger.error("Problem getting file with file ID: " + fileId);
throw e;
} finally {
ida.close();
}
// get visibilities
UserService userService = new UserService(
CaNanoLabConstants.CSM_APP_NAME);
List<String> accessibleGroups = userService.getAccessibleGroups(
fileBean.getId(), CaNanoLabConstants.CSM_READ_ROLE);
String[] visibilityGroups = accessibleGroups.toArray(new String[0]);
fileBean.setVisibilityGroups(visibilityGroups);
return fileBean;
}
/**
* Load the derived data file for the given fileId from the database
*
* @param fileId
* @return
*/
public DerivedBioAssayDataBean getDerivedBioAssayData(String fileId)
throws Exception {
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
DerivedBioAssayDataBean fileBean = null;
try {
ida.open();
DerivedBioAssayData file = (DerivedBioAssayData) ida.load(
DerivedBioAssayData.class, StringUtils
.convertToLong(fileId));
// load keywords
file.getKeywordCollection();
fileBean = new DerivedBioAssayDataBean(file,
CaNanoLabConstants.OUTPUT);
} catch (Exception e) {
e.printStackTrace();
ida.rollback();
logger.error("Problem getting file with file ID: " + fileId);
throw e;
} finally {
ida.close();
}
// get visibilities
UserService userService = new UserService(
CaNanoLabConstants.CSM_APP_NAME);
List<String> accessibleGroups = userService.getAccessibleGroups(
fileBean.getId(), CaNanoLabConstants.CSM_READ_ROLE);
String[] visibilityGroups = accessibleGroups.toArray(new String[0]);
fileBean.setVisibilityGroups(visibilityGroups);
return fileBean;
}
/**
* Get the list of all run output files associated with a particle
*
* @param particleName
* @return
* @throws Exception
*/
public List<LabFileBean> getAllRunFiles(String particleName)
throws Exception {
List<LabFileBean> runFiles = new ArrayList<LabFileBean>();
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
String query = "select distinct outFile from Run run join run.outputFileCollection outFile join run.runSampleContainerCollection runContainer where runContainer.sampleContainer.sample.name='"
+ particleName + "'";
List results = ida.search(query);
for (Object obj : results) {
OutputFile file = (OutputFile) obj;
// active status only
if (file.getDataStatus() == null) {
LabFileBean fileBean = new LabFileBean();
fileBean.setId(file.getId().toString());
fileBean.setName(file.getFilename());
fileBean.setUri(file.getUri());
runFiles.add(fileBean);
}
}
} catch (Exception e) {
e.printStackTrace();
ida.rollback();
logger.error("Problem getting run files for particle: "
+ particleName);
throw e;
} finally {
ida.close();
}
return runFiles;
}
/**
* Update the meta data associated with a file stored in the database
*
* @param fileBean
* @throws Exception
*/
public void updateFileMetaData(LabFileBean fileBean) throws Exception {
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
LabFile file = (LabFile) ida.load(LabFile.class, StringUtils
.convertToLong(fileBean.getId()));
file.setTitle(fileBean.getTitle().toUpperCase());
file.setDescription(fileBean.getDescription());
file.setComments(fileBean.getComments());
} catch (Exception e) {
e.printStackTrace();
ida.rollback();
logger.error("Problem updating file meta data: ");
throw e;
} finally {
ida.close();
}
userService.setVisiblity(fileBean.getId(), fileBean
.getVisibilityGroups());
}
/**
* Update the meta data associated with a file stored in the database
*
* @param fileBean
* @throws Exception
*/
public void updateDerivedBioAssayDataMetaData(
DerivedBioAssayDataBean fileBean) throws Exception {
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
DerivedBioAssayData file = (DerivedBioAssayData) ida.load(
DerivedBioAssayData.class, StringUtils
.convertToLong(fileBean.getId()));
file.setTitle(fileBean.getTitle().toUpperCase());
file.setDescription(fileBean.getDescription());
file.getKeywordCollection().clear();
if (fileBean.getKeywords() != null) {
for (String keyword : fileBean.getKeywords()) {
Keyword keywordObj = new Keyword();
keywordObj.setName(keyword);
file.getKeywordCollection().add(keywordObj);
}
}
} catch (Exception e) {
e.printStackTrace();
ida.rollback();
logger.error("Problem updating derived data file meta data: ");
throw e;
} finally {
ida.close();
}
userService.setVisiblity(fileBean.getId(), fileBean
.getVisibilityGroups());
}
/**
* Delete the characterization
*/
public void deleteCharacterization(String strCharId) throws Exception {
// if ID is not set save to the database otherwise update
HibernateDataAccess ida = (HibernateDataAccess) (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
// Get ID
Long charId = Long.parseLong(strCharId);
Object charObj = ida.load(Characterization.class, charId);
ida.delete(charObj);
} catch (Exception e) {
e.printStackTrace();
ida.rollback();
logger.error("Problem saving characterization: ");
throw e;
} finally {
ida.close();
}
}
/**
* Delete the characterizations
*/
public void deleteCharacterizations(String particleName,
String particleType, String[] charIds) throws Exception {
// if ID is not set save to the database otherwise update
HibernateDataAccess ida = (HibernateDataAccess) (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
// Get ID
for (String strCharId : charIds) {
Long charId = Long.parseLong(strCharId);
Object charObj = ida.load(Characterization.class, charId);
// deassociate first
String hqlString = "from Nanoparticle particle where particle.characterizationCollection.id = '"
+ strCharId + "'";
List results = ida.search(hqlString);
for (Object obj : results) {
Nanoparticle particle = (Nanoparticle) obj;
particle.getCharacterizationCollection().remove(charObj);
}
// then delete
ida.delete(charObj);
}
} catch (Exception e) {
e.printStackTrace();
ida.rollback();
logger.error("Problem deleting characterization: ");
throw new Exception(
"The characterization is no longer exist in the database, please login again to refresh the view.");
} finally {
ida.close();
}
}
}
|
package gov.nih.nci.calab.service.submit;
import gov.nih.nci.calab.db.DataAccessProxy;
import gov.nih.nci.calab.db.HibernateDataAccess;
import gov.nih.nci.calab.db.IDataAccess;
import gov.nih.nci.calab.domain.Instrument;
import gov.nih.nci.calab.domain.InstrumentConfiguration;
import gov.nih.nci.calab.domain.Keyword;
import gov.nih.nci.calab.domain.LabFile;
import gov.nih.nci.calab.domain.LookupType;
import gov.nih.nci.calab.domain.MeasureType;
import gov.nih.nci.calab.domain.MeasureUnit;
import gov.nih.nci.calab.domain.OutputFile;
import gov.nih.nci.calab.domain.nano.characterization.Characterization;
import gov.nih.nci.calab.domain.nano.characterization.CharacterizationFileType;
import gov.nih.nci.calab.domain.nano.characterization.DatumName;
import gov.nih.nci.calab.domain.nano.characterization.DerivedBioAssayData;
import gov.nih.nci.calab.domain.nano.characterization.DerivedBioAssayDataCategory;
import gov.nih.nci.calab.domain.nano.characterization.invitro.CFU_GM;
import gov.nih.nci.calab.domain.nano.characterization.invitro.Caspase3Activation;
import gov.nih.nci.calab.domain.nano.characterization.invitro.CellLineType;
import gov.nih.nci.calab.domain.nano.characterization.invitro.CellViability;
import gov.nih.nci.calab.domain.nano.characterization.invitro.Chemotaxis;
import gov.nih.nci.calab.domain.nano.characterization.invitro.Coagulation;
import gov.nih.nci.calab.domain.nano.characterization.invitro.ComplementActivation;
import gov.nih.nci.calab.domain.nano.characterization.invitro.CytokineInduction;
import gov.nih.nci.calab.domain.nano.characterization.invitro.EnzymeInduction;
import gov.nih.nci.calab.domain.nano.characterization.invitro.Hemolysis;
import gov.nih.nci.calab.domain.nano.characterization.invitro.LeukocyteProliferation;
import gov.nih.nci.calab.domain.nano.characterization.invitro.NKCellCytotoxicActivity;
import gov.nih.nci.calab.domain.nano.characterization.invitro.OxidativeBurst;
import gov.nih.nci.calab.domain.nano.characterization.invitro.OxidativeStress;
import gov.nih.nci.calab.domain.nano.characterization.invitro.Phagocytosis;
import gov.nih.nci.calab.domain.nano.characterization.invitro.PlasmaProteinBinding;
import gov.nih.nci.calab.domain.nano.characterization.invitro.PlateletAggregation;
import gov.nih.nci.calab.domain.nano.characterization.physical.MolecularWeight;
import gov.nih.nci.calab.domain.nano.characterization.physical.Morphology;
import gov.nih.nci.calab.domain.nano.characterization.physical.MorphologyType;
import gov.nih.nci.calab.domain.nano.characterization.physical.Purity;
import gov.nih.nci.calab.domain.nano.characterization.physical.Shape;
import gov.nih.nci.calab.domain.nano.characterization.physical.ShapeType;
import gov.nih.nci.calab.domain.nano.characterization.physical.Size;
import gov.nih.nci.calab.domain.nano.characterization.physical.Solubility;
import gov.nih.nci.calab.domain.nano.characterization.physical.SolventType;
import gov.nih.nci.calab.domain.nano.characterization.physical.Surface;
import gov.nih.nci.calab.domain.nano.characterization.physical.composition.ParticleComposition;
import gov.nih.nci.calab.domain.nano.function.Agent;
import gov.nih.nci.calab.domain.nano.function.Attachment;
import gov.nih.nci.calab.domain.nano.function.BondType;
import gov.nih.nci.calab.domain.nano.function.Function;
import gov.nih.nci.calab.domain.nano.function.ImageContrastAgent;
import gov.nih.nci.calab.domain.nano.function.ImageContrastAgentType;
import gov.nih.nci.calab.domain.nano.function.Linkage;
import gov.nih.nci.calab.domain.nano.particle.Nanoparticle;
import gov.nih.nci.calab.dto.characterization.CharacterizationBean;
import gov.nih.nci.calab.dto.characterization.DatumBean;
import gov.nih.nci.calab.dto.characterization.DerivedBioAssayDataBean;
import gov.nih.nci.calab.dto.characterization.composition.CompositionBean;
import gov.nih.nci.calab.dto.characterization.invitro.CytotoxicityBean;
import gov.nih.nci.calab.dto.characterization.physical.MorphologyBean;
import gov.nih.nci.calab.dto.characterization.physical.ShapeBean;
import gov.nih.nci.calab.dto.characterization.physical.SolubilityBean;
import gov.nih.nci.calab.dto.characterization.physical.SurfaceBean;
import gov.nih.nci.calab.dto.common.LabFileBean;
import gov.nih.nci.calab.dto.function.FunctionBean;
import gov.nih.nci.calab.exception.CalabException;
import gov.nih.nci.calab.service.common.FileService;
import gov.nih.nci.calab.service.security.UserService;
import gov.nih.nci.calab.service.util.CaNanoLabConstants;
import gov.nih.nci.calab.service.util.PropertyReader;
import gov.nih.nci.calab.service.util.StringUtils;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
/**
* This class includes service calls involved in creating nanoparticle general
* info and adding functions and characterizations for nanoparticles, as well as
* creating reports.
*
* @author pansu
*
*/
public class SubmitNanoparticleService {
private static Logger logger = Logger
.getLogger(SubmitNanoparticleService.class);
// remove existing visibilities for the data
private UserService userService;
public SubmitNanoparticleService() throws Exception {
userService = new UserService(CaNanoLabConstants.CSM_APP_NAME);
}
/**
* Update keywords and visibilities for the particle with the given name and
* type
*
* @param particleType
* @param particleName
* @param keywords
* @param visibilities
* @throws Exception
*/
public void addParticleGeneralInfo(String particleType,
String particleName, String[] keywords, String[] visibilities)
throws Exception {
// save nanoparticle to the database
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
// get the existing particle from database created during sample
// creation
List results = ida.search("from Nanoparticle where name='"
+ particleName + "' and type='" + particleType + "'");
Nanoparticle particle = null;
for (Object obj : results) {
particle = (Nanoparticle) obj;
}
if (particle == null) {
throw new CalabException("No such particle in the database");
}
particle.getKeywordCollection().clear();
if (keywords != null) {
for (String keyword : keywords) {
Keyword keywordObj = new Keyword();
keywordObj.setName(keyword);
particle.getKeywordCollection().add(keywordObj);
}
}
} catch (Exception e) {
ida.rollback();
logger
.error("Problem updating particle with name: "
+ particleName);
throw e;
} finally {
ida.close();
}
userService.setVisiblity(particleName, visibilities);
}
/**
* Save characterization to the database.
*
* @param particleType
* @param particleName
* @param achar
* @throws Exception
*/
private void addParticleCharacterization(String particleType,
String particleName, Characterization achar,
CharacterizationBean charBean) throws Exception {
// if ID is not set save to the database otherwise update
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
Nanoparticle particle = null;
try {
ida.open();
// check if viewTitle is already used the same type of
// characterization for the same particle
boolean viewTitleUsed = isCharacterizationViewTitleUsed(ida,
particleType, particleName, achar);
if (viewTitleUsed) {
throw new RuntimeException(
"The view title is already in use. Please enter a different one.");
} else {
if (achar.getInstrumentConfiguration() != null) {
addInstrumentConfig(achar.getInstrumentConfiguration(), ida);
}
// if ID exists, do update
if (achar.getId() != null) {
// check if ID is still valid
try {
Characterization storedChara = (Characterization) ida
.load(Characterization.class, achar.getId());
} catch (Exception e) {
throw new Exception(
"This characterization is no longer in the database. Please log in again to refresh.");
}
ida.store(achar);
} else {// get the existing particle and characterizations
// from database created during sample creation
List results = ida
.search("select particle from Nanoparticle particle left join fetch particle.characterizationCollection where particle.name='"
+ particleName
+ "' and particle.type='"
+ particleType + "'");
for (Object obj : results) {
particle = (Nanoparticle) obj;
}
if (particle != null) {
particle.getCharacterizationCollection().add(achar);
}
}
}
} catch (Exception e) {
e.printStackTrace();
ida.rollback();
logger.error("Problem saving characterization. ");
throw e;
} finally {
ida.close();
}
// save file to the file system
// if this block of code is inside the db try catch block, hibernate
// doesn't persist derivedBioAssayData
if (!achar.getDerivedBioAssayDataCollection().isEmpty()) {
int count = 0;
for (DerivedBioAssayData derivedBioAssayData : achar
.getDerivedBioAssayDataCollection()) {
DerivedBioAssayDataBean derivedBioAssayDataBean = new DerivedBioAssayDataBean(
derivedBioAssayData);
// assign visibility
DerivedBioAssayDataBean unsaved = charBean
.getDerivedBioAssayDataList().get(count);
derivedBioAssayDataBean.setVisibilityGroups(unsaved
.getVisibilityGroups());
saveCharacterizationFile(derivedBioAssayDataBean);
count++;
}
}
}
public void addNewCharacterizationDataDropdowns(
CharacterizationBean charBean, String characterizationName)
throws Exception {
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
if (!charBean.getDerivedBioAssayDataList().isEmpty()) {
for (DerivedBioAssayDataBean derivedBioAssayDataBean : charBean
.getDerivedBioAssayDataList()) {
// add new characterization file type if necessary
if (derivedBioAssayDataBean.getType().length() > 0) {
CharacterizationFileType fileType = new CharacterizationFileType();
addLookupType(ida, fileType, derivedBioAssayDataBean
.getType());
}
// add new derived data cateory
for (String category : derivedBioAssayDataBean
.getCategories()) {
addDerivedDataCategory(ida, category,
characterizationName);
}
// add new datum name, measure type, and unit
for (DatumBean datumBean : derivedBioAssayDataBean
.getDatumList()) {
addDatumName(ida, datumBean.getName(),
characterizationName);
MeasureType measureType = new MeasureType();
addLookupType(ida, measureType, datumBean
.getStatisticsType());
addMeasureUnit(ida, datumBean.getUnit(),
characterizationName);
}
}
}
} catch (Exception e) {
e.printStackTrace();
ida.rollback();
logger.error("Problem saving characterization data drop downs. ");
throw e;
} finally {
ida.close();
}
}
/*
* check if viewTitle is already used the same type of characterization for
* the same particle
*/
private boolean isCharacterizationViewTitleUsed(IDataAccess ida,
String particleType, String particleName, Characterization achar)
throws Exception {
String viewTitleQuery = "";
if (achar.getId() == null) {
viewTitleQuery = "select count(achar.identificationName) from Nanoparticle particle join particle.characterizationCollection achar where particle.name='"
+ particleName
+ "' and particle.type='"
+ particleType
+ "' and achar.identificationName='"
+ achar.getIdentificationName()
+ "' and achar.name='"
+ achar.getName() + "'";
} else {
viewTitleQuery = "select count(achar.identificationName) from Nanoparticle particle join particle.characterizationCollection achar where particle.name='"
+ particleName
+ "' and particle.type='"
+ particleType
+ "' and achar.identificationName='"
+ achar.getIdentificationName()
+ "' and achar.name='"
+ achar.getName() + "' and achar.id!=" + achar.getId();
}
List viewTitleResult = ida.search(viewTitleQuery);
int existingViewTitleCount = -1;
for (Object obj : viewTitleResult) {
existingViewTitleCount = ((Integer) (obj)).intValue();
}
if (existingViewTitleCount > 0) {
return true;
} else {
return false;
}
}
/**
* Save the file to the file system
*
* @param fileBean
*/
public void saveCharacterizationFile(DerivedBioAssayDataBean fileBean)
throws Exception {
byte[] fileContent = fileBean.getFileContent();
String rootPath = PropertyReader.getProperty(
CaNanoLabConstants.FILEUPLOAD_PROPERTY, "fileRepositoryDir");
if (fileContent != null) {
FileService fileService = new FileService();
fileService.writeFile(fileContent, rootPath + File.separator
+ fileBean.getUri());
}
userService.setVisiblity(fileBean.getId(), fileBean
.getVisibilityGroups());
}
private void addInstrumentConfig(InstrumentConfiguration instrumentConfig,
IDataAccess ida) throws Exception {
Instrument instrument = instrumentConfig.getInstrument();
// check if instrument is already in database
List instrumentResults = ida
.search("select instrument from Instrument instrument where instrument.type='"
+ instrument.getType()
+ "' and instrument.manufacturer='"
+ instrument.getManufacturer() + "'");
Instrument storedInstrument = null;
for (Object obj : instrumentResults) {
storedInstrument = (Instrument) obj;
}
if (storedInstrument != null) {
instrument.setId(storedInstrument.getId());
} else {
ida.createObject(instrument);
}
// if new instrumentConfig, save it
if (instrumentConfig.getId() == null) {
ida.createObject(instrumentConfig);
} else {
InstrumentConfiguration storedInstrumentConfig = (InstrumentConfiguration) ida
.load(InstrumentConfiguration.class, instrumentConfig
.getId());
storedInstrumentConfig.setDescription(instrumentConfig
.getDescription());
storedInstrumentConfig.setInstrument(instrument);
}
}
/**
* Saves the particle composition to the database
*
* @param particleType
* @param particleName
* @param composition
* @throws Exception
*/
public void addParticleComposition(String particleType,
String particleName, CompositionBean composition) throws Exception {
ParticleComposition doComp = composition.getDomainObj();
addParticleCharacterization(particleType, particleName, doComp,
composition);
}
/**
* O Saves the size characterization to the database
*
* @param particleType
* @param particleName
* @param size
* @throws Exception
*/
public void addParticleSize(String particleType, String particleName,
CharacterizationBean size) throws Exception {
Size doSize = new Size();
size.updateDomainObj(doSize);
addParticleCharacterization(particleType, particleName, doSize, size);
}
/**
* Saves the size characterization to the database
*
* @param particleType
* @param particleName
* @param surface
* @throws Exception
*/
public void addParticleSurface(String particleType, String particleName,
CharacterizationBean surface) throws Exception {
Surface doSurface = new Surface();
((SurfaceBean) surface).updateDomainObj(doSurface);
addParticleCharacterization(particleType, particleName, doSurface,
surface);
// addMeasureUnit(doSurface.getCharge().getUnitOfMeasurement(),
// CaNanoLabConstants.UNIT_TYPE_CHARGE);
// addMeasureUnit(doSurface.getSurfaceArea().getUnitOfMeasurement(),
// CaNanoLabConstants.UNIT_TYPE_AREA);
// addMeasureUnit(doSurface.getZetaPotential().getUnitOfMeasurement(),
// CaNanoLabConstants.UNIT_TYPE_ZETA_POTENTIAL);
}
private void addLookupType(IDataAccess ida, LookupType lookupType,
String type) throws Exception {
String className = lookupType.getClass().getSimpleName();
if (type != null && type.length() > 0) {
List results = ida.search("select count(distinct name) from "
+ className + " type where name='" + type + "'");
lookupType.setName(type);
int count = -1;
for (Object obj : results) {
count = ((Integer) (obj)).intValue();
}
if (count == 0) {
ida.createObject(lookupType);
}
}
}
private void addDatumName(IDataAccess ida, String name,
String characterizationName) throws Exception {
List results = ida.search("select count(distinct name) from DatumName"
+ " where characterizationName='" + characterizationName + "'"
+ " and name='" + name + "'");
DatumName datumName = new DatumName();
datumName.setName(name);
datumName.setCharacterizationName(characterizationName);
datumName.setDatumParsed(false);
int count = -1;
for (Object obj : results) {
count = ((Integer) (obj)).intValue();
}
if (count == 0) {
ida.createObject(datumName);
}
}
private void addDerivedDataCategory(IDataAccess ida, String name,
String characterizationName) throws Exception {
List results = ida
.search("select count(distinct name) from DerivedBioAssayDataCategory"
+ " where characterizationName='"
+ characterizationName
+ "'"
+ " and name='"
+ name
+ "'");
DerivedBioAssayDataCategory category = new DerivedBioAssayDataCategory();
category.setName(name);
category.setCharacterizationName(characterizationName);
int count = -1;
for (Object obj : results) {
count = ((Integer) (obj)).intValue();
}
if (count == 0) {
ida.createObject(category);
}
}
private void addLookupType(LookupType lookupType, String type)
throws Exception {
if (type != null && type.length() > 0) {
// if ID is not set save to the database otherwise update
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
String className = lookupType.getClass().getSimpleName();
try {
ida.open();
List results = ida.search("select count(distinct name) from "
+ className + " type where name='" + type + "'");
lookupType.setName(type);
int count = -1;
for (Object obj : results) {
count = ((Integer) (obj)).intValue();
}
if (count == 0) {
ida.createObject(lookupType);
}
} catch (Exception e) {
e.printStackTrace();
ida.rollback();
logger.error("Problem saving look up type: " + type);
throw e;
} finally {
ida.close();
}
}
}
// private void addMeasureUnit(String unit, String type) throws Exception {
// if (unit == null || unit.length() == 0) {
// return;
// // if ID is not set save to the database otherwise update
// IDataAccess ida = (new DataAccessProxy())
// .getInstance(IDataAccess.HIBERNATE);
// MeasureUnit measureUnit = new MeasureUnit();
// try {
// ida.open();
// List results = ida
// .search("select count(distinct measureUnit.name) from "
// + "MeasureUnit measureUnit where measureUnit.name='"
// + unit + "' and measureUnit.type='" + type + "'");
// int count = -1;
// for (Object obj : results) {
// count = ((Integer) (obj)).intValue();
// if (count == 0) {
// measureUnit.setName(unit);
// measureUnit.setType(type);
// ida.createObject(measureUnit);
// } catch (Exception e) {
// e.printStackTrace();
// ida.rollback();
// logger.error("Problem saving look up type: " + type);
// throw e;
// } finally {
// ida.close();
private void addMeasureUnit(IDataAccess ida, String unit, String type)
throws Exception {
if (unit == null || unit.length() == 0) {
return;
}
List results = ida.search("select count(distinct name) from "
+ " MeasureUnit where name='" + unit + "' and type='" + type
+ "'");
int count = -1;
for (Object obj : results) {
count = ((Integer) (obj)).intValue();
}
MeasureUnit measureUnit = new MeasureUnit();
if (count == 0) {
measureUnit.setName(unit);
measureUnit.setType(type);
ida.createObject(measureUnit);
}
}
/**
* Saves the molecular weight characterization to the database
*
* @param particleType
* @param particleName
* @param molecularWeight
* @throws Exception
*/
public void addParticleMolecularWeight(String particleType,
String particleName, CharacterizationBean molecularWeight)
throws Exception {
MolecularWeight doMolecularWeight = new MolecularWeight();
molecularWeight.updateDomainObj(doMolecularWeight);
addParticleCharacterization(particleType, particleName,
doMolecularWeight, molecularWeight);
}
/**
* Saves the morphology characterization to the database
*
* @param particleType
* @param particleName
* @param morphology
* @throws Exception
*/
public void addParticleMorphology(String particleType, String particleName,
CharacterizationBean morphology) throws Exception {
Morphology doMorphology = new Morphology();
((MorphologyBean) morphology).updateDomainObj(doMorphology);
addParticleCharacterization(particleType, particleName, doMorphology,
morphology);
MorphologyType morphologyType = new MorphologyType();
addLookupType(morphologyType, doMorphology.getType());
}
/**
* Saves the shape characterization to the database
*
* @param particleType
* @param particleName
* @param shape
* @throws Exception
*/
public void addParticleShape(String particleType, String particleName,
CharacterizationBean shape) throws Exception {
Shape doShape = new Shape();
((ShapeBean) shape).updateDomainObj(doShape);
addParticleCharacterization(particleType, particleName, doShape, shape);
ShapeType shapeType = new ShapeType();
addLookupType(shapeType, doShape.getType());
}
/**
* Saves the purity characterization to the database
*
* @param particleType
* @param particleName
* @param purity
* @throws Exception
*/
public void addParticlePurity(String particleType, String particleName,
CharacterizationBean purity) throws Exception {
Purity doPurity = new Purity();
purity.updateDomainObj(doPurity);
// TODO think about how to deal with characterization file.
addParticleCharacterization(particleType, particleName, doPurity,
purity);
}
/**
* Saves the solubility characterization to the database
*
* @param particleType
* @param particleName
* @param solubility
* @throws Exception
*/
public void addParticleSolubility(String particleType, String particleName,
CharacterizationBean solubility) throws Exception {
Solubility doSolubility = new Solubility();
((SolubilityBean) solubility).updateDomainObj(doSolubility);
// TODO think about how to deal with characterization file.
addParticleCharacterization(particleType, particleName, doSolubility,
solubility);
SolventType solventType = new SolventType();
addLookupType(solventType, doSolubility.getSolvent());
// addMeasureUnit(doSolubility.getCriticalConcentration()
// .getUnitOfMeasurement(),
// CaNanoLabConstants.UNIT_TYPE_CONCENTRATION);
}
/**
* Saves the invitro hemolysis characterization to the database
*
* @param particleType
* @param particleName
* @param hemolysis
* @throws Exception
*/
public void addHemolysis(String particleType, String particleName,
CharacterizationBean hemolysis) throws Exception {
Hemolysis doHemolysis = new Hemolysis();
hemolysis.updateDomainObj(doHemolysis);
// TODO think about how to deal with characterization file.
addParticleCharacterization(particleType, particleName, doHemolysis,
hemolysis);
}
/**
* Saves the invitro coagulation characterization to the database
*
* @param particleType
* @param particleName
* @param coagulation
* @throws Exception
*/
public void addCoagulation(String particleType, String particleName,
CharacterizationBean coagulation) throws Exception {
Coagulation doCoagulation = new Coagulation();
coagulation.updateDomainObj(doCoagulation);
addParticleCharacterization(particleType, particleName, doCoagulation,
coagulation);
}
/**
* Saves the invitro plate aggregation characterization to the database
*
* @param particleType
* @param particleName
* @param plateletAggregation
* @throws Exception
*/
public void addPlateletAggregation(String particleType,
String particleName, CharacterizationBean plateletAggregation)
throws Exception {
PlateletAggregation doPlateletAggregation = new PlateletAggregation();
plateletAggregation.updateDomainObj(doPlateletAggregation);
addParticleCharacterization(particleType, particleName,
doPlateletAggregation, plateletAggregation);
}
/**
* Saves the invitro Complement Activation characterization to the database
*
* @param particleType
* @param particleName
* @param complementActivation
* @throws Exception
*/
public void addComplementActivation(String particleType,
String particleName, CharacterizationBean complementActivation)
throws Exception {
ComplementActivation doComplementActivation = new ComplementActivation();
complementActivation.updateDomainObj(doComplementActivation);
addParticleCharacterization(particleType, particleName,
doComplementActivation, complementActivation);
}
/**
* Saves the invitro chemotaxis characterization to the database
*
* @param particleType
* @param particleName
* @param chemotaxis
* @throws Exception
*/
public void addChemotaxis(String particleType, String particleName,
CharacterizationBean chemotaxis) throws Exception {
Chemotaxis doChemotaxis = new Chemotaxis();
chemotaxis.updateDomainObj(doChemotaxis);
addParticleCharacterization(particleType, particleName, doChemotaxis,
chemotaxis);
}
/**
* Saves the invitro NKCellCytotoxicActivity characterization to the
* database
*
* @param particleType
* @param particleName
* @param nkCellCytotoxicActivity
* @throws Exception
*/
public void addNKCellCytotoxicActivity(String particleType,
String particleName, CharacterizationBean nkCellCytotoxicActivity)
throws Exception {
NKCellCytotoxicActivity doNKCellCytotoxicActivity = new NKCellCytotoxicActivity();
nkCellCytotoxicActivity.updateDomainObj(doNKCellCytotoxicActivity);
addParticleCharacterization(particleType, particleName,
doNKCellCytotoxicActivity, nkCellCytotoxicActivity);
}
/**
* Saves the invitro LeukocyteProliferation characterization to the database
*
* @param particleType
* @param particleName
* @param leukocyteProliferation
* @throws Exception
*/
public void addLeukocyteProliferation(String particleType,
String particleName, CharacterizationBean leukocyteProliferation)
throws Exception {
LeukocyteProliferation doLeukocyteProliferation = new LeukocyteProliferation();
leukocyteProliferation.updateDomainObj(doLeukocyteProliferation);
addParticleCharacterization(particleType, particleName,
doLeukocyteProliferation, leukocyteProliferation);
}
/**
* Saves the invitro CFU_GM characterization to the database
*
* @param particleType
* @param particleName
* @param cfu_gm
* @throws Exception
*/
public void addCFU_GM(String particleType, String particleName,
CharacterizationBean cfu_gm) throws Exception {
CFU_GM doCFU_GM = new CFU_GM();
cfu_gm.updateDomainObj(doCFU_GM);
addParticleCharacterization(particleType, particleName, doCFU_GM,
cfu_gm);
}
/**
* Saves the invitro OxidativeBurst characterization to the database
*
* @param particleType
* @param particleName
* @param oxidativeBurst
* @throws Exception
*/
public void addOxidativeBurst(String particleType, String particleName,
CharacterizationBean oxidativeBurst) throws Exception {
OxidativeBurst doOxidativeBurst = new OxidativeBurst();
oxidativeBurst.updateDomainObj(doOxidativeBurst);
addParticleCharacterization(particleType, particleName,
doOxidativeBurst, oxidativeBurst);
}
/**
* Saves the invitro Phagocytosis characterization to the database
*
* @param particleType
* @param particleName
* @param phagocytosis
* @throws Exception
*/
public void addPhagocytosis(String particleType, String particleName,
CharacterizationBean phagocytosis) throws Exception {
Phagocytosis doPhagocytosis = new Phagocytosis();
phagocytosis.updateDomainObj(doPhagocytosis);
addParticleCharacterization(particleType, particleName, doPhagocytosis,
phagocytosis);
}
/**
* Saves the invitro CytokineInduction characterization to the database
*
* @param particleType
* @param particleName
* @param cytokineInduction
* @throws Exception
*/
public void addCytokineInduction(String particleType, String particleName,
CharacterizationBean cytokineInduction) throws Exception {
CytokineInduction doCytokineInduction = new CytokineInduction();
cytokineInduction.updateDomainObj(doCytokineInduction);
addParticleCharacterization(particleType, particleName,
doCytokineInduction, cytokineInduction);
}
/**
* Saves the invitro plasma protein binding characterization to the database
*
* @param particleType
* @param particleName
* @param plasmaProteinBinding
* @throws Exception
*/
public void addProteinBinding(String particleType, String particleName,
CharacterizationBean plasmaProteinBinding) throws Exception {
PlasmaProteinBinding doProteinBinding = new PlasmaProteinBinding();
plasmaProteinBinding.updateDomainObj(doProteinBinding);
addParticleCharacterization(particleType, particleName,
doProteinBinding, plasmaProteinBinding);
}
/**
* Saves the invitro binding characterization to the database
*
* @param particleType
* @param particleName
* @param cellViability
* @throws Exception
*/
public void addCellViability(String particleType, String particleName,
CharacterizationBean cellViability) throws Exception {
CellViability doCellViability = new CellViability();
((CytotoxicityBean) cellViability).updateDomainObj(doCellViability);
addParticleCharacterization(particleType, particleName,
doCellViability, cellViability);
CellLineType cellLineType = new CellLineType();
addLookupType(cellLineType, doCellViability.getCellLine());
}
/**
* Saves the invitro EnzymeInduction binding characterization to the
* database
*
* @param particleType
* @param particleName
* @param enzymeInduction
* @throws Exception
*/
public void addEnzymeInduction(String particleType, String particleName,
CharacterizationBean enzymeInduction) throws Exception {
EnzymeInduction doEnzymeInduction = new EnzymeInduction();
enzymeInduction.updateDomainObj(doEnzymeInduction);
addParticleCharacterization(particleType, particleName,
doEnzymeInduction, enzymeInduction);
}
/**
* Saves the invitro OxidativeStress characterization to the database
*
* @param particleType
* @param particleName
* @param oxidativeStress
* @throws Exception
*/
public void addOxidativeStress(String particleType, String particleName,
CharacterizationBean oxidativeStress) throws Exception {
OxidativeStress doOxidativeStress = new OxidativeStress();
oxidativeStress.updateDomainObj(doOxidativeStress);
addParticleCharacterization(particleType, particleName,
doOxidativeStress, oxidativeStress);
}
/**
* Saves the invitro Caspase3Activation characterization to the database
*
* @param particleType
* @param particleName
* @param caspase3Activation
* @throws Exception
*/
public void addCaspase3Activation(String particleType, String particleName,
CharacterizationBean caspase3Activation) throws Exception {
Caspase3Activation doCaspase3Activation = new Caspase3Activation();
caspase3Activation.updateDomainObj(doCaspase3Activation);
addParticleCharacterization(particleType, particleName,
doCaspase3Activation, caspase3Activation);
CellLineType cellLineType = new CellLineType();
addLookupType(cellLineType, doCaspase3Activation.getCellLine());
}
public void setCharacterizationFile(String particleName,
String characterizationName, LabFileBean fileBean) {
}
public void addParticleFunction(String particleType, String particleName,
FunctionBean function) throws Exception {
// if ID is not set save to the database otherwise update
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
Nanoparticle particle = null;
Function doFunction = new Function();
try {
ida.open();
boolean viewTitleUsed = isFunctionViewTitleUsed(ida, particleType,
particleName, doFunction);
if (viewTitleUsed) {
throw new RuntimeException(
"The view title is already in use. Please enter a different one.");
} else {
// if function already exists in the database
if (function.getId() != null) {
doFunction = (Function) ida.get(Function.class, new Long(
function.getId()));
function.updateDomainObj(doFunction);
} else {
function.updateDomainObj(doFunction);
List results = ida
.search("select particle from Nanoparticle particle left join fetch particle.functionCollection where particle.name='"
+ particleName
+ "' and particle.type='"
+ particleType + "'");
for (Object obj : results) {
particle = (Nanoparticle) obj;
}
if (particle != null) {
particle.getFunctionCollection().add(doFunction);
}
}
}
// persist bondType and image contrast agent type drop-down
for (Linkage linkage : doFunction.getLinkageCollection()) {
if (linkage instanceof Attachment) {
String bondType = ((Attachment) linkage).getBondType();
BondType lookup = new BondType();
addLookupType(ida, lookup, bondType);
}
Agent agent = linkage.getAgent();
if (agent instanceof ImageContrastAgent) {
String agentType = ((ImageContrastAgent) agent).getType();
ImageContrastAgentType lookup = new ImageContrastAgentType();
addLookupType(ida, lookup, agentType);
}
}
} catch (Exception e) {
e.printStackTrace();
ida.rollback();
logger.error("Problem saving function: ");
throw e;
} finally {
ida.close();
}
}
/*
* check if viewTitle is already used the same type of function for the same
* particle
*/
private boolean isFunctionViewTitleUsed(IDataAccess ida,
String particleType, String particleName, Function function)
throws Exception {
// check if viewTitle is already used the same type of
// function for the same particle
String viewTitleQuery = "";
if (function.getId() == null) {
viewTitleQuery = "select count(function.identificationName) from Nanoparticle particle join particle.functionCollection function where particle.name='"
+ particleName
+ "' and particle.type='"
+ particleType
+ "' and function.identificationName='"
+ function.getIdentificationName()
+ "' and function.type='" + function.getType() + "'";
} else {
viewTitleQuery = "select count(function.identificationName) from Nanoparticle particle join particle.functionCollection function where particle.name='"
+ particleName
+ "' and particle.type='"
+ particleType
+ "' and function.identificationName='"
+ function.getIdentificationName()
+ "' and function.id!="
+ function.getId()
+ " and function.type='"
+ function.getType() + "'";
}
List viewTitleResult = ida.search(viewTitleQuery);
int existingViewTitleCount = -1;
for (Object obj : viewTitleResult) {
existingViewTitleCount = ((Integer) (obj)).intValue();
}
if (existingViewTitleCount > 0) {
return true;
} else {
return false;
}
}
/**
* Load the file for the given fileId from the database
*
* @param fileId
* @return
*/
public LabFileBean getFile(String fileId) throws Exception {
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
LabFileBean fileBean = null;
try {
ida.open();
LabFile file = (LabFile) ida.load(LabFile.class, StringUtils
.convertToLong(fileId));
fileBean = new LabFileBean(file);
} catch (Exception e) {
e.printStackTrace();
ida.rollback();
logger.error("Problem getting file with file ID: " + fileId);
throw e;
} finally {
ida.close();
}
// get visibilities
UserService userService = new UserService(
CaNanoLabConstants.CSM_APP_NAME);
List<String> accessibleGroups = userService.getAccessibleGroups(
fileBean.getId(), CaNanoLabConstants.CSM_READ_ROLE);
String[] visibilityGroups = accessibleGroups.toArray(new String[0]);
fileBean.setVisibilityGroups(visibilityGroups);
return fileBean;
}
/**
* Load the derived data file for the given fileId from the database
*
* @param fileId
* @return
*/
public DerivedBioAssayDataBean getDerivedBioAssayData(String fileId)
throws Exception {
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
DerivedBioAssayDataBean fileBean = null;
try {
ida.open();
DerivedBioAssayData file = (DerivedBioAssayData) ida.load(
DerivedBioAssayData.class, StringUtils
.convertToLong(fileId));
// load keywords
file.getKeywordCollection();
fileBean = new DerivedBioAssayDataBean(file,
CaNanoLabConstants.OUTPUT);
} catch (Exception e) {
e.printStackTrace();
ida.rollback();
logger.error("Problem getting file with file ID: " + fileId);
throw e;
} finally {
ida.close();
}
// get visibilities
UserService userService = new UserService(
CaNanoLabConstants.CSM_APP_NAME);
List<String> accessibleGroups = userService.getAccessibleGroups(
fileBean.getId(), CaNanoLabConstants.CSM_READ_ROLE);
String[] visibilityGroups = accessibleGroups.toArray(new String[0]);
fileBean.setVisibilityGroups(visibilityGroups);
return fileBean;
}
/**
* Get the list of all run output files associated with a particle
*
* @param particleName
* @return
* @throws Exception
*/
public List<LabFileBean> getAllRunFiles(String particleName)
throws Exception {
List<LabFileBean> runFiles = new ArrayList<LabFileBean>();
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
String query = "select distinct outFile from Run run join run.outputFileCollection outFile join run.runSampleContainerCollection runContainer where runContainer.sampleContainer.sample.name='"
+ particleName + "'";
List results = ida.search(query);
for (Object obj : results) {
OutputFile file = (OutputFile) obj;
// active status only
if (file.getDataStatus() == null) {
LabFileBean fileBean = new LabFileBean();
fileBean.setId(file.getId().toString());
fileBean.setName(file.getFilename());
fileBean.setUri(file.getUri());
runFiles.add(fileBean);
}
}
} catch (Exception e) {
e.printStackTrace();
ida.rollback();
logger.error("Problem getting run files for particle: "
+ particleName);
throw e;
} finally {
ida.close();
}
return runFiles;
}
/**
* Update the meta data associated with a file stored in the database
*
* @param fileBean
* @throws Exception
*/
public void updateFileMetaData(LabFileBean fileBean) throws Exception {
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
LabFile file = (LabFile) ida.load(LabFile.class, StringUtils
.convertToLong(fileBean.getId()));
file.setTitle(fileBean.getTitle().toUpperCase());
file.setDescription(fileBean.getDescription());
file.setComments(fileBean.getComments());
} catch (Exception e) {
e.printStackTrace();
ida.rollback();
logger.error("Problem updating file meta data: ");
throw e;
} finally {
ida.close();
}
userService.setVisiblity(fileBean.getId(), fileBean
.getVisibilityGroups());
}
/**
* Update the meta data associated with a file stored in the database
*
* @param fileBean
* @throws Exception
*/
public void updateDerivedBioAssayDataMetaData(
DerivedBioAssayDataBean fileBean) throws Exception {
IDataAccess ida = (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
DerivedBioAssayData file = (DerivedBioAssayData) ida.load(
DerivedBioAssayData.class, StringUtils
.convertToLong(fileBean.getId()));
file.setTitle(fileBean.getTitle().toUpperCase());
file.setDescription(fileBean.getDescription());
file.getKeywordCollection().clear();
if (fileBean.getKeywords() != null) {
for (String keyword : fileBean.getKeywords()) {
Keyword keywordObj = new Keyword();
keywordObj.setName(keyword);
file.getKeywordCollection().add(keywordObj);
}
}
} catch (Exception e) {
e.printStackTrace();
ida.rollback();
logger.error("Problem updating derived data file meta data: ");
throw e;
} finally {
ida.close();
}
userService.setVisiblity(fileBean.getId(), fileBean
.getVisibilityGroups());
}
/**
* Delete the characterizations
*/
public void deleteCharacterizations(String particleName,
String particleType, String[] charIds) throws Exception {
// if ID is not set save to the database otherwise update
HibernateDataAccess ida = (HibernateDataAccess) (new DataAccessProxy())
.getInstance(IDataAccess.HIBERNATE);
try {
ida.open();
// Get ID
for (String strCharId : charIds) {
Long charId = Long.parseLong(strCharId);
Object charObj = ida.load(Characterization.class, charId);
// deassociate first
String hqlString = "from Nanoparticle particle where particle.characterizationCollection.id = '"
+ strCharId + "'";
List results = ida.search(hqlString);
for (Object obj : results) {
Nanoparticle particle = (Nanoparticle) obj;
particle.getCharacterizationCollection().remove(charObj);
}
// then delete
ida.delete(charObj);
}
} catch (Exception e) {
e.printStackTrace();
ida.rollback();
logger.error("Problem deleting characterization: ");
throw new Exception(
"The characterization is no longer exist in the database, please login again to refresh the view.");
} finally {
ida.close();
}
}
}
|
package gov.nih.nci.rembrandt.web.helper;
import java.io.File;
import org.apache.log4j.Logger;
import gov.nih.nci.caintegrator.ui.graphing.util.FileDeleter;
import gov.nih.nci.rembrandt.cache.RembrandtContextListener;
/**
* This class handles image files for the rembrandt application. Since this
* effort should be application specific, it is named RembrandtImageFileHandler.
* When given a user session, and image extension, and an image size, it will
* creat all the necessary strings and directories for handling dynamically
* created images for the application.
*
* @author DBauer
*
*/
public class RembrandtImageFileHandler {
private String finalPath = "";
private String URLPath;
private String chartName;
//default values
private int imageHeight = 400;
private int imageWidth = 600;
//The specific temp directory for the application
private static String tempDir = "";
private static Logger logger = Logger.getLogger(RembrandtImageFileHandler.class);
private static String fileSeperator = File.separator;
public RembrandtImageFileHandler(String userSessionId,String imageTypeExtension, int width, int height) {
if(tempDir.equals("")) {
/**
* TOTAL HACK! Since I am not sure how to handle dynamic
* image content when running in a compressed war I am grabbing
* the temp directory from JBoss and walking through the directories
* until I either find the expanded Rembrandt war or nothing. This is
* always assuming that I am running in JBoss for now (but should be moved
* out later). If the expanded archive is not found, then it just sets
* the temp directory to the Context.
*/
String jbossTempDirPath = System.getProperty("jboss.server.temp.dir");
String jbossTempDeployDirPath = jbossTempDirPath+fileSeperator+"deploy"+fileSeperator;
File directory = new File(jbossTempDeployDirPath);
String[] list = directory.list();
File[] fileList = directory.listFiles();
for(File file:fileList) {
if(file.isDirectory()) {
if(file.getName().contains("rembrandt")&&file.getName().contains(".war")){
tempDir = file.getPath();
break;
}
}
}
if(tempDir.equals("")) {
tempDir = RembrandtContextListener.getContextPath();
}
}
logger.debug("Temp Directory has been set to:"+tempDir);
if(width!=0&&height!=0) {
imageWidth = width;
imageHeight = height;
}
String relativeSessionTempPath = tempDir+fileSeperator+"images"+fileSeperator+userSessionId+fileSeperator;
//Path that will be used in the <img /> tag without the file name
URLPath = "images"+fileSeperator+userSessionId+fileSeperator;
//the actual unique chart name
chartName = createUniqueChartName(imageTypeExtension);
/*
* Creates the session image temp folder if the
* folder does not already exist
*/
File dir = new File(relativeSessionTempPath);
boolean dirCreated = dir.mkdir();
setSessionTempFolder(relativeSessionTempPath+fileSeperator+chartName);
/*
* Cleans out the session image temp folder if it did already
* exist. However, because of threading issues it appears to work
* intermitently, but it does work.
*/
if(!dirCreated) {
FileDeleter fd = new FileDeleter();
//This could probably be a * but I am not sure just yet, need to test
//fd.deleteFiles(getSessionWebAppImagePath(), imageTypeExtension);
}
}
public String createUniqueChartName(String extension) {
double time = (double)System.currentTimeMillis();
double random = (1-Math.random());
String one = String.valueOf(random*time);
String finalAnswer = one.substring(10);
return finalAnswer+"."+extension;
}
public String createUniqueMapName() {
double time = (double)System.currentTimeMillis();
double random = (1-Math.random());
String one = String.valueOf(random*time);
String finalAnswer = one.substring(10);
return finalAnswer;
}
/**
* @return Returns the uRLPath.
*/
public String getURLPath() {
return URLPath;
}
private void setSessionTempFolder(String path) {
this.finalPath = path;
}
/**
* This will return the final complete local path to the folder
* for storing any temporary files for the given session.
*
* @return local path to store temp files
*/
public String getSessionTempFolder() {
return this.finalPath;
}
public String getFinalURLPath() {
return URLPath+chartName;
}
public String getImageTag() {
String tag = null;
if ((imageWidth < 0)&&(imageHeight < 0)) {
//this is for a case where the image width and height are not known.
tag = "<img src=\""+getFinalURLPath()+"\" border=0>";
}
else {
tag = "<img src=\""+getFinalURLPath()+"\" width="+imageWidth+" height="+imageHeight+" border=0>";
}
logger.debug("Returned Image Tag: "+tag);
return tag;
}
/**
* Returns an image tag adding the image map file name to the tag
* @param mapFileName the name of the image map file name you want added
* @return the final image tag
*/
public String getImageTag(String mapFileName){
String tag = "<img src=\""+getFinalURLPath()+"\" usemap=\"#"+mapFileName + "\"" + "id=\"geneChart\"" + " border=0>";
logger.debug("Returned Image Tag: "+tag);
return tag;
}
}
|
package org.apache.commons.dbcp.jdbc2pool;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Properties;
import javax.naming.BinaryRefAddr;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.Name;
import javax.naming.NamingException;
import javax.naming.RefAddr;
import javax.naming.Reference;
import javax.naming.Referenceable;
import javax.naming.StringRefAddr;
import javax.naming.spi.ObjectFactory;
import javax.sql.ConnectionPoolDataSource;
import javax.sql.DataSource;
import javax.sql.PooledConnection;
import org.apache.commons.collections.FastHashMap;
import org.apache.commons.collections.LRUMap;
import org.apache.commons.pool.KeyedObjectPool;
import org.apache.commons.pool.ObjectPool;
import org.apache.commons.pool.impl.GenericKeyedObjectPool;
import org.apache.commons.pool.impl.GenericObjectPool;
/**
* <p>
* A pooling <code>DataSource</code> appropriate for deployment within
* J2EE environment. There are many configuration options. Multiple users
* can share a common set of parameters, such as a single maximum number
* of Connections. The pool can also support individual pools per user, if the
* deployment environment can support initialization of mapped properties.
* So for example, a pool of admin or write-access Connections can be
* guaranteed a certain number of connections, separate from a maximum
* set for read-only connections.
* </p>
*
* <p>
* A J2EE container will normally provide some method of initializing the
* <code>DataSource</code> whose attributes are presented
* as bean getters/setters and then deploying it via JNDI. It is then
* available to an application as a source of pooled logical connections to
* the database. The pool needs a source of physical connections. This
* source is in the form of a <code>ConnectionPoolDataSource</code> that
* can be specified via the {@link #setDataSourceName(String)} used to
* lookup the source via JNDI.
* </p>
*
* <p>
* Although normally used within a JNDI environment, Jdbc2PoolDataSource
* can be instantiated and initialized as any bean. In this case the
* <code>ConnectionPoolDataSource</code> will likely be instantiated in
* a similar manner. The source can then be attached directly to this
* pool using the
* {@link #setConnectionPoolDataSource(ConnectionPoolDataSource)} method.
* </p>
*
* <p>
* If this <code>DataSource</code>
* is requested via JNDI multiple times, it maintains
* state between lookups. Also, multiple instances can be deployed using
* different backend <code>ConnectionPoolDataSource</code> sources.
* </p>
*
* <p>
* The dbcp package contains an adapter,
* {@link org.apache.commons.dbcp.cpdsadapter.DriverAdapterCPDS},
* that can be used to allow the
* use of Jdbc2PoolDataSource with jdbc driver implementations that
* do not supply a <code>ConnectionPoolDataSource</code>, but still
* provide a {@link java.sql.Driver} implementation.
* </p>
*
* <p>
* The <a href="package-summary.html">package documentation</a> contains an
* example using catalina and JNDI and it also contains a non-JNDI example.
* </p>
*
* @author <a href="mailto:jmcnally@collab.net">John D. McNally</a>
* @version $Id: Jdbc2PoolDataSource.java,v 1.14 2003/08/11 14:08:39 dirkv Exp $
*/
public class Jdbc2PoolDataSource
implements DataSource, Referenceable, Serializable, ObjectFactory {
private static final String GET_CONNECTION_CALLED
= "A Connection was already requested from this source, "
+ "further initialization is not allowed.";
private static Map dsInstanceMap = new HashMap();
private static final Map userKeys = new LRUMap(10);
private static final Map poolKeys = new HashMap();
private boolean getConnectionCalled = false;
private ConnectionPoolDataSource cpds = null;
/** DataSource Name used to find the ConnectionPoolDataSource */
private String dataSourceName = null;
private boolean defaultAutoCommit = false;
private int defaultMaxActive = GenericObjectPool.DEFAULT_MAX_ACTIVE;
private int defaultMaxIdle = GenericObjectPool.DEFAULT_MAX_IDLE;
private int defaultMaxWait = (int)Math.min((long)Integer.MAX_VALUE,
GenericObjectPool.DEFAULT_MAX_WAIT);
private boolean defaultReadOnly = false;
/** Description */
private String description = null;
/** Environment that may be used to set up a jndi initial context. */
private Properties jndiEnvironment = null;
/** Login TimeOut in seconds */
private int loginTimeout = 0;
/** Log stream */
private PrintWriter logWriter = null;
private Map perUserDefaultAutoCommit = null;
private Map perUserMaxActive = null;
private Map perUserMaxIdle = null;
private Map perUserMaxWait = null;
private Map perUserDefaultReadOnly = null;
private boolean _testOnBorrow = GenericObjectPool.DEFAULT_TEST_ON_BORROW;
private boolean _testOnReturn = GenericObjectPool.DEFAULT_TEST_ON_RETURN;
private int _timeBetweenEvictionRunsMillis = (int)
Math.min((long)Integer.MAX_VALUE,
GenericObjectPool.DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS);
private int _numTestsPerEvictionRun =
GenericObjectPool.DEFAULT_NUM_TESTS_PER_EVICTION_RUN;
private int _minEvictableIdleTimeMillis = (int)
Math.min((long)Integer.MAX_VALUE,
GenericObjectPool.DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS);
private boolean _testWhileIdle = GenericObjectPool.DEFAULT_TEST_WHILE_IDLE;
private String validationQuery = null;
private boolean testPositionSet = false;
private boolean isNew = false;
private Integer instanceKey = null;
/**
* Default no-arg constructor for Serialization
*/
public Jdbc2PoolDataSource() {
isNew = true;
defaultAutoCommit = true;
}
private void assertInitializationAllowed()
throws IllegalStateException {
if (getConnectionCalled) {
throw new IllegalStateException(GET_CONNECTION_CALLED);
}
}
/**
* Close all pools associated with this class.
*/
public static void closeAll() {
//Get iterator to loop over all instances of this datasource.
Iterator instanceIterator = dsInstanceMap.entrySet().iterator();
while (instanceIterator.hasNext()) {
Map.Entry nextInstance = (Map.Entry) instanceIterator.next();
Map nextPoolMap = (Map) nextInstance.getValue();
close(nextPoolMap);
}
dsInstanceMap.clear();
}
/**
* Close all pools in the given Map.
*/
private static void close(Map poolMap) {
//Get iterator to loop over all pools.
Iterator poolIter = poolMap.entrySet().iterator();
while (poolIter.hasNext()) {
Map.Entry nextPoolEntry = (Map.Entry) poolIter.next();
if (nextPoolEntry.getValue() instanceof ObjectPool) {
ObjectPool nextPool = (ObjectPool) nextPoolEntry.getValue();
try {
nextPool.close();
} catch (Exception closePoolException) {
//ignore and try to close others.
}
} else {
KeyedObjectPool nextPool =
(KeyedObjectPool) nextPoolEntry.getValue();
try {
nextPool.close();
} catch (Exception closePoolException) {
//ignore and try to close others.
}
}
}
}
/**
* Close pool(s) being maintained by this datasource.
*/
public void close() {
close((Map)dsInstanceMap.get(instanceKey));
}
// Properties
/**
* Get the value of connectionPoolDataSource. This method will return
* null, if the backing datasource is being accessed via jndi.
*
* @return value of connectionPoolDataSource.
*/
public ConnectionPoolDataSource getConnectionPoolDataSource() {
return cpds;
}
/**
* Set the backend ConnectionPoolDataSource. This property should not be
* set if using jndi to access the datasource.
*
* @param v Value to assign to connectionPoolDataSource.
*/
public void setConnectionPoolDataSource(ConnectionPoolDataSource v) {
assertInitializationAllowed();
if (dataSourceName != null) {
throw new IllegalStateException(
"Cannot set the DataSource, if JNDI is used.");
}
this.cpds = v;
if (isNew) {
registerInstance();
}
}
/**
* Get the name of the ConnectionPoolDataSource which backs this pool.
* This name is used to look up the datasource from a jndi service
* provider.
*
* @return value of dataSourceName.
*/
public String getDataSourceName() {
return dataSourceName;
}
/**
* Set the name of the ConnectionPoolDataSource which backs this pool.
* This name is used to look up the datasource from a jndi service
* provider.
*
* @param v Value to assign to dataSourceName.
*/
public void setDataSourceName(String v) {
assertInitializationAllowed();
if (cpds != null) {
throw new IllegalStateException(
"Cannot set the JNDI name for the DataSource, if already " +
"set using setConnectionPoolDataSource.");
}
this.dataSourceName = v;
if (isNew) {
registerInstance();
}
}
/**
* Get the value of defaultAutoCommit, which defines the state of
* connections handed out from this pool. The value can be changed
* on the Connection using Connection.setAutoCommit(boolean).
* The default is true.
*
* @return value of defaultAutoCommit.
*/
public boolean isDefaultAutoCommit() {
return defaultAutoCommit;
}
/**
* Set the value of defaultAutoCommit, which defines the state of
* connections handed out from this pool. The value can be changed
* on the Connection using Connection.setAutoCommit(boolean).
* The default is true.
*
* @param v Value to assign to defaultAutoCommit.
*/
public void setDefaultAutoCommit(boolean v) {
assertInitializationAllowed();
this.defaultAutoCommit = v;
}
/**
* The maximum number of active connections that can be allocated from
* this pool at the same time, or zero for no limit.
* This value is used for any username which is not specified
* in perUserMaxConnections. The default is 0.
*/
public int getDefaultMaxActive() {
return (this.defaultMaxActive);
}
/**
* The maximum number of active connections that can be allocated from
* this pool at the same time, or zero for no limit.
* This value is used for any username which is not specified
* in perUserMaxConnections. The default is 0.
*/
public void setDefaultMaxActive(int maxActive) {
assertInitializationAllowed();
this.defaultMaxActive = maxActive;
}
/**
* The maximum number of active connections that can remain idle in the
* pool, without extra ones being released, or zero for no limit.
* This value is used for any username which is not specified
* in perUserMaxIdle. The default is 0.
*/
public int getDefaultMaxIdle() {
return (this.defaultMaxIdle);
}
/**
* The maximum number of active connections that can remain idle in the
* pool, without extra ones being released, or zero for no limit.
* This value is used for any username which is not specified
* in perUserMaxIdle. The default is 0.
*/
public void setDefaultMaxIdle(int defaultMaxIdle) {
assertInitializationAllowed();
this.defaultMaxIdle = defaultMaxIdle;
}
/**
* The maximum number of milliseconds that the pool will wait (when there
* are no available connections) for a connection to be returned before
* throwing an exception, or -1 to wait indefinitely. Will fail
* immediately if value is 0.
* This value is used for any username which is not specified
* in perUserMaxWait. The default is -1.
*/
public int getDefaultMaxWait() {
return (this.defaultMaxWait);
}
/**
* The maximum number of milliseconds that the pool will wait (when there
* are no available connections) for a connection to be returned before
* throwing an exception, or -1 to wait indefinitely. Will fail
* immediately if value is 0.
* This value is used for any username which is not specified
* in perUserMaxWait. The default is -1.
*/
public void setDefaultMaxWait(int defaultMaxWait) {
assertInitializationAllowed();
this.defaultMaxWait = defaultMaxWait;
}
/**
* Get the value of defaultReadOnly, which defines the state of
* connections handed out from this pool. The value can be changed
* on the Connection using Connection.setReadOnly(boolean).
* The default is false.
*
* @return value of defaultReadOnly.
*/
public boolean isDefaultReadOnly() {
return defaultReadOnly;
}
/**
* Set the value of defaultReadOnly, which defines the state of
* connections handed out from this pool. The value can be changed
* on the Connection using Connection.setReadOnly(boolean).
* The default is false.
*
* @param v Value to assign to defaultReadOnly.
*/
public void setDefaultReadOnly(boolean v) {
assertInitializationAllowed();
this.defaultReadOnly = v;
}
/**
* Get the description. This property is defined by jdbc as for use with
* GUI (or other) tools that might deploy the datasource. It serves no
* internal purpose.
*
* @return value of description.
*/
public String getDescription() {
return description;
}
/**
* Set the description. This property is defined by jdbc as for use with
* GUI (or other) tools that might deploy the datasource. It serves no
* internal purpose.
*
* @param v Value to assign to description.
*/
public void setDescription(String v) {
this.description = v;
}
/**
* Get the value of jndiEnvironment which is used when instantiating
* a jndi InitialContext. This InitialContext is used to locate the
* backend ConnectionPoolDataSource.
*
* @return value of jndiEnvironment.
*/
public String getJndiEnvironment(String key) {
String value = null;
if (jndiEnvironment != null) {
value = jndiEnvironment.getProperty(key);
}
return value;
}
/**
* Set the value of jndiEnvironment which is used when instantiating
* a jndi InitialContext. This InitialContext is used to locate the
* backend ConnectionPoolDataSource.
*
* @param v Value to assign to jndiEnvironment.
*/
public void setJndiEnvironment(String key, String value) {
if (jndiEnvironment == null) {
jndiEnvironment = new Properties();
}
jndiEnvironment.setProperty(key, value);
}
/**
* Get the value of loginTimeout.
* @return value of loginTimeout.
*/
public int getLoginTimeout() {
return loginTimeout;
}
/**
* Set the value of loginTimeout.
* @param v Value to assign to loginTimeout.
*/
public void setLoginTimeout(int v) {
this.loginTimeout = v;
}
/**
* Get the value of logWriter.
* @return value of logWriter.
*/
public PrintWriter getLogWriter() {
if (logWriter == null) {
logWriter = new PrintWriter(System.out);
}
return logWriter;
}
/**
* Set the value of logWriter.
* @param v Value to assign to logWriter.
*/
public void setLogWriter(PrintWriter v) {
this.logWriter = v;
}
/**
* The keys are usernames and the value is the --. Any
* username specified here will override the value of defaultAutoCommit.
*/
public Boolean getPerUserDefaultAutoCommit(String key) {
Boolean value = null;
if (perUserDefaultAutoCommit != null) {
value = (Boolean) perUserDefaultAutoCommit.get(key);
}
return value;
}
/**
* The keys are usernames and the value is the --. Any
* username specified here will override the value of defaultAutoCommit.
*/
public void setPerUserDefaultAutoCommit(String username, Boolean value) {
assertInitializationAllowed();
if (perUserDefaultAutoCommit == null) {
perUserDefaultAutoCommit = new HashMap();
}
perUserDefaultAutoCommit.put(username, value);
}
/**
* The maximum number of active connections that can be allocated from
* this pool at the same time, or zero for no limit.
* The keys are usernames and the value is the maximum connections. Any
* username specified here will override the value of defaultMaxActive.
*/
public Integer getPerUserMaxActive(String username) {
Integer value = null;
if (perUserMaxActive != null) {
value = (Integer) perUserMaxActive.get(username);
}
return value;
}
/**
* The maximum number of active connections that can be allocated from
* this pool at the same time, or zero for no limit.
* The keys are usernames and the value is the maximum connections. Any
* username specified here will override the value of defaultMaxActive.
*/
public void setPerUserMaxActive(String username, Integer value) {
assertInitializationAllowed();
if (perUserMaxActive == null) {
perUserMaxActive = new HashMap();
}
perUserMaxActive.put(username, value);
}
/**
* The maximum number of active connections that can remain idle in the
* pool, without extra ones being released, or zero for no limit.
* The keys are usernames and the value is the maximum connections. Any
* username specified here will override the value of defaultMaxIdle.
*/
public Integer getPerUserMaxIdle(String username) {
Integer value = null;
if (perUserMaxIdle != null) {
value = (Integer) perUserMaxIdle.get(username);
}
return value;
}
/**
* The maximum number of active connections that can remain idle in the
* pool, without extra ones being released, or zero for no limit.
* The keys are usernames and the value is the maximum connections. Any
* username specified here will override the value of defaultMaxIdle.
*/
public void setPerUserMaxIdle(String username, Integer value) {
assertInitializationAllowed();
if (perUserMaxIdle == null) {
perUserMaxIdle = new HashMap();
}
perUserMaxIdle.put(username, value);
}
/**
* The maximum number of milliseconds that the pool will wait (when there
* are no available connections) for a connection to be returned before
* throwing an exception, or -1 to wait indefinitely. Will fail
* immediately if value is 0.
* The keys are usernames and the value is the maximum connections. Any
* username specified here will override the value of defaultMaxWait.
*/
public Integer getPerUserMaxWait(String username) {
Integer value = null;
if (perUserMaxWait != null) {
value = (Integer) perUserMaxWait.get(username);
}
return value;
}
/**
* The maximum number of milliseconds that the pool will wait (when there
* are no available connections) for a connection to be returned before
* throwing an exception, or -1 to wait indefinitely. Will fail
* immediately if value is 0.
* The keys are usernames and the value is the maximum connections. Any
* username specified here will override the value of defaultMaxWait.
*/
public void setPerUserMaxWait(String username, Integer value) {
assertInitializationAllowed();
if (perUserMaxWait == null) {
perUserMaxWait = new HashMap();
}
perUserMaxWait.put(username, value);
}
/**
* The keys are usernames and the value is the --. Any
* username specified here will override the value of defaultReadOnly.
*/
public Boolean getPerUserDefaultReadOnly(String username) {
Boolean value = null;
if (perUserDefaultReadOnly != null) {
value = (Boolean) perUserDefaultReadOnly.get(username);
}
return value;
}
/**
* The keys are usernames and the value is the --. Any
* username specified here will override the value of defaultReadOnly.
*/
public void setPerUserDefaultReadOnly(String username, Boolean value) {
assertInitializationAllowed();
if (perUserDefaultReadOnly == null) {
perUserDefaultReadOnly = new HashMap();
}
perUserDefaultReadOnly.put(username, value);
}
/**
* @see #getTestOnBorrow
*/
public final boolean isTestOnBorrow() {
return getTestOnBorrow();
}
/**
* When <tt>true</tt>, objects will be
* {*link PoolableObjectFactory#validateObject validated}
* before being returned by the {*link #borrowObject}
* method. If the object fails to validate,
* it will be dropped from the pool, and we will attempt
* to borrow another.
*
* @see #setTestOnBorrow
*/
public boolean getTestOnBorrow() {
return _testOnBorrow;
}
/**
* When <tt>true</tt>, objects will be
* {*link PoolableObjectFactory#validateObject validated}
* before being returned by the {*link #borrowObject}
* method. If the object fails to validate,
* it will be dropped from the pool, and we will attempt
* to borrow another.
*
* @see #getTestOnBorrow
*/
public void setTestOnBorrow(boolean testOnBorrow) {
assertInitializationAllowed();
_testOnBorrow = testOnBorrow;
testPositionSet = true;
}
/**
* @see #getTestOnReturn
*/
public final boolean isTestOnReturn() {
return getTestOnReturn();
}
/**
* When <tt>true</tt>, objects will be
* {*link PoolableObjectFactory#validateObject validated}
* before being returned to the pool within the
* {*link #returnObject}.
*
* @see #setTestOnReturn
*/
public boolean getTestOnReturn() {
return _testOnReturn;
}
/**
* When <tt>true</tt>, objects will be
* {*link PoolableObjectFactory#validateObject validated}
* before being returned to the pool within the
* {*link #returnObject}.
*
* @see #getTestOnReturn
*/
public void setTestOnReturn(boolean testOnReturn) {
assertInitializationAllowed();
_testOnReturn = testOnReturn;
testPositionSet = true;
}
/**
* Returns the number of milliseconds to sleep between runs of the
* idle object evictor thread.
* When non-positive, no idle object evictor thread will be
* run.
*
* @see #setTimeBetweenEvictionRunsMillis
*/
public int getTimeBetweenEvictionRunsMillis() {
return _timeBetweenEvictionRunsMillis;
}
/**
* Sets the number of milliseconds to sleep between runs of the
* idle object evictor thread.
* When non-positive, no idle object evictor thread will be
* run.
*
* @see #getTimeBetweenEvictionRunsMillis
*/
public void
setTimeBetweenEvictionRunsMillis(int timeBetweenEvictionRunsMillis) {
assertInitializationAllowed();
_timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
}
/**
* Returns the number of objects to examine during each run of the
* idle object evictor thread (if any).
*
* @see #setNumTestsPerEvictionRun
* @see #setTimeBetweenEvictionRunsMillis
*/
public int getNumTestsPerEvictionRun() {
return _numTestsPerEvictionRun;
}
/**
* Sets the number of objects to examine during each run of the
* idle object evictor thread (if any).
* <p>
* When a negative value is supplied, <tt>ceil({*link #numIdle})/abs({*link #getNumTestsPerEvictionRun})</tt>
* tests will be run. I.e., when the value is <i>-n</i>, roughly one <i>n</i>th of the
* idle objects will be tested per run.
*
* @see #getNumTestsPerEvictionRun
* @see #setTimeBetweenEvictionRunsMillis
*/
public void setNumTestsPerEvictionRun(int numTestsPerEvictionRun) {
assertInitializationAllowed();
_numTestsPerEvictionRun = numTestsPerEvictionRun;
}
/**
* Returns the minimum amount of time an object may sit idle in the pool
* before it is eligable for eviction by the idle object evictor
* (if any).
*
* @see #setMinEvictableIdleTimeMillis
* @see #setTimeBetweenEvictionRunsMillis
*/
public int getMinEvictableIdleTimeMillis() {
return _minEvictableIdleTimeMillis;
}
/**
* Sets the minimum amount of time an object may sit idle in the pool
* before it is eligable for eviction by the idle object evictor
* (if any).
* When non-positive, no objects will be evicted from the pool
* due to idle time alone.
*
* @see #getMinEvictableIdleTimeMillis
* @see #setTimeBetweenEvictionRunsMillis
*/
public void setMinEvictableIdleTimeMillis(int minEvictableIdleTimeMillis) {
assertInitializationAllowed();
_minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
}
/**
* @see #getTestWhileIdle
*/
public final boolean isTestWhileIdle() {
return getTestWhileIdle();
}
/**
* When <tt>true</tt>, objects will be
* {*link PoolableObjectFactory#validateObject validated}
* by the idle object evictor (if any). If an object
* fails to validate, it will be dropped from the pool.
*
* @see #setTestWhileIdle
* @see #setTimeBetweenEvictionRunsMillis
*/
public boolean getTestWhileIdle() {
return _testWhileIdle;
}
/**
* When <tt>true</tt>, objects will be
* {*link PoolableObjectFactory#validateObject validated}
* by the idle object evictor (if any). If an object
* fails to validate, it will be dropped from the pool.
*
* @see #getTestWhileIdle
* @see #setTimeBetweenEvictionRunsMillis
*/
public void setTestWhileIdle(boolean testWhileIdle) {
assertInitializationAllowed();
_testWhileIdle = testWhileIdle;
testPositionSet = true;
}
/**
* The SQL query that will be used to validate connections from this pool
* before returning them to the caller. If specified, this query
* <strong>MUST</strong> be an SQL SELECT statement that returns at least
* one row.
*/
public String getValidationQuery() {
return (this.validationQuery);
}
/**
* The SQL query that will be used to validate connections from this pool
* before returning them to the caller. If specified, this query
* <strong>MUST</strong> be an SQL SELECT statement that returns at least
* one row. Default behavior is to test the connection when it is
* borrowed.
*/
public void setValidationQuery(String validationQuery) {
assertInitializationAllowed();
this.validationQuery = validationQuery;
if (!testPositionSet) {
setTestOnBorrow(true);
}
}
// Instrumentation Methods
/**
* Get the number of active connections in the default pool.
*/
public int getNumActive() {
return getNumActive(null, null);
}
/**
* Get the number of active connections in the pool for a given user.
*/
public int getNumActive(String username, String password) {
PoolKey key = getPoolKey(username);
Object pool = ((Map) dsInstanceMap.get(instanceKey)).get(key);
if (pool instanceof ObjectPool) {
return ((ObjectPool) pool).getNumActive();
} else {
return ((KeyedObjectPool) pool).getNumActive();
}
}
/**
* Get the number of idle connections in the default pool.
*/
public int getNumIdle() {
return getNumIdle(null, null);
}
/**
* Get the number of idle connections in the pool for a given user.
*/
public int getNumIdle(String username, String password) {
PoolKey key = getPoolKey(username);
Object pool = ((Map) dsInstanceMap.get(instanceKey)).get(key);
if (pool instanceof ObjectPool) {
return ((ObjectPool) pool).getNumIdle();
} else {
return ((KeyedObjectPool) pool).getNumIdle();
}
}
// DataSource implementation
/**
* Attempt to establish a database connection.
*/
public Connection getConnection() throws SQLException {
return getConnection(null, null);
}
/**
* Attempt to establish a database connection.
*/
public synchronized Connection getConnection(String username,
String password)
throws SQLException {
if (isNew) {
throw new SQLException("Must set the ConnectionPoolDataSource "
+ "through setDataSourceName or setConnectionPoolDataSource"
+ " before calling getConnection.");
}
getConnectionCalled = true;
Map pools = (Map) dsInstanceMap.get(instanceKey);
PoolKey key = getPoolKey(username);
Object pool = pools.get(key);
if (pool == null) {
try {
registerPool(username, password);
pool = pools.get(key);
} catch (NamingException e) {
e.printStackTrace();
throw new SQLException(e.getMessage());
}
}
PooledConnectionAndInfo info = null;
if (pool instanceof ObjectPool) {
try {
info = (PooledConnectionAndInfo)
((ObjectPool) pool).borrowObject();
} catch (NoSuchElementException e) {
closeDueToException(info);
throw new SQLException(e.getMessage());
} catch (RuntimeException e) {
closeDueToException(info);
throw e;
} catch (SQLException e) {
closeDueToException(info);
throw e;
} catch (Exception e) {
closeDueToException(info);
throw new SQLException(e.getMessage());
}
} else {
// assume KeyedObjectPool
try {
UserPassKey upkey = getUserPassKey(username, password);
info = (PooledConnectionAndInfo)
((KeyedObjectPool) pool).borrowObject(upkey);
} catch (NoSuchElementException e) {
closeDueToException(info);
throw new SQLException(e.getMessage());
} catch (RuntimeException e) {
closeDueToException(info);
throw e;
} catch (SQLException e) {
closeDueToException(info);
throw e;
} catch (Exception e) {
closeDueToException(info);
throw new SQLException(e.getMessage());
}
}
if (!(null == password ? null == info.getPassword()
: password.equals(info.getPassword()))) {
closeDueToException(info);
throw new SQLException("Given password did not match password used "
+ "to create the PooledConnection.");
}
PooledConnection pc = info.getPooledConnection();
boolean defaultAutoCommit = isDefaultAutoCommit();
if (username != null) {
Boolean userMax = getPerUserDefaultAutoCommit(username);
if (userMax != null) {
defaultAutoCommit = userMax.booleanValue();
}
}
boolean defaultReadOnly = isDefaultReadOnly();
if (username != null) {
Boolean userMax = getPerUserDefaultReadOnly(username);
if (userMax != null) {
defaultReadOnly = userMax.booleanValue();
}
}
Connection con = pc.getConnection();
con.setAutoCommit(defaultAutoCommit);
con.setReadOnly(defaultReadOnly);
return con;
}
private void closeDueToException(PooledConnectionAndInfo info) {
if (info != null) {
try {
info.getPooledConnection().getConnection().close();
} catch (Exception e) {
// do not throw this exception because we are in the middle
// of handling another exception. But record it because
// it potentially leaks connections from the pool.
getLogWriter().println("[ERROR] Could not return connection to "
+ "pool during exception handling. " + e.getMessage());
}
}
}
private PoolKey getPoolKey(String username) {
PoolKey key = null;
if (username != null && (perUserMaxActive == null
|| !perUserMaxActive.containsKey(username))) {
username = null;
}
String dsName = getDataSourceName();
Map dsMap = (Map) poolKeys.get(dsName);
if (dsMap != null) {
key = (PoolKey) dsMap.get(username);
}
if (key == null) {
key = new PoolKey(dsName, username);
if (dsMap == null) {
dsMap = new HashMap();
poolKeys.put(dsName, dsMap);
}
dsMap.put(username, key);
}
return key;
}
private UserPassKey getUserPassKey(String username, String password) {
UserPassKey key = (UserPassKey) userKeys.get(username);
if (key == null) {
key = new UserPassKey(username, password);
userKeys.put(username, key);
}
return key;
}
private synchronized void registerInstance() {
if (isNew) {
int max = 0;
Iterator i = dsInstanceMap.keySet().iterator();
while (i.hasNext()) {
int key = ((Integer) i.next()).intValue();
max = Math.max(max, key);
}
instanceKey = new Integer(max + 1);
FastHashMap fhm = new FastHashMap();
fhm.setFast(true);
dsInstanceMap.put(instanceKey, fhm);
isNew = false;
}
}
private synchronized void registerPool(String username, String password)
throws javax.naming.NamingException, SQLException {
Map pools = (Map) dsInstanceMap.get(instanceKey);
PoolKey key = getPoolKey(username);
if (!pools.containsKey(key)) {
int maxActive = getDefaultMaxActive();
int maxIdle = getDefaultMaxIdle();
int maxWait = getDefaultMaxWait();
// The source of physical db connections
ConnectionPoolDataSource cpds = this.cpds;
if (cpds == null) {
Context ctx = null;
if (jndiEnvironment == null) {
ctx = new InitialContext();
} else {
ctx = new InitialContext(jndiEnvironment);
}
cpds = (ConnectionPoolDataSource) ctx.lookup(dataSourceName);
}
// try to get a connection with the supplied username/password
PooledConnection conn = null;
try {
if (username != null) {
conn = cpds.getPooledConnection(username, password);
}
else {
conn = cpds.getPooledConnection();
}
if (conn == null) {
throw new SQLException("Cannot connect using the supplied username/password");
}
}
finally {
if (conn != null) {
try {
conn.close();
}
catch (SQLException e) {
// at least we could connect
}
}
}
Object whicheverPool = null;
if (perUserMaxActive != null
&& perUserMaxActive.containsKey(username)) {
Integer userMax = getPerUserMaxActive(username);
if (userMax != null) {
maxActive = userMax.intValue();
}
userMax = getPerUserMaxIdle(username);
if (userMax != null) {
maxIdle = userMax.intValue();
}
userMax = getPerUserMaxWait(username);
if (userMax != null) {
maxWait = userMax.intValue();
}
// Create an object pool to contain our PooledConnections
GenericObjectPool pool = new GenericObjectPool(null);
pool.setMaxActive(maxActive);
pool.setMaxIdle(maxIdle);
pool.setMaxWait(maxWait);
pool.setWhenExhaustedAction(
getWhenExhausted(maxActive, maxWait));
pool.setTestOnBorrow(getTestOnBorrow());
pool.setTestOnReturn(getTestOnReturn());
pool.setTimeBetweenEvictionRunsMillis(
getTimeBetweenEvictionRunsMillis());
pool.setNumTestsPerEvictionRun(getNumTestsPerEvictionRun());
pool.setMinEvictableIdleTimeMillis(
getMinEvictableIdleTimeMillis());
pool.setTestWhileIdle(getTestWhileIdle());
// Set up the factory we will use (passing the pool associates
// the factory with the pool, so we do not have to do so
// explicitly)
new CPDSConnectionFactory(cpds, pool, validationQuery,
username, password);
whicheverPool = pool;
} else {
// use default pool
// Create an object pool to contain our PooledConnections
GenericKeyedObjectPool pool = new GenericKeyedObjectPool(null);
pool.setMaxActive(maxActive);
pool.setMaxIdle(maxIdle);
pool.setMaxWait(maxWait);
pool.setWhenExhaustedAction(
getWhenExhausted(maxActive, maxWait));
pool.setTestOnBorrow(getTestOnBorrow());
pool.setTestOnReturn(getTestOnReturn());
pool.setTimeBetweenEvictionRunsMillis(
getTimeBetweenEvictionRunsMillis());
pool.setNumTestsPerEvictionRun(getNumTestsPerEvictionRun());
pool.setMinEvictableIdleTimeMillis(
getMinEvictableIdleTimeMillis());
pool.setTestWhileIdle(getTestWhileIdle());
// Set up the factory we will use (passing the pool associates
// the factory with the pool, so we do not have to do so
// explicitly)
new KeyedCPDSConnectionFactory(cpds, pool, validationQuery);
whicheverPool = pool;
}
// pools is a FastHashMap set to put the pool in a thread-safe way
pools.put(key, whicheverPool);
}
}
private byte getWhenExhausted(int maxActive, int maxWait) {
byte whenExhausted = GenericObjectPool.WHEN_EXHAUSTED_BLOCK;
if (maxActive <= 0) {
whenExhausted = GenericObjectPool.WHEN_EXHAUSTED_GROW;
} else if (maxWait == 0) {
whenExhausted = GenericObjectPool.WHEN_EXHAUSTED_FAIL;
}
return whenExhausted;
}
// Referenceable implementation
/**
* <CODE>Referenceable</CODE> implementation prepares object for
* binding in jndi.
*/
public Reference getReference() throws NamingException {
// this class implements its own factory
String factory = getClass().getName();
Reference ref = new Reference(getClass().getName(), factory, null);
ref.add(new StringRefAddr("isNew", String.valueOf(isNew)));
ref.add(new StringRefAddr("instanceKey",
(instanceKey == null ? null : instanceKey.toString())));
ref.add(new StringRefAddr("dataSourceName", getDataSourceName()));
ref.add(new StringRefAddr("defaultAutoCommit",
String.valueOf(isDefaultAutoCommit())));
ref.add(new StringRefAddr("defaultMaxActive",
String.valueOf(getDefaultMaxActive())));
ref.add(new StringRefAddr("defaultMaxIdle",
String.valueOf(getDefaultMaxIdle())));
ref.add(new StringRefAddr("defaultMaxWait",
String.valueOf(getDefaultMaxWait())));
ref.add(new StringRefAddr("defaultReadOnly",
String.valueOf(isDefaultReadOnly())));
ref.add(new StringRefAddr("description", getDescription()));
byte[] ser = null;
// BinaryRefAddr does not allow null byte[].
if (jndiEnvironment != null) {
try {
ser = serialize(jndiEnvironment);
ref.add(new BinaryRefAddr("jndiEnvironment", ser));
} catch (IOException ioe) {
throw new NamingException("An IOException prevented "
+ "serializing the jndiEnvironment properties.");
}
}
ref.add(new StringRefAddr("loginTimeout",
String.valueOf(getLoginTimeout())));
if (perUserDefaultAutoCommit != null) {
try {
ser = serialize((Serializable) perUserDefaultAutoCommit);
ref.add(new BinaryRefAddr("perUserDefaultAutoCommit", ser));
} catch (IOException ioe) {
throw new NamingException("An IOException prevented "
+ "serializing the perUserDefaultAutoCommit "
+ "properties.");
}
}
if (perUserMaxActive != null) {
try {
ser = serialize((Serializable) perUserMaxActive);
ref.add(new BinaryRefAddr("perUserMaxActive", ser));
} catch (IOException ioe) {
throw new NamingException("An IOException prevented "
+ "serializing the perUserMaxActive properties.");
}
}
if (perUserMaxIdle != null) {
try {
ser = serialize((Serializable) perUserMaxIdle);
ref.add(new BinaryRefAddr("perUserMaxIdle", ser));
} catch (IOException ioe) {
throw new NamingException("An IOException prevented "
+ "serializing the perUserMaxIdle properties.");
}
}
if (perUserMaxWait != null) {
try {
ser = serialize((Serializable) perUserMaxWait);
ref.add(new BinaryRefAddr("perUserMaxWait", ser));
} catch (IOException ioe) {
throw new NamingException("An IOException prevented "
+ "serializing the perUserMaxWait properties.");
}
}
if (perUserDefaultReadOnly != null) {
try {
ser = serialize((Serializable) perUserDefaultReadOnly);
ref.add(new BinaryRefAddr("perUserDefaultReadOnly", ser));
} catch (IOException ioe) {
throw new NamingException("An IOException prevented "
+ "serializing the perUserDefaultReadOnly properties.");
}
}
ref.add(new StringRefAddr("testOnBorrow",
String.valueOf(getTestOnBorrow())));
ref.add(new StringRefAddr("testOnReturn",
String.valueOf(getTestOnReturn())));
ref.add(new StringRefAddr("timeBetweenEvictionRunsMillis",
String.valueOf(getTimeBetweenEvictionRunsMillis())));
ref.add(new StringRefAddr("numTestsPerEvictionRun",
String.valueOf(getNumTestsPerEvictionRun())));
ref.add(new StringRefAddr("minEvictableIdleTimeMillis",
String.valueOf(getMinEvictableIdleTimeMillis())));
ref.add(new StringRefAddr("testWhileIdle",
String.valueOf(getTestWhileIdle())));
ref.add(new StringRefAddr("validationQuery", getValidationQuery()));
return ref;
}
/**
* Converts a object to a byte array for storage/serialization.
*
* @param obj The Serializable to convert.
* @return A byte[] with the converted Serializable.
* @exception IOException, if conversion to a byte[] fails.
*/
private static byte[] serialize(Serializable obj) throws IOException {
byte[] byteArray = null;
ByteArrayOutputStream baos = null;
ObjectOutputStream out = null;
try {
// These objects are closed in the finally.
baos = new ByteArrayOutputStream();
out = new ObjectOutputStream(baos);
out.writeObject(obj);
byteArray = baos.toByteArray();
} finally {
if (out != null) {
out.close();
}
}
return byteArray;
}
// ObjectFactory implementation
/**
* implements ObjectFactory to create an instance of this class
*/
public Object getObjectInstance(Object refObj, Name name,
Context context, Hashtable env)
throws Exception {
// The spec says to return null if we can't create an instance
// of the reference
Jdbc2PoolDataSource ds = null;
if (refObj instanceof Reference) {
Reference ref = (Reference) refObj;
if (ref.getClassName().equals(getClass().getName())) {
RefAddr ra = ref.get("isNew");
if (ra != null && ra.getContent() != null) {
isNew = Boolean.valueOf(ra.getContent().toString())
.booleanValue();
}
ra = ref.get("instanceKey");
if (ra != null && ra.getContent() != null) {
instanceKey = new Integer(ra.getContent().toString());
}
ra = ref.get("dataSourceName");
if (ra != null && ra.getContent() != null) {
setDataSourceName(ra.getContent().toString());
}
ra = ref.get("defaultAutoCommit");
if (ra != null && ra.getContent() != null) {
setDefaultAutoCommit(Boolean.valueOf(
ra.getContent().toString()).booleanValue());
}
ra = ref.get("defaultMaxActive");
if (ra != null && ra.getContent() != null) {
setDefaultMaxActive(
Integer.parseInt(ra.getContent().toString()));
}
ra = ref.get("defaultMaxIdle");
if (ra != null && ra.getContent() != null) {
setDefaultMaxIdle(
Integer.parseInt(ra.getContent().toString()));
}
ra = ref.get("defaultMaxWait");
if (ra != null && ra.getContent() != null) {
setDefaultMaxWait(
Integer.parseInt(ra.getContent().toString()));
}
ra = ref.get("defaultReadOnly");
if (ra != null && ra.getContent() != null) {
setDefaultReadOnly(Boolean.valueOf(
ra.getContent().toString()).booleanValue());
}
ra = ref.get("description");
if (ra != null && ra.getContent() != null) {
setDescription(ra.getContent().toString());
}
ra = ref.get("jndiEnvironment");
if (ra != null && ra.getContent() != null) {
byte[] serialized = (byte[]) ra.getContent();
jndiEnvironment = (Properties) deserialize(serialized);
}
ra = ref.get("loginTimeout");
if (ra != null && ra.getContent() != null) {
setLoginTimeout(
Integer.parseInt(ra.getContent().toString()));
}
ra = ref.get("perUserDefaultAutoCommit");
if (ra != null && ra.getContent() != null) {
byte[] serialized = (byte[]) ra.getContent();
perUserDefaultAutoCommit = (Map) deserialize(serialized);
}
ra = ref.get("perUserMaxActive");
if (ra != null && ra.getContent() != null) {
byte[] serialized = (byte[]) ra.getContent();
perUserMaxActive = (Map) deserialize(serialized);
}
ra = ref.get("perUserMaxIdle");
if (ra != null && ra.getContent() != null) {
byte[] serialized = (byte[]) ra.getContent();
perUserMaxIdle = (Map) deserialize(serialized);
}
ra = ref.get("perUserMaxWait");
if (ra != null && ra.getContent() != null) {
byte[] serialized = (byte[]) ra.getContent();
perUserMaxWait = (Map) deserialize(serialized);
}
ra = ref.get("perUserDefaultReadOnly");
if (ra != null && ra.getContent() != null) {
byte[] serialized = (byte[]) ra.getContent();
perUserDefaultReadOnly = (Map) deserialize(serialized);
}
ra = ref.get("testOnBorrow");
if (ra != null && ra.getContent() != null) {
setTestOnBorrow(Boolean.valueOf(ra.getContent().toString())
.booleanValue());
}
ra = ref.get("testOnReturn");
if (ra != null && ra.getContent() != null) {
setTestOnReturn(Boolean.valueOf(ra.getContent().toString())
.booleanValue());
}
ra = ref.get("timeBetweenEvictionRunsMillis");
if (ra != null && ra.getContent() != null) {
setTimeBetweenEvictionRunsMillis(
Integer.parseInt(ra.getContent().toString()));
}
ra = ref.get("numTestsPerEvictionRun");
if (ra != null && ra.getContent() != null) {
setNumTestsPerEvictionRun(
Integer.parseInt(ra.getContent().toString()));
}
ra = ref.get("minEvictableIdleTimeMillis");
if (ra != null && ra.getContent() != null) {
setMinEvictableIdleTimeMillis(
Integer.parseInt(ra.getContent().toString()));
}
ra = ref.get("testWhileIdle");
if (ra != null && ra.getContent() != null) {
setTestWhileIdle(Boolean.valueOf(ra.getContent().toString())
.booleanValue());
}
ra = ref.get("validationQuery");
if (ra != null && ra.getContent() != null) {
setValidationQuery(ra.getContent().toString());
}
ds = this;
}
}
return ds;
}
private final Object deserialize(byte[] data) throws Exception {
ObjectInputStream in = null;
try {
in = new ObjectInputStream(new ByteArrayInputStream(data));
return in.readObject();
} finally {
try {
in.close();
} catch (IOException ex) {
}
}
}
}
|
package org.apache.velocity.util.introspection;
import java.util.Map;
import java.util.Hashtable;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
public class ClassMethodMap
{
/**
* Class passed into the constructor used to as
* the basis for the Method map.
*/
private Class clazz;
/**
* Map of methods that can be accessed directly
* with a method key.
*/
private Map directHits = new Hashtable();
/**
* Map of nulls that represent methodKeys that
* will never return a valid method.
*/
private Map directMisses = new Hashtable();
/**
* Standard constructor
*/
public ClassMethodMap(Class clazz)
{
this.clazz = clazz;
populateDirectHits();
}
/**
* Find a Method using the methodKey
* provided. First try a direct hit, if
* that doesn't work then we have to do some
* work to find out if we can return a Method
* or not. Will implement this ASAP. If we
* find a valid Method then we can generate
* a methodKey and add it to the
* directHits Map.
*/
public Method findMethod(String methodKey)
{
return (Method) directHits.get(methodKey);
}
/**
* Populate the Map of direct hits. These
* are taken from all the public method
* that our class provides.
*/
private void populateDirectHits()
{
Method[] methods = clazz.getMethods();
StringBuffer methodKey;
for (int i = 0; i < methods.length; i++)
if (Modifier.isPublic(methods[i].getModifiers()))
directHits.put(makeMethodKey(methods[i]), methods[i]);
}
/**
* Make a methodKey for the given method using
* the concatenation of the name and the
* types of the method parameters.
*/
private String makeMethodKey(Method method)
{
Class[] parameterTypes = method.getParameterTypes();
StringBuffer methodKey = new StringBuffer().append(method.getName());
for (int j = 0; j < parameterTypes.length; j++)
methodKey.append(parameterTypes[j].getName());
return methodKey.toString();
}
}
|
package org.dellroad.stuff.pobj;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLEventWriter;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLOutputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.stax.StAXResult;
import javax.xml.transform.stax.StAXSource;
import javax.xml.transform.stream.StreamResult;
import org.dellroad.stuff.schema.AbstractSchemaUpdater;
/**
* Support superclass for {@link PersistentObject} schema updaters.
*
* <p>
* This class holds a nested {@link PersistentObject} and ensures that it's up to date when started.
* Use {@link #getPersistentObject} to access it.
*
* <p>
* Updates are tracked by "secretly" inserting <code>{@link XMLConstants#UPDATES_ELEMENT_NAME <pobj:updates>}</code>
* elements into the serialized XML document; these updates are transparently removed when the document is read back.
* In this way the document and its set of applied updates always travel together.
*
* <p>
* Subclasses will typically override {@link #getInitialValue} for when there is no persistent file yet.
*
* @param <T> type of the root persistent object
*/
public class PersistentObjectSchemaUpdater<T> extends AbstractSchemaUpdater<File, PersistentFileTransaction> {
protected File file;
protected long writeDelay;
protected PersistentObjectDelegate<T> delegate;
private ArrayList<String> updateNames;
private PersistentObject<T> persistentObject;
/**
* Configure the file used to store this object persistently. Required property.
*/
public void setFile(File file) {
this.file = file;
}
/**
* Configure the maximum delay after an update operation before a write-back to the persistent file
* must be initiated. Default is zero.
*/
public void setWriteDelay(long writeDelay) {
this.writeDelay = writeDelay;
}
/**
* Configure the {@link PersistentObjectDelegate}. Required property.
*/
public void setDelegate(PersistentObjectDelegate<T> delegate) {
this.delegate = delegate;
}
public synchronized void start() {
// Already started?
if (this.persistentObject != null)
return;
// Sanity check
if (this.file == null)
throw new IllegalArgumentException("no file configured");
if (this.writeDelay < 0)
throw new IllegalArgumentException("negative writeDelay file configured");
if (this.delegate == null)
throw new IllegalArgumentException("no delegate configured");
// Do schema updates
try {
this.initializeAndUpdateDatabase(this.file);
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new PersistentObjectException(e);
}
// Create and start persistent object
PersistentObject<T> pobj = new PersistentObject<T>(new UpdaterDelegate(), this.file, this.writeDelay);
pobj.start();
// Done
this.persistentObject = pobj;
}
/**
* Stop this instance. Does nothing if already stopped.
*
* @throws PersistentObjectException if a delayed write back is pending and error occurs during writing
*/
public synchronized void stop() {
// Already stopped?
if (this.persistentObject == null)
return;
// Stop
this.persistentObject.stop();
this.persistentObject = null;
}
public synchronized PersistentObject<T> getPersistentObject() {
if (this.persistentObject == null)
throw new IllegalStateException("not started");
return this.persistentObject;
}
/**
* Get the initial value for the persistent object when no persistent file is found.
*
* <p>
* The implementation in {@link PersistentObjectSchemaUpdater} just returns null.
* Subclasses should override as desired.
*
* <p>
* The returned value must properly validate.
*/
protected T getInitialValue() {
return null;
}
@Override
protected boolean databaseNeedsInitialization(PersistentFileTransaction transaction) throws Exception {
return transaction.getData() == null;
}
@Override
@SuppressWarnings("unchecked")
protected void initializeDatabase(PersistentFileTransaction transaction) throws Exception {
// Get initial value
T initialValue = this.getInitialValue();
if (initialValue == null)
return;
// Validate it
Set<ConstraintViolation<T>> violations = this.delegate.validate(initialValue);
if (!violations.isEmpty())
throw new PersistentObjectValidationException((Set<ConstraintViolation<?>>)(Object)violations);
// Serialize it
ByteArrayOutputStream buffer = new ByteArrayOutputStream(PersistentFileTransaction.FILE_BUFFER_SIZE);
StreamResult result = new StreamResult(buffer);
this.delegate.serialize(initialValue, result);
// Set it in the transaction
transaction.setData(buffer.toByteArray());
}
@Override
protected PersistentFileTransaction openTransaction(File file) throws Exception {
return new PersistentFileTransaction(file);
}
@Override
protected void commitTransaction(PersistentFileTransaction transaction) throws Exception {
this.updateNames = new ArrayList<String>(transaction.getUpdates());
transaction.commit();
}
@Override
protected void rollbackTransaction(PersistentFileTransaction transaction) throws Exception {
transaction.rollback();
}
@Override
protected Set<String> getAppliedUpdateNames(PersistentFileTransaction transaction) throws Exception {
return new HashSet<String>(transaction.getUpdates());
}
@Override
protected void recordUpdateApplied(PersistentFileTransaction transaction, String name) throws Exception {
transaction.addUpdate(name);
}
// Our PersistentObjectDelegate that hides the updates when (de)serializing
private class UpdaterDelegate extends FilterDelegate<T> {
private final XMLInputFactory xmlInputFactory = XMLInputFactory.newFactory();
private final XMLOutputFactory xmlOutputFactory = XMLOutputFactory.newFactory();
UpdaterDelegate() {
super(PersistentObjectSchemaUpdater.this.delegate);
}
/**
* Serialize object to XML, adding update list.
*/
@Override
public void serialize(T obj, Result result) throws IOException {
try {
XMLEventWriter eventWriter = this.xmlOutputFactory.createXMLEventWriter(result);
UpdatesXMLEventWriter updatesWriter = new UpdatesXMLEventWriter(eventWriter,
PersistentObjectSchemaUpdater.this.updateNames);
super.serialize(obj, new StAXResult(updatesWriter));
updatesWriter.close();
} catch (IOException e) {
throw e;
} catch (XMLStreamException e) {
throw new PersistentObjectException(e);
}
}
/**
* Deserialize object from XML, removing update list.
*/
@Override
public T deserialize(Source source) throws IOException {
try {
XMLEventReader eventReader = this.xmlInputFactory.createXMLEventReader(source);
UpdatesXMLEventReader updatesReader = new UpdatesXMLEventReader(eventReader);
return super.deserialize(new StAXSource(updatesReader));
} catch (IOException e) {
throw e;
} catch (XMLStreamException e) {
throw new PersistentObjectException(e);
}
}
}
}
|
package org.helioviewer.gl3d.model.image;
import java.awt.Point;
import java.util.ArrayList;
import javax.media.opengl.GL2;
import org.helioviewer.base.physics.Constants;
import org.helioviewer.gl3d.camera.GL3DCamera;
import org.helioviewer.gl3d.camera.GL3DCameraListener;
import org.helioviewer.gl3d.model.GL3DHitReferenceShape;
import org.helioviewer.gl3d.scenegraph.GL3DGroup;
import org.helioviewer.gl3d.scenegraph.GL3DShape;
import org.helioviewer.gl3d.scenegraph.GL3DState;
import org.helioviewer.gl3d.scenegraph.math.GL3DVec3d;
import org.helioviewer.gl3d.scenegraph.math.GL3DVec4d;
import org.helioviewer.gl3d.scenegraph.rt.GL3DRay;
import org.helioviewer.gl3d.scenegraph.rt.GL3DRayTracer;
import org.helioviewer.gl3d.shader.GL3DImageFragmentShaderProgram;
import org.helioviewer.gl3d.view.GL3DImageTextureView;
import org.helioviewer.gl3d.view.GL3DView;
import org.helioviewer.viewmodel.changeevent.ChangeEvent;
import org.helioviewer.viewmodel.metadata.MetaData;
import org.helioviewer.viewmodel.region.Region;
import org.helioviewer.viewmodel.region.StaticRegion;
import org.helioviewer.viewmodel.view.ImageInfoView;
import org.helioviewer.viewmodel.view.MetaDataView;
import org.helioviewer.viewmodel.view.RegionView;
import org.helioviewer.viewmodel.view.View;
import org.helioviewer.viewmodel.view.ViewListener;
/**
* This is the scene graph equivalent of an image layer sub view chain attached
* to the GL3DLayeredView. It represents exactly one image layer in the view
* chain
*
* @author Simon Spoerri (simon.spoerri@fhnw.ch)
*
*/
public abstract class GL3DImageLayer extends GL3DGroup implements GL3DCameraListener, ViewListener {
private static int nextLayerId = 0;
private final int layerId;
private GL3DVec4d direction = new GL3DVec4d(0, 0, 1, 0);
public int getLayerId() {
return layerId;
}
protected GL3DView mainLayerView;
protected GL3DImageTextureView imageTextureView;
protected MetaDataView metaDataView;
protected RegionView regionView;
protected GL3DImageLayers layerGroup;
public double minZ = -Constants.SunRadius;
public double maxZ = Constants.SunRadius;
protected GL3DHitReferenceShape accellerationShape;
protected boolean doUpdateROI = true;
private final ArrayList<Point> points = new ArrayList<Point>();
private final double lastViewAngle = 0.0;
protected GL2 gl;
protected GL3DImageFragmentShaderProgram sphereFragmentShader = null;
private final ImageInfoView jpxView;
public GL3DImageLayer(String name, GL3DView mainLayerView) {
super(name);
layerId = nextLayerId++;
this.mainLayerView = mainLayerView;
if (this.mainLayerView == null) {
throw new NullPointerException("Cannot create GL3DImageLayer from null Layer");
}
this.imageTextureView = this.mainLayerView.getAdapter(GL3DImageTextureView.class);
if (this.imageTextureView == null) {
throw new IllegalStateException("Cannot create GL3DImageLayer when no GL3DImageTextureView is present in Layer");
}
this.metaDataView = this.mainLayerView.getAdapter(MetaDataView.class);
if (this.metaDataView == null) {
throw new IllegalStateException("Cannot create GL3DImageLayer when no MetaDataView is present in Layer");
}
this.regionView = this.mainLayerView.getAdapter(RegionView.class);
if (this.regionView == null) {
throw new IllegalStateException("Cannot create GL3DImageLayer when no RegionView is present in Layer");
}
this.accellerationShape = new GL3DHitReferenceShape(false);
this.jpxView = this.mainLayerView.getAdapter(ImageInfoView.class);
if (this.regionView != null) {
this.jpxView.addViewListener(this.accellerationShape);
this.jpxView.addViewListener(this);
}
this.doUpdateROI = true;
this.markAsChanged();
}
@Override
public void shapeInit(GL3DState state) {
this.createImageMeshNodes(state.gl);
this.addNode(this.accellerationShape);
super.shapeInit(state);
this.doUpdateROI = true;
this.markAsChanged();
updateROI(state.getActiveCamera());
state.getActiveCamera().updateCameraTransformation();
}
protected abstract void createImageMeshNodes(GL2 gl);
protected abstract GL3DImageMesh getImageSphere();
@Override
public void shapeUpdate(GL3DState state) {
super.shapeUpdate(state);
// Log.debug("GL3DImageLayer: '"+getName()+" is updating its ROI");
this.updateROI(state.getActiveCamera());
doUpdateROI = false;
this.accellerationShape.setUnchanged();
}
@Override
public void cameraMoved(GL3DCamera camera) {
doUpdateROI = true;
this.accellerationShape.markAsChanged();
}
public double getLastViewAngle() {
return lastViewAngle;
}
@Override
public void cameraMoving(GL3DCamera camera) {
}
public GL3DVec4d getLayerDirection() {
return direction;
}
public void setLayerDirection(GL3DVec4d direction) {
this.direction = direction;
}
private void updateROI(GL3DCamera activeCamera) {
MetaData metaData = metaDataView.getMetaData();
if (metaData == null) {
return;
}
GL3DRayTracer rayTracer = new GL3DRayTracer(this.accellerationShape, activeCamera);
int width = (int) activeCamera.getWidth();
int height = (int) activeCamera.getHeight();
double minPhysicalX = Double.MAX_VALUE;
double minPhysicalY = Double.MAX_VALUE;
double maxPhysicalX = -Double.MAX_VALUE;
double maxPhysicalY = -Double.MAX_VALUE;
double res = 10.;
for (int i = 0; i <= res; i++) {
for (int j = 0; j <= 1; j++) {
for (final boolean on : new boolean[] { false, true }) {
this.accellerationShape.setHitCoronaPlane(on);
GL3DRay ray = rayTracer.cast((int) (i * width / res), (int) (j * height / 1.));
GL3DVec3d hitPoint = ray.getHitPoint();
if (hitPoint != null) {
hitPoint = ray.getHitPoint();
minPhysicalX = Math.min(minPhysicalX, hitPoint.x);
minPhysicalY = Math.min(minPhysicalY, hitPoint.y);
maxPhysicalX = Math.max(maxPhysicalX, hitPoint.x);
maxPhysicalY = Math.max(maxPhysicalY, hitPoint.y);
}
}
}
}
for (int i = 0; i <= 1; i++) {
for (int j = 0; j <= res; j++) {
for (final boolean on : new boolean[] { false, true }) {
this.accellerationShape.setHitCoronaPlane(on);
GL3DRay ray = rayTracer.cast((int) (i * width / 1.), (int) (j * height / res));
GL3DVec3d hitPoint = ray.getHitPoint();
if (hitPoint != null) {
hitPoint = ray.getHitPoint();
minPhysicalX = Math.min(minPhysicalX, hitPoint.x);
minPhysicalY = Math.min(minPhysicalY, hitPoint.y);
maxPhysicalX = Math.max(maxPhysicalX, hitPoint.x);
maxPhysicalY = Math.max(maxPhysicalY, hitPoint.y);
}
}
}
}
if (minPhysicalX < metaData.getPhysicalLowerLeft().getX())
minPhysicalX = metaData.getPhysicalLowerLeft().getX();
if (minPhysicalY < metaData.getPhysicalLowerLeft().getY())
minPhysicalY = metaData.getPhysicalLowerLeft().getY();
if (maxPhysicalX > metaData.getPhysicalUpperRight().getX())
maxPhysicalX = metaData.getPhysicalUpperRight().getX();
if (maxPhysicalY > metaData.getPhysicalUpperRight().getY())
maxPhysicalY = metaData.getPhysicalUpperRight().getY();
double regionWidth = maxPhysicalX - minPhysicalX;
double regionHeight = maxPhysicalY - minPhysicalY;
if (regionWidth > 0 && regionHeight > 0) {
Region newRegion = StaticRegion.createAdaptedRegion(minPhysicalX, minPhysicalY, regionWidth, regionHeight);
this.regionView.setRegion(newRegion, new ChangeEvent());
} else {
Region newRegion = StaticRegion.createAdaptedRegion(metaData.getPhysicalLowerLeft().getX(), metaData.getPhysicalLowerLeft().getY(), metaData.getPhysicalUpperRight().getX() - metaData.getPhysicalLowerLeft().getX(), metaData.getPhysicalUpperRight().getY() - metaData.getPhysicalLowerLeft().getY());
this.regionView.setRegion(newRegion, new ChangeEvent());
}
this.markAsChanged();
}
protected GL3DImageTextureView getImageTextureView() {
return this.imageTextureView;
}
public void setLayerGroup(GL3DImageLayers layers) {
layerGroup = layers;
}
public GL3DImageLayers getLayerGroup() {
return layerGroup;
}
public GL3DImageFragmentShaderProgram getSphereFragmentShader() {
return sphereFragmentShader;
}
@Override
public void viewChanged(View sender, ChangeEvent aEvent) {
this.updateROI(GL3DState.get().getActiveCamera());
}
protected GL3DShape getImageCorona() {
return null;
}
public void setCoronaVisibility(boolean visible) {
}
}
|
package StevenDimDoors.mod_pocketDim.config;
import java.io.File;
import net.minecraftforge.common.Configuration;
import StevenDimDoors.mod_pocketDim.blocks.BlockRift;
import StevenDimDoors.mod_pocketDim.ticking.CustomLimboPopulator;
import StevenDimDoors.mod_pocketDim.world.fortresses.DDStructureNetherBridgeStart;
import StevenDimDoors.mod_pocketDim.world.gateways.GatewayGenerator;
public class DDProperties
{
/**
* Block IDs
*/
public final int UnstableDoorID;
public final int DimensionalDoorID;
public final int GoldenDoorID;
public final int GoldenDimensionalDoorID;
public final int WarpDoorID;
public final int TransTrapdoorID;
public final int TransientDoorID;
public final int FabricBlockID;
public final int RiftBlockID;
/**
* World Generation Block IDs
*/
public final int LimboBlockID;
public final int PermaFabricBlockID;
/**
* Item IDs
*/
public final int RiftBladeItemID;
public final int RiftSignatureItemID;
public final int GoldenDimensionalDoorItemID;
public final int GoldenDoorItemID;
public final int RiftRemoverItemID;
public final int StableFabricItemID;
public final int StabilizedRiftSignatureItemID;
public final int DimensionalDoorItemID;
public final int UnstableDoorItemID;
public final int WarpDoorItemID;
public final int WorldThreadItemID;
/**
* Other IDs
*/
public final int LimboBiomeID;
public final int PocketBiomeID;
public final int LimboDimensionID;
public final int LimboProviderID;
public final int PocketProviderID;
public final int DoorRenderEntityID;
public final int MonolithEntityID;
/**
* Crafting Flags
*/
public final boolean CraftingDimensionalDoorAllowed;
public final boolean CraftingWarpDoorAllowed;
public final boolean CraftingRiftSignatureAllowed;
public final boolean CraftingRiftRemoverAllowed;
public final boolean CraftingUnstableDoorAllowed;
public final boolean CraftingRiftBladeAllowed;
public final boolean CraftingTransTrapdoorAllowed;
public final boolean CraftingStabilizedRiftSignatureAllowed;
public final boolean CraftingStableFabricAllowed;
public final boolean CraftingGoldenDimensionalDoorAllowed;
public final boolean CraftingGoldenDoorAllowed;
/**
* Loot Flags
*/
public final boolean RiftBladeLootEnabled;
public final boolean FabricOfRealityLootEnabled;
public final boolean WorldThreadLootEnabled;
/**
* Other Flags
*/
public final boolean RiftSpreadEnabled;
public final boolean RiftGriefingEnabled;
public final boolean RiftsSpawnEndermenEnabled;
public final boolean LimboEnabled;
public final boolean HardcoreLimboEnabled;
public final boolean LimboReturnsInventoryEnabled;
public final boolean DoorRenderingEnabled;
public final boolean TNFREAKINGT_Enabled;
public final boolean MonolithTeleportationEnabled;
/**
* Other
*/
public final int NonTntWeight;
public final int ClusterGenerationChance;
public final int GatewayGenerationChance;
public final int FortressGatewayGenerationChance;
public final int MonolithSpawningChance;
public final int WorldThreadDropChance;
public final int LimboEntryRange;
public final int LimboReturnRange;
public final int WorldThreadRequirementLevel;
public final String CustomSchematicDirectory;
//Singleton instance
private static DDProperties instance = null;
//Path for custom dungeons within configuration directory
private final String CUSTOM_SCHEMATIC_SUBDIRECTORY = "/DimDoors_Custom_schematics";
//Names of categories
private final String CATEGORY_CRAFTING = "crafting";
private final String CATEGORY_ENTITY = "entity";
private final String CATEGORY_DIMENSION = "dimension";
private final String CATEGORY_PROVIDER = "provider";
private final String CATEGORY_BIOME = "biome";
private final String CATEGORY_LOOT = "loot";
private DDProperties(File configFile)
{
//Load the configuration. This must be done in the constructor, even though I'd rather have a separate
//function, because "blank final" variables must be initialized within the constructor.
CustomSchematicDirectory = configFile.getParent() + CUSTOM_SCHEMATIC_SUBDIRECTORY;
Configuration config = new Configuration(configFile);
config.load();
CraftingDimensionalDoorAllowed = config.get(CATEGORY_CRAFTING, "Allow Crafting Dimensional Door", true).getBoolean(true);
CraftingWarpDoorAllowed = config.get(CATEGORY_CRAFTING, "Allow Crafting Warp Door", true).getBoolean(true);
CraftingUnstableDoorAllowed = config.get(CATEGORY_CRAFTING, "Allow Crafting Unstable Door", true).getBoolean(true);
CraftingTransTrapdoorAllowed = config.get(CATEGORY_CRAFTING, "Allow Crafting Transdimensional Trapdoor", true).getBoolean(true);
CraftingRiftSignatureAllowed = config.get(CATEGORY_CRAFTING, "Allow Crafting Rift Signature", true).getBoolean(true);
CraftingRiftRemoverAllowed = config.get(CATEGORY_CRAFTING, "Allow Crafting Rift Remover", true).getBoolean(true);
CraftingStabilizedRiftSignatureAllowed = config.get(CATEGORY_CRAFTING, "Allow Crafting Stabilized Rift Signature", true).getBoolean(true);
CraftingRiftBladeAllowed = config.get(CATEGORY_CRAFTING, "Allow Crafting Rift Blade", true).getBoolean(true);
CraftingStableFabricAllowed = config.get(CATEGORY_CRAFTING, "Allow Crafting Stable Fabric", true).getBoolean(true);
CraftingGoldenDoorAllowed = config.get(CATEGORY_CRAFTING, "Allow Crafting Golden Door", true).getBoolean(true);
CraftingGoldenDimensionalDoorAllowed = config.get(CATEGORY_CRAFTING, "Allow Crafting Golden Dimensional Door", true).getBoolean(true);
WorldThreadRequirementLevel = config.get(CATEGORY_CRAFTING, "World Thread Requirement Level", 4,
"Controls the amount of World Thread needed to craft Stable Fabric. The number must be an " +
"integer from 1 to 4. The levels change the recipe to use 1, 2, 4, or 8 threads, respectively. The default level is 4.").getInt();
RiftBladeLootEnabled = config.get(CATEGORY_LOOT, "Enable Rift Blade Loot", true).getBoolean(true);
FabricOfRealityLootEnabled = config.get(CATEGORY_LOOT, "Enable Fabric of Reality Loot", true).getBoolean(true);
WorldThreadLootEnabled = config.get(CATEGORY_LOOT, "Enable World Thread Loot", true).getBoolean(true);
RiftGriefingEnabled = config.get(Configuration.CATEGORY_GENERAL, "Enable Rift Griefing", true,
"Sets whether rifts destroy blocks around them or not").getBoolean(true);
RiftSpreadEnabled = config.get(Configuration.CATEGORY_GENERAL, "Enable Rift Spread", true,
"Sets whether rifts create more rifts when they are near other rifts").getBoolean(true);
RiftsSpawnEndermenEnabled = config.get(Configuration.CATEGORY_GENERAL, "Enable Endermen Spawning from Rifts", true,
"Sets whether groups of connected rifts will spawn Endermen").getBoolean(true);
LimboEnabled = config.get(Configuration.CATEGORY_GENERAL, "Enable Limbo", true,
"Sets whether players are teleported to Limbo when they die in any pocket dimension").getBoolean(true);
LimboReturnsInventoryEnabled = config.get(Configuration.CATEGORY_GENERAL, "Enable Limbo Returns Inventory", true,
"Sets whether players keep their inventories upon dying and respawning in Limbo").getBoolean(true);
HardcoreLimboEnabled = config.get(Configuration.CATEGORY_GENERAL, "Enable Hardcore Limbo", false,
"Sets whether players that die in Limbo will respawn there").getBoolean(false);
LimboEntryRange = config.get(Configuration.CATEGORY_GENERAL, "Limbo Entry Range", 500,
"Sets the farthest distance that players may be moved at random when sent to Limbo. Must be greater than or equal to 0.").getInt();
LimboReturnRange = config.get(Configuration.CATEGORY_GENERAL, "Limbo Return Range", 500,
"Sets the farthest distance that players may be moved at random when sent from Limbo to the Overworld. Must be greater than or equal to 0.").getInt();
DoorRenderingEnabled = config.get(Configuration.CATEGORY_GENERAL, "Enable Door Rendering", true).getBoolean(true);
TNFREAKINGT_Enabled = config.get(Configuration.CATEGORY_GENERAL, "EXPLOSIONS!!???!!!?!?!!", false).getBoolean(false);
NonTntWeight = config.get(Configuration.CATEGORY_GENERAL, "HOWMUCHTNT", 25,
"Weighs the chance that a block will not be TNT. Must be greater than or equal to 0. " +
"EXPLOSIONS must be set to true for this to have any effect.").getInt();
DoorRenderEntityID = config.get(CATEGORY_ENTITY, "Door Render Entity ID", 89).getInt();
MonolithEntityID = config.get(CATEGORY_ENTITY, "Monolith Entity ID", 125).getInt();
DimensionalDoorID = config.getBlock("Dimensional Door Block ID", 1970).getInt();
TransTrapdoorID = config.getBlock("Transdimensional Trapdoor Block ID", 1971).getInt();
FabricBlockID =config.getBlock("Fabric Of Reality Block ID", 1973).getInt();
WarpDoorID = config.getBlock("Warp Door Block ID", 1975).getInt();
RiftBlockID = config.getBlock("Rift Block ID", 1977).getInt();
UnstableDoorID = config.getBlock("Unstable Door Block ID", 1978).getInt();
TransientDoorID = config.getBlock("Transient Door Block ID", 1979).getInt();
GoldenDoorID = config.getBlock("Gold Door Block ID", 1980).getInt();
GoldenDimensionalDoorID = config.getBlock("Gold Dim Door Block ID", 1981).getInt();
WarpDoorItemID = config.getItem("Warp Door Item ID", 5670).getInt();
RiftRemoverItemID = config.getItem("Rift Remover Item ID", 5671).getInt();
StableFabricItemID = config.getItem("Stable Fabric Item ID", 5672).getInt();
UnstableDoorItemID = config.getItem("Unstable Door Item ID", 5673).getInt();
DimensionalDoorItemID = config.getItem("Dimensional Door Item ID", 5674).getInt();
RiftSignatureItemID = config.getItem("Rift Signature Item ID", 5675).getInt();
RiftBladeItemID = config.getItem("Rift Blade Item ID", 5676).getInt();
StabilizedRiftSignatureItemID = config.getItem("Stabilized Rift Signature Item ID", 5677).getInt();
GoldenDoorItemID = config.getItem("Gold Door Item ID", 5678).getInt();
GoldenDimensionalDoorItemID = config.getItem("Gold Dim Door Item ID", 5679).getInt();
WorldThreadItemID = config.getItem("World Thread Item ID", 5680).getInt();
LimboBlockID = config.getTerrainBlock("World Generation Block IDs - must be less than 256", "Limbo Block ID", 217,
"Blocks used for the terrain in Limbo").getInt();
PermaFabricBlockID = config.getTerrainBlock("World Generation Block IDs - must be less than 256",
"Perma Fabric Block ID", 220, "Blocks used for enclosing pocket dimensions").getInt();
LimboDimensionID = config.get(CATEGORY_DIMENSION, "Limbo Dimension ID", -23).getInt();
PocketProviderID = config.get(CATEGORY_PROVIDER, "Pocket Provider ID", 124).getInt();
LimboProviderID = config.get(CATEGORY_PROVIDER, "Limbo Provider ID", 113).getInt();
MonolithTeleportationEnabled = config.get(Configuration.CATEGORY_GENERAL, "Enable Monolith Teleportation", true,
"Sets whether Monoliths can teleport players").getBoolean(true);
MonolithSpawningChance = config.get(Configuration.CATEGORY_GENERAL, "Monolith Spawning Chance", 28,
"Sets the chance (out of " + CustomLimboPopulator.MAX_MONOLITH_SPAWNING_CHANCE + ") that Monoliths will " +
"spawn in a given Limbo chunk. The default chance is 28.").getInt();
ClusterGenerationChance = config.get(Configuration.CATEGORY_GENERAL, "Cluster Generation Chance", 2,
"Sets the chance (out of " + GatewayGenerator.MAX_CLUSTER_GENERATION_CHANCE + ") that a cluster of rifts will " +
"generate in a given chunk. The default chance is 2.").getInt();
GatewayGenerationChance = config.get(Configuration.CATEGORY_GENERAL, "Gateway Generation Chance", 15,
"Sets the chance (out of " + GatewayGenerator.MAX_GATEWAY_GENERATION_CHANCE + ") that a Rift Gateway will " +
"generate in a given chunk. The default chance is 15.").getInt();
FortressGatewayGenerationChance = config.get(Configuration.CATEGORY_GENERAL, "Fortress Gateway Generation Chance", 33,
"Sets the chance (out of " + DDStructureNetherBridgeStart.MAX_GATEWAY_GENERATION_CHANCE + ") that a Rift Gateway will " +
"generate as part of a Nether Fortress. The default chance is 33.").getInt();
WorldThreadDropChance = config.get(Configuration.CATEGORY_GENERAL, "World Thread Drop Chance", 50,
"Sets the chance (out of " + BlockRift.MAX_WORLD_THREAD_DROP_CHANCE + ") that a rift will " +
"drop World Thread when it destroys a block. The default chance is 50.").getInt();
LimboBiomeID = config.get(CATEGORY_BIOME, "Limbo Biome ID", 148).getInt();
PocketBiomeID = config.get(CATEGORY_BIOME, "Pocket Biome ID", 149).getInt();
config.save();
// Unfortunately, there are users out there who have been misconfiguring the worldgen blocks to have IDs above 255.
// This leads to disastrous and cryptic errors in other areas of Minecraft. To prevent headaches, we'll throw
// an exception here if the blocks have invalid IDs.
if (LimboBlockID > 255 || PermaFabricBlockID > 255)
{
throw new IllegalStateException("World generation blocks MUST have block IDs less than 256. Fix your configuration!");
}
}
public static DDProperties initialize(File configFile)
{
if (instance == null)
instance = new DDProperties(configFile);
else
throw new IllegalStateException("Cannot initialize DDProperties twice");
return instance;
}
public static DDProperties instance()
{
if (instance == null)
{
//This is to prevent some frustrating bugs that could arise when classes
//are loaded in the wrong order. Trust me, I had to squash a few...
throw new IllegalStateException("Instance of DDProperties requested before initialization");
}
return instance;
}
}
|
package alien4cloud.plugin.marathon;
import static com.google.common.collect.Maps.newHashMap;
import static java.util.Collections.emptyMap;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import com.google.common.base.Functions;
import com.google.common.collect.Collections2;
import com.google.common.collect.Lists;
import alien4cloud.orchestrators.plugin.ILocationConfiguratorPlugin;
import alien4cloud.orchestrators.plugin.IOrchestratorPlugin;
import alien4cloud.orchestrators.plugin.model.PluginArchive;
import alien4cloud.paas.IPaaSCallback;
import alien4cloud.paas.exception.MaintenanceModeException;
import alien4cloud.paas.exception.OperationExecutionException;
import alien4cloud.paas.exception.PluginConfigurationException;
import alien4cloud.paas.model.AbstractMonitorEvent;
import alien4cloud.paas.model.DeploymentStatus;
import alien4cloud.paas.model.InstanceInformation;
import alien4cloud.paas.model.InstanceStatus;
import alien4cloud.paas.model.NodeOperationExecRequest;
import alien4cloud.paas.model.PaaSDeploymentContext;
import alien4cloud.paas.model.PaaSTopologyDeploymentContext;
import alien4cloud.plugin.marathon.config.MarathonConfig;
import alien4cloud.plugin.marathon.location.MarathonLocationConfiguratorFactory;
import alien4cloud.plugin.marathon.service.BuilderService;
import alien4cloud.plugin.marathon.service.EventService;
import alien4cloud.plugin.marathon.service.MappingService;
import alien4cloud.utils.MapUtil;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import mesosphere.marathon.client.Marathon;
import mesosphere.marathon.client.MarathonClient;
import mesosphere.marathon.client.model.v2.App;
import mesosphere.marathon.client.model.v2.Deployment;
import mesosphere.marathon.client.model.v2.GetAppResponse;
import mesosphere.marathon.client.model.v2.Group;
import mesosphere.marathon.client.model.v2.HealthCheckResult;
import mesosphere.marathon.client.model.v2.Result;
import mesosphere.marathon.client.model.v2.Task;
import mesosphere.marathon.client.utils.MarathonException;
/**
* The Marathon orchestrator implementation.
*
* @author Adrian Fraisse
*/
@Slf4j
@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@Scope("prototype")
public class MarathonOrchestrator implements IOrchestratorPlugin<MarathonConfig> {
private final @NonNull BuilderService builderService;
private final @NonNull MappingService mappingService;
private final @NonNull EventService eventService;
private @NonNull MarathonLocationConfiguratorFactory marathonLocationConfiguratorFactory;
private Marathon marathonClient;
@Override
public void setConfiguration(String orchestratorId, MarathonConfig marathonConfig) throws PluginConfigurationException {
// Set up the connexion to Marathon
marathonClient = MarathonClient.getInstance(marathonConfig.getMarathonURL());
eventService.subscribe(marathonConfig.getMarathonURL().concat("/v2"));
}
@Override
public void init(Map<String, PaaSTopologyDeploymentContext> activeDeployments) {
// Init mapping
mappingService.init(activeDeployments.values());
}
@Override
public void deploy(PaaSTopologyDeploymentContext paaSTopologyDeploymentContext, IPaaSCallback<?> iPaaSCallback) {
Group group = builderService.buildGroupDefinition(paaSTopologyDeploymentContext);
try {
Result result = marathonClient.createGroup(group);
// Store the deployment ID to handle event mapping
mappingService.registerDeploymentInfo(result.getDeploymentId(), paaSTopologyDeploymentContext.getDeploymentId(),
DeploymentStatus.DEPLOYMENT_IN_PROGRESS);
} catch (MarathonException e) {
log.error("Failure while deploying - Got error code [" + e.getStatus() + "] with message: " + e.getMessage());
}
// No callback
}
@Override
public void update(PaaSTopologyDeploymentContext deploymentContext, IPaaSCallback<?> callback) {
return;
}
@Override
public void undeploy(PaaSDeploymentContext paaSDeploymentContext, IPaaSCallback<?> iPaaSCallback) {
// TODO: Add force option in Marathon-client to always force undeployment - better : cancel running deployment
try {
Result result = marathonClient.deleteGroup(paaSDeploymentContext.getDeploymentPaaSId().toLowerCase());
mappingService.registerDeploymentInfo(result.getDeploymentId(), paaSDeploymentContext.getDeploymentId(), DeploymentStatus.UNDEPLOYMENT_IN_PROGRESS);
} catch (MarathonException e) {
log.error("Failure while undeploying - Got error code [" + e.getStatus() + "] with message: " + e.getMessage());
iPaaSCallback.onFailure(e);
}
iPaaSCallback.onSuccess(null);
}
@Override
public void getStatus(PaaSDeploymentContext paaSDeploymentContext, IPaaSCallback<DeploymentStatus> iPaaSCallback) {
final String groupID = paaSDeploymentContext.getDeploymentPaaSId().toLowerCase();
try {
DeploymentStatus status = Optional.ofNullable(marathonClient.getGroup(groupID)) // Retrieve the application group of this topology
.map(this::getTopologyDeploymentStatus).orElse(DeploymentStatus.UNDEPLOYED); // Check its status
// Finally, delegate to callback
iPaaSCallback.onSuccess(status);
} catch (MarathonException e) {
switch (e.getStatus()) {
case 404: // If 404 then the group was not found on Marathon
iPaaSCallback.onSuccess(DeploymentStatus.UNDEPLOYED);
break;
default: // Other codes are errors
log.error("Unable to reach Marathon - Got error code [" + e.getStatus() + "] with message: " + e.getMessage());
iPaaSCallback.onFailure(e);
}
} catch (RuntimeException e) {
iPaaSCallback.onFailure(e.getCause());
}
}
/**
* Retrieves the status of a Topology which has already been deployed on Marathon.
*
* @param group The topology's Marathon group
* @return A <code>DeploymentStatus</code> representing the state of the topology in Marathon
* @throws RuntimeException Any exception while reaching Marathon.
*/
private DeploymentStatus getTopologyDeploymentStatus(Group group) throws RuntimeException {
try {
return marathonClient.getDeployments().stream() // Retrieve deployments
.filter(deployment ->
// If any deployment affects an app from the group, then it means the group is undertaking deployment
deployment.getAffectedApps().stream().anyMatch(s -> s.matches("^//" + group.getId() + "//"))).findFirst().map(this::getRunningDeploymentStatus) // A
// deployment
// matches
// check
// deploying
// undeploying
.orElseGet(() -> getDeployedTopologyStatus(group));// No deployment but the group exists in Marathon => the topology is deployed, check
// states
} catch (MarathonException e) {
log.error("Failure reaching for deployments - Got error code [" + e.getStatus() + "] with message: " + e.getMessage());
throw new RuntimeException(e);
}
}
/**
* Given a running Deployment, returns if it is actually deploying or un-deploying a topology.
*
* @param deployment A running deployment on Marathon.
* @return <code>DeploymentStatus.DEPLOYMENT_IN_PROGRESS</code> or <code>DeploymentStatus.UNDEPLOYMENT_IN_PROGRESS</code>.
*/
private DeploymentStatus getRunningDeploymentStatus(Deployment deployment) {
return deployment.getCurrentActions().stream().noneMatch(action -> // All actions but StopApplication reflect a deployment in progress
action.getType().matches("^StopApplication$")) ? DeploymentStatus.DEPLOYMENT_IN_PROGRESS : DeploymentStatus.UNDEPLOYMENT_IN_PROGRESS;
}
/**
* Given a deployed topology, get its status.
*
* @param group The Marathon application group.
* @return <code>DeploymentStatus.DEPLOYED</code> if all apps are healthy or <code>DeploymentStatus.FAILURE</code> if not.
*/
private DeploymentStatus getDeployedTopologyStatus(Group group) throws RuntimeException {
// First, we retrieve the Apps info from marathon
List<App> appInfo = Lists.newArrayList();
group.getApps().forEach(app -> {
try {
appInfo.add(marathonClient.getApp(app.getId()).getApp());
} catch (MarathonException e) {
log.error("Failure reaching for apps - Got error code [" + e.getStatus() + "] with message: " + e.getMessage());
switch (e.getStatus()) {
case 404:
break;
// Continue checking for apps
default:
throw new RuntimeException(e);
}
}
});
// Then check task status for each app
if (appInfo.size() < group.getApps().size() && appInfo.stream().map(App::getTasksUnhealthy).reduce(Integer::sum).orElse(0) > 0)
return DeploymentStatus.FAILURE; // If any of the Tasks is unhealthy, then consider the topology to be failing
else
return DeploymentStatus.DEPLOYED;
}
@Override
public void getInstancesInformation(PaaSTopologyDeploymentContext paaSTopologyDeploymentContext,
IPaaSCallback<Map<String, Map<String, InstanceInformation>>> iPaaSCallback) {
final Map<String, Map<String, InstanceInformation>> topologyInfo = newHashMap();
final String groupID = paaSTopologyDeploymentContext.getDeploymentPaaSId().toLowerCase();
// For each app query Marathon for its tasks
paaSTopologyDeploymentContext.getPaaSTopology().getNonNatives().forEach(paaSNodeTemplate -> {
Map<String, InstanceInformation> instancesInfo = newHashMap();
final String appID = groupID + "/" + paaSNodeTemplate.getId().toLowerCase();
try {
// Marathon tasks are alien instances
final Collection<Task> tasks = marathonClient.getAppTasks(appID).getTasks();
tasks.forEach(task -> {
final InstanceInformation instanceInformation = this.getInstanceInformation(task);
instancesInfo.put(task.getId(), instanceInformation);
});
topologyInfo.put(paaSNodeTemplate.getId(), instancesInfo);
} catch (MarathonException e) {
switch (e.getStatus()) {
case 404: // The app cannot be found in marathon - we display no information
break;
default:
iPaaSCallback.onFailure(e);
}
}
});
paaSTopologyDeploymentContext.getPaaSTopology().getVolumes().forEach(volumeTemplate -> {
// Volumes have the same state than their app
final InstanceInformation volumeInstanceInfo = volumeTemplate.getRelationshipTemplates().stream()
.filter(paaSRelationshipTemplate -> "alien.relationships.MountDockerVolume".equals(paaSRelationshipTemplate.getTemplate().getType()))
.findFirst() // Retrieve the node this volume is attached to
.map(paaSRelationshipTemplate -> paaSRelationshipTemplate.getTemplate().getTarget()).map(topologyInfo::get) // Retrieve the
// InstanceInformation map of
// the node the volume is
// attached to
.flatMap(instancesInfoMap -> // Use any instance of the node as base for the volume's InstanceInformation
instancesInfoMap.entrySet().stream().findAny()
.map(instanceInfoEntry -> new InstanceInformation(instanceInfoEntry.getValue().getState(), instanceInfoEntry.getValue().getInstanceStatus(),
emptyMap(), emptyMap(), emptyMap())))
.orElse(new InstanceInformation("uninitialized", InstanceStatus.PROCESSING, emptyMap(), emptyMap(), emptyMap()));
topologyInfo.put(volumeTemplate.getId(),
MapUtil.newHashMap(new String[] { volumeTemplate.getId() }, new InstanceInformation[] { volumeInstanceInfo }));
});
iPaaSCallback.onSuccess(topologyInfo);
}
/**
* Get instance information, eg. status and runtime properties, from a Marathon Task.
*
* @param task A Marathon Task
* @return An InstanceInformation
*/
private InstanceInformation getInstanceInformation(Task task) {
final Map<String, String> runtimeProps = newHashMap();
// Outputs Marathon endpoints as host:port1,port2, ...
final Collection<String> ports = Collections2.transform(task.getPorts(), Functions.toStringFunction());
runtimeProps.put("endpoint", "http://".concat(task.getHost().concat(":").concat(String.join(",", ports))));
InstanceStatus instanceStatus;
String state;
// Leverage Mesos's TASK_STATUS - TODO: add Mesos 1.0 task states
switch (task.getState()) {
case "TASK_RUNNING":
state = "started";
// Retrieve health checks results - if no healthcheck then assume healthy
instanceStatus = Optional.ofNullable(task.getHealthCheckResults())
.map(healthCheckResults -> healthCheckResults.stream().findFirst().map(HealthCheckResult::isAlive)
.map(alive -> alive ? InstanceStatus.SUCCESS : InstanceStatus.FAILURE).orElse(InstanceStatus.PROCESSING))
.orElse(InstanceStatus.SUCCESS);
break;
case "TASK_STARTING":
state = "starting";
instanceStatus = InstanceStatus.PROCESSING;
break;
case "TASK_STAGING":
state = "creating";
instanceStatus = InstanceStatus.PROCESSING;
break;
case "TASK_ERROR":
state = "stopped";
instanceStatus = InstanceStatus.FAILURE;
break;
default:
state = "uninitialized"; // Unknown
instanceStatus = InstanceStatus.PROCESSING;
}
return new InstanceInformation(state, instanceStatus, runtimeProps, runtimeProps, newHashMap());
}
@Override
public void getEventsSince(Date date, int i, IPaaSCallback<AbstractMonitorEvent[]> iPaaSCallback) {
iPaaSCallback.onSuccess(eventService.flushEvents());
}
@Override
public void executeOperation(PaaSTopologyDeploymentContext paaSTopologyDeploymentContext, NodeOperationExecRequest nodeOperationExecRequest,
IPaaSCallback<Map<String, String>> iPaaSCallback) throws OperationExecutionException {
}
@Override
public ILocationConfiguratorPlugin getConfigurator(String locationType) {
return marathonLocationConfiguratorFactory.newInstance(locationType);
}
@Override
public List<PluginArchive> pluginArchives() {
return Collections.emptyList();
}
@Override
public void switchMaintenanceMode(PaaSDeploymentContext paaSDeploymentContext, boolean b) throws MaintenanceModeException {
}
@Override
public void switchInstanceMaintenanceMode(PaaSDeploymentContext paaSDeploymentContext, String s, String s1, boolean b) throws MaintenanceModeException {
}
@Override
public void scale(PaaSDeploymentContext paaSDeploymentContext, String nodeTemplateId, int instances, IPaaSCallback<?> iPaaSCallback) {
String appId = paaSDeploymentContext.getDeploymentPaaSId().toLowerCase() + "/" + nodeTemplateId.toLowerCase();
try {
// retrieve the app
Optional.ofNullable(marathonClient.getApp(appId)).map(GetAppResponse::getApp).map(App::getInstances).ifPresent(currentInstances -> {
currentInstances += instances;
App app = new App();
app.setInstances(currentInstances);
try {
marathonClient.updateApp(appId, app, true);
iPaaSCallback.onSuccess(null);
} catch (MarathonException e) {
log.error("Failure while scaling - Got error code [" + e.getStatus() + "] with message: " + e.getMessage());
iPaaSCallback.onFailure(e);
}
});
} catch (MarathonException e) {
e.printStackTrace();
}
}
@Override
public void launchWorkflow(PaaSDeploymentContext paaSDeploymentContext, String s, Map<String, Object> map, IPaaSCallback<?> iPaaSCallback) {
}
}
|
package aoetk.bookmarkviewer.view;
import aoetk.bookmarkviewer.conf.ApplicationContext;
import aoetk.bookmarkviewer.conf.BookmarkViewSettings;
import aoetk.bookmarkviewer.model.BookmarkEntry;
import aoetk.bookmarkviewer.model.BookmarkModel;
import aoetk.bookmarkviewer.service.DiigoServiceClient;
import aoetk.bookmarkviewer.service.LoadingBookmarkService;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.concurrent.Worker;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.*;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.input.KeyCombination;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.Region;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebHistory;
import javafx.scene.web.WebView;
import org.owasp.encoder.Encode;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import javax.ws.rs.core.Cookie;
import java.io.IOException;
import java.net.CookieHandler;
import java.net.URI;
import java.net.URL;
import java.text.MessageFormat;
import java.util.*;
import java.util.stream.Collectors;
public class BookmarkViewController implements Initializable {
private static final String DIIGOLET_URL = "https:
private static final String EVERNOTE_CLIPPER_SCRIPT =
"javascript:(function(){EN_CLIP_HOST='http:
"try{var x=document.createElement('SCRIPT');x.type='text/javascript';" +
"x.src=EN_CLIP_HOST+'/public/bookmarkClipper.js?'+(new Date().getTime()/100000);" +
"document.getElementsByTagName('head')[0].appendChild(x);}" +
"catch(e){location.href=EN_CLIP_HOST+'/clip.action?url=" +
"'+encodeURIComponent(location.href)+'&title='+encodeURIComponent(document.title);}})();";
private static final String FIND_FUNCTION = "window.find(\"{0}\", false, false, true, false, true, false)";
@FXML
MenuItem tagSearchMenu;
@FXML
MenuItem pageSearchMenu;
@FXML
SplitPane baseSplitPane;
@FXML
Label pageTitle;
@FXML
TextField pageSearchBox;
@FXML
Label progressLabel;
@FXML
ProgressIndicator webIndicator;
@FXML
Button stopButton;
@FXML
Button backButton;
@FXML
Button forwardButton;
@FXML
TextField locationBar;
@FXML
WebView webView;
@FXML
StackPane basePane;
@FXML
TextField searchBox;
@FXML
ListView<String> tagListView;
@FXML
ListView<BookmarkEntry> bookmarkListView;
@FXML
Region vailRegion;
@FXML
VBox indicatorBox;
private BookmarkModel bookmarkModel;
private LoadingBookmarkService loadingBookmarkService;
private WebEngine webEngine;
private WebHistory history;
private Worker<Void> loadWorker;
private LoginDialog dialog;
private boolean firstLoad = true;
/**
* . , .
*
* @param url FXMLURL
* @param resourceBundle
*/
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
bookmarkListView.setCellFactory(bookmarkEntryListView -> new BookmarkCell());
ApplicationContext context = ApplicationContext.getInstance();
BookmarkViewSettings bookmarkViewSettings = context.getBookmarkViewSettings();
initViewSettings(bookmarkViewSettings);
webEngine = webView.getEngine();
history = webEngine.getHistory();
loadWorker = webEngine.getLoadWorker();
dialog = new LoginDialog();
dialog.setOnAction(actionEvent -> {
dialog.setVisible(false);
loadBookmark(dialog.getUser(), dialog.getPassword());
});
basePane.getChildren().add(dialog);
}
private void initViewSettings(BookmarkViewSettings bookmarkViewSettings) {
basePane.setPrefWidth(bookmarkViewSettings.baseWidthProperty().get());
basePane.setPrefHeight(bookmarkViewSettings.baseHeightProperty().get());
ObservableList<SplitPane.Divider> dividers = baseSplitPane.getDividers();
assert dividers.size() == 2;
dividers.get(0).setPosition(bookmarkViewSettings.leftDividerPosProperty().get());
dividers.get(1).setPosition(bookmarkViewSettings.rightDividerPosProperty().get());
// bind
bookmarkViewSettings.baseWidthProperty().bind(basePane.widthProperty());
bookmarkViewSettings.baseHeightProperty().bind(basePane.heightProperty());
bookmarkViewSettings.leftDividerPosProperty().bind(dividers.get(0).positionProperty());
bookmarkViewSettings.rightDividerPosProperty().bind(dividers.get(1).positionProperty());
}
private void loadBookmark(String userName, String password) {
loadingBookmarkService = new LoadingBookmarkService(new DiigoServiceClient(userName, password));
loadingBookmarkService.setOnSucceeded(workerStateEvent -> {
bookmarkModel = loadingBookmarkService.getValue();
setListContent();
if (firstLoad) {
setCookie(loadingBookmarkService.getLoginCookies());
addListeners();
setBindings();
firstLoad = false;
}
});
loadingBookmarkService.setOnFailed(workerStateEvent -> {
loadingBookmarkService.getException().printStackTrace();
dialog.showAlertText();
dialog.setVisible(true);
});
indicatorBox.visibleProperty().bind(loadingBookmarkService.runningProperty());
vailRegion.visibleProperty().bind(loadingBookmarkService.runningProperty());
pageSearchMenu.disableProperty().bind(vailRegion.visibleProperty());
tagSearchMenu.disableProperty().bind(vailRegion.visibleProperty());
progressLabel.textProperty().bind(loadingBookmarkService.messageProperty());
loadingBookmarkService.start();
}
private void setCookie(List<Cookie> loginCookies) {
final URI uri = URI.create("https:
final Map<String, List<String>> headerMap = new LinkedHashMap<>();
final List<String> cookieStrings = loginCookies.stream()
.map(item -> item.getName() + "=" + item.getValue())
.collect(Collectors.toList());
headerMap.put("Set-Cookie", cookieStrings);
try {
CookieHandler.getDefault().put(uri, headerMap);
} catch (IOException e) {
e.printStackTrace();
}
}
private void setBindings() {
webIndicator.visibleProperty().bind(webEngine.getLoadWorker().stateProperty().isEqualTo(Worker.State.RUNNING));
backButton.disableProperty().bind(history.currentIndexProperty().isEqualTo(0));
stopButton.disableProperty().bind(loadWorker.runningProperty().not());
pageSearchBox.disableProperty().bind(loadWorker.runningProperty());
pageTitle.textProperty().bind(webEngine.titleProperty());
}
private void addListeners() {
final KeyCombination combinationForLocationBar =
new KeyCodeCombination(KeyCode.L, KeyCombination.SHORTCUT_DOWN);
basePane.getScene().addEventHandler(KeyEvent.KEY_RELEASED, event -> {
if (combinationForLocationBar.match(event)) {
focusLocationBar();
}
});
searchBox.textProperty().addListener((observable, oldValue, newValue)
-> bookmarkModel.selectTagsByKeyword(Optional.of(newValue)));
final MultipleSelectionModel<String> tagSelectionModel = tagListView.getSelectionModel();
tagSelectionModel.setSelectionMode(SelectionMode.MULTIPLE);
tagSelectionModel.getSelectedItems().addListener((ListChangeListener.Change<? extends String> change) -> {
if (change != null) {
bookmarkModel.selectedEntriesByTags(Optional.of(Collections.unmodifiableList(change.getList())));
}
});
final MultipleSelectionModel<BookmarkEntry> selectedBookmarks = bookmarkListView.getSelectionModel();
selectedBookmarks.selectedItemProperty().addListener((property, oldEntry, newEntry) -> {
if (newEntry != null) {
loadWebContent(newEntry.urlProperty().get());
}
});
bookmarkListView.addEventFilter(ActionEvent.ACTION, event -> {
if (event.getTarget() instanceof Hyperlink) {
handleTagLinkAction(event, tagSelectionModel);
}
});
// WebView
history.currentIndexProperty().addListener((property, oldValue, newValue) ->
forwardButton.setDisable(history.getCurrentIndex() + 1 == history.getEntries().size()));
webEngine.locationProperty().addListener((observableValue, oldVal, newVal) -> locationBar.setText(newVal));
// Web
pageSearchBox.textProperty().addListener(
(observable, oldValue, newValue) -> highlightPage(Optional.ofNullable(newValue)));
}
/**
* .
*
* @param event
*/
@FXML
void handleBackButtonAction(ActionEvent event) {
if (history.getCurrentIndex() > 0) {
history.go(-1);
}
}
/**
* .
*
* @param event
*/
@FXML
void handleForwardButtonAction(ActionEvent event) {
if (history.getCurrentIndex() + 1 < history.getEntries().size()) {
history.go(1);
}
}
/**
* . Enter.
*
* @param event
*/
@FXML
void handleLocationBarKeyPressed(KeyEvent event) {
if (event.getCode() == KeyCode.ENTER && !locationBar.getText().isEmpty()) {
loadWebContent(locationBar.getText());
}
}
/**
* .
*
* @param event
*/
@FXML
void handleStopButtonAction(ActionEvent event) {
loadWorker.cancel();
}
/**
* Diigolet.
*
* @param event
*/
@FXML
void handleDiigoButtonAction(ActionEvent event) {
Optional.ofNullable(webEngine.getDocument()).ifPresent(document -> addScriptElement(document, DIIGOLET_URL));
}
/**
* Evernote Web.
*
* @param event
*/
@FXML
void handleClipButtonAction(ActionEvent event) {
if (webEngine.getDocument() != null) {
webEngine.executeScript(EVERNOTE_CLIPPER_SCRIPT);
}
}
/**
* .
*
* @param actionEvent
*/
@FXML
void handleReloadButtonAction(ActionEvent actionEvent) {
searchBox.setText("");
tagListView.getSelectionModel().clearSelection();
bookmarkListView.getSelectionModel().clearSelection();
loadingBookmarkService.reset();
loadingBookmarkService.start();
}
/**
* .
*
* @param event
*/
@FXML
void handleSearchTagMenuAction(ActionEvent event) {
searchBox.requestFocus();
}
/**
* .
*
* @param event
*/
@FXML
void handlePageSearchMenuAction(ActionEvent event) {
pageSearchBox.requestFocus();
}
/**
* . .
*
* @param event
*/
@FXML
void handleSearchBoxAction(ActionEvent event) {
highlightPage(Optional.ofNullable(pageSearchBox.getText()));
}
private void focusLocationBar() {
locationBar.requestFocus();
locationBar.selectAll();
}
private void handleTagLinkAction(ActionEvent event, final MultipleSelectionModel<String> tagSelectionModel) {
Hyperlink tagLink = (Hyperlink) event.getTarget();
searchBox.setText("");
tagSelectionModel.clearSelection();
tagSelectionModel.select(tagLink.getText());
tagListView.scrollTo(tagLink.getText());
}
private void loadWebContent(String url) {
webEngine.load(url);
}
private void setListContent() {
tagListView.setItems(bookmarkModel.getSelectedTags());
bookmarkListView.setItems(bookmarkModel.getSelectedEntries());
}
private void addScriptElement(Document document, String url) {
final Element scriptElm = document.createElement("script");
scriptElm.setAttribute("type", "text/javascript");
scriptElm.setAttribute("src", url);
NodeList bodys = document.getElementsByTagName("body");
if (bodys != null && bodys.getLength() > 0) {
bodys.item(0).appendChild(scriptElm);
}
}
private void addStyleElement(Document document, String styleContent) {
final Element styleElm = document.createElement("style");
styleElm.setAttribute("type", "text/css");
styleElm.setTextContent(styleContent);
NodeList bodys = document.getElementsByTagName("body");
if (bodys != null && bodys.getLength() > 0) {
bodys.item(0).appendChild(styleElm);
}
}
private void highlightPage(Optional<String> word) {
if (webEngine.getDocument() != null) {
final String keyword = word.orElse("");
if (!keyword.isEmpty()) {
webEngine.executeScript(MessageFormat.format(FIND_FUNCTION, Encode.forJavaScript(keyword)));
}
}
}
}
|
package be.yildiz.module.network.protocol;
import be.yildiz.common.collections.Lists;
import be.yildiz.common.collections.Maps;
import be.yildiz.common.id.ActionId;
import be.yildiz.common.id.EntityId;
import be.yildiz.common.id.PlayerId;
import be.yildiz.common.vector.Point3D;
import be.yildiz.module.network.exceptions.InvalidNetworkMessage;
import java.security.InvalidParameterException;
import java.util.*;
public abstract class NetworkMessage {
private static final Map<Class, ObjectMapper> mappers = Maps.newMap();
/**
* Message parameters.
*/
private final String[] params;
/**
* index of the current parameter read.
*/
private int index;
/**
* Full constructor.
*
* @param param List of parameters contained in the message.
*/
protected NetworkMessage(final String... param) {
super();
this.params = param;
}
/**
* Build a NetworkMessage from a received message.
*
* @param message Received message, cannot be null.
*/
protected NetworkMessage(final MessageWrapper message) {
this(getParamsFromMessage(message.message));
this.index = 0;
}
public static final <T> void registerMapper(Class<T> c, ObjectMapper<T> m) {
mappers.put(c, m);
}
/**
* Retrieve the command from the message, it is the first parameter and is in numeric format.
*
* @param message Message containing the command.
* @return The number corresponding to the command.
* @throws InvalidNetworkMessage If the message cannot be correctly parsed.
*/
public static int getCommandFromMessage(final MessageWrapper message) throws InvalidNetworkMessage {
final String[] base = message.message.split(MessageSeparation.COMMAND_SEPARATOR);
try {
return Integer.parseInt(base[0]);
} catch (NumberFormatException e) {
throw new InvalidNetworkMessage("Invalid command in message: " + message, e);
}
}
/**
* Build a list of String from a list of objects. List can be used but not arrays
*
* @param o Objects to convert.
* @return A list containing all converted objects.
*/
@SuppressWarnings({"rawtypes"})
protected static String[] convertParams(final Object... o) {
final String[] s = new String[o.length];
for (int i = 0; i < s.length; i++) {
if (o[i] instanceof Collection) {
@SuppressWarnings("unchecked")
final List l = Lists.newList((Collection) o[i]);
final StringBuilder sb = new StringBuilder();
for (final Object obj : l) {
sb.append(obj.toString());
sb.append(MessageSeparation.COLLECTION_SEPARATOR);
}
if (sb.length() > 0) {
sb.deleteCharAt(sb.length() - 1);
}
s[i] = sb.toString();
} else if (o[i] instanceof Point3D) {
Point3D p = (Point3D) o[i];
final float eps = 0.001f;
if (p.y < eps && p.y > -eps) {
String ssb = String.valueOf(p.x) +
MessageSeparation.COLLECTION_SEPARATOR +
p.z;
s[i] = ssb;
} else {
s[i] = p.toString();
}
} else {
s[i] = o[i].toString();
}
}
return s;
}
/**
* Split the message to extract its parameters.
*
* @param message Network message.
* @return The message String value parameters.
*/
private static String[] getParamsFromMessage(final String message) {
final String[] base = message.split(MessageSeparation.COMMAND_SEPARATOR);
return Arrays.copyOfRange(base, 1, base.length);
}
/**
* Append all parameters to create a unique message string.
*
* @return the built message.
*/
public final String buildMessage() {
final StringBuilder message = new StringBuilder();
message.append(MessageSeparation.MESSAGE_BEGIN);
message.append(this.command());
for (final Object o : this.params) {
message.append(MessageSeparation.COMMAND_SEPARATOR);
message.append(o);
}
message.append(MessageSeparation.MESSAGE_END);
return message.toString();
}
public final <T> T get(Class<T> c) throws InvalidNetworkMessage {
this.positionCheck(this.index);
this.nullCheck(this.params[this.index]);
T result = (T)mappers.get(c).to(this.params[this.index]);
this.index++;
return result;
}
/**
* Convert the parameter into a String.
*
* @return The String value of the parameter.
* @throws InvalidNetworkMessage If the parameter cannot be correctly parsed into String.
*/
protected final String getString() throws InvalidNetworkMessage {
this.positionCheck(this.index);
this.nullCheck(this.params[this.index]);
String result = this.params[this.index];
this.index++;
return result;
}
/**
* Convert the parameter into a boolean.
*
* @return The boolean value of the parameter.
* @throws InvalidNetworkMessage If the parameter cannot be correctly parsed into a boolean.
*/
protected final boolean getBoolean() throws InvalidNetworkMessage {
this.positionCheck(this.index);
this.nullCheck(this.params[this.index]);
boolean result = Boolean.parseBoolean(this.params[this.index]);
this.index++;
return result;
}
/**
* Convert the parameter into an integer.
*
* @return The integer value of the parameter.
* @throws InvalidNetworkMessage If the parameter cannot be correctly parsed into an integer.
*/
protected final int getInt() throws InvalidNetworkMessage {
this.positionCheck(this.index);
this.nullCheck(this.params[this.index]);
try {
int result = Integer.parseInt(this.params[this.index]);
this.index++;
return result;
} catch (final NumberFormatException nfe) {
throw new InvalidNetworkMessage("Error parsing int", nfe);
}
}
/**
* Convert the parameter into a long.
*
* @return The long value of the parameter.
* @throws InvalidNetworkMessage If the parameter cannot be correctly parsed into a long.
*/
protected final long getLong() throws InvalidNetworkMessage {
this.positionCheck(this.index);
this.nullCheck(this.params[this.index]);
try {
long result = Long.parseLong(this.params[this.index]);
this.index++;
return result;
} catch (final NumberFormatException nfe) {
throw new InvalidNetworkMessage("Error parsing long", nfe);
}
}
/**
* Convert the parameter into a float.
*
* @return The float value of the parameter.
* @throws InvalidNetworkMessage If the parameter cannot be correctly parsed into a float.
*/
protected final float getFloat() throws InvalidNetworkMessage {
this.positionCheck(this.index);
this.nullCheck(this.params[this.index]);
try {
float result = Float.parseFloat(this.params[this.index]);
this.index++;
return result;
} catch (final NumberFormatException nfe) {
throw new InvalidNetworkMessage("Error parsing float", nfe);
}
}
/**
* Convert the parameter into a Point3D.
*
* @return The Point3D value of the parameter.
* @throws InvalidNetworkMessage If the parameter cannot be correctly parsed into a Point3D.
*/
protected final Point3D getPoint3D() throws InvalidNetworkMessage {
this.positionCheck(this.index);
this.nullCheck(this.params[this.index]);
try {
Point3D result = new Point3D(this.params[this.index]);
this.index++;
return result;
} catch (final InvalidParameterException e) {
throw new InvalidNetworkMessage("Error retrieving Point3D", e);
}
}
/**
* Convert the parameter into an Id.
*
* @return The Id value of the parameter.
* @throws InvalidNetworkMessage If the parameter cannot be correctly parsed into an Id.
*/
protected final EntityId getEntityId() throws InvalidNetworkMessage {
this.positionCheck(this.index);
this.nullCheck(this.params[this.index]);
try {
EntityId result = EntityId.get(Long.parseLong(this.params[this.index]));
this.index++;
return result;
} catch (final NumberFormatException nfe) {
throw new InvalidNetworkMessage("Error retrieving id", nfe);
}
}
/**
* Convert the parameter into an Id.
*
* @return The Id value of the parameter.
* @throws InvalidNetworkMessage If the parameter cannot be correctly parsed into an Id.
*/
protected final ActionId getActionId() throws InvalidNetworkMessage {
this.positionCheck(this.index);
this.nullCheck(this.params[this.index]);
try {
ActionId result = ActionId.get(Integer.parseInt(this.params[this.index]));
this.index++;
return result;
} catch (final NumberFormatException nfe) {
throw new InvalidNetworkMessage("Error retrieving id", nfe);
}
}
/**
* Convert the parameter into an Id.
*
* @return The Id value of the parameter.
* @throws InvalidNetworkMessage If the parameter cannot be correctly parsed into an Id.
*/
protected final PlayerId getPlayerId() throws InvalidNetworkMessage {
this.positionCheck(this.index);
this.nullCheck(this.params[this.index]);
try {
PlayerId result = PlayerId.get(Integer.parseInt(this.params[this.index]));
this.index++;
return result;
} catch (final NumberFormatException nfe) {
throw new InvalidNetworkMessage("Error retrieving id", nfe);
}
}
/**
* Convert the parameter into a List of Float.
*
* @return A list of Float objects.
* @throws InvalidNetworkMessage If the parameter cannot be correctly parsed into a List of Float.
*/
protected final List<Float> getFloatList() throws InvalidNetworkMessage {
this.positionCheck(this.index);
this.nullCheck(this.params[this.index]);
String param = this.params[this.index];
param = param.replace("[", "");
param = param.replace("]", "");
final String[] values = param.split(MessageSeparation.COLLECTION_SEPARATOR);
final List<Float> result = Lists.newList(values.length);
for (final String current : values) {
result.add(Float.valueOf(current));
}
this.index++;
return result;
}
/**
* Convert the parameter into a List of String.
*
* @return A list of String objects.
* @throws InvalidNetworkMessage If the parameter cannot be correctly parsed into a List of String.
*/
protected final List<String> getStringList() throws InvalidNetworkMessage {
this.nullCheck(this.params[this.index]);
String param = this.params[this.index];
param = param.replace("[", "");
param = param.replace("]", "");
final String[] values = param.split(MessageSeparation.COLLECTION_SEPARATOR);
final List<String> result = Lists.newList(values.length);
Collections.addAll(result, values);
this.index++;
return result;
}
protected final List<EntityId> getEntityIdList() throws InvalidNetworkMessage {
this.positionCheck(this.index);
this.nullCheck(this.params[this.index]);
String param = this.params[this.index];
param = param.replace("[", "");
param = param.replace("]", "");
final String[] values = param.split(MessageSeparation.COLLECTION_SEPARATOR);
final List<EntityId> result = Lists.newList(values.length);
for (final String current : values) {
result.add(EntityId.get(Long.parseLong(current.trim())));
}
this.index++;
return result;
}
protected final List<ActionId> getActionIdList() throws InvalidNetworkMessage {
this.positionCheck(this.index);
this.nullCheck(this.params[this.index]);
String param = this.params[this.index];
param = param.replace("[", "");
param = param.replace("]", "");
final String[] values = param.split(MessageSeparation.COLLECTION_SEPARATOR);
final List<ActionId> result = Lists.newList(values.length);
for (final String current : values) {
result.add(ActionId.get(Integer.parseInt(current.trim())));
}
this.index++;
return result;
}
/**
* Check if the parameter is <code>null</code>.
*
* @param value Value to check.
* @throws InvalidNetworkMessage If the given parameter is <code>null</code>.
*/
private void nullCheck(final String value) throws InvalidNetworkMessage {
if (value == null) {
throw new InvalidNetworkMessage("Null value");
}
}
/**
* Check if the parameter position is correctly in the parameter array.
*
* @param value Value to check.
* @throws InvalidNetworkMessage If the position is not correct.
*/
private void positionCheck(final int value) throws InvalidNetworkMessage {
if (value > this.params.length - 1 || value < 0) {
throw new InvalidNetworkMessage("Message incomplete");
}
}
/**
* @return The command to use with the message type.
*/
public abstract int command();
@Override
public final String toString() {
return this.buildMessage();
}
}
|
package br.com.leandromoreira.jdcpu16br;
import static br.com.leandromoreira.jdcpu16br.OpCodes.*;
public class InstructionTable {
private static final int NUMBER_OF_INSTRUCTIONS = 0x10;
private static final int ZERO = 0;
private static final HexaFormatter formatter = new HexaFormatter();
private CPU cpu;
public Instruction[] instructionSet(final CPU cpu) {
this.cpu = cpu;
final Instruction[] instruction = new Instruction[NUMBER_OF_INSTRUCTIONS];
instruction[NOT_BASIC] = new DefaultInstruction() {
private int cycles = 2;
private String assembler = "";
@Override
public void execute() {
final int syscall = cpu.getCurrentWord().a();
final int a = cpu.getCurrentWord().b();
final ParameterDecoder aDecoded = cpu.decoderFor(a);
switch (syscall) {
case SYSCALL_JSR:
final int newPC = aDecoded.read();
assembler = "JSR " + formatter.toHexadecimal(newPC);
cpu.setStackPointer(cpu.getProgramCounter() + 1);
cpu.setProgramCounter(newPC);
defaultSumToNextInstruction = ZERO;
break;
default:
assembler = "SYSCALL RESERVED " + formatter.toHexadecimal(syscall);
break;
}
}
@Override
public int cycles() {
return cycles;
}
@Override
public String toString() {
return assembler;
}
};
instruction[SET] = new DefaultInstruction() {
@Override
public void execute() {
cpu.parameterA().write(cpu.parameterB().read());
}
};
instruction[ADD] = new DefaultInstruction() {
@Override
public void execute() {
cpu.parameterA().write(cpu.parameterA().read() + cpu.parameterB().read());
final int newOverflow = (cpu.parameterA().read() > 0xFFFF) ? 0x0001 : 0x0000;
cpu.setOverflow(newOverflow);
}
@Override
public int cycles() {
return 2;
}
};
instruction[SUB] = new DefaultInstruction() {
@Override
public void execute() {
cpu.parameterA().write(cpu.parameterA().read() - cpu.parameterB().read());
final int newOverflow = (cpu.parameterA().read() < 0x0000) ? 0xFFFF : 0x0000;
cpu.setOverflow(newOverflow);
}
@Override
public int cycles() {
return 2;
}
};
instruction[MUL] = new DefaultInstruction() {
@Override
public void execute() {
cpu.parameterA().write(cpu.parameterA().read() * cpu.parameterB().read());
cpu.setOverflow((cpu.parameterA().read() >> 16) & 0xFFF);
}
@Override
public int cycles() {
return 2;
}
};
instruction[DIV] = new DefaultInstruction() {
@Override
public void execute() {
if (cpu.parameterB().read() != ZERO) {
cpu.parameterA().write(cpu.parameterA().read() / cpu.parameterB().read());
cpu.setOverflow(((cpu.parameterA().read() << 16) / cpu.parameterB().read()) & 0xFFFF);
} else {
cpu.parameterA().write(ZERO);
cpu.setOverflow(ZERO);
}
}
@Override
public int cycles() {
return 3;
}
};
instruction[MOD] = new DefaultInstruction() {
@Override
public void execute() {
final int mod = (cpu.parameterB().read() == 0) ? ZERO : cpu.parameterA().read() % cpu.parameterB().read();
cpu.parameterA().write(mod);
}
@Override
public int cycles() {
return 3;
}
};
instruction[SHL] = new DefaultInstruction() {
@Override
public void execute() {
cpu.setOverflow(((cpu.parameterA().read() << cpu.parameterB().read()) >> 16) & 0xFFFF);
cpu.parameterA().write(cpu.parameterA().read() << cpu.parameterB().read());
}
@Override
public int cycles() {
return 2;
}
};
instruction[SHR] = new DefaultInstruction() {
@Override
public void execute() {
cpu.setOverflow(((cpu.parameterA().read() << 16) >> cpu.parameterB().read()) & 0xFFFF);
cpu.parameterA().write(cpu.parameterA().read() >> cpu.parameterB().read());
}
@Override
public int cycles() {
return 2;
}
};
instruction[AND] = new DefaultInstruction() {
@Override
public void execute() {
cpu.parameterA().write(cpu.parameterA().read() & cpu.parameterB().read());
}
};
instruction[BOR] = new DefaultInstruction() {
@Override
public void execute() {
cpu.parameterA().write(cpu.parameterA().read() | cpu.parameterB().read());
}
};
instruction[XOR] = new DefaultInstruction() {
@Override
public void execute() {
cpu.parameterA().write(cpu.parameterA().read() ^ cpu.parameterB().read());
}
};
instruction[IFE] = new DefaultInstruction() {
private int costOfFaling = 0;
@Override
public void execute() {
if (cpu.parameterA().read() != cpu.parameterB().read()) {
defaultSumToNextInstruction += nextInstructionSize(cpu.getProgramCounter() + 1);
costOfFaling = 1;
} else {
costOfFaling = 0;
}
}
@Override
public int cycles() {
return 2 + costOfFaling;
}
};
instruction[IFN] = new DefaultInstruction() {
private int costOfFaling = 0;
@Override
public void execute() {
if (cpu.parameterA().read() == cpu.parameterB().read()) {
defaultSumToNextInstruction += nextInstructionSize(cpu.getProgramCounter() + 1);
costOfFaling = 1;
} else {
costOfFaling = 0;
}
}
@Override
public int cycles() {
return 2 + costOfFaling;
}
};
instruction[IFG] = new DefaultInstruction() {
private int costOfFaling = 0;
@Override
public void execute() {
if (cpu.parameterA().read() < cpu.parameterB().read()) {
defaultSumToNextInstruction += nextInstructionSize(cpu.getProgramCounter() + 1);
costOfFaling = 1;
} else {
costOfFaling = 0;
}
}
@Override
public int cycles() {
return 2 + costOfFaling;
}
};
instruction[IFB] = new DefaultInstruction() {
private int costOfFaling = 0;
@Override
public void execute() {
if ((cpu.parameterA().read() & cpu.parameterB().read()) == ZERO) {
defaultSumToNextInstruction += nextInstructionSize(cpu.getProgramCounter() + 1);
costOfFaling = 1;
} else {
costOfFaling = 0;
}
}
@Override
public int cycles() {
return 2 + costOfFaling;
}
};
return instruction;
}
public int nextInstructionSize(final int newProgramCounter) {
final Word currentWord = new Word(cpu.memory().readFrom(newProgramCounter));
final ParameterDecoder a = cpu.decoderFor(currentWord.a());
final ParameterDecoder b = cpu.decoderFor(currentWord.b());
final Instruction instruction = cpu.getInstructions()[currentWord.code()];
return (instruction.sumToPC() != 0) ? instruction.sumToPC() + a.size() + b.size() : 0;
}
}
|
package br.com.sistemaescolar.controller;
import java.util.List;
import javax.inject.Inject;
import javax.transaction.Transactional;
import javax.validation.Valid;
import br.com.caelum.vraptor.Controller;
import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Path;
import br.com.caelum.vraptor.Post;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.validator.Validator;
import br.com.sistemaescolar.modelo.Turma;
import br.com.sistemaescolar.service.CursoService;
import br.com.sistemaescolar.service.TurmaService;
/**
* @author Leonardo Ribeiro
* @since 16/10/2015
*/
@Controller
public class TurmaController {
@Inject
private TurmaService turmaService;
@Inject
private CursoService cursoService;
@Inject
private Result result;
@Inject
private Validator validator;
@Path("/turma/novo")
public void novo() {
result.include("cursos", cursoService.listarTodos());
}
@Post
public void adiciona(Turma turma) {
turmaService.insert(turma);
result.redirectTo(TurmaController.class).novo();
}
@Get("/turma/listar")
public void listar() {
List<Turma> turmas = turmaService.listarTodas();
result.include("listaTurmas", turmas);
}
@Get("/turma/{turma.id}")
public void atualizarFormulario(Turma turma) {
result.include("disciplina", turmaService.buscarPorId(turma.getId()));
}
@Post("/turma/{id}")
@Transactional
public void atualizar(Long id, @Valid Turma turma) {
turma.setId(id);
validator.onErrorForwardTo(this).atualizarFormulario(turma);
turmaService.atualizar(turma);
result.redirectTo(this).listar();
}
@Get("/turma/delete/{id}")
@Transactional
public void remove(Long id) {
Turma turma = turmaService.buscarPorId(id);
turmaService.remove(turma);
result.redirectTo(this).listar();
}
}
|
package br.senac.tads.pi3.uriel.exercicio01;
import java.awt.HeadlessException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;
/**
*
* @author uriel.pgoliveira
*/
public class exercicios01 {
public static Scanner teclado = new Scanner(System.in);
String connectionUrl = "jdbc:sqlserver://localhost:1433;\" +\n"
+ " \"databaseName=db1;user=usuarioDB;password=1234";
public boolean conexaoDb() {
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver").newInstance();
Connection conn = DriverManager.getConnection(connectionUrl);
System.out.println("Conexão obtida com sucesso.");
PreparedStatement ps = conn.prepareStatement("INSERT INTO dbo.info (nome, email, telefone, dataNascto)"
+ "VALUES (?, ?, ?, ?)");
ps.setString(1, getNome());
int result = ps.executeUpdate();
return true;
} catch (SQLException ex) {
System.out.println("SQLException: " + ex.getMessage());
System.out.println("SQLState: " + ex.getSQLState());
System.out.println("VendorError: " + ex.getErrorCode());
return false;
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | HeadlessException e) {
System.out.println("Problemas ao tentar conectar com o banco de dados: " + e);
return false;
}
}
public static void main(String args[]){
String nome,email,telefone,dataNasct;
byte cod=0;
do {
System.out.println("Deseja realizar o cadastro?\n"
+ "Digite 1 para sim\n"
+ "Digite 2 para sair\n");
cod = teclado.nextByte();
System.out.println("Digite seu nome: ");
nome = teclado.nextLine();
teclado.next();
System.out.println("Digite seu email: ");
email = teclado.nextLine();
teclado.next();
System.out.println("Digite seu telefone: ");
telefone = teclado.nextLine();
teclado.next();
System.out.println("Digite a data de nascimento (DD/MM/AA): ");
dataNasct = teclado.nextLine();
teclado.next();
} while(cod!=2);
}
}
|
package ch.wisv.payments.security;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import lombok.Getter;
import lombok.Setter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.http.HttpStatus;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.client.oidc.userinfo.OidcUserRequest;
import org.springframework.security.oauth2.client.oidc.userinfo.OidcUserService;
import org.springframework.security.oauth2.client.userinfo.OAuth2UserService;
import org.springframework.security.oauth2.core.oidc.OidcIdToken;
import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser;
import org.springframework.security.oauth2.core.oidc.user.OidcUser;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.HttpStatusEntryPoint;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
/**
* CHConnectConfiguration class.
*/
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
@ConfigurationProperties(prefix = "wisvch.connect")
@Validated
@Profile("!test")
public class ChConnectConfiguration extends WebSecurityConfigurerAdapter {
/**
* Groups that are admin in the system.
*/
@Getter
@Setter
private List<String> adminGroups;
/**
* List of all the users that are allowed in the beta.
*/
@Getter
@Setter
private List<String> betaUsers;
/**
* The configuration of the authentication.
* @param http
* @throws Exception
*/
public void configure(HttpSecurity http) throws Exception {
http
.cors()
.and()
/**
* Configure the CORS response.
* @return CorsConfigurationSource
*/
@Bean
public CorsConfigurationSource corsConfigurationSource() {
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
/**
* OidcUserService. This decides the right of the logged-in user.
* @return OAuth2UserService
*/
private OAuth2UserService<OidcUserRequest, OidcUser> oidcUserService() {
final OidcUserService delegate = new OidcUserService();
return (userRequest) -> {
OidcUser oidcUser = delegate.loadUser(userRequest);
SimpleGrantedAuthority roleAdmin = new SimpleGrantedAuthority("ROLE_ADMIN");
SimpleGrantedAuthority roleCommittee = new SimpleGrantedAuthority("ROLE_COMMITTEE");
SimpleGrantedAuthority roleUser = new SimpleGrantedAuthority("ROLE_USER");
OidcIdToken idToken = oidcUser.getIdToken();
Collection<String> groups = (Collection<String>) idToken.getClaims().get("ldap_groups");
List<SimpleGrantedAuthority> authorities = new ArrayList<>();
authorities.add(roleUser);
if (groups.stream().anyMatch(o -> adminGroups.contains(o))) {
authorities.add(roleAdmin);
}
if (groups.stream().anyMatch(group -> !group.equals("users"))) {
authorities.add(roleCommittee);
}
return new DefaultOidcUser(authorities, idToken, oidcUser.getUserInfo());
};
}
}
|
package com.buuz135.industrial.item.addon;
import com.buuz135.industrial.proxy.ItemRegistry;
import com.buuz135.industrial.tile.WorkingAreaElectricMachine;
import com.buuz135.industrial.utils.RecipeUtils;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.client.util.ITooltipFlag;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.ItemStack;
import net.minecraft.util.NonNullList;
import net.minecraft.world.World;
import net.minecraftforge.client.model.ModelLoader;
import net.ndrei.teslacorelib.tileentities.SidedTileEntity;
import javax.annotation.Nullable;
import java.util.List;
public class RangeAddonItem extends CustomAddon {
public RangeAddonItem() {
super("range_addon");
setMaxStackSize(1);
setHasSubtypes(true);
}
@Override
public boolean canBeAddedTo(SidedTileEntity machine) {
return !machine.getAddons().contains(this) && machine instanceof WorkingAreaElectricMachine && ((WorkingAreaElectricMachine) machine).canAcceptRangeUpgrades();
}
@Override
public void getSubItems(CreativeTabs tab, NonNullList<ItemStack> items) {
if (isInCreativeTab(tab)) for (int i = 0; i < 12; ++i) items.add(new ItemStack(this, 1, i));
}
@Override
public void registerRenderer() {
for (int i = 0; i < 12; ++i)
ModelLoader.setCustomModelResourceLocation(this, i, new ModelResourceLocation(this.getRegistryName().toString() + i, "inventory"));
}
@Override
public void addInformation(ItemStack stack, @Nullable World worldIn, List<String> tooltip, ITooltipFlag flagIn) {
super.addInformation(stack, worldIn, tooltip, flagIn);
tooltip.add("Range: +" + (stack.getMetadata() + 1));
}
public void createRecipe() {
Object[] items = new Object[]{new ItemStack(Blocks.COBBLESTONE), new ItemStack(Items.DYE, 1, 4), "ingotIron", "TIER3", "TIER4", "TIER5", "TIER6", "ingotGold", new ItemStack(Items.QUARTZ), new ItemStack(Items.DIAMOND), "TIER10", new ItemStack(Items.EMERALD)};
for (int i = 0; i < 12; ++i) {
RecipeUtils.addShapedRecipe(new ItemStack(this, 1, i), "ipi", "igi", "ipi",
'i', items[i],
'p', ItemRegistry.plastic,
'g', "paneGlass");
}
}
}
|
package com.celements.navigation.service;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.xwiki.component.annotation.Component;
import org.xwiki.component.annotation.Requirement;
import org.xwiki.context.Execution;
import org.xwiki.model.EntityType;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.model.reference.EntityReference;
import org.xwiki.model.reference.EntityReferenceSerializer;
import com.celements.inheritor.InheritorFactory;
import com.celements.navigation.Navigation;
import com.celements.navigation.TreeNode;
import com.celements.navigation.filter.INavFilter;
import com.celements.navigation.filter.InternalRightsFilter;
import com.celements.web.service.IWebUtilsService;
import com.celements.web.service.WebUtilsService;
import com.xpn.xwiki.XWikiContext;
import com.xpn.xwiki.XWikiException;
import com.xpn.xwiki.doc.XWikiDocument;
import com.xpn.xwiki.objects.BaseCollection;
import com.xpn.xwiki.objects.BaseObject;
/**
* TreeNodeService
*
* access a tree node structure through the method of this service.
*
* @author Fabian Pichler
*
*/
@Component
public class TreeNodeService implements ITreeNodeService {
private static Log LOGGER = LogFactory.getFactory().getInstance(TreeNodeService.class);
@Requirement
Execution execution;
@Requirement
ITreeNodeCache treeNodeCache;
@Requirement("default")
EntityReferenceSerializer<String> serializer;
@Requirement
IWebUtilsService webUtilsService;
private InheritorFactory injectedInheritorFactory;
@Requirement
Map<String, ITreeNodeProvider> nodeProviders;
private XWikiContext getContext() {
return (XWikiContext)execution.getContext().getProperty("xwikicontext");
}
public int getActiveMenuItemPos(int menuLevel, String menuPart) {
List<DocumentReference> parents = webUtilsService.getDocumentParentsList(
getContext().getDoc().getDocumentReference(), true);
if (parents.size() >= menuLevel) {
return getMenuItemPos(parents.get(parents.size() - menuLevel), menuPart);
}
return -1;
}
public int getMenuItemPos(DocumentReference docRef, String menuPart) {
try {
DocumentReference parent = getParentRef(docRef);
int pos = -1;
for (TreeNode menuItem : getSubNodesForParent(parent, menuPart)) {
pos = pos + 1;
if (docRef.equals(menuItem.getDocumentReference())) {
return pos;
}
}
} catch (XWikiException e) {
LOGGER.error(e);
}
return -1;
}
/**
*
* @deprecated since 2.17.0 use getSubNodesForParent(EntityReference, INavFilter) or
* getSubNodesForParent(EntityReference, String) instead
*/
@Deprecated
public <T> List<TreeNode> getSubNodesForParent(String parent, String menuSpace,
INavFilter<T> filter) {
if("".equals(menuSpace)) {
menuSpace = getContext().getDoc().getDocumentReference().getLastSpaceReference(
).getName();
}
String parentKey = getParentKey(parent, menuSpace);
return getSubNodesForParent(resolveEntityReference(parentKey), filter);
}
String getParentKey(String parent, String menuSpace) {
String parentKey = "";
if (parent != null) {
parentKey = parent;
}
if(parentKey.indexOf('.') < 0) {
parentKey = menuSpace + "." + parentKey;
}
if(parentKey.indexOf(':') < 0) {
parentKey = getContext().getDatabase() + ":" + parentKey;
}
return parentKey;
}
String getParentKey(EntityReference reference, boolean withDataBase) {
String parentKey = "";
if (reference != null) {
parentKey = serializer.serialize(reference);
if (!parentKey.contains(":") && !parentKey.endsWith(":")) {
parentKey += ":";
} else if (!parentKey.contains(".") && !parentKey.endsWith(".")) {
parentKey += ".";
}
if (!withDataBase) {
parentKey = parentKey.substring(parentKey.indexOf(":") + 1);
}
}
LOGGER.debug("getParentKey: returning [" + parentKey + "] for entityref ["
+ reference + "].");
return parentKey;
}
public <T> List<TreeNode> getSubNodesForParent(EntityReference entRef,
INavFilter<T> filter) {
ArrayList<TreeNode> menuArray = new ArrayList<TreeNode>();
for(TreeNode node : fetchNodesForParentKey(entRef)) {
if((node!=null) && filter.includeTreeNode(node, getContext())) {
// show only Menuitems of pages accessible to the current user
menuArray.add(node);
}
}
return menuArray;
}
/**
*
* @deprecated since 2.17.0 use getSubNodesForParent(EntityReference, INavFilter) or
* getSubNodesForParent(EntityReference, String) instead
*/
@Deprecated
public List<TreeNode> getSubNodesForParent(String parent, String menuSpace,
String menuPart) {
InternalRightsFilter filter = new InternalRightsFilter();
filter.setMenuPart(menuPart);
List<TreeNode> subNodesForParent = getSubNodesForParent(parent, menuSpace, filter);
LOGGER.debug("getSubNodesForParent deprecated use: parent [" + parent
+ "] menuSpace [" + menuSpace + "] menuPart [" + menuPart + "] returning ["
+ subNodesForParent.size() + "].");
return subNodesForParent;
}
public List<TreeNode> getSubNodesForParent(EntityReference entRef, String menuPart) {
InternalRightsFilter filter = new InternalRightsFilter();
filter.setMenuPart(menuPart);
return getSubNodesForParent(entRef, filter);
}
/**
* fetchNodesForParentKey
* @param parentKey
* @param context
* @return Collection keeps ordering of TreeNodes according to posId
*/
List<TreeNode> fetchNodesForParentKey(EntityReference parentRef) {
String parentKey = getParentKey(parentRef, true);
LOGGER.trace("fetchNodesForParentKey: parentRef [" + parentRef + "] parentKey ["
+ parentKey+ "].");
long starttotal = System.currentTimeMillis();
long start = System.currentTimeMillis();
List<TreeNode> nodes = fetchNodesForParentKey_internal(parentKey, starttotal, start);
if ((nodeProviders != null) && (nodeProviders.values().size() > 0)) {
TreeMap<Integer, TreeNode> treeNodesMergedMap = new TreeMap<Integer, TreeNode>();
for (TreeNode node : nodes) {
treeNodesMergedMap.put(new Integer(node.getPosition()), node);
}
for (ITreeNodeProvider tnProvider : nodeProviders.values()) {
try {
for (TreeNode node : tnProvider.getTreeNodesForParent(parentKey)) {
treeNodesMergedMap.put(new Integer(node.getPosition()), node);
}
} catch(Exception exp) {
LOGGER.warn("Failed on provider [" + tnProvider.getClass()
+ "] to get nodes for parentKey [" + parentKey + "].", exp);
}
}
nodes = new ArrayList<TreeNode>(treeNodesMergedMap.values());
long end = System.currentTimeMillis();
LOGGER.info("fetchNodesForParentKey: [" + parentKey + "] totaltime for list of ["
+ nodes.size() + "]: " + (end-starttotal));
}
return nodes;
}
private List<TreeNode> fetchNodesForParentKey_internal(String parentKey,
long starttotal, long start) {
List<TreeNode> notMappedmenuItems = treeNodeCache.getNotMappedMenuItemsForParentCmd(
).getTreeNodesForParentKey(parentKey, getContext());
long end = System.currentTimeMillis();
LOGGER.debug("fetchNodesForParentKey_internal: time for"
+ " getNotMappedMenuItemsFromDatabase: " + (end-start));
start = System.currentTimeMillis();
List<TreeNode> mappedTreeNodes = treeNodeCache.getMappedMenuItemsForParentCmd(
).getTreeNodesForParentKey(parentKey, getContext());
end = System.currentTimeMillis();
LOGGER.debug("fetchNodesForParentKey_internal: time for"
+ " getMappedMenuItemsForParentCmd: " + (end-start));
start = System.currentTimeMillis();
TreeMap<Integer, TreeNode> menuItemsMergedMap = null;
if ((notMappedmenuItems == null) || (notMappedmenuItems.size() == 0)) {
end = System.currentTimeMillis();
LOGGER.info("fetchNodesForParentKey_internal: [" + parentKey
+ "] totaltime for list of [" + mappedTreeNodes.size() + "]: "
+ (end - starttotal));
return mappedTreeNodes;
} else if (mappedTreeNodes.size() == 0) {
end = System.currentTimeMillis();
LOGGER.info("fetchNodesForParentKey_internal: [" + parentKey
+ "] totaltime for list of [" + notMappedmenuItems.size() + "]: "
+ (end - starttotal));
return notMappedmenuItems;
} else {
menuItemsMergedMap = new TreeMap<Integer, TreeNode>();
for (TreeNode node : notMappedmenuItems) {
menuItemsMergedMap.put(new Integer(node.getPosition()), node);
}
for (TreeNode node : mappedTreeNodes) {
menuItemsMergedMap.put(new Integer(node.getPosition()), node);
}
end = System.currentTimeMillis();
LOGGER.debug("fetchNodesForParentKey_internal: time for merging menu items: "
+ (end-start));
ArrayList<TreeNode> menuItems = new ArrayList<TreeNode>(menuItemsMergedMap.values(
));
LOGGER.info("fetchNodesForParentKey_internal: [" + parentKey
+ "] totaltime for list of [" + menuItems.size() + "]: " + (end-starttotal));
return menuItems;
}
}
/**
*
* @param parentKey
* @param context
* @return Collection keeps ordering of menuItems according to posId
*
* @deprecated since 2.14.0 use new fetchNodesForParentKey instead
*/
@Deprecated
List<BaseObject> fetchMenuItemsForXWiki(String parentKey) {
long starttotal = System.currentTimeMillis();
List<BaseObject> menuItemList = new ArrayList<BaseObject>();
EntityReference refParent = resolveEntityReference(parentKey);
for (TreeNode node : fetchNodesForParentKey(refParent)) {
try {
XWikiDocument itemdoc = getContext().getWiki().getDocument(node.getFullName(),
getContext());
BaseObject cobj = itemdoc.getObject("Celements2.MenuItem");
if(cobj != null) {
menuItemList.add(cobj);
}
} catch (XWikiException exp) {
LOGGER.error("failed to get doc for menuItem", exp);
}
}
long end = System.currentTimeMillis();
LOGGER.info("fetchMenuItemsForXWiki: [" + parentKey + "] totaltime for list of ["
+ menuItemList.size() + "]: " + (end-starttotal));
return menuItemList;
}
EntityReference resolveEntityReference(String name) {
String
wikiName = "",
spaceName = "",
docName = "";
String[] name_a = name.split("\\.");
String[] name_b = name_a[0].split(":");
//wikiName:spaceName
if(name_b.length>1){
wikiName = name_b[0];
spaceName = name_b[1];
//wikiName:
} else if(name_a[0].endsWith(":")){
if(name_b.length>0){
wikiName = name_b[0];
}
//spaceName
} else{
wikiName = getContext().getDatabase();
if(name_b.length>0){
spaceName = name_b[0];
}
}
if(name_a.length>1){
docName = name_a[1];
}
EntityReference entRef = new EntityReference(wikiName, EntityType.WIKI);
if(spaceName.length()>0){
entRef = new EntityReference(spaceName, EntityType.SPACE, entRef);
if(docName.length()>0){
entRef = new EntityReference(docName, EntityType.DOCUMENT, entRef);
}
}
LOGGER.debug("resolveEntityReference: for [" + name + "] returning [" + entRef
+ "].");
return entRef;
}
/**
*
* @deprecated since 2.14.0 use getSubNodesForParent(EntityReference, INavFilter) or
* getSubNodesForParent(EntityReference, String) instead
*/
@Deprecated
public <T> List<T> getSubMenuItemsForParent(String parent, String menuSpace,
INavFilter<T> filter) {
if("".equals(menuSpace)) {
menuSpace = getContext().getDoc().getSpace();
}
String parentKey = getParentKey(parent, menuSpace);
ArrayList<T> menuArray = new ArrayList<T>();
for (BaseObject baseObj : fetchMenuItemsForXWiki(parentKey)) {
if(filter.includeMenuItem(baseObj, getContext())) {
// show only Menuitems of pages accessible to the current user
menuArray.add(filter.convertObject(baseObj, getContext()));
}
}
return menuArray;
}
public Integer getMaxConfiguredNavigationLevel() {
try {
BaseCollection navConfigObj = getInheritorFactory().getConfigDocFieldInheritor(
Navigation.NAVIGATION_CONFIG_CLASS, getParentKey(
getContext().getDoc().getDocumentReference(), false),
getContext()).getObject("menu_element_name");
if(navConfigObj!=null){
XWikiDocument navConfigDoc = getContext().getWiki().getDocument(
navConfigObj.getDocumentReference(), getContext());
List<BaseObject> navConfigObjects = navConfigDoc.getXObjects(
getRef(Navigation.NAVIGATION_CONFIG_CLASS_SPACE,
Navigation.NAVIGATION_CONFIG_CLASS_DOC));
int maxLevel = 0;
if (navConfigObj != null) {
for (BaseObject navObj : navConfigObjects) {
if (navObj != null) {
maxLevel = Math.max(maxLevel, navObj.getIntValue("to_hierarchy_level"));
}
}
}
return maxLevel;
}
} catch (XWikiException e) {
LOGGER.error("unable to get configDoc.", e);
}
return Navigation.DEFAULT_MAX_LEVEL;
}
public TreeNode getPrevMenuItem(DocumentReference docRef) throws XWikiException {
return getSiblingMenuItem(docRef, true);
}
public TreeNode getNextMenuItem(DocumentReference docRef) throws XWikiException {
return getSiblingMenuItem(docRef, false);
}
TreeNode getSiblingMenuItem(DocumentReference docRef, boolean previous)
throws XWikiException {
XWikiDocument doc = getContext().getWiki().getDocument(docRef, getContext());
BaseObject menuItem = doc.getXObject(getRef("Celements2", "MenuItem"));
if(menuItem!=null){
DocumentReference parent;
try {
parent = getParentRef(docRef);
List<TreeNode> subMenuItems = getSubNodesForParent(parent,
menuItem.getStringValue("part_name"));
LOGGER.debug("getPrevMenuItem: " + subMenuItems.size()
+ " subMenuItems found for parent '" + parent + "'. "
+ Arrays.deepToString(subMenuItems.toArray()));
int pos = getMenuItemPos(docRef, menuItem.getStringValue("part_name"));
if(previous && (pos>0)){
return subMenuItems.get(pos - 1);
} else if (!previous && (pos < (subMenuItems.size() - 1))) {
return subMenuItems.get(pos + 1);
}
LOGGER.info("getPrevMenuItem: no previous MenuItem found for "
+ getParentKey(docRef, true));
} catch (XWikiException e) {
LOGGER.error(e);
}
} else {
LOGGER.debug("getPrevMenuItem: no MenuItem Object found on doc "
+ getParentKey(docRef, true));
}
return null;
}
public List<TreeNode> getMenuItemsForHierarchyLevel(int menuLevel, String menuPart) {
DocumentReference parent = new WebUtilsService().getParentForLevel(menuLevel);
if (parent != null) {
List<TreeNode> submenuItems = getSubNodesForParent(parent, menuPart);
LOGGER.debug("submenuItems for parent: " + parent + " ; " + submenuItems);
return submenuItems;
}
LOGGER.debug("parent is null");
return new ArrayList<TreeNode>();
}
DocumentReference getRef(String spaceName, String pageName){
return new DocumentReference(getContext().getDatabase(), spaceName, pageName);
}
private DocumentReference getParentRef(DocumentReference docRef) throws XWikiException {
return getContext().getWiki().getDocument(docRef, getContext()).getParentReference();
}
/**
* FOR TEST PURPOSES ONLY
*/
public void injectInheritorFactory(InheritorFactory injectedInheritorFactory) {
this.injectedInheritorFactory = injectedInheritorFactory;
}
private InheritorFactory getInheritorFactory() {
if (injectedInheritorFactory != null) {
return injectedInheritorFactory;
}
return new InheritorFactory();
}
}
|
package com.elmakers.mine.bukkit.dynmap;
import java.io.InvalidClassException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.bukkit.Color;
import org.bukkit.Location;
import org.bukkit.plugin.Plugin;
import org.bukkit.util.Vector;
import org.dynmap.DynmapCommonAPI;
import org.dynmap.markers.CircleMarker;
import org.dynmap.markers.Marker;
import org.dynmap.markers.MarkerAPI;
import org.dynmap.markers.MarkerIcon;
import org.dynmap.markers.MarkerSet;
import org.dynmap.markers.PolyLineMarker;
import com.elmakers.mine.bukkit.api.spell.SpellResult;
import com.elmakers.mine.bukkit.api.magic.Mage;
import com.elmakers.mine.bukkit.api.spell.Spell;
public class DynmapController {
private final Plugin plugin;
private DynmapCommonAPI dynmap = null;
private DateFormat dateFormatter = new SimpleDateFormat("yy-MM-dd HH:mm");
public DynmapController(Plugin plugin, Plugin dynmapPlugin) throws InvalidClassException {
this.plugin = plugin;
if (dynmapPlugin != null && !(dynmapPlugin instanceof DynmapCommonAPI)) {
throw new InvalidClassException("Dynmap plugin found, but class is not DynmapCommonAPI");
}
dynmap = (DynmapCommonAPI)dynmapPlugin;
}
public void showCastMarker(Mage mage, Spell spell, SpellResult result) {
if (dynmap != null && dynmap.markerAPIInitialized()) {
MarkerAPI markers = dynmap.getMarkerAPI();
MarkerSet spellSet = markers.getMarkerSet("Spells");
if (spellSet == null) {
spellSet = markers.createMarkerSet("Spells", "Spell Casts", null, false);
}
final String markerId = "Spell-" + mage.getId();
final String targetId = "SpellTarget-" + mage.getId();
int range = 32;
double radius = 3.0 * mage.getPower() + 3;
int width = (int)(2.0 * mage.getPower()) + 2;
radius = Math.min(64, radius);
width = Math.min(8, width);
final Location location = spell.getLocation();
if (location == null) return;
Color mageColor = mage.getEffectColor();
mageColor = mageColor == null ? Color.PURPLE : mageColor;
Color spellColor = spell.getColor();
spellColor = spellColor == null ? mageColor : spellColor;
final String worldName = location.getWorld().getName();
Date now = new Date();
String label = spell.getName() + " : " + mage.getName() + " @ " + dateFormatter.format(now);
// Create a circular disc for a spell cast
CircleMarker marker = spellSet.findCircleMarker(markerId);
if (marker != null) {
marker.setCenter(worldName, location.getX(), location.getY(), location.getZ());
marker.setLabel(label);
} else {
marker = spellSet.createCircleMarker(markerId, label, false, worldName, location.getX(), location.getY(), location.getZ(), radius, radius, false);
}
marker.setRadius(radius, radius);
marker.setLineStyle(1, 0.9, spellColor.asRGB());
marker.setFillStyle(0.5, mageColor.asRGB());
// Create a targeting indicator line
Location target = null;
if (result != SpellResult.AREA) {
target = spell.getTargetLocation();
if (target == null) {
target = location.clone();
Vector direction = location.getDirection();
direction.normalize().multiply(range);
target.add(direction);
}
} else {
target = location;
}
PolyLineMarker targetMarker = spellSet.findPolyLineMarker(targetId);
if (targetMarker != null) {
targetMarker.setCornerLocation(0, location.getX(), location.getY(), location.getZ());
targetMarker.setCornerLocation(1, target.getX(), target.getY(), target.getZ());
targetMarker.setLabel(label);
} else {
double[] x = {location.getX(), target.getX()};
double[] y = {location.getY(), target.getY()};
double[] z = {location.getZ(), target.getZ()};
targetMarker = spellSet.createPolyLineMarker(targetId, label, false, worldName, x, y, z, false);
}
targetMarker.setLineStyle(width, 0.8, spellColor.asRGB());
}
}
public boolean isReady() {
return dynmap == null || dynmap.markerAPIInitialized();
}
public boolean addMarker(String id, String group, String title, String world, int x, int y, int z, String description) {
boolean created = false;
if (dynmap != null && dynmap.markerAPIInitialized())
{
MarkerAPI markers = dynmap.getMarkerAPI();
MarkerSet markerSet = markers.getMarkerSet(group);
if (markerSet == null) {
markerSet = markers.createMarkerSet(group, group, null, false);
}
MarkerIcon wandIcon = markers.getMarkerIcon("wand");
if (wandIcon == null) {
wandIcon = markers.createMarkerIcon("wand", "Wand", plugin.getResource("wand_icon32.png"));
}
Marker marker = markerSet.findMarker(id);
if (marker == null) {
created = true;
marker = markerSet.createMarker(id, title, world, x, y, z, wandIcon, false);
} else {
marker.setLocation(world, x, y, z);
marker.setLabel(title);
}
if (description != null) {
marker.setDescription(description);
}
}
return created;
}
public boolean removeMarker(String id, String group)
{
boolean removed = false;
if (dynmap != null && dynmap.markerAPIInitialized())
{
MarkerAPI markers = dynmap.getMarkerAPI();
MarkerSet markerSet = markers.getMarkerSet(group);
if (markerSet != null) {
Marker marker = markerSet.findMarker(id);
if (marker != null) {
removed = true;
marker.deleteMarker();
}
}
}
return removed;
}
public int triggerRenderOfVolume(String wid, int minx, int miny, int minz, int maxx, int maxy, int maxz)
{
if (dynmap == null) return 0;
return dynmap.triggerRenderOfVolume(wid, minx, miny, minz, maxx, maxy, maxz);
}
public int triggerRenderOfBlock(String wid, int x, int y, int z)
{
if (dynmap == null) return 0;
return dynmap.triggerRenderOfBlock(wid, x, y, z);
}
}
|
package com.elmakers.mine.bukkit.plugins.magic.wand;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.UUID;
import org.apache.commons.lang.StringUtils;
import org.bukkit.ChatColor;
import org.bukkit.Color;
import org.bukkit.DyeColor;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Sound;
import org.bukkit.TreeSpecies;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.player.PlayerExpChangeEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.inventory.meta.ItemMeta;
import com.elmakers.mine.bukkit.blocks.MaterialAndData;
import com.elmakers.mine.bukkit.blocks.MaterialBrush;
import com.elmakers.mine.bukkit.blocks.MaterialBrushData;
import com.elmakers.mine.bukkit.effects.EffectRing;
import com.elmakers.mine.bukkit.effects.ParticleType;
import com.elmakers.mine.bukkit.plugins.magic.BrushSpell;
import com.elmakers.mine.bukkit.plugins.magic.CastingCost;
import com.elmakers.mine.bukkit.plugins.magic.CostReducer;
import com.elmakers.mine.bukkit.plugins.magic.Mage;
import com.elmakers.mine.bukkit.plugins.magic.MagicController;
import com.elmakers.mine.bukkit.plugins.magic.Spell;
import com.elmakers.mine.bukkit.plugins.magic.WandMode;
import com.elmakers.mine.bukkit.utilities.InventoryUtils;
import com.elmakers.mine.bukkit.utilities.Messages;
import com.elmakers.mine.bukkit.utilities.borrowed.ConfigurationNode;
public class Wand implements CostReducer {
public final static int INVENTORY_SIZE = 27;
public final static int HOTBAR_SIZE = 9;
public final static String[] PROPERTY_KEYS = {
"active_spell", "active_material", "xp", "xp_regeneration", "xp_max", "health_regeneration",
"hunger_regeneration", "uses",
"cost_reduction", "cooldown_reduction", "power", "protection", "protection_physical",
"protection_projectiles", "protection_falling", "protection_fire", "protection_explosions",
"haste", "has_inventory", "modifiable", "effect_color", "effect_particle", "effect_particle_data",
"effect_bubbles", "materials", "spells", "mode"};
private ItemStack item;
private MagicController controller;
private Mage mage;
// Cached state
private String id;
private Inventory hotbar;
private List<Inventory> inventories;
private String activeSpell = "";
private String activeMaterial = "";
private String wandName = "";
private String description = "";
private String owner = "";
private float costReduction = 0;
private float cooldownReduction = 0;
private float damageReduction = 0;
private float damageReductionPhysical = 0;
private float damageReductionProjectiles = 0;
private float damageReductionFalling = 0;
private float damageReductionFire = 0;
private float damageReductionExplosions = 0;
private float power = 0;
private boolean hasInventory = false;
private boolean modifiable = true;
private int uses = 0;
private int xp = 0;
private int xpRegeneration = 0;
private int xpMax = 50;
private int healthRegeneration = 0;
private int hungerRegeneration = 0;
private int effectColor = 0;
private ParticleType effectParticle = null;
private float effectParticleData = 0;
private boolean effectBubbles = false;
private float defaultWalkSpeed = 0.2f;
private float defaultFlySpeed = 0.1f;
private float speedIncrease = 0;
private int storedXpLevel = 0;
private int storedXp = 0;
private float storedXpProgress = 0;
// Kinda of a hacky initialization optimization :\
private boolean suspendSave = false;
private static DecimalFormat floatFormat = new DecimalFormat("
public static boolean SchematicsEnabled = false;
public static Material WandMaterial = Material.BLAZE_ROD;
public static Material EnchantableWandMaterial = Material.WOOD_SWORD;
public static Material EraseMaterial = Material.SULPHUR;
public static Material CopyMaterial = Material.SUGAR;
public static Material CloneMaterial = Material.NETHER_STALK;
public static Material ReplicateMaterial = Material.PUMPKIN_SEEDS;
public static Material MapMaterial = Material.MAP;
public static Material SchematicMaterial = Material.PAPER;
public static final String ERASE_MATERIAL_KEY = "erase";
public static final String COPY_MATERIAL_KEY = "copy";
public static final String CLONE_MATERIAL_KEY = "clone";
public static final String REPLICATE_MATERIAL_KEY = "replicate";
public static final String MAP_MATERIAL_KEY = "map";
public static final String SCHEMATIC_MATERIAL_KEY = "schematic";
// Wand configurations
protected static Map<String, ConfigurationNode> wandTemplates = new HashMap<String, ConfigurationNode>();
// Inventory functionality
WandMode mode = null;
int openInventoryPage = 0;
boolean inventoryIsOpen = false;
Inventory displayInventory = null;
private Wand(ItemStack itemStack) {
hotbar = InventoryUtils.createInventory(null, 9, "Wand");
inventories = new ArrayList<Inventory>();
item = itemStack;
}
public Wand(MagicController spells) {
// This will make the Bukkit ItemStack into a real ItemStack with NBT data.
this(InventoryUtils.getCopy(new ItemStack(WandMaterial)));
InventoryUtils.addGlow(item);
this.controller = spells;
id = UUID.randomUUID().toString();
wandName = Messages.get("wand.default_name");
updateName();
saveState();
}
public Wand(MagicController spells, ItemStack item) {
this(item);
this.controller = spells;
loadState();
}
public void setActiveSpell(String activeSpell) {
this.activeSpell = activeSpell;
updateName();
updateInventoryNames(true);
saveState();
}
public void activateBrush(ItemStack itemStack) {
if (!isBrush(itemStack)) return;
setActiveMaterial(getMaterialKey(itemStack));
if (activeMaterial != null) {
String materialKey = activeMaterial;
if (materialKey.contains(":")) {
materialKey = StringUtils.split(materialKey, ":")[0];
}
if (materialKey.equals(CLONE_MATERIAL_KEY) || materialKey.equals(REPLICATE_MATERIAL_KEY)) {
MaterialBrush brush = mage.getBrush();
Location cloneLocation = mage.getLocation();
cloneLocation.setY(cloneLocation.getY() - 1);
brush.setCloneLocation(cloneLocation);
} else if (materialKey.equals(MAP_MATERIAL_KEY) || materialKey.equals(SCHEMATIC_MATERIAL_KEY)) {
MaterialBrush brush = mage.getBrush();
brush.clearCloneTarget();
}
}
}
protected void setActiveMaterial(String materialKey) {
this.activeMaterial = materialKey;
updateName();
updateActiveMaterial();
updateInventoryNames(true);
saveState();
}
public int getXpRegeneration() {
return xpRegeneration;
}
public int getXpMax() {
return xpMax;
}
public int getExperience() {
return xp;
}
public void removeExperience(int amount) {
xp = Math.max(0, xp - amount);
updateMana();
}
public int getHealthRegeneration() {
return healthRegeneration;
}
public int getHungerRegeneration() {
return hungerRegeneration;
}
public boolean isModifiable() {
return modifiable;
}
public boolean usesMana() {
return xpMax > 0 && xpRegeneration > 0 && getCostReduction() < 1;
}
public float getCooldownReduction() {
return controller.getCooldownReduction() + cooldownReduction;
}
public float getCostReduction() {
return controller.getCostReduction() + costReduction;
}
public void setCooldownReduction(float reduction) {
cooldownReduction = reduction;
}
public boolean getHasInventory() {
return hasInventory;
}
public float getPower() {
return power;
}
public float getDamageReduction() {
return damageReduction;
}
public float getDamageReductionPhysical() {
return damageReductionPhysical;
}
public float getDamageReductionProjectiles() {
return damageReductionProjectiles;
}
public float getDamageReductionFalling() {
return damageReductionFalling;
}
public float getDamageReductionFire() {
return damageReductionFire;
}
public float getDamageReductionExplosions() {
return damageReductionExplosions;
}
public int getUses() {
return uses;
}
public String getName() {
return wandName;
}
public String getDescription() {
return description;
}
public String getOwner() {
return owner;
}
public void setName(String name) {
wandName = name;
updateName();
}
protected void setDescription(String description) {
this.description = description;
updateLore();
}
protected void takeOwnership(Player player) {
owner = player.getName();
}
public void takeOwnership(Player player, String name, boolean updateDescription) {
setName(name);
takeOwnership(player);
if (updateDescription) {
setDescription("");
}
}
public ItemStack getItem() {
return item;
}
protected List<Inventory> getAllInventories() {
List<Inventory> allInventories = new ArrayList<Inventory>(inventories.size() + 1);
allInventories.add(hotbar);
allInventories.addAll(inventories);
return allInventories;
}
public Set<String> getSpells() {
return getSpells(false);
}
protected Set<String> getSpells(boolean includePositions) {
Set<String> spellNames = new TreeSet<String>();
List<Inventory> allInventories = getAllInventories();
int index = 0;
for (Inventory inventory : allInventories) {
ItemStack[] items = inventory.getContents();
for (int i = 0; i < items.length; i++) {
if (items[i] != null && !isWand(items[i])) {
if (isSpell(items[i])) {
String spellName = getSpell(items[i]);
if (includePositions) {
spellName += "@" + index;
}
spellNames.add(spellName);
}
}
index++;
}
}
return spellNames;
}
protected String getSpellString() {
return StringUtils.join(getSpells(true), "|");
}
public Set<String> getMaterialKeys() {
return getMaterialKeys(false);
}
protected Set<String> getMaterialKeys(boolean includePositions) {
Set<String> materialNames = new TreeSet<String>();
List<Inventory> allInventories = new ArrayList<Inventory>(inventories.size() + 1);
allInventories.add(hotbar);
allInventories.addAll(inventories);
Integer index = 0;
for (Inventory inventory : allInventories) {
ItemStack[] items = inventory.getContents();
for (int i = 0; i < items.length; i++) {
String materialKey = getMaterialKey(items[i], includePositions ? index : null);
if (materialKey != null) {
materialNames.add(materialKey);
}
index++;
}
}
return materialNames;
}
protected String getMaterialString() {
return StringUtils.join(getMaterialKeys(true), "|");
}
protected Integer parseSlot(String[] pieces) {
Integer slot = null;
if (pieces.length > 0) {
try {
slot = Integer.parseInt(pieces[1]);
} catch (Exception ex) {
slot = null;
}
if (slot != null && slot < 0) {
slot = null;
}
}
return slot;
}
protected void addToInventory(ItemStack itemStack) {
// Set the wand item
WandMode wandMode = getMode();
Integer selectedItem = null;
if (wandMode == WandMode.INVENTORY) {
if (mage != null && mage.getPlayer() != null) {
selectedItem = mage.getPlayer().getInventory().getHeldItemSlot();
hotbar.setItem(selectedItem, item);
}
}
List<Inventory> checkInventories = wandMode == WandMode.INVENTORY ? getAllInventories() : inventories;
boolean added = false;
for (Inventory inventory : checkInventories) {
HashMap<Integer, ItemStack> returned = inventory.addItem(itemStack);
if (returned.size() == 0) {
added = true;
break;
}
}
if (!added) {
Inventory newInventory = InventoryUtils.createInventory(null, INVENTORY_SIZE, "Wand");
newInventory.addItem(itemStack);
inventories.add(newInventory);
}
// Restore empty wand slot
if (selectedItem != null) {
hotbar.setItem(selectedItem, null);
}
}
protected Inventory getDisplayInventory() {
if (displayInventory == null) {
displayInventory = InventoryUtils.createInventory(null, INVENTORY_SIZE, "Wand");
}
return displayInventory;
}
protected Inventory getInventoryByIndex(int inventoryIndex) {
while (inventoryIndex >= inventories.size()) {
inventories.add(InventoryUtils.createInventory(null, INVENTORY_SIZE, "Wand"));
}
return inventories.get(inventoryIndex);
}
protected Inventory getInventory(Integer slot) {
Inventory inventory = hotbar;
if (slot >= HOTBAR_SIZE) {
int inventoryIndex = (slot - HOTBAR_SIZE) / INVENTORY_SIZE;
inventory = getInventoryByIndex(inventoryIndex);
}
return inventory;
}
protected int getInventorySlot(Integer slot) {
if (slot < HOTBAR_SIZE) {
return slot;
}
return ((slot - HOTBAR_SIZE) % INVENTORY_SIZE);
}
protected void addToInventory(ItemStack itemStack, Integer slot) {
if (slot == null) {
addToInventory(itemStack);
return;
}
Inventory inventory = getInventory(slot);
slot = getInventorySlot(slot);
ItemStack existing = inventory.getItem(slot);
inventory.setItem(slot, itemStack);
if (existing != null && existing.getType() != Material.AIR) {
addToInventory(existing);
}
}
protected void parseInventoryStrings(String spellString, String materialString) {
hotbar.clear();
inventories.clear();
String[] spellNames = StringUtils.split(spellString, "|");
for (String spellName : spellNames) {
String[] pieces = spellName.split("@");
Integer slot = parseSlot(pieces);
ItemStack itemStack = createSpellItem(pieces[0]);
if (itemStack == null) {
controller.getPlugin().getLogger().warning("Unable to create spell icon for key " + pieces[0]);
continue;
}
addToInventory(itemStack, slot);
}
String[] materialNames = StringUtils.split(materialString, "|");
for (String materialName : materialNames) {
String[] pieces = materialName.split("@");
Integer slot = parseSlot(pieces);
ItemStack itemStack = createMaterialItem(pieces[0]);
if (itemStack == null) {
controller.getPlugin().getLogger().warning("Unable to create material icon for key " + pieces[0]);
continue;
}
addToInventory(itemStack, slot);
}
hasInventory = spellNames.length + materialNames.length > 1;
}
@SuppressWarnings("deprecation")
protected ItemStack createSpellItem(String spellName) {
Spell spell = controller.getSpell(spellName);
if (spell == null) return null;
MaterialAndData icon = spell.getIcon();
if (icon == null) {
controller.getPlugin().getLogger().warning("Unable to create spell icon for " + spell.getName() + ", missing material");
}
ItemStack itemStack = null;
ItemStack originalItemStack = null;
try {
originalItemStack = new ItemStack(icon.getMaterial(), 1, (short)0, (byte)icon.getData());
itemStack = InventoryUtils.getCopy(originalItemStack);
} catch (Exception ex) {
itemStack = null;
}
if (itemStack == null) {
controller.getPlugin().getLogger().warning("Unable to create spell icon with material " + icon.getMaterial().name());
return originalItemStack;
}
updateSpellName(itemStack, spell, true);
return itemStack;
}
private String getActiveWandName(String materialKey) {
Spell spell = controller.getSpell(activeSpell);
return getActiveWandName(spell, materialKey);
}
@SuppressWarnings("deprecation")
protected ItemStack createMaterialItem(String materialKey) {
MaterialBrushData brushData = parseMaterialKey(materialKey);
Material material = brushData.getMaterial();
byte dataId = brushData.getData();
ItemStack originalItemStack = new ItemStack(material, 1, (short)0, (byte)dataId);
ItemStack itemStack = InventoryUtils.getCopy(originalItemStack);
if (itemStack == null) {
controller.getPlugin().getLogger().warning("Unable to create material icon for " + material.name() + ": " + originalItemStack.getType());
return originalItemStack;
}
ItemMeta meta = itemStack.getItemMeta();
List<String> lore = new ArrayList<String>();
if (material != null) {
lore.add(ChatColor.GRAY + Messages.get("wand.building_material_info").replace("$material", getMaterialName(materialKey)));
if (material == EraseMaterial) {
lore.add(Messages.get("wand.erase_material_description"));
} else if (material == CopyMaterial) {
lore.add(Messages.get("wand.copy_material_description"));
} else if (material == CloneMaterial) {
lore.add(Messages.get("wand.clone_material_description"));
} else if (material == ReplicateMaterial) {
lore.add(Messages.get("wand.replicate_material_description"));
} else if (material == MapMaterial) {
lore.add(Messages.get("wand.map_material_description"));
} else if (material == SchematicMaterial) {
lore.add(Messages.get("wand.schematic_material_description").replace("$schematic", brushData.getSchematicName()));
} else {
lore.add(ChatColor.LIGHT_PURPLE + Messages.get("wand.building_material_description"));
}
}
meta.setLore(lore);
itemStack.setItemMeta(meta);
updateMaterialName(itemStack, materialKey, true);
return itemStack;
}
protected void saveState(boolean force) {
if (force) suspendSave = false;
saveState();
}
protected void saveState() {
if (suspendSave) return;
Object wandNode = InventoryUtils.createNode(item, "wand");
InventoryUtils.setMeta(wandNode, "id", id);
String wandMaterials = getMaterialString();
String wandSpells = getSpellString();
InventoryUtils.setMeta(wandNode, "materials", wandMaterials);
InventoryUtils.setMeta(wandNode, "spells", wandSpells);
InventoryUtils.setMeta(wandNode, "active_spell", activeSpell);
InventoryUtils.setMeta(wandNode, "active_material", activeMaterial);
InventoryUtils.setMeta(wandNode, "name", wandName);
InventoryUtils.setMeta(wandNode, "description", description);
InventoryUtils.setMeta(wandNode, "owner", owner);
InventoryUtils.setMeta(wandNode, "cost_reduction", floatFormat.format(costReduction));
InventoryUtils.setMeta(wandNode, "cooldown_reduction", floatFormat.format(cooldownReduction));
InventoryUtils.setMeta(wandNode, "power", floatFormat.format(power));
InventoryUtils.setMeta(wandNode, "protection", floatFormat.format(damageReduction));
InventoryUtils.setMeta(wandNode, "protection_physical", floatFormat.format(damageReductionPhysical));
InventoryUtils.setMeta(wandNode, "protection_projectiles", floatFormat.format(damageReductionProjectiles));
InventoryUtils.setMeta(wandNode, "protection_falling", floatFormat.format(damageReductionFalling));
InventoryUtils.setMeta(wandNode, "protection_fire", floatFormat.format(damageReductionFire));
InventoryUtils.setMeta(wandNode, "protection_explosions", floatFormat.format(damageReductionExplosions));
InventoryUtils.setMeta(wandNode, "haste", floatFormat.format(speedIncrease));
InventoryUtils.setMeta(wandNode, "xp", Integer.toString(xp));
InventoryUtils.setMeta(wandNode, "xp_regeneration", Integer.toString(xpRegeneration));
InventoryUtils.setMeta(wandNode, "xp_max", Integer.toString(xpMax));
InventoryUtils.setMeta(wandNode, "health_regeneration", Integer.toString(healthRegeneration));
InventoryUtils.setMeta(wandNode, "hunger_regeneration", Integer.toString(hungerRegeneration));
InventoryUtils.setMeta(wandNode, "uses", Integer.toString(uses));
InventoryUtils.setMeta(wandNode, "has_inventory", Integer.toString((hasInventory ? 1 : 0)));
InventoryUtils.setMeta(wandNode, "modifiable", Integer.toString((modifiable ? 1 : 0)));
InventoryUtils.setMeta(wandNode, "effect_color", Integer.toString(effectColor, 16));
InventoryUtils.setMeta(wandNode, "effect_bubbles", Integer.toString(effectBubbles ? 1 : 0));
InventoryUtils.setMeta(wandNode, "effect_particle_data", Float.toString(effectParticleData));
if (effectParticle != null) {
InventoryUtils.setMeta(wandNode, "effect_particle", effectParticle.name());
}
if (mode != null) {
InventoryUtils.setMeta(wandNode, "mode", mode.name());
}
}
protected void loadState() {
Object wandNode = InventoryUtils.getNode(item, "wand");
if (wandNode == null) {
controller.getPlugin().getLogger().warning("Found a wand with missing NBT data. This may be an old wand, or something may have wiped its data");
return;
}
// Don't generate a UUID unless we need to, not sure how expensive that is.
id = InventoryUtils.getMeta(wandNode, "id");
id = id == null || id.length() == 0 ? UUID.randomUUID().toString() : id;
wandName = InventoryUtils.getMeta(wandNode, "name", wandName);
description = InventoryUtils.getMeta(wandNode, "description", description);
owner = InventoryUtils.getMeta(wandNode, "owner", owner);
activeSpell = InventoryUtils.getMeta(wandNode, "active_spell", activeSpell);
activeMaterial = InventoryUtils.getMeta(wandNode, "active_material", activeMaterial);
String wandMaterials = InventoryUtils.getMeta(wandNode, "materials", "");
String wandSpells = InventoryUtils.getMeta(wandNode, "spells", "");
parseInventoryStrings(wandSpells, wandMaterials);
costReduction = Float.parseFloat(InventoryUtils.getMeta(wandNode, "cost_reduction", floatFormat.format(costReduction)));
cooldownReduction = Float.parseFloat(InventoryUtils.getMeta(wandNode, "cooldown_reduction", floatFormat.format(cooldownReduction)));
power = Float.parseFloat(InventoryUtils.getMeta(wandNode, "power", floatFormat.format(power)));
damageReduction = Float.parseFloat(InventoryUtils.getMeta(wandNode, "protection", floatFormat.format(damageReduction)));
damageReductionPhysical = Float.parseFloat(InventoryUtils.getMeta(wandNode, "protection_physical", floatFormat.format(damageReductionPhysical)));
damageReductionProjectiles = Float.parseFloat(InventoryUtils.getMeta(wandNode, "protection_projectiles", floatFormat.format(damageReductionProjectiles)));
damageReductionFalling = Float.parseFloat(InventoryUtils.getMeta(wandNode, "protection_falling", floatFormat.format(damageReductionFalling)));
damageReductionFire = Float.parseFloat(InventoryUtils.getMeta(wandNode, "protection_fire", floatFormat.format(damageReductionFire)));
damageReductionExplosions = Float.parseFloat(InventoryUtils.getMeta(wandNode, "protection_explosions", floatFormat.format(damageReductionExplosions)));
speedIncrease = Float.parseFloat(InventoryUtils.getMeta(wandNode, "haste", floatFormat.format(speedIncrease)));
xp = Integer.parseInt(InventoryUtils.getMeta(wandNode, "xp", Integer.toString(xp)));
xpRegeneration = Integer.parseInt(InventoryUtils.getMeta(wandNode, "xp_regeneration", Integer.toString(xpRegeneration)));
xpMax = Integer.parseInt(InventoryUtils.getMeta(wandNode, "xp_max", Integer.toString(xpMax)));
healthRegeneration = Integer.parseInt(InventoryUtils.getMeta(wandNode, "health_regeneration", Integer.toString(healthRegeneration)));
hungerRegeneration = Integer.parseInt(InventoryUtils.getMeta(wandNode, "hunger_regeneration", Integer.toString(hungerRegeneration)));
uses = Integer.parseInt(InventoryUtils.getMeta(wandNode, "uses", Integer.toString(uses)));
hasInventory = Integer.parseInt(InventoryUtils.getMeta(wandNode, "has_inventory", (hasInventory ? "1" : "0"))) != 0;
modifiable = Integer.parseInt(InventoryUtils.getMeta(wandNode, "modifiable", (modifiable ? "1" : "0"))) != 0;
effectColor = Integer.parseInt(InventoryUtils.getMeta(wandNode, "effect_color", Integer.toString(effectColor, 16)), 16);
effectBubbles = Integer.parseInt(InventoryUtils.getMeta(wandNode, "effect_bubbles", (effectBubbles ? "1" : "0"))) != 0;
effectParticleData = Float.parseFloat(InventoryUtils.getMeta(wandNode, "effect_particle_data", floatFormat.format(effectParticleData)));
parseParticleEffect(InventoryUtils.getMeta(wandNode, "effect_particle", effectParticle == null ? "" : effectParticle.name()));
mode = parseWandMode(InventoryUtils.getMeta(wandNode, "mode", ""), mode);
}
protected void parseParticleEffect(String effectParticleName) {
if (effectParticleName.length() > 0) {
String testName = effectParticleName.toUpperCase().replace("_", "");
try {
for (ParticleType testType : ParticleType.values()) {
String testTypeName = testType.name().replace("_", "");
if (testTypeName.equals(testName)) {
effectParticle = testType;
break;
}
}
} catch (Exception ex) {
effectParticle = null;
}
} else {
effectParticle = null;
}
}
public void describe(CommandSender sender) {
Object wandNode = InventoryUtils.getNode(item, "wand");
if (wandNode == null) {
sender.sendMessage("Found a wand with missing NBT data. This may be an old wand, or something may have wiped its data");
return;
}
ChatColor wandColor = modifiable ? ChatColor.AQUA : ChatColor.RED;
sender.sendMessage(wandColor + wandName);
if (description.length() > 0) {
sender.sendMessage(ChatColor.ITALIC + "" + ChatColor.GREEN + description);
} else {
sender.sendMessage(ChatColor.ITALIC + "" + ChatColor.GREEN + "(No Description)");
}
if (owner.length() > 0) {
sender.sendMessage(ChatColor.ITALIC + "" + ChatColor.WHITE + owner);
} else {
sender.sendMessage(ChatColor.ITALIC + "" + ChatColor.WHITE + "(No Owner)");
}
for (String key : PROPERTY_KEYS) {
String value = InventoryUtils.getMeta(wandNode, key);
if (value != null && value.length() > 0) {
sender.sendMessage(key + ": " + value);
}
}
}
public boolean removeMaterial(String materialKey) {
if (!modifiable || materialKey == null) return false;
if (isInventoryOpen()) {
saveInventory();
}
if (materialKey.equals(activeMaterial)) {
activeMaterial = null;
}
List<Inventory> allInventories = getAllInventories();
boolean found = false;
for (Inventory inventory : allInventories) {
ItemStack[] items = inventory.getContents();
for (int index = 0; index < items.length; index++) {
ItemStack itemStack = items[index];
if (itemStack != null && isBrush(itemStack)) {
String itemKey = getMaterialKey(itemStack);
if (itemKey.equals(materialKey)) {
found = true;
inventory.setItem(index, null);
} else if (activeMaterial == null) {
activeMaterial = materialKey;
}
if (found && activeMaterial != null) {
break;
}
}
}
}
updateActiveMaterial();
updateInventoryNames(true);
updateName();
updateLore();
saveState();
if (isInventoryOpen()) {
updateInventory();
}
return found;
}
public boolean hasMaterial(String materialKey) {
return getMaterialKeys().contains(materialKey);
}
public boolean hasSpell(String spellName) {
return getSpells().contains(spellName);
}
public boolean addMaterial(String materialKey, boolean makeActive, boolean force) {
if (!modifiable && !force) return false;
boolean addedNew = !hasMaterial(materialKey);
if (addedNew) {
addToInventory(createMaterialItem(materialKey));
}
if (activeMaterial == null || activeMaterial.length() == 0 || makeActive) {
activeMaterial = materialKey;
}
updateActiveMaterial();
updateInventoryNames(true);
updateName();
updateLore();
saveState();
if (isInventoryOpen()) {
updateInventory();
}
hasInventory = getSpells().size() + getMaterialKeys().size() > 1;
return addedNew;
}
public boolean addMaterial(Material material, byte data, boolean makeActive, boolean force) {
if (!modifiable && !force) return false;
if (isInventoryOpen()) {
saveInventory();
}
String materialKey = getMaterialKey(material, data);
return addMaterial(materialKey, makeActive, force);
}
public boolean removeSpell(String spellName) {
if (!modifiable) return false;
if (isInventoryOpen()) {
saveInventory();
}
if (spellName.equals(activeSpell)) {
activeSpell = null;
}
List<Inventory> allInventories = getAllInventories();
boolean found = false;
for (Inventory inventory : allInventories) {
ItemStack[] items = inventory.getContents();
for (int index = 0; index < items.length; index++) {
ItemStack itemStack = items[index];
if (itemStack != null && itemStack.getType() != Material.AIR && !isWand(itemStack) && isSpell(itemStack)) {
if (getSpell(itemStack).equals(spellName)) {
found = true;
inventory.setItem(index, null);
} else if (activeSpell == null) {
activeSpell = getSpell(itemStack);
}
if (found && activeSpell != null) {
break;
}
}
}
}
updateInventoryNames(true);
updateName();
updateLore();
saveState();
if (isInventoryOpen()) {
updateInventory();
}
return found;
}
public boolean addSpell(String spellName, boolean makeActive) {
if (!modifiable) return false;
if (isInventoryOpen()) {
saveInventory();
}
boolean addedNew = !hasSpell(spellName);
ItemStack spellItem = createSpellItem(spellName);
if (spellItem == null) {
controller.getPlugin().getLogger().info("Unknown spell: " + spellName);
return false;
}
if (addedNew) {
addToInventory(spellItem);
}
if (activeSpell == null || activeSpell.length() == 0 || makeActive) {
activeSpell = spellName;
}
hasInventory = getSpells().size() + getMaterialKeys().size() > 1;
updateInventoryNames(true);
updateName();
updateLore();
saveState();
if (isInventoryOpen()) {
updateInventory();
}
return addedNew;
}
public boolean addSpell(String spellName) {
return addSpell(spellName, false);
}
private String getActiveWandName(Spell spell, String materialKey) {
// Build wand name
ChatColor wandColor = modifiable ? ChatColor.AQUA : ChatColor.RED;
String name = wandColor + wandName;
// Add active spell to description
if (spell != null) {
if (materialKey != null && (spell instanceof BrushSpell) && !((BrushSpell)spell).hasBrushOverride()) {
String materialName = getMaterialName(materialKey);
if (materialName == null) {
materialName = "none";
}
name = ChatColor.GOLD + spell.getName() + ChatColor.GRAY + " " + materialName + ChatColor.WHITE + " (" + wandColor + wandName + ChatColor.WHITE + ")";
} else {
name = ChatColor.GOLD + spell.getName() + ChatColor.WHITE + " (" + wandColor + wandName + ChatColor.WHITE + ")";
}
}
int remaining = getRemainingUses();
if (remaining > 0) {
name = name + " : " + ChatColor.RED + Messages.get("wand.uses_remaining_brief").replace("$count", ((Integer)remaining).toString());
}
return name;
}
private String getActiveWandName(Spell spell) {
return getActiveWandName(spell, activeMaterial);
}
private static String getMaterialKey(Material material) {
String materialKey = null;
if (material == null) return null;
if (material == EraseMaterial) {
materialKey = ERASE_MATERIAL_KEY;
} else if (material == CopyMaterial) {
materialKey = COPY_MATERIAL_KEY;
} else if (material == CloneMaterial) {
materialKey = CLONE_MATERIAL_KEY;
} else if (material == MapMaterial) {
materialKey = MAP_MATERIAL_KEY;
} else if (material == ReplicateMaterial) {
materialKey = REPLICATE_MATERIAL_KEY;
} else if (SchematicsEnabled && material == SchematicMaterial) {
// This would be kinda broken.. might want to revisit all this.
// This method is only called by addMaterial at this point,
// which should only be called with real materials anyway.
materialKey = SCHEMATIC_MATERIAL_KEY;
} else if (material.isBlock()) {
materialKey = material.name().toLowerCase();
}
return materialKey;
}
private static String getMaterialKey(Material material, byte data) {
String materialKey = getMaterialKey(material);
if (materialKey == null) {
return null;
}
if (data != 0) {
materialKey += ":" + data;
}
return materialKey;
}
@SuppressWarnings("deprecation")
private static String getMaterialName(String materialKey) {
if (materialKey == null) return null;
String materialName = materialKey;
String[] namePieces = StringUtils.split(materialName, ":");
if (namePieces.length == 0) return null;
materialName = namePieces[0];
if (!isSpecialMaterialKey(materialKey)) {
MaterialBrushData brushData = parseMaterialKey(materialKey);
if (brushData == null) return null;
Material material = brushData.getMaterial();
byte data = brushData.getData();
// This is the "right" way to do this, but relies on Bukkit actually updating Material in a timely fashion :P
/*
Class<? extends MaterialData> materialData = material.getData();
Bukkit.getLogger().info("Material " + material + " has " + materialData);
if (Wool.class.isAssignableFrom(materialData)) {
Wool wool = new Wool(material, data);
materialName += " " + wool.getColor().name();
} else if (Dye.class.isAssignableFrom(materialData)) {
Dye dye = new Dye(material, data);
materialName += " " + dye.getColor().name();
} else if (Dye.class.isAssignableFrom(materialData)) {
Dye dye = new Dye(material, data);
materialName += " " + dye.getColor().name();
}
*/
// Using raw id's for 1.6 support... because... bukkit... bleh.
//if (material == Material.CARPET || material == Material.STAINED_GLASS || material == Material.STAINED_CLAY || material == Material.STAINED_GLASS_PANE || material == Material.WOOL) {
if (material == Material.CARPET || material.getId() == 95 || material.getId() ==159 || material.getId() == 160 || material == Material.WOOL) {
// Note that getByDyeData doesn't work for stained glass or clay. Kind of misleading?
DyeColor color = DyeColor.getByWoolData(data);
materialName = color.name().toLowerCase().replace('_', ' ') + " " + materialName;
} else if (material == Material.WOOD || material == Material.LOG || material == Material.SAPLING || material == Material.LEAVES) {
TreeSpecies treeSpecies = TreeSpecies.getByData(data);
materialName = treeSpecies.name().toLowerCase().replace('_', ' ') + " " + materialName;
} else {
materialName = material.name();
}
materialName = materialName.toLowerCase().replace('_', ' ');
} else if (materialName.startsWith(SCHEMATIC_MATERIAL_KEY) && namePieces.length > 1) {
materialName = namePieces[1];
}
return materialName;
}
private String getActiveWandName() {
Spell spell = null;
if (hasInventory) {
spell = controller.getSpell(activeSpell);
}
return getActiveWandName(spell);
}
public void updateName(boolean isActive) {
ItemMeta meta = item.getItemMeta();
meta.setDisplayName(isActive ? getActiveWandName() : wandName);
item.setItemMeta(meta);
// Reset Enchantment glow
InventoryUtils.addGlow(item);
// The all-important last step of restoring the meta state, something
// the Anvil will blow away.
saveState();
}
private void updateName() {
updateName(true);
}
private String getLevelString(String prefix, float amount) {
String suffix = "";
if (amount > 1) {
suffix = Messages.get("wand.enchantment_level_max");
} else if (amount > 0.8) {
suffix = Messages.get("wand.enchantment_level_5");
} else if (amount > 0.6) {
suffix = Messages.get("wand.enchantment_level_4");
} else if (amount > 0.4) {
suffix = Messages.get("wand.enchantment_level_3");
} else if (amount > 0.2) {
suffix = Messages.get("wand.enchantment_level_2");
} else {
suffix = Messages.get("wand.enchantment_level_1");
}
return prefix + " " + suffix;
}
protected static String convertToHTML(String line) {
int tagCount = 1;
line = "<span style=\"color:white\">" + line;
for (ChatColor c : ChatColor.values()) {
tagCount += StringUtils.countMatches(line, c.toString());
String replaceStyle = "";
if (c == ChatColor.ITALIC) {
replaceStyle = "font-style: italic";
} else if (c == ChatColor.BOLD) {
replaceStyle = "font-weight: bold";
} else if (c == ChatColor.UNDERLINE) {
replaceStyle = "text-decoration: underline";
} else {
String color = c.name().toLowerCase().replace("_", "");
if (c == ChatColor.LIGHT_PURPLE) {
color = "mediumpurple";
}
replaceStyle = "color:" + color;
}
line = line.replace(c.toString(), "<span style=\"" + replaceStyle + "\">");
}
for (int i = 0; i < tagCount; i++) {
line += "</span>";
}
return line;
}
public String getHTMLDescription() {
Collection<String> rawLore = getLore();
Collection<String> lore = new ArrayList<String>();
lore.add("<h2>" + convertToHTML(getActiveWandName()) + "</h2>");
for (String line : rawLore) {
lore.add(convertToHTML(line));
}
return "<div style=\"background-color: black; margin: 8px; padding: 8px\">" + StringUtils.join(lore, "<br/>") + "</div>";
}
private List<String> getLore() {
return getLore(getSpells().size(), getMaterialKeys().size());
}
private List<String> getLore(int spellCount, int materialCount) {
List<String> lore = new ArrayList<String>();
Spell spell = controller.getSpell(activeSpell);
if (spell != null && spellCount == 1 && materialCount <= 1) {
addSpellLore(spell, lore);
} else {
if (description.length() > 0) {
lore.add(ChatColor.ITALIC + "" + ChatColor.GREEN + description);
}
if (owner.length() > 0) {
String ownerDescription = Messages.get("wand.owner_description", "$name").replace("$name", owner);
lore.add(ChatColor.ITALIC + "" + ChatColor.DARK_GREEN + ownerDescription);
}
lore.add(Messages.get("wand.spell_count").replace("$count", ((Integer)spellCount).toString()));
if (materialCount > 0) {
lore.add(Messages.get("wand.material_count").replace("$count", ((Integer)materialCount).toString()));
}
}
int remaining = getRemainingUses();
if (remaining > 0) {
lore.add(ChatColor.RED + Messages.get("wand.uses_remaining").replace("$count", ((Integer)remaining).toString()));
}
if (usesMana()) {
lore.add(ChatColor.LIGHT_PURPLE + "" + ChatColor.ITALIC + Messages.get("wand.mana_amount").replace("$amount", ((Integer)xpMax).toString()));
lore.add(ChatColor.RESET + "" + ChatColor.LIGHT_PURPLE + getLevelString(Messages.get("wand.mana_regeneration"), (float)xpRegeneration / (float)WandLevel.maxXpRegeneration));
}
if (costReduction > 0) lore.add(ChatColor.AQUA + getLevelString(Messages.get("wand.cost_reduction"), costReduction));
if (cooldownReduction > 0) lore.add(ChatColor.AQUA + getLevelString(Messages.get("wand.cooldown_reduction"), cooldownReduction));
if (power > 0) lore.add(ChatColor.AQUA + getLevelString(Messages.get("wand.power"), power));
if (speedIncrease > 0) lore.add(ChatColor.AQUA + getLevelString(Messages.get("wand.haste"), speedIncrease));
if (damageReduction > 0) lore.add(ChatColor.AQUA + getLevelString(Messages.get("wand.protection"), damageReduction));
if (damageReduction < 1) {
if (damageReductionPhysical > 0) lore.add(ChatColor.AQUA + getLevelString(Messages.get("wand.protection_physical"), damageReductionPhysical));
if (damageReductionProjectiles > 0) lore.add(ChatColor.AQUA + getLevelString(Messages.get("wand.protection_projectile"), damageReductionProjectiles));
if (damageReductionFalling > 0) lore.add(ChatColor.AQUA + getLevelString(Messages.get("wand.protection_fall"), damageReductionFalling));
if (damageReductionFire > 0) lore.add(ChatColor.AQUA + getLevelString(Messages.get("wand.protection_fire"), damageReductionFire));
if (damageReductionExplosions > 0) lore.add(ChatColor.AQUA + getLevelString(Messages.get("wand.protection_blast"), damageReductionExplosions));
}
if (healthRegeneration > 0) lore.add(ChatColor.AQUA + getLevelString(Messages.get("wand.health_regeneration"), healthRegeneration / WandLevel.maxRegeneration));
if (hungerRegeneration > 0) lore.add(ChatColor.AQUA + getLevelString(Messages.get("wand.hunger_regeneration"), hungerRegeneration / WandLevel.maxRegeneration));
return lore;
}
private void updateLore() {
ItemMeta meta = item.getItemMeta();
List<String> lore = getLore();
meta.setLore(lore);
item.setItemMeta(meta);
InventoryUtils.addGlow(item);
// Reset spell list and wand config
saveState();
}
public int getRemainingUses() {
return uses;
}
public void makeEnchantable(boolean enchantable) {
item.setType(enchantable ? EnchantableWandMaterial : WandMaterial);
updateName();
}
public static boolean hasActiveWand(Player player) {
ItemStack activeItem = player.getInventory().getItemInHand();
return isWand(activeItem);
}
public static Wand getActiveWand(MagicController spells, Player player) {
ItemStack activeItem = player.getInventory().getItemInHand();
if (isWand(activeItem)) {
return new Wand(spells, activeItem);
}
return null;
}
public static boolean isSpecialMaterialKey(String materialKey) {
if (materialKey == null || materialKey.length() == 0) return false;
if (materialKey.contains(":")) {
materialKey = StringUtils.split(materialKey, ":")[0];
}
return COPY_MATERIAL_KEY.equals(materialKey) || ERASE_MATERIAL_KEY.equals(materialKey) ||
REPLICATE_MATERIAL_KEY.equals(materialKey) || CLONE_MATERIAL_KEY.equals(materialKey) ||
MAP_MATERIAL_KEY.equals(materialKey) || (SchematicsEnabled && SCHEMATIC_MATERIAL_KEY.equals(materialKey));
}
public static boolean isWand(ItemStack item) {
// Special-case here for porting old wands. Could be removed eventually.
return item != null && (item.getType() == WandMaterial || item.getType() == EnchantableWandMaterial) && (InventoryUtils.hasMeta(item, "wand") || InventoryUtils.hasMeta(item, "magic_wand"));
}
public static boolean isSpell(ItemStack item) {
return item != null && InventoryUtils.hasMeta(item, "spell");
}
public static boolean isBrush(ItemStack item) {
return item != null && InventoryUtils.hasMeta(item, "brush");
}
public static String getSpell(ItemStack item) {
if (!isSpell(item)) return null;
Object spellNode = InventoryUtils.getNode(item, "spell");
return InventoryUtils.getMeta(spellNode, "key");
}
public static String getMaterialKey(ItemStack item) {
if (!isBrush(item)) return null;
Object brushNode = InventoryUtils.getNode(item, "brush");
return InventoryUtils.getMeta(brushNode, "key");
}
protected static String getMaterialKey(ItemStack itemStack, Integer index) {
String materialKey = getMaterialKey(itemStack);
if (materialKey == null) return null;
if (index != null) {
materialKey += "@" + index;
}
return materialKey;
}
public void updateInventoryNames(boolean activeHotbarNames, boolean activeAllNames) {
if (mage == null || !isInventoryOpen() || !mage.hasStoredInventory() || mode != WandMode.INVENTORY) return;
ItemStack[] contents = mage.getPlayer().getInventory().getContents();
for (int i = 0; i < contents.length; i++) {
ItemStack item = contents[i];
if (item == null || item.getType() == Material.AIR || isWand(item)) continue;
boolean activeName = activeAllNames || (activeHotbarNames && i < Wand.HOTBAR_SIZE);
updateInventoryName(item, activeName);
}
}
public void updateInventoryNames() {
updateInventoryNames(true, false);
}
public void updateInventoryNames(boolean activeHotbarNames) {
updateInventoryNames(activeHotbarNames, false);
}
protected void updateInventoryName(ItemStack item, boolean activeName) {
if (isSpell(item)) {
Spell spell = mage.getSpell(getSpell(item));
if (spell != null) {
updateSpellName(item, spell, activeName);
}
} else if (isBrush(item)) {
updateMaterialName(item, getMaterialKey(item), activeName);
}
}
protected void updateSpellName(ItemStack itemStack, Spell spell, boolean activeName) {
ItemMeta meta = itemStack.getItemMeta();
String displayName = null;
if (activeName) {
displayName = getActiveWandName(spell);
} else {
displayName = ChatColor.GOLD + spell.getName();
}
meta.setDisplayName(displayName);
List<String> lore = new ArrayList<String>();
addSpellLore(spell, lore);
meta.setLore(lore);
itemStack.setItemMeta(meta);
InventoryUtils.addGlow(itemStack);
Object spellNode = InventoryUtils.createNode(itemStack, "spell");
InventoryUtils.setMeta(spellNode, "key", spell.getKey());
}
protected void updateMaterialName(ItemStack itemStack, String materialKey, boolean activeName) {
ItemMeta meta = itemStack.getItemMeta();
String displayName = null;
if (activeName) {
displayName = getActiveWandName(materialKey);
} else {
displayName = getMaterialName(materialKey);
}
meta.setDisplayName(displayName);
itemStack.setItemMeta(meta);
Object brushNode = InventoryUtils.createNode(itemStack, "brush");
InventoryUtils.setMeta(brushNode, "key", materialKey);
}
@SuppressWarnings("deprecation")
private void updateInventory() {
if (mage == null) return;
if (!isInventoryOpen()) return;
Player player = mage.getPlayer();
if (player == null) return;
WandMode wandMode = getMode();
if (wandMode == WandMode.INVENTORY) {
if (!mage.hasStoredInventory()) return;
PlayerInventory inventory = player.getInventory();
inventory.clear();
updateHotbar(inventory);
updateInventory(inventory, HOTBAR_SIZE);
updateName();
player.updateInventory();
} else if (wandMode == WandMode.CHEST) {
Inventory inventory = getDisplayInventory();
inventory.clear();
updateInventory(inventory, 0);
player.updateInventory();
}
}
private void updateHotbar(PlayerInventory playerInventory) {
// Check for an item already in the player's held slot, which
// we are about to replace with the wand.
int currentSlot = playerInventory.getHeldItemSlot();
ItemStack existingHotbar = hotbar.getItem(currentSlot);
if (existingHotbar != null && existingHotbar.getType() != Material.AIR && !isWand(existingHotbar)) {
// Toss the item back into the wand inventory, it'll find a home somewhere.
addToInventory(existingHotbar);
hotbar.setItem(currentSlot, null);
}
// Put the wand in the player's active slot.
playerInventory.setItem(currentSlot, item);
// Set hotbar items from remaining list
for (int hotbarSlot = 0; hotbarSlot < HOTBAR_SIZE; hotbarSlot++) {
if (hotbarSlot != currentSlot) {
playerInventory.setItem(hotbarSlot, hotbar.getItem(hotbarSlot));
}
}
}
private void updateInventory(Inventory targetInventory, int startOffset) {
// Set inventory from current page
if (openInventoryPage < inventories.size()) {
Inventory inventory = inventories.get(openInventoryPage);
ItemStack[] contents = inventory.getContents();
for (int i = 0; i < contents.length; i++) {
targetInventory.setItem(i + startOffset, contents[i]);
}
}
}
protected void addSpellLore(Spell spell, List<String> lore) {
String description = spell.getDescription();
String usage = spell.getUsage();
if (description != null && description.length() > 0) {
lore.add(description);
}
if (usage != null && usage.length() > 0) {
lore.add(usage);
}
List<CastingCost> costs = spell.getCosts();
if (costs != null) {
for (CastingCost cost : costs) {
if (cost.hasCosts(this)) {
lore.add(ChatColor.YELLOW + Messages.get("wand.costs_description").replace("$description", cost.getFullDescription(this)));
}
}
}
List<CastingCost> activeCosts = spell.getActiveCosts();
if (activeCosts != null) {
for (CastingCost cost : activeCosts) {
if (cost.hasCosts(this)) {
lore.add(ChatColor.YELLOW + Messages.get("wand.active_costs_description").replace("$description", cost.getFullDescription(this)));
}
}
}
}
protected Inventory getOpenInventory() {
while (openInventoryPage >= inventories.size()) {
inventories.add(InventoryUtils.createInventory(null, INVENTORY_SIZE, "Wand"));
}
return inventories.get(openInventoryPage);
}
public void saveInventory() {
if (mage == null) return;
if (!isInventoryOpen()) return;
if (mage.getPlayer() == null) return;
if (getMode() != WandMode.INVENTORY) return;
if (!mage.hasStoredInventory()) return;
// Fill in the hotbar
Player player = mage.getPlayer();
PlayerInventory playerInventory = player.getInventory();
for (int i = 0; i < HOTBAR_SIZE; i++) {
ItemStack playerItem = playerInventory.getItem(i);
if (isWand(playerItem)) {
playerItem = null;
}
hotbar.setItem(i, playerItem);
}
// Fill in the active inventory page
Inventory openInventory = getOpenInventory();
for (int i = 0; i < openInventory.getSize(); i++) {
openInventory.setItem(i, playerInventory.getItem(i + HOTBAR_SIZE));
}
saveState();
}
public static boolean isActive(Player player) {
ItemStack activeItem = player.getInventory().getItemInHand();
return isWand(activeItem);
}
protected void randomize(int totalLevels, boolean additive) {
if (!wandTemplates.containsKey("random")) return;
if (!additive) {
wandName = Messages.get("wands.random.name", wandName);
}
int maxLevel = WandLevel.getMaxLevel();
int addLevels = Math.min(totalLevels, maxLevel);
while (addLevels > 0) {
WandLevel.randomizeWand(this, additive, addLevels);
totalLevels -= maxLevel;
addLevels = Math.min(totalLevels, maxLevel);
additive = true;
}
}
public static Wand createWand(MagicController controller, String templateName) {
return createWand(controller, templateName, null);
}
public static Wand createWand(MagicController controller, String templateName, Mage owner) {
Wand wand = new Wand(controller);
wand.suspendSave = true;
String wandName = Messages.get("wand.default_name");
String wandDescription = "";
// Check for default wand
if ((templateName == null || templateName.length() == 0) && wandTemplates.containsKey("default"))
{
templateName = "default";
}
// See if there is a template with this key
if (templateName != null && templateName.length() > 0) {
if ((templateName.equals("random") || templateName.startsWith("random(")) && wandTemplates.containsKey("random")) {
int level = 1;
if (!templateName.equals("random")) {
String randomLevel = templateName.substring(templateName.indexOf('(') + 1, templateName.length() - 1);
level = Integer.parseInt(randomLevel);
}
ConfigurationNode randomTemplate = wandTemplates.get("random");
wand.randomize(level, false);
wand.modifiable = (boolean)randomTemplate.getBoolean("modifiable", true);
wand.saveState(true);
return wand;
}
if (!wandTemplates.containsKey(templateName)) {
return null;
}
ConfigurationNode wandConfig = wandTemplates.get(templateName);
wandName = Messages.get("wands." + templateName + ".name", wandName);
wandDescription = Messages.get("wands." + templateName + ".description", wandDescription);
List<Object> spellList = wandConfig.getList("spells");
if (spellList != null) {
for (Object spellName : spellList) {
wand.addSpell((String)spellName);
}
}
List<Object> materialList = wandConfig.getList("materials");
if (materialList != null) {
for (Object materialKey : materialList) {
if (!isValidMaterial((String)materialKey)) {
controller.getPlugin().getLogger().info("Unknown material: " + materialKey);
} else {
wand.addMaterial((String)materialKey, false, true);
}
}
}
wand.configureProperties(wandConfig);
if (wandConfig.getBoolean("organize", false)) {
wand.organizeInventory(owner);
}
}
if (owner != null) {
wand.takeOwnership(owner.getPlayer());
}
wand.setDescription(wandDescription);
wand.setName(wandName);
wand.saveState(true);
return wand;
}
public void add(Wand other) {
if (!modifiable || !other.modifiable) return;
costReduction = Math.max(costReduction, other.costReduction);
power = Math.max(power, other.power);
damageReduction = Math.max(damageReduction, other.damageReduction);
damageReductionPhysical = Math.max(damageReductionPhysical, other.damageReductionPhysical);
damageReductionProjectiles = Math.max(damageReductionProjectiles, other.damageReductionProjectiles);
damageReductionFalling = Math.max(damageReductionFalling, other.damageReductionFalling);
damageReductionFire = Math.max(damageReductionFire, other.damageReductionFire);
damageReductionExplosions = Math.max(damageReductionExplosions, other.damageReductionExplosions);
healthRegeneration = Math.max(healthRegeneration, other.healthRegeneration);
hungerRegeneration = Math.max(hungerRegeneration, other.hungerRegeneration);
speedIncrease = Math.max(speedIncrease, other.speedIncrease);
// Mix colors
if (effectColor == 0) {
effectColor = other.effectColor;
} else if (other.effectColor != 0){
Color color1 = Color.fromBGR(effectColor);
Color color2 = Color.fromBGR(other.effectColor);
Color newColor = color1.mixColors(color2);
effectColor = newColor.asRGB();
}
effectColor = Math.max(effectColor, other.effectColor);
effectBubbles = effectBubbles || other.effectBubbles;
if (effectParticle == null) {
effectParticle = other.effectParticle;
effectParticleData = other.effectParticleData;
}
// Don't need mana if cost-free
if (costReduction >= 1) {
xpRegeneration = 0;
xpMax = 0;
xp = 0;
} else {
xpRegeneration = Math.max(xpRegeneration, other.xpRegeneration);
xpMax = Math.max(xpMax, other.xpMax);
xp = Math.max(xp, other.xp);
}
// Eliminate limited-use wands
if (uses == 0 || other.uses == 0) {
uses = 0;
} else {
// Otherwise add them
uses = uses + other.uses;
}
// Add spells
Set<String> spells = other.getSpells();
for (String spell : spells) {
addSpell(spell, false);
}
// Add materials
Set<String> materials = other.getMaterialKeys();
for (String material : materials) {
addMaterial(material, false, true);
}
saveState();
updateName();
updateLore();
}
public void configureProperties(ConfigurationNode wandConfig) {
configureProperties(wandConfig, false);
}
public void configureProperties(ConfigurationNode wandConfig, boolean safe) {
modifiable = (boolean)wandConfig.getBoolean("modifiable", modifiable);
float _costReduction = (float)wandConfig.getDouble("cost_reduction", costReduction);
costReduction = safe ? Math.max(_costReduction, costReduction) : _costReduction;
float _cooldownReduction = (float)wandConfig.getDouble("cooldown_reduction", cooldownReduction);
cooldownReduction = safe ? Math.max(_cooldownReduction, cooldownReduction) : _cooldownReduction;
float _power = (float)wandConfig.getDouble("power", power);
power = safe ? Math.max(_power, power) : _power;
float _damageReduction = (float)wandConfig.getDouble("protection", damageReduction);
damageReduction = safe ? Math.max(_damageReduction, damageReduction) : _damageReduction;
float _damageReductionPhysical = (float)wandConfig.getDouble("protection_physical", damageReductionPhysical);
damageReductionPhysical = safe ? Math.max(_damageReductionPhysical, damageReductionPhysical) : _damageReductionPhysical;
float _damageReductionProjectiles = (float)wandConfig.getDouble("protection_projectiles", damageReductionProjectiles);
damageReductionProjectiles = safe ? Math.max(_damageReductionProjectiles, damageReductionPhysical) : _damageReductionProjectiles;
float _damageReductionFalling = (float)wandConfig.getDouble("protection_falling", damageReductionFalling);
damageReductionFalling = safe ? Math.max(_damageReductionFalling, damageReductionFalling) : _damageReductionFalling;
float _damageReductionFire = (float)wandConfig.getDouble("protection_fire", damageReductionFire);
damageReductionFire = safe ? Math.max(_damageReductionFire, damageReductionFire) : _damageReductionFire;
float _damageReductionExplosions = (float)wandConfig.getDouble("protection_explosions", damageReductionExplosions);
damageReductionExplosions = safe ? Math.max(_damageReductionExplosions, damageReductionExplosions) : _damageReductionExplosions;
int _xpRegeneration = wandConfig.getInt("xp_regeneration", xpRegeneration);
xpRegeneration = safe ? Math.max(_xpRegeneration, xpRegeneration) : _xpRegeneration;
int _xpMax = wandConfig.getInt("xp_max", xpMax);
xpMax = safe ? Math.max(_xpMax, xpMax) : _xpMax;
int _xp = wandConfig.getInt("xp", xp);
xp = safe ? Math.max(_xp, xp) : _xp;
int _healthRegeneration = wandConfig.getInt("health_regeneration", healthRegeneration);
healthRegeneration = safe ? Math.max(_healthRegeneration, healthRegeneration) : _healthRegeneration;
int _hungerRegeneration = wandConfig.getInt("hunger_regeneration", hungerRegeneration);
hungerRegeneration = safe ? Math.max(_hungerRegeneration, hungerRegeneration) : _hungerRegeneration;
int _uses = wandConfig.getInt("uses", uses);
uses = safe ? Math.max(_uses, uses) : _uses;
float _speedIncrease = (float)wandConfig.getDouble("haste", speedIncrease);
speedIncrease = safe ? Math.max(_speedIncrease, speedIncrease) : _speedIncrease;
if (wandConfig.containsKey("effect_color") && !safe) {
try {
effectColor = Integer.parseInt(wandConfig.getString("effect_color", "0"), 16);
} catch (Exception ex) {
}
}
if (wandConfig.containsKey("effect_bubbles")) {
boolean _effectBubbles = (boolean)wandConfig.getBoolean("effect_bubbles", effectBubbles);
effectBubbles = safe ? _effectBubbles || effectBubbles : _effectBubbles;
}
if (wandConfig.containsKey("effect_particle") && !safe) {
parseParticleEffect(wandConfig.getString("effect_particle"));
}
if (wandConfig.containsKey("effect_particle_data") && !safe) {
effectParticleData = Float.parseFloat(wandConfig.getString("effect_particle_data"));
}
mode = parseWandMode(wandConfig.getString("mode"), mode);
owner = wandConfig.getString("owner", owner);
description = wandConfig.getString("description", description);
saveState();
updateName();
updateLore();
}
public static void loadTemplates(ConfigurationNode properties) {
wandTemplates.clear();
List<String> wandKeys = properties.getKeys();
for (String key : wandKeys)
{
ConfigurationNode wandNode = properties.getNode(key);
wandNode.setProperty("key", key);
ConfigurationNode existing = wandTemplates.get(key);
if (existing != null) {
List<String> overrideKeys = existing.getKeys();
for (String propertyKey : overrideKeys) {
existing.setProperty(propertyKey, existing.getProperty(key));
}
} else {
wandTemplates.put(key, wandNode);
}
if (!wandNode.getBoolean("enabled", true)) {
wandTemplates.remove(key);
}
if (key.equals("random")) {
WandLevel.mapLevels(wandNode);
}
}
}
public static Collection<String> getWandKeys() {
return wandTemplates.keySet();
}
public static Collection<ConfigurationNode> getWandTemplates() {
return wandTemplates.values();
}
public static WandMode parseWandMode(String modeString, WandMode defaultValue) {
for (WandMode testMode : WandMode.values()) {
if (testMode.name().equalsIgnoreCase(modeString)) {
return testMode;
}
}
return defaultValue;
}
@SuppressWarnings("deprecation")
public static MaterialBrushData parseMaterialKey(String materialKey) {
if (materialKey == null || materialKey.length() == 0) return null;
Material material = Material.DIRT;
byte data = 0;
String schematicName = "";
String[] pieces = StringUtils.split(materialKey, ":");
if (materialKey.equals(ERASE_MATERIAL_KEY)) {
material = EraseMaterial;
} else if (materialKey.equals(COPY_MATERIAL_KEY)) {
material = CopyMaterial;
} else if (materialKey.equals(CLONE_MATERIAL_KEY)) {
material = CloneMaterial;
} else if (materialKey.equals(REPLICATE_MATERIAL_KEY)) {
material = ReplicateMaterial;
} else if (materialKey.equals(MAP_MATERIAL_KEY)) {
material = MapMaterial;
} else if (SchematicsEnabled && pieces[0].equals(SCHEMATIC_MATERIAL_KEY)) {
material = SchematicMaterial;
schematicName = pieces[1];
} else {
try {
if (pieces.length > 0) {
// Legacy material id loading
try {
Integer id = Integer.parseInt(pieces[0]);
material = Material.getMaterial(id);
} catch (Exception ex) {
material = Material.getMaterial(pieces[0].toUpperCase());
}
}
// Prevent building with items
if (material != null && !material.isBlock()) {
material = null;
}
} catch (Exception ex) {
material = null;
}
try {
if (pieces.length > 1) {
data = Byte.parseByte(pieces[1]);
}
} catch (Exception ex) {
data = 0;
}
}
if (material == null) return null;
return new MaterialBrushData(material, data, schematicName);
}
public static boolean isValidMaterial(String materialKey) {
return parseMaterialKey(materialKey) != null;
}
private void updateActiveMaterial() {
if (mage == null) return;
if (activeMaterial == null) {
mage.clearBuildingMaterial();
} else {
String pieces[] = StringUtils.split(activeMaterial, ":");
MaterialBrush brush = mage.getBrush();
if (activeMaterial.equals(COPY_MATERIAL_KEY)) {
brush.enableCopying();
} else if (activeMaterial.equals(CLONE_MATERIAL_KEY)) {
brush.enableCloning();
} else if (activeMaterial.equals(REPLICATE_MATERIAL_KEY)) {
brush.enableReplication();
} else if (activeMaterial.equals(MAP_MATERIAL_KEY)) {
brush.enableMap();
} else if (activeMaterial.equals(ERASE_MATERIAL_KEY)) {
brush.enableErase();
} else if (pieces.length > 1 && pieces[0].equals(SCHEMATIC_MATERIAL_KEY)) {
brush.enableSchematic(pieces[1]);
} else {
MaterialAndData material = parseMaterialKey(activeMaterial);
if (material != null) {
brush.setMaterial(material.getMaterial(), material.getData());
}
}
}
}
public void toggleInventory() {
if (!hasInventory) {
return;
}
if (!isInventoryOpen()) {
openInventory();
} else {
closeInventory();
}
}
@SuppressWarnings("deprecation")
public void cycleInventory() {
if (!hasInventory) {
return;
}
if (isInventoryOpen()) {
saveInventory();
openInventoryPage = (openInventoryPage + 1) % inventories.size();
updateInventory();
if (mage != null && inventories.size() > 1) {
mage.playSound(Sound.CHEST_OPEN, 0.3f, 1.5f);
mage.getPlayer().updateInventory();
}
}
}
@SuppressWarnings("deprecation")
private void openInventory() {
if (mage == null) return;
WandMode wandMode = getMode();
if (wandMode == WandMode.CHEST) {
// Hacky work-around for switching between modes. This mode has no hotbar!
for (int i = 0; i < HOTBAR_SIZE; i++) {
// Put hotbar items in main inventory since we don't show the hotbar in chest mode.
ItemStack hotbarItem = hotbar.getItem(i);
if (hotbarItem != null && hotbarItem.getType() != Material.AIR) {
hotbar.setItem(i, null);
addToInventory(hotbarItem);
}
}
inventoryIsOpen = true;
mage.playSound(Sound.CHEST_OPEN, 0.4f, 0.2f);
updateInventory();
mage.getPlayer().openInventory(getDisplayInventory());
} else if (wandMode == WandMode.INVENTORY) {
if (mage.hasStoredInventory()) return;
if (mage.storeInventory()) {
inventoryIsOpen = true;
mage.playSound(Sound.CHEST_OPEN, 0.4f, 0.2f);
updateInventory();
updateInventoryNames();
mage.getPlayer().updateInventory();
}
}
}
@SuppressWarnings("deprecation")
public void closeInventory() {
if (!isInventoryOpen()) return;
saveInventory();
inventoryIsOpen = false;
if (mage != null) {
mage.playSound(Sound.CHEST_CLOSE, 0.4f, 0.2f);
if (getMode() == WandMode.INVENTORY) {
mage.restoreInventory();
Player player = mage.getPlayer();
player.setItemInHand(item);
player.updateInventory();
} else {
mage.getPlayer().closeInventory();
}
}
saveState();
}
protected void updateSpeed(Player player) {
if (speedIncrease > 0) {
try {
float newWalkSpeed = defaultWalkSpeed + (speedIncrease * WandLevel.maxWalkSpeedIncrease);
newWalkSpeed = Math.min(WandLevel.maxWalkSpeed, newWalkSpeed);
if (newWalkSpeed != player.getWalkSpeed()) {
player.setWalkSpeed(newWalkSpeed);
}
float newFlySpeed = defaultFlySpeed + (speedIncrease * WandLevel.maxFlySpeedIncrease);
newFlySpeed = Math.min(WandLevel.maxFlySpeed, newFlySpeed);
if (newFlySpeed != player.getFlySpeed()) {
player.setFlySpeed(newFlySpeed);
}
} catch(Exception ex2) {
try {
player.setWalkSpeed(defaultWalkSpeed);
player.setFlySpeed(defaultFlySpeed);
} catch(Exception ex) {
}
}
}
}
public void activate(Mage mage) {
this.mage = mage;
Player player = mage.getPlayer();
if (!Wand.hasActiveWand(player)) {
controller.getLogger().warning("Wand activated without holding a wand!");
return;
}
// Update held item, it may have been copied since this wand was created.
item = player.getItemInHand();
saveState();
mage.setActiveWand(this);
if (owner.length() == 0) {
takeOwnership(player);
}
updateSpeed(player);
if (usesMana()) {
storedXpLevel = player.getLevel();
storedXpProgress = player.getExp();
storedXp = 0;
updateMana();
}
updateActiveMaterial();
updateName();
updateLore();
updateEffects();
}
@SuppressWarnings("deprecation")
protected void updateEffects() {
if (mage == null) return;
Player player = mage.getPlayer();
if (player == null) return;
// Update Bubble effects effects
if (effectColor != 0 && effectBubbles) {
InventoryUtils.addPotionEffect(player, effectColor);
}
// TODO: More customization?
if (effectParticle != null) {
Location effectLocation = player.getEyeLocation();
EffectRing effect = new EffectRing(controller.getPlugin(), effectLocation, 1, 8);
effect.setParticleType(effectParticle);
effect.setEffectData(effectParticleData);
if (effectParticle == ParticleType.BLOCK_BREAKING) {
Block block = mage.getLocation().getBlock().getRelative(BlockFace.DOWN);
Material blockType = block.getType();
// Filter to prevent client crashing... hopefully this is enough?
if (blockType.isSolid()) {
effect.setParticleSubType("" + blockType.getId());
effect.setParticleCount(3);
effect.start();
}
} else {
effect.setParticleCount(1);
effect.start();
}
}
}
protected void updateMana() {
if (mage != null && xpMax > 0 && xpRegeneration > 0) {
Player player = mage.getPlayer();
player.setLevel(0);
player.setExp((float)xp / (float)xpMax);
}
}
public boolean isInventoryOpen() {
return mage != null && inventoryIsOpen;
}
public void deactivate() {
if (mage == null) return;
saveState();
if (effectColor > 0) {
InventoryUtils.removePotionEffect(mage.getPlayer());
}
// This is a tying wands together with other spells, potentially
// But with the way the mana system works, this seems like the safest route.
mage.deactivateAllSpells();
if (isInventoryOpen()) {
closeInventory();
}
// Extra just-in-case
mage.restoreInventory();
if (usesMana()) {
mage.getPlayer().setExp(storedXpProgress);
mage.getPlayer().setLevel(storedXpLevel);
mage.getPlayer().giveExp(storedXp);
storedXp = 0;
storedXpProgress = 0;
storedXpLevel = 0;
}
if (speedIncrease > 0) {
try {
mage.getPlayer().setWalkSpeed(defaultWalkSpeed);
mage.getPlayer().setFlySpeed(defaultFlySpeed);
} catch(Exception ex) {
}
}
mage.setActiveWand(null);
mage = null;
}
public Spell getActiveSpell() {
if (mage == null) return null;
return mage.getSpell(activeSpell);
}
public boolean cast() {
Spell spell = getActiveSpell();
if (spell != null) {
if (spell.cast()) {
use();
return true;
}
}
return false;
}
@SuppressWarnings("deprecation")
protected void use() {
if (mage == null) return;
if (uses > 0) {
uses
if (uses <= 0) {
Player player = mage.getPlayer();
mage.playSound(Sound.ITEM_BREAK, 1.0f, 0.8f);
PlayerInventory playerInventory = player.getInventory();
playerInventory.setItemInHand(new ItemStack(Material.AIR, 1));
player.updateInventory();
deactivate();
} else {
updateName();
updateLore();
saveState();
}
}
}
public void onPlayerExpChange(PlayerExpChangeEvent event) {
if (mage == null) return;
if (usesMana()) {
storedXp += event.getAmount();
event.setAmount(0);
}
}
public void tick() {
if (mage == null) return;
Player player = mage.getPlayer();
updateSpeed(player);
if (usesMana()) {
xp = Math.min(xpMax, xp + xpRegeneration);
updateMana();
}
double maxHealth = player.getMaxHealth();
if (healthRegeneration > 0 && player.getHealth() < maxHealth) {
player.setHealth(Math.min(maxHealth, player.getHealth() + healthRegeneration));
}
double maxFoodLevel = 20;
if (hungerRegeneration > 0 && player.getFoodLevel() < maxFoodLevel) {
player.setExhaustion(0);
player.setFoodLevel(Math.min(20, player.getFoodLevel() + hungerRegeneration));
}
if (damageReductionFire > 0 && player.getFireTicks() > 0) {
player.setFireTicks(0);
}
updateEffects();
}
@Override
public boolean equals(Object other) {
if (other == null) return false;
if (!(other instanceof Wand)) return false;
Wand otherWand = ((Wand)other);
if (this.id == null || otherWand.id == null) return false;
return otherWand.id.equals(this.id);
}
public MagicController getMaster() {
return controller;
}
public void cycleSpells() {
Set<String> spellsSet = getSpells();
ArrayList<String> spells = new ArrayList<String>(spellsSet);
if (spells.size() == 0) return;
if (activeSpell == null) {
activeSpell = spells.get(0).split("@")[0];
return;
}
int spellIndex = 0;
for (int i = 0; i < spells.size(); i++) {
if (spells.get(i).split("@")[0].equals(activeSpell)) {
spellIndex = i;
break;
}
}
spellIndex = (spellIndex + 1) % spells.size();
setActiveSpell(spells.get(spellIndex).split("@")[0]);
}
public void cycleMaterials() {
Set<String> materialsSet = getMaterialKeys();
ArrayList<String> materials = new ArrayList<String>(materialsSet);
if (materials.size() == 0) return;
if (activeMaterial == null) {
activeMaterial = materials.get(0).split("@")[0];
return;
}
int materialIndex = 0;
for (int i = 0; i < materials.size(); i++) {
if (materials.get(i).split("@")[0].equals(activeMaterial)) {
materialIndex = i;
break;
}
}
materialIndex = (materialIndex + 1) % materials.size();
setActiveMaterial(materials.get(materialIndex).split("@")[0]);
}
public boolean hasExperience() {
return xpRegeneration > 0;
}
public void organizeInventory(Mage mage) {
WandOrganizer organizer = new WandOrganizer(this, mage);
organizer.organize();
openInventoryPage = 0;
saveState();
}
public void organizeInventory() {
WandOrganizer organizer = new WandOrganizer(this, null);
organizer.organize();
openInventoryPage = 0;
saveState();
}
public Mage getActivePlayer() {
return mage;
}
public String getId() {
return this.id;
}
protected void clearInventories() {
inventories.clear();
}
public int getEffectColor() {
return effectColor;
}
public Inventory getHotbar() {
return hotbar;
}
public WandMode getMode() {
return mode != null ? mode : controller.getDefaultWandMode();
}
}
|
package com.fatico.winthing.systems.radeon;
import com.fatico.winthing.systems.radeon.jna.AtiAdl;
import com.google.common.collect.ComparisonChain;
import com.google.inject.Inject;
import com.sun.jna.Memory;
import com.sun.jna.Pointer;
import com.sun.jna.ptr.IntByReference;
import com.sun.jna.ptr.PointerByReference;
import java.util.Arrays;
import java.util.Collections;
import java.util.NoSuchElementException;
import java.util.Objects;
public class RadeonService {
private final AtiAdl atiAdl;
private final Pointer context;
@Inject
public RadeonService(final AtiAdl atiAdl) {
this.atiAdl = Objects.requireNonNull(atiAdl);
{
final PointerByReference contextReference = new PointerByReference();
final int result = atiAdl.ADL2_Main_Control_Create(
new MallocCallback(),
1,
contextReference
);
if (result != AtiAdl.ADL_OK) {
throw new AdlException("ADL2_Main_Control_Create", result);
}
this.context = contextReference.getValue();
}
}
@Override
protected void finalize() throws Throwable {
atiAdl.ADL2_Main_Control_Destroy(context);
super.finalize();
}
public int getPrimaryAdapterIndex() {
final IntByReference adapterIndexReference = new IntByReference();
final int result = atiAdl.ADL2_Adapter_Primary_Get(
context,
adapterIndexReference
);
if (result != AtiAdl.ADL_OK) {
throw new AdlException("ADL2_Display_CustomizedModeListNum_Get", result);
}
return adapterIndexReference.getValue();
}
public void setBestResolution(final int adapterIndex) {
final AtiAdl.ADLMode mode = getBestMode(adapterIndex);
setMode(adapterIndex, mode);
}
public void setResolution(final int adapterIndex, final int width, final int height) {
final AtiAdl.ADLMode mode = getBestMode(adapterIndex);
mode.iXRes = width;
mode.iYRes = height;
setMode(adapterIndex, mode);
}
private void setMode(final int adapterIndex, final AtiAdl.ADLMode mode) {
final int result = atiAdl.ADL2_Display_Modes_Set(
context,
adapterIndex,
-1,
1,
(AtiAdl.ADLMode[]) mode.toArray(1)
);
if (result != AtiAdl.ADL_OK) {
throw new AdlException("ADL2_Display_Modes_Set", result);
}
}
private AtiAdl.ADLMode getBestMode(final int adapterIndex) {
final AtiAdl.ADLMode[] modes;
{
final IntByReference numberOfModesReference = new IntByReference();
final PointerByReference pointer = new PointerByReference();
final int result = atiAdl.ADL2_Display_PossibleMode_Get(
context,
adapterIndex,
numberOfModesReference,
pointer
);
if (result != AtiAdl.ADL_OK) {
throw new AdlException("ADL2_Display_Modes_Get", result);
}
modes = (AtiAdl.ADLMode[]) new AtiAdl.ADLMode(pointer.getValue()).toArray(
numberOfModesReference.getValue()
);
}
if (modes.length == 0) {
throw new NoSuchElementException();
}
return Collections.max(Arrays.asList(modes), (left, right) -> ComparisonChain.start()
.compare(left.iColourDepth, right.iColourDepth)
.compare(left.iXRes, right.iXRes)
.compare(left.iYRes, right.iYRes)
.compare(left.fRefreshRate, right.fRefreshRate)
.result()
);
}
private static class MallocCallback extends Memory implements AtiAdl.ADL_MAIN_MALLOC_CALLBACK {
@Override
public Pointer invoke(int size) {
return new Pointer(Memory.malloc(size));
}
}
}
|
package com.fewlaps.quitnowemailsuggester;
import com.fewlaps.quitnowemailsuggester.exception.InvalidEmailException;
import java.util.Arrays;
import java.util.List;
public class EmailSuggester {
public static final String YAHOO = "yahoo";
public static final String GMAIL = "gmail";
public static final String HOTMAIL = "hotmail";
public static final String OUTLOOK = "outlook";
public static final String COM = "com";
public static final String DOTCOM = ".com";
public static final String DOTNET = ".net";
public List<EmailCorrection> tldCorrections = Arrays.asList(
new EmailCorrection(".cpm", DOTCOM),
new EmailCorrection(".cpn", DOTCOM),
new EmailCorrection(".con", DOTCOM),
new EmailCorrection(".col", DOTCOM),
new EmailCorrection(".comm", DOTCOM),
new EmailCorrection(".cxom", DOTCOM),
new EmailCorrection(".coml", DOTCOM),
new EmailCorrection(".ney", DOTNET)
);
public List<EmailCorrection> domainCorrections = Arrays.asList(
new EmailCorrection("gnail", GMAIL),
new EmailCorrection("gmial", GMAIL),
new EmailCorrection("gmaail", GMAIL),
new EmailCorrection("gnail", GMAIL),
new EmailCorrection("gamil", GMAIL),
new EmailCorrection("gmal", GMAIL),
new EmailCorrection("ygmail", GMAIL),
new EmailCorrection("gmai", GMAIL),
new EmailCorrection("gimail", GMAIL),
new EmailCorrection("hotmaail", HOTMAIL),
new EmailCorrection("hotmal", HOTMAIL),
new EmailCorrection("hotmai", HOTMAIL),
new EmailCorrection("hotmali", HOTMAIL),
new EmailCorrection("hitmail", HOTMAIL),
new EmailCorrection("hotmial", HOTMAIL),
new EmailCorrection("hotmale", HOTMAIL),
new EmailCorrection("homtail", HOTMAIL),
new EmailCorrection("yaho", YAHOO),
new EmailCorrection("yaoo", YAHOO),
new EmailCorrection("yaboo", YAHOO),
new EmailCorrection("outllok", OUTLOOK)
);
public List<EmailCorrection> domainAndTldCorrections = Arrays.asList(
new EmailCorrection("gmail.co", GMAIL + DOTCOM),
new EmailCorrection("yahoo.om", YAHOO + DOTCOM),
new EmailCorrection("gmail.om", GMAIL + DOTCOM)
);
public String getSuggestedEmail(String email) throws InvalidEmailException {
if (email == null) {
throw new InvalidEmailException();
}
email = fixComWithAnotherChar(email);
for (EmailCorrection correction : tldCorrections) {
email = fixTld(email, correction.getBadEnd(), correction.getGoodEnd());
}
for (EmailCorrection correction : domainCorrections) {
email = fixDomain(email, correction.getBadEnd(), correction.getGoodEnd());
}
for (EmailCorrection correction : domainAndTldCorrections) {
email = fixDomainAndTld(email, correction.getBadEnd(), correction.getGoodEnd());
}
return email;
}
private String fixComWithAnotherChar(String email) throws InvalidEmailException {
EmailParts ep = new EmailParts();
String tld = ep.getTld(email);
if (tld.contains(COM) && tld.length() == COM.length()+1) {//if it's coma, comb, comc, acom, bcom, ccom...
return fixTld(email, tld, COM);
} else {
return email;
}
}
private String fixTld(String email, String badTld, String goodTld) {
if (email.endsWith(badTld)) {
email = email.substring(0, email.length() - badTld.length()).concat(goodTld);
}
return email;
}
private String fixDomain(String email, String badDomain, String goodDomain) throws InvalidEmailException {
EmailParts ep = new EmailParts();
String domain = ep.getDomainWithoutTld(email);
if (domain.equals(badDomain)) {
email = email.replaceAll(domain, goodDomain);
}
return email;
}
private String fixDomainAndTld(String email, String badDomainAndTld, String goodDomainAndTld) {
if (email.endsWith(badDomainAndTld)) {
email = email.substring(0, email.length() - badDomainAndTld.length()).concat(goodDomainAndTld);
}
return email;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.