gt
stringclasses
1 value
context
stringlengths
2.05k
161k
package org.xmlactions.db; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.sql.Date; import java.text.DateFormat; import java.text.Format; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.TimeZone; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xmlactions.db.DBUtils; public class DBUtils { public static final String XSD_LONG_DATE_TIME_FMT = "yyyy-MM-dd HH:mm:ss.SSS"; private final static Logger log = LoggerFactory.getLogger(DBUtils.class); public static void closeQuietly(Connection conn) { try { if (conn != null) { conn.close(); } } catch (Exception ex) { log.error(ex.getMessage(), ex); } } public static void closeQuietly(Statement stmt) { try { if (stmt != null) { stmt.close(); } } catch (Exception ex) { log.error(ex.getMessage(), ex); } } public static void closeQuietly(ResultSet rset) { try { if (rset != null) { rset.close(); } } catch (Exception ex) { log.error(ex.getMessage(), ex); } } public static String getDate(long timeInMillis) { Date date = new Date(timeInMillis); return date.toString(); } /** * * @param timeInMillis * @param dateFormat * default is 'yyyy-MM-dd HH:mm' * @return */ public static String formatDate(long timeInMillis, String dateFormat) { Date date = new Date(timeInMillis); Format formatter; // Some examples formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm"); String s = formatter.format(date); return s; } /** * Build a Date from a String date and a formatter * @param date as a string format * @param formatter * @return date constructed from the date input */ public static Date buildDate(String date, String dateFormat) { try { return new Date(new SimpleDateFormat(dateFormat).parse(date).getTime()); } catch (Exception ex) { throw new IllegalArgumentException("buildDate:The Date [" + date + "] using a formatter of [" + dateFormat + "] format is incorrect.", ex); } } /** * Build a Date from a String date. The format is expected to match * #DBUtils.XSD_LONG_DATE_TIME_FMT * @param date as a string format * @return date constructed from the date input */ public static Date buildDate(String date) { return buildDate(date, XSD_LONG_DATE_TIME_FMT); } /** * Build a Date from a String date. The format is expected to match * "yyyy-MM-dd hh:mm:ss.sss" or "yyyy-MM-dd" or "hh:mm:ss.sss" * @param date as a string format * @return date constructed from the date input * @throws SQLException */ public static Date buildDateFromString(String datetime) throws SQLException { // this is a fix for dojo time format that includes a T at the start of the time. if (datetime.startsWith("T")) { datetime = datetime.substring(1); } String errorString = "Invalid date time format for [" + datetime + "]. Must match 'yyyy-MM-dd hh:mm:ss.sss' or 'yyyy-MM-dd' or 'hh:mm:ss.sss'"; String [] datePatterns = new String [] {"yyyy","-MM","-dd"}; String [] timePatterns = new String [] {"HH",":mm", ":ss", ".SSS"}; int datePatternIndex = 0; int timePatternIndex = 0; int wasDate = 1; int wasTime = 2; StringBuilder dateBuilder = new StringBuilder(); StringBuilder timeBuilder = new StringBuilder(); int lastStoreWas = 0; int lastPos = 0; for (int pos = 0 ; pos < datetime.length()+1; pos++) { char c; if (pos == datetime.length()) { if (lastStoreWas == wasDate) c = '-'; else c = ':'; } else { c = datetime.charAt(pos); } if(c == '-') { lastStoreWas = wasDate; String pattern = getPatternByIndex(datePatterns, datePatternIndex); if (pattern == null) { throw new SQLException(errorString); } dateBuilder.append(pattern); datePatternIndex++; lastPos = pos; } else if (c == ':' || c=='.') { lastStoreWas = wasTime; String pattern = getPatternByIndex(timePatterns, timePatternIndex); if (pattern == null) { throw new SQLException(errorString); } timeBuilder.append(pattern); timePatternIndex++; lastPos = pos; } else if (c == ' ') { if (lastStoreWas == wasDate) { String pattern = getPatternByIndex(datePatterns, datePatternIndex); if (pattern == null) { throw new SQLException(errorString); } dateBuilder.append(pattern); datePatternIndex++; } else if (lastStoreWas == wasTime) { String pattern = getPatternByIndex(timePatterns, timePatternIndex); if (pattern == null) { throw new SQLException(errorString); } timeBuilder.append(pattern); timePatternIndex++; } lastStoreWas = 0; lastPos = pos+1; } else if (isNumber(c)==false) { throw new SQLException(errorString); } } String pattern = ""; if (dateBuilder.length() > 0) { if (timeBuilder.length() > 0) { pattern = dateBuilder.toString() + " " + timeBuilder.toString(); } else { pattern = dateBuilder.toString(); } } else if (timeBuilder.length() > 0) { pattern = timeBuilder.toString(); } if (pattern.length() == 0) { throw new SQLException(errorString); } return buildDate(datetime, pattern); } private static boolean isNumber(char c) { if (c < '0' || c > '9') { return false; } return true; } private static String getPatternByIndex (String [] patterns, int index) { if (index > -1 && index < patterns.length) { return patterns[index]; } return null; } }
/** * Copyright 2014 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package rx; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyInt; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.isA; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import java.util.ArrayList; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.NoSuchElementException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; import org.junit.Before; import org.junit.Test; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import rx.Observable.OnSubscribe; import rx.functions.Action1; import rx.functions.Action2; import rx.functions.Func1; import rx.functions.Func2; import rx.observables.ConnectableObservable; import rx.schedulers.TestScheduler; import rx.subscriptions.BooleanSubscription; public class ObservableTests { @Mock Observer<Integer> w; private static final Func1<Integer, Boolean> IS_EVEN = new Func1<Integer, Boolean>() { @Override public Boolean call(Integer value) { return value % 2 == 0; } }; @Before public void before() { MockitoAnnotations.initMocks(this); } @Test public void fromArray() { String[] items = new String[] { "one", "two", "three" }; assertEquals(new Integer(3), Observable.from(items).count().toBlocking().single()); assertEquals("two", Observable.from(items).skip(1).take(1).toBlocking().single()); assertEquals("three", Observable.from(items).takeLast(1).toBlocking().single()); } @Test public void fromIterable() { ArrayList<String> items = new ArrayList<String>(); items.add("one"); items.add("two"); items.add("three"); assertEquals(new Integer(3), Observable.from(items).count().toBlocking().single()); assertEquals("two", Observable.from(items).skip(1).take(1).toBlocking().single()); assertEquals("three", Observable.from(items).takeLast(1).toBlocking().single()); } @Test public void fromArityArgs3() { Observable<String> items = Observable.from("one", "two", "three"); assertEquals(new Integer(3), items.count().toBlocking().single()); assertEquals("two", items.skip(1).take(1).toBlocking().single()); assertEquals("three", items.takeLast(1).toBlocking().single()); } @Test public void fromArityArgs1() { Observable<String> items = Observable.from("one"); assertEquals(new Integer(1), items.count().toBlocking().single()); assertEquals("one", items.takeLast(1).toBlocking().single()); } @Test public void testCreate() { Observable<String> observable = Observable.create(new OnSubscribe<String>() { @Override public void call(Subscriber<? super String> Observer) { Observer.onNext("one"); Observer.onNext("two"); Observer.onNext("three"); Observer.onCompleted(); } }); @SuppressWarnings("unchecked") Observer<String> observer = mock(Observer.class); observable.subscribe(observer); verify(observer, times(1)).onNext("one"); verify(observer, times(1)).onNext("two"); verify(observer, times(1)).onNext("three"); verify(observer, never()).onError(any(Throwable.class)); verify(observer, times(1)).onCompleted(); } @Test public void testCountAFewItems() { Observable<String> observable = Observable.from("a", "b", "c", "d"); observable.count().subscribe(w); // we should be called only once verify(w, times(1)).onNext(anyInt()); verify(w).onNext(4); verify(w, never()).onError(any(Throwable.class)); verify(w, times(1)).onCompleted(); } @Test public void testCountZeroItems() { Observable<String> observable = Observable.empty(); observable.count().subscribe(w); // we should be called only once verify(w, times(1)).onNext(anyInt()); verify(w).onNext(0); verify(w, never()).onError(any(Throwable.class)); verify(w, times(1)).onCompleted(); } @Test public void testCountError() { Observable<String> o = Observable.create(new OnSubscribe<String>() { @Override public void call(Subscriber<? super String> obsv) { obsv.onError(new RuntimeException()); } }); o.count().subscribe(w); verify(w, never()).onNext(anyInt()); verify(w, never()).onCompleted(); verify(w, times(1)).onError(any(RuntimeException.class)); } public void testTakeFirstWithPredicateOfSome() { Observable<Integer> observable = Observable.from(1, 3, 5, 4, 6, 3); observable.takeFirst(IS_EVEN).subscribe(w); verify(w, times(1)).onNext(anyInt()); verify(w).onNext(4); verify(w, times(1)).onCompleted(); verify(w, never()).onError(any(Throwable.class)); } @Test public void testTakeFirstWithPredicateOfNoneMatchingThePredicate() { Observable<Integer> observable = Observable.from(1, 3, 5, 7, 9, 7, 5, 3, 1); observable.takeFirst(IS_EVEN).subscribe(w); verify(w, never()).onNext(anyInt()); verify(w, times(1)).onCompleted(); verify(w, never()).onError(any(Throwable.class)); } @Test public void testTakeFirstOfSome() { Observable<Integer> observable = Observable.from(1, 2, 3); observable.take(1).subscribe(w); verify(w, times(1)).onNext(anyInt()); verify(w).onNext(1); verify(w, times(1)).onCompleted(); verify(w, never()).onError(any(Throwable.class)); } @Test public void testTakeFirstOfNone() { Observable<Integer> observable = Observable.empty(); observable.take(1).subscribe(w); verify(w, never()).onNext(anyInt()); verify(w, times(1)).onCompleted(); verify(w, never()).onError(any(Throwable.class)); } @Test public void testFirstOfNone() { Observable<Integer> observable = Observable.empty(); observable.first().subscribe(w); verify(w, never()).onNext(anyInt()); verify(w, never()).onCompleted(); verify(w, times(1)).onError(isA(NoSuchElementException.class)); } @Test public void testFirstWithPredicateOfNoneMatchingThePredicate() { Observable<Integer> observable = Observable.from(1, 3, 5, 7, 9, 7, 5, 3, 1); observable.first(IS_EVEN).subscribe(w); verify(w, never()).onNext(anyInt()); verify(w, never()).onCompleted(); verify(w, times(1)).onError(isA(NoSuchElementException.class)); } @Test public void testReduce() { Observable<Integer> observable = Observable.from(1, 2, 3, 4); observable.reduce(new Func2<Integer, Integer, Integer>() { @Override public Integer call(Integer t1, Integer t2) { return t1 + t2; } }).subscribe(w); // we should be called only once verify(w, times(1)).onNext(anyInt()); verify(w).onNext(10); } /** * A reduce should fail with an NoSuchElementException if done on an empty Observable. */ @Test(expected = NoSuchElementException.class) public void testReduceWithEmptyObservable() { Observable<Integer> observable = Observable.range(1, 0); observable.reduce(new Func2<Integer, Integer, Integer>() { @Override public Integer call(Integer t1, Integer t2) { return t1 + t2; } }).toBlocking().forEach(new Action1<Integer>() { @Override public void call(Integer t1) { // do nothing ... we expect an exception instead } }); fail("Expected an exception to be thrown"); } /** * A reduce on an empty Observable and a seed should just pass the seed through. * * This is confirmed at https://github.com/Netflix/RxJava/issues/423#issuecomment-27642456 */ @Test public void testReduceWithEmptyObservableAndSeed() { Observable<Integer> observable = Observable.range(1, 0); int value = observable.reduce(1, new Func2<Integer, Integer, Integer>() { @Override public Integer call(Integer t1, Integer t2) { return t1 + t2; } }).toBlocking().last(); assertEquals(1, value); } @Test public void testReduceWithInitialValue() { Observable<Integer> observable = Observable.from(1, 2, 3, 4); observable.reduce(50, new Func2<Integer, Integer, Integer>() { @Override public Integer call(Integer t1, Integer t2) { return t1 + t2; } }).subscribe(w); // we should be called only once verify(w, times(1)).onNext(anyInt()); verify(w).onNext(60); } @Test public void testOnSubscribeFails() { @SuppressWarnings("unchecked") Observer<String> observer = mock(Observer.class); final RuntimeException re = new RuntimeException("bad impl"); Observable<String> o = Observable.create(new OnSubscribe<String>() { @Override public void call(Subscriber<? super String> t1) { throw re; } }); o.subscribe(observer); verify(observer, times(0)).onNext(anyString()); verify(observer, times(0)).onCompleted(); verify(observer, times(1)).onError(re); } @Test public void testMaterializeDematerializeChaining() { Observable<Integer> obs = Observable.just(1); Observable<Integer> chained = obs.materialize().dematerialize(); @SuppressWarnings("unchecked") Observer<Integer> observer = mock(Observer.class); chained.subscribe(observer); verify(observer, times(1)).onNext(1); verify(observer, times(1)).onCompleted(); verify(observer, times(0)).onError(any(Throwable.class)); } /** * The error from the user provided Observer is not handled by the subscribe method try/catch. * * It is handled by the AtomicObserver that wraps the provided Observer. * * Result: Passes (if AtomicObserver functionality exists) */ @Test public void testCustomObservableWithErrorInObserverAsynchronous() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); final AtomicInteger count = new AtomicInteger(); final AtomicReference<Throwable> error = new AtomicReference<Throwable>(); Observable.create(new OnSubscribe<String>() { @Override public void call(final Subscriber<? super String> observer) { final BooleanSubscription s = new BooleanSubscription(); new Thread(new Runnable() { @Override public void run() { try { if (!s.isUnsubscribed()) { observer.onNext("1"); observer.onNext("2"); observer.onNext("three"); observer.onNext("4"); observer.onCompleted(); } } finally { latch.countDown(); } } }).start(); } }).subscribe(new Subscriber<String>() { @Override public void onCompleted() { System.out.println("completed"); } @Override public void onError(Throwable e) { error.set(e); System.out.println("error"); e.printStackTrace(); } @Override public void onNext(String v) { int num = Integer.parseInt(v); System.out.println(num); // doSomething(num); count.incrementAndGet(); } }); // wait for async sequence to complete latch.await(); assertEquals(2, count.get()); assertNotNull(error.get()); if (!(error.get() instanceof NumberFormatException)) { fail("It should be a NumberFormatException"); } } /** * The error from the user provided Observer is handled by the subscribe try/catch because this is synchronous * * Result: Passes */ @Test public void testCustomObservableWithErrorInObserverSynchronous() { final AtomicInteger count = new AtomicInteger(); final AtomicReference<Throwable> error = new AtomicReference<Throwable>(); Observable.create(new OnSubscribe<String>() { @Override public void call(Subscriber<? super String> observer) { observer.onNext("1"); observer.onNext("2"); observer.onNext("three"); observer.onNext("4"); observer.onCompleted(); } }).subscribe(new Subscriber<String>() { @Override public void onCompleted() { System.out.println("completed"); } @Override public void onError(Throwable e) { error.set(e); System.out.println("error"); e.printStackTrace(); } @Override public void onNext(String v) { int num = Integer.parseInt(v); System.out.println(num); // doSomething(num); count.incrementAndGet(); } }); assertEquals(2, count.get()); assertNotNull(error.get()); if (!(error.get() instanceof NumberFormatException)) { fail("It should be a NumberFormatException"); } } /** * The error from the user provided Observable is handled by the subscribe try/catch because this is synchronous * * * Result: Passes */ @Test public void testCustomObservableWithErrorInObservableSynchronous() { final AtomicInteger count = new AtomicInteger(); final AtomicReference<Throwable> error = new AtomicReference<Throwable>(); Observable.create(new OnSubscribe<String>() { @Override public void call(Subscriber<? super String> observer) { observer.onNext("1"); observer.onNext("2"); throw new NumberFormatException(); } }).subscribe(new Subscriber<String>() { @Override public void onCompleted() { System.out.println("completed"); } @Override public void onError(Throwable e) { error.set(e); System.out.println("error"); e.printStackTrace(); } @Override public void onNext(String v) { System.out.println(v); count.incrementAndGet(); } }); assertEquals(2, count.get()); assertNotNull(error.get()); if (!(error.get() instanceof NumberFormatException)) { fail("It should be a NumberFormatException"); } } @Test public void testPublish() throws InterruptedException { final AtomicInteger counter = new AtomicInteger(); ConnectableObservable<String> o = Observable.create(new OnSubscribe<String>() { @Override public void call(final Subscriber<? super String> observer) { new Thread(new Runnable() { @Override public void run() { counter.incrementAndGet(); observer.onNext("one"); observer.onCompleted(); } }).start(); } }).publish(); final CountDownLatch latch = new CountDownLatch(2); // subscribe once o.subscribe(new Action1<String>() { @Override public void call(String v) { assertEquals("one", v); latch.countDown(); } }); // subscribe again o.subscribe(new Action1<String>() { @Override public void call(String v) { assertEquals("one", v); latch.countDown(); } }); Subscription s = o.connect(); try { if (!latch.await(1000, TimeUnit.MILLISECONDS)) { fail("subscriptions did not receive values"); } assertEquals(1, counter.get()); } finally { s.unsubscribe(); } } @Test public void testPublishLast() throws InterruptedException { final AtomicInteger count = new AtomicInteger(); ConnectableObservable<String> connectable = Observable.create(new OnSubscribe<String>() { @Override public void call(final Subscriber<? super String> observer) { count.incrementAndGet(); new Thread(new Runnable() { @Override public void run() { observer.onNext("first"); observer.onNext("last"); observer.onCompleted(); } }).start(); } }).publishLast(); // subscribe once final CountDownLatch latch = new CountDownLatch(1); connectable.subscribe(new Action1<String>() { @Override public void call(String value) { assertEquals("last", value); latch.countDown(); } }); // subscribe twice connectable.subscribe(new Action1<String>() { @Override public void call(String ignored) { } }); Subscription subscription = connectable.connect(); assertTrue(latch.await(1000, TimeUnit.MILLISECONDS)); assertEquals(1, count.get()); subscription.unsubscribe(); } @Test public void testReplay() throws InterruptedException { final AtomicInteger counter = new AtomicInteger(); ConnectableObservable<String> o = Observable.create(new OnSubscribe<String>() { @Override public void call(final Subscriber<? super String> observer) { new Thread(new Runnable() { @Override public void run() { counter.incrementAndGet(); observer.onNext("one"); observer.onCompleted(); } }).start(); } }).replay(); // we connect immediately and it will emit the value Subscription s = o.connect(); try { // we then expect the following 2 subscriptions to get that same value final CountDownLatch latch = new CountDownLatch(2); // subscribe once o.subscribe(new Action1<String>() { @Override public void call(String v) { assertEquals("one", v); latch.countDown(); } }); // subscribe again o.subscribe(new Action1<String>() { @Override public void call(String v) { assertEquals("one", v); latch.countDown(); } }); if (!latch.await(1000, TimeUnit.MILLISECONDS)) { fail("subscriptions did not receive values"); } assertEquals(1, counter.get()); } finally { s.unsubscribe(); } } @Test public void testCache() throws InterruptedException { final AtomicInteger counter = new AtomicInteger(); Observable<String> o = Observable.create(new OnSubscribe<String>() { @Override public void call(final Subscriber<? super String> observer) { new Thread(new Runnable() { @Override public void run() { counter.incrementAndGet(); observer.onNext("one"); observer.onCompleted(); } }).start(); } }).cache(); // we then expect the following 2 subscriptions to get that same value final CountDownLatch latch = new CountDownLatch(2); // subscribe once o.subscribe(new Action1<String>() { @Override public void call(String v) { assertEquals("one", v); latch.countDown(); } }); // subscribe again o.subscribe(new Action1<String>() { @Override public void call(String v) { assertEquals("one", v); latch.countDown(); } }); if (!latch.await(1000, TimeUnit.MILLISECONDS)) { fail("subscriptions did not receive values"); } assertEquals(1, counter.get()); } /** * https://github.com/Netflix/RxJava/issues/198 * * Rx Design Guidelines 5.2 * * "when calling the Subscribe method that only has an onNext argument, the OnError behavior will be * to rethrow the exception on the thread that the message comes out from the Observable. * The OnCompleted behavior in this case is to do nothing." */ @Test public void testErrorThrownWithoutErrorHandlerSynchronous() { try { Observable.error(new RuntimeException("failure")).subscribe(new Action1<Object>() { @Override public void call(Object t1) { // won't get anything } }); fail("expected exception"); } catch (Throwable e) { assertEquals("failure", e.getMessage()); } } /** * https://github.com/Netflix/RxJava/issues/198 * * Rx Design Guidelines 5.2 * * "when calling the Subscribe method that only has an onNext argument, the OnError behavior will be * to rethrow the exception on the thread that the message comes out from the Observable. * The OnCompleted behavior in this case is to do nothing." * * @throws InterruptedException */ @Test public void testErrorThrownWithoutErrorHandlerAsynchronous() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); final AtomicReference<Throwable> exception = new AtomicReference<Throwable>(); Observable.create(new OnSubscribe<String>() { @Override public void call(final Subscriber<? super String> observer) { new Thread(new Runnable() { @Override public void run() { try { observer.onError(new Error("failure")); } catch (Throwable e) { // without an onError handler it has to just throw on whatever thread invokes it exception.set(e); } latch.countDown(); } }).start(); } }).subscribe(new Action1<String>() { @Override public void call(String t1) { } }); // wait for exception latch.await(3000, TimeUnit.MILLISECONDS); assertNotNull(exception.get()); assertEquals("failure", exception.get().getMessage()); } @Test public void testTakeWithErrorInObserver() { final AtomicInteger count = new AtomicInteger(); final AtomicReference<Throwable> error = new AtomicReference<Throwable>(); Observable.from("1", "2", "three", "4").take(3).subscribe(new Subscriber<String>() { @Override public void onCompleted() { System.out.println("completed"); } @Override public void onError(Throwable e) { error.set(e); System.out.println("error"); e.printStackTrace(); } @Override public void onNext(String v) { int num = Integer.parseInt(v); System.out.println(num); // doSomething(num); count.incrementAndGet(); } }); assertEquals(2, count.get()); assertNotNull(error.get()); if (!(error.get() instanceof NumberFormatException)) { fail("It should be a NumberFormatException"); } } @Test public void testOfType() { Observable<String> observable = Observable.from(1, "abc", false, 2L).ofType(String.class); @SuppressWarnings("unchecked") Observer<Object> observer = mock(Observer.class); observable.subscribe(observer); verify(observer, never()).onNext(1); verify(observer, times(1)).onNext("abc"); verify(observer, never()).onNext(false); verify(observer, never()).onNext(2L); verify(observer, never()).onError( org.mockito.Matchers.any(Throwable.class)); verify(observer, times(1)).onCompleted(); } @Test public void testOfTypeWithPolymorphism() { ArrayList<Integer> l1 = new ArrayList<Integer>(); l1.add(1); LinkedList<Integer> l2 = new LinkedList<Integer>(); l2.add(2); @SuppressWarnings("rawtypes") Observable<List> observable = Observable.<Object> from(l1, l2, "123").ofType(List.class); @SuppressWarnings("unchecked") Observer<Object> observer = mock(Observer.class); observable.subscribe(observer); verify(observer, times(1)).onNext(l1); verify(observer, times(1)).onNext(l2); verify(observer, never()).onNext("123"); verify(observer, never()).onError( org.mockito.Matchers.any(Throwable.class)); verify(observer, times(1)).onCompleted(); } @Test public void testContains() { Observable<Boolean> observable = Observable.from("a", "b", null).contains("b"); @SuppressWarnings("unchecked") Observer<Object> observer = mock(Observer.class); observable.subscribe(observer); verify(observer, times(1)).onNext(true); verify(observer, never()).onNext(false); verify(observer, never()).onError( org.mockito.Matchers.any(Throwable.class)); verify(observer, times(1)).onCompleted(); } @Test public void testContainsWithInexistence() { Observable<Boolean> observable = Observable.from("a", "b", null).contains("c"); @SuppressWarnings("unchecked") Observer<Object> observer = mock(Observer.class); observable.subscribe(observer); verify(observer, times(1)).onNext(false); verify(observer, never()).onNext(true); verify(observer, never()).onError( org.mockito.Matchers.any(Throwable.class)); verify(observer, times(1)).onCompleted(); } @Test public void testContainsWithNull() { Observable<Boolean> observable = Observable.from("a", "b", null).contains(null); @SuppressWarnings("unchecked") Observer<Object> observer = mock(Observer.class); observable.subscribe(observer); verify(observer, times(1)).onNext(true); verify(observer, never()).onNext(false); verify(observer, never()).onError( org.mockito.Matchers.any(Throwable.class)); verify(observer, times(1)).onCompleted(); } @Test public void testContainsWithEmptyObservable() { Observable<Boolean> observable = Observable.<String> empty().contains("a"); @SuppressWarnings("unchecked") Observer<Object> observer = mock(Observer.class); observable.subscribe(observer); verify(observer, times(1)).onNext(false); verify(observer, never()).onNext(true); verify(observer, never()).onError( org.mockito.Matchers.any(Throwable.class)); verify(observer, times(1)).onCompleted(); } @Test public void testIgnoreElements() { Observable<Integer> observable = Observable.from(1, 2, 3).ignoreElements(); @SuppressWarnings("unchecked") Observer<Integer> observer = mock(Observer.class); observable.subscribe(observer); verify(observer, never()).onNext(any(Integer.class)); verify(observer, never()).onError(any(Throwable.class)); verify(observer, times(1)).onCompleted(); } @Test public void testFromWithScheduler() { TestScheduler scheduler = new TestScheduler(); Observable<Integer> observable = Observable.from(Arrays.asList(1, 2), scheduler); @SuppressWarnings("unchecked") Observer<Integer> observer = mock(Observer.class); observable.subscribe(observer); scheduler.advanceTimeBy(1, TimeUnit.MILLISECONDS); InOrder inOrder = inOrder(observer); inOrder.verify(observer, times(1)).onNext(1); inOrder.verify(observer, times(1)).onNext(2); inOrder.verify(observer, times(1)).onCompleted(); inOrder.verifyNoMoreInteractions(); } @Test public void testStartWithWithScheduler() { TestScheduler scheduler = new TestScheduler(); Observable<Integer> observable = Observable.from(3, 4).startWith(Arrays.asList(1, 2), scheduler); @SuppressWarnings("unchecked") Observer<Integer> observer = mock(Observer.class); observable.subscribe(observer); scheduler.advanceTimeBy(1, TimeUnit.MILLISECONDS); InOrder inOrder = inOrder(observer); inOrder.verify(observer, times(1)).onNext(1); inOrder.verify(observer, times(1)).onNext(2); inOrder.verify(observer, times(1)).onNext(3); inOrder.verify(observer, times(1)).onNext(4); inOrder.verify(observer, times(1)).onCompleted(); inOrder.verifyNoMoreInteractions(); } @Test public void testRangeWithScheduler() { TestScheduler scheduler = new TestScheduler(); Observable<Integer> observable = Observable.range(3, 4, scheduler); @SuppressWarnings("unchecked") Observer<Integer> observer = mock(Observer.class); observable.subscribe(observer); scheduler.advanceTimeBy(1, TimeUnit.MILLISECONDS); InOrder inOrder = inOrder(observer); inOrder.verify(observer, times(1)).onNext(3); inOrder.verify(observer, times(1)).onNext(4); inOrder.verify(observer, times(1)).onNext(5); inOrder.verify(observer, times(1)).onNext(6); inOrder.verify(observer, times(1)).onCompleted(); inOrder.verifyNoMoreInteractions(); } @Test public void testCollectToList() { List<Integer> list = Observable.from(1, 2, 3).collect(new ArrayList<Integer>(), new Action2<List<Integer>, Integer>() { @Override public void call(List<Integer> list, Integer v) { list.add(v); } }).toBlocking().last(); assertEquals(3, list.size()); assertEquals(1, list.get(0).intValue()); assertEquals(2, list.get(1).intValue()); assertEquals(3, list.get(2).intValue()); } @Test public void testCollectToString() { String value = Observable.from(1, 2, 3).collect(new StringBuilder(), new Action2<StringBuilder, Integer>() { @Override public void call(StringBuilder sb, Integer v) { if (sb.length() > 0) { sb.append("-"); } sb.append(v); } }).toBlocking().last().toString(); assertEquals("1-2-3", value); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.solr.search.function; import org.apache.lucene.analysis.Analyzer; import org.apache.lucene.analysis.MockAnalyzer; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.apache.lucene.document.Field.Store; import org.apache.lucene.document.FieldType; import org.apache.lucene.document.NumericDocValuesField; import org.apache.lucene.document.SortedDocValuesField; import org.apache.lucene.document.TextField; import org.apache.lucene.index.DirectoryReader; import org.apache.lucene.index.IndexReader; import org.apache.lucene.index.IndexWriterConfig; import org.apache.lucene.index.RandomIndexWriter; import org.apache.lucene.queries.function.FunctionQuery; import org.apache.lucene.queries.function.ValueSource; import org.apache.lucene.queries.function.valuesource.FloatFieldSource; import org.apache.lucene.queries.function.valuesource.IntFieldSource; import org.apache.lucene.search.IndexSearcher; import org.apache.lucene.search.Query; import org.apache.lucene.search.QueryUtils; import org.apache.lucene.search.ScoreDoc; import org.apache.lucene.search.TopDocs; import org.apache.lucene.store.Directory; import org.apache.lucene.util.BytesRef; import org.apache.lucene.util.TestUtil; import org.apache.solr.SolrTestCase; import org.apache.solr.legacy.LegacyFloatField; import org.apache.solr.legacy.LegacyIntField; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; /** * Test search based on OrdFieldSource and ReverseOrdFieldSource. * * <p>Tests here create an index with a few documents, each having an indexed "id" field. The ord * values of this field are later used for scoring. * * <p>The order tests use Hits to verify that docs are ordered as expected. * * <p>The exact score tests use TopDocs top to verify the exact score. */ public class TestOrdValues extends SolrTestCase { @BeforeClass public static void beforeClass() throws Exception { createIndex(false); } /** Test OrdFieldSource */ @Test public void testOrdFieldRank() throws Exception { doTestRank(ID_FIELD, true); } /** Test ReverseOrdFieldSource */ @Test public void testReverseOrdFieldRank() throws Exception { doTestRank(ID_FIELD, false); } // Test that queries based on reverse/ordFieldScore scores correctly private void doTestRank(String field, boolean inOrder) throws Exception { IndexReader r = DirectoryReader.open(dir); IndexSearcher s = newSearcher(r); ValueSource vs; if (inOrder) { vs = new OrdFieldSource(field); } else { vs = new ReverseOrdFieldSource(field); } Query q = new FunctionQuery(vs); log("test: " + q); QueryUtils.check(random(), q, s); ScoreDoc[] h = s.search(q, 1000).scoreDocs; assertEquals("All docs should be matched!", N_DOCS, h.length); String prevID = inOrder ? "IE" // greater than all ids of docs in this test ("ID0001", etc.) : "IC"; // smaller than all ids of docs in this test ("ID0001", etc.) for (int i = 0; i < h.length; i++) { String resID = s.doc(h[i].doc).get(ID_FIELD); log(i + ". score=" + h[i].score + " - " + resID); log(s.explain(q, h[i].doc)); if (inOrder) { assertTrue( "res id " + resID + " should be < prev res id " + prevID, resID.compareTo(prevID) < 0); } else { assertTrue( "res id " + resID + " should be > prev res id " + prevID, resID.compareTo(prevID) > 0); } prevID = resID; } r.close(); } /** Test exact score for OrdFieldSource */ @Test public void testOrdFieldExactScore() throws Exception { doTestExactScore(ID_FIELD, true); } /** Test exact score for ReverseOrdFieldSource */ @Test public void testReverseOrdFieldExactScore() throws Exception { doTestExactScore(ID_FIELD, false); } // Test that queries based on reverse/ordFieldScore returns docs with expected score. private void doTestExactScore(String field, boolean inOrder) throws Exception { IndexReader r = DirectoryReader.open(dir); IndexSearcher s = newSearcher(r); ValueSource vs; if (inOrder) { vs = new OrdFieldSource(field); } else { vs = new ReverseOrdFieldSource(field); } Query q = new FunctionQuery(vs); TopDocs td = s.search(q, 1000); assertEquals("All docs should be matched!", N_DOCS, td.totalHits.value); ScoreDoc sd[] = td.scoreDocs; for (int i = 0; i < sd.length; i++) { float score = sd[i].score; String id = s.getIndexReader().document(sd[i].doc).get(ID_FIELD); log("-------- " + i + ". Explain doc " + id); log(s.explain(q, sd[i].doc)); float expectedScore = N_DOCS - i - 1; assertEquals( "score of result " + i + " should be " + expectedScore + " != " + score, expectedScore, score, TEST_SCORE_TOLERANCE_DELTA); String expectedId = inOrder ? id2String(N_DOCS - i) // in-order ==> larger values first : id2String(i + 1); // reverse ==> smaller values first assertTrue( "id of result " + i + " should be " + expectedId + " != " + score, expectedId.equals(id)); } r.close(); } // LUCENE-1250 public void testEqualsNull() throws Exception { OrdFieldSource ofs = new OrdFieldSource("f"); assertFalse(ofs.equals(null)); ReverseOrdFieldSource rofs = new ReverseOrdFieldSource("f"); assertFalse(rofs.equals(null)); } /** * Actual score computation order is slightly different than assumptios this allows for a small * amount of variation */ protected static float TEST_SCORE_TOLERANCE_DELTA = 0.001f; protected static final int N_DOCS = 17; // select a primary number > 2 protected static final String ID_FIELD = "id"; protected static final String TEXT_FIELD = "text"; protected static final String INT_FIELD = "iii"; protected static final String FLOAT_FIELD = "fff"; protected ValueSource INT_VALUESOURCE = new IntFieldSource(INT_FIELD); protected ValueSource FLOAT_VALUESOURCE = new FloatFieldSource(FLOAT_FIELD); private static final String DOC_TEXT_LINES[] = { "Well, this is just some plain text we use for creating the ", "test documents. It used to be a text from an online collection ", "devoted to first aid, but if there was there an (online) lawyers ", "first aid collection with legal advices, \"it\" might have quite ", "probably advised one not to include \"it\"'s text or the text of ", "any other online collection in one's code, unless one has money ", "that one don't need and one is happy to donate for lawyers ", "charity. Anyhow at some point, rechecking the usage of this text, ", "it became uncertain that this text is free to use, because ", "the web site in the disclaimer of he eBook containing that text ", "was not responding anymore, and at the same time, in projGut, ", "searching for first aid no longer found that eBook as well. ", "So here we are, with a perhaps much less interesting ", "text for the test, but oh much much safer. ", }; protected static Directory dir; protected static Analyzer anlzr; @AfterClass public static void afterClassFunctionTestSetup() throws Exception { if (null != dir) { dir.close(); } dir = null; anlzr = null; } protected static void createIndex(boolean doMultiSegment) throws Exception { if (VERBOSE) { System.out.println("TEST: setUp"); } // prepare a small index with just a few documents. dir = newDirectory(); anlzr = new MockAnalyzer(random()); IndexWriterConfig iwc = newIndexWriterConfig(anlzr).setMergePolicy(newLogMergePolicy()); if (doMultiSegment) { iwc.setMaxBufferedDocs(TestUtil.nextInt(random(), 2, 7)); } RandomIndexWriter iw = new RandomIndexWriter(random(), dir, iwc); // add docs not exactly in natural ID order, to verify we do check the order of docs by scores int remaining = N_DOCS; boolean done[] = new boolean[N_DOCS]; int i = 0; while (remaining > 0) { if (done[i]) { throw new Exception( "to set this test correctly N_DOCS=" + N_DOCS + " must be primary and greater than 2!"); } addDoc(iw, i); done[i] = true; i = (i + 4) % N_DOCS; remaining--; } if (!doMultiSegment) { if (VERBOSE) { System.out.println("TEST: setUp full merge"); } iw.forceMerge(1); } iw.close(); if (VERBOSE) { System.out.println("TEST: setUp done close"); } } private static void addDoc(RandomIndexWriter iw, int i) throws Exception { Document d = new Document(); Field f; int scoreAndID = i + 1; FieldType customType = new FieldType(TextField.TYPE_STORED); customType.setTokenized(false); customType.setOmitNorms(true); f = newField(ID_FIELD, id2String(scoreAndID), customType); // for debug purposes d.add(f); d.add(new SortedDocValuesField(ID_FIELD, new BytesRef(id2String(scoreAndID)))); FieldType customType2 = new FieldType(TextField.TYPE_NOT_STORED); customType2.setOmitNorms(true); f = newField( TEXT_FIELD, "text of doc" + scoreAndID + textLine(i), customType2); // for regular search d.add(f); f = new LegacyIntField(INT_FIELD, scoreAndID, Store.YES); // for function scoring d.add(f); d.add(new NumericDocValuesField(INT_FIELD, scoreAndID)); f = new LegacyFloatField(FLOAT_FIELD, scoreAndID, Store.YES); // for function scoring d.add(f); d.add(new NumericDocValuesField(FLOAT_FIELD, Float.floatToRawIntBits(scoreAndID))); iw.addDocument(d); log("added: " + d); } // 17 --> ID00017 protected static String id2String(int scoreAndID) { String s = "000000000" + scoreAndID; int n = ("" + N_DOCS).length() + 3; int k = s.length() - n; return "ID" + s.substring(k); } // some text line for regular search private static String textLine(int docNum) { return DOC_TEXT_LINES[docNum % DOC_TEXT_LINES.length]; } // extract expected doc score from its ID Field: "ID7" --> 7.0 protected static float expectedFieldScore(String docIDFieldVal) { return Float.parseFloat(docIDFieldVal.substring(2)); } // debug messages (change DBG to true for anything to print) protected static void log(Object o) { if (VERBOSE) { System.out.println(o.toString()); } } }
package org.heigit.ors.api.requests.isochrones; import com.vividsolutions.jts.geom.Coordinate; import com.vividsolutions.jts.geom.Polygon; import org.heigit.ors.api.requests.common.APIEnums; import org.heigit.ors.api.requests.routing.RequestProfileParams; import org.heigit.ors.api.requests.routing.RequestProfileParamsRestrictions; import org.heigit.ors.api.requests.routing.RequestProfileParamsWeightings; import org.heigit.ors.api.requests.routing.RouteRequestOptions; import org.heigit.ors.common.TravelRangeType; import org.heigit.ors.common.TravellerInfo; import org.heigit.ors.exceptions.ParameterOutOfRangeException; import org.heigit.ors.exceptions.ParameterValueException; import org.heigit.ors.isochrones.IsochroneRequest; import org.heigit.ors.routing.*; import org.heigit.ors.routing.pathprocessors.BordersExtractor; import org.json.simple.JSONArray; import org.json.simple.JSONObject; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; import java.util.List; public class IsochronesRequestHandlerTest { IsochronesRequest request; private RequestProfileParamsRestrictions vehicleParams; private RequestProfileParamsRestrictions cyclingParams; private RequestProfileParamsRestrictions walkingParams; private RequestProfileParamsRestrictions wheelchairParams; private JSONObject geoJsonPolygon; private JSONObject constructGeoJson() { JSONObject geoJsonPolygon = new JSONObject(); geoJsonPolygon.put("type", "Polygon"); JSONArray coordsArray = new JSONArray(); coordsArray.add(new Double[] { 49.0, 8.0}); coordsArray.add(new Double[] { 49.005, 8.01}); coordsArray.add(new Double[] { 49.01, 8.0}); coordsArray.add(new Double[] { 49.0, 8.0}); JSONArray coordinates = new JSONArray(); coordinates.add(coordsArray); geoJsonPolygon.put("coordinates", coordinates); return geoJsonPolygon; } @Before public void init() throws Exception { System.setProperty("ors_config", "target/test-classes/ors-config-test.json"); geoJsonPolygon = constructGeoJson(); Double[][] coords = new Double[2][2]; coords[0] = new Double[]{24.5, 39.2}; coords[1] = new Double[]{27.4, 38.6}; request = new IsochronesRequest(); request.setLocations(coords); request.setProfile(APIEnums.Profile.DRIVING_CAR); request.setAttributes(new IsochronesRequestEnums.Attributes[]{IsochronesRequestEnums.Attributes.AREA, IsochronesRequestEnums.Attributes.REACH_FACTOR}); request.setResponseType(APIEnums.RouteResponseType.GEOJSON); RouteRequestOptions options = new RouteRequestOptions(); options.setAvoidBorders(APIEnums.AvoidBorders.CONTROLLED); options.setAvoidCountries(new String[]{"115"}); options.setAvoidFeatures(new APIEnums.AvoidFeatures[]{APIEnums.AvoidFeatures.FORDS}); options.setAvoidPolygonFeatures(geoJsonPolygon); vehicleParams = new RequestProfileParamsRestrictions(); vehicleParams.setAxleLoad(10.0f); vehicleParams.setHazardousMaterial(true); vehicleParams.setHeight(5.0f); vehicleParams.setLength(15.0f); vehicleParams.setWeight(30.0f); vehicleParams.setWidth(4.5f); wheelchairParams = new RequestProfileParamsRestrictions(); wheelchairParams.setMaxIncline(3); wheelchairParams.setMaxSlopedKerb(1.0f); wheelchairParams.setMinWidth(2.0f); wheelchairParams.setSmoothnessType(APIEnums.SmoothnessTypes.SMOOTHNESS_GOOD); wheelchairParams.setSurfaceType("asphalt"); RequestProfileParams params = new RequestProfileParams(); RequestProfileParamsWeightings weightings = new RequestProfileParamsWeightings(); weightings.setGreenIndex(0.5f); weightings.setQuietIndex(0.2f); weightings.setSteepnessDifficulty(3); params.setWeightings(weightings); options.setProfileParams(params); request.setIsochronesOptions(options); } @Test public void convertSmoothing() throws ParameterValueException { Float smoothing = request.convertSmoothing(10.234); Assert.assertEquals(10.234, smoothing, 0.01); } @Test(expected = ParameterValueException.class) public void convertSmoothingFailWhenTooHigh() throws ParameterValueException { request.convertSmoothing(105.0); } @Test(expected = ParameterValueException.class) public void convertSmoothingFailWhenTooLow() throws ParameterValueException { request.convertSmoothing(-5.0); } @Test public void convertLocationType() throws ParameterValueException { String locationType = request.convertLocationType(IsochronesRequestEnums.LocationType.DESTINATION); Assert.assertEquals("destination", locationType); locationType = request.convertLocationType(IsochronesRequestEnums.LocationType.START); Assert.assertEquals("start", locationType); } @Test public void convertRangeType() throws ParameterValueException { TravelRangeType rangeType = request.convertRangeType(IsochronesRequestEnums.RangeType.DISTANCE); Assert.assertEquals(TravelRangeType.DISTANCE, rangeType); rangeType = request.convertRangeType(IsochronesRequestEnums.RangeType.TIME); Assert.assertEquals(TravelRangeType.TIME, rangeType); } @Test public void convertAreaUnit() throws ParameterValueException { String unit = request.convertAreaUnit(APIEnums.Units.KILOMETRES); Assert.assertEquals("km", unit); unit = request.convertAreaUnit(APIEnums.Units.METRES); Assert.assertEquals("m", unit); unit = request.convertAreaUnit(APIEnums.Units.MILES); Assert.assertEquals("mi", unit); } @Test public void convertRangeUnit() throws ParameterValueException { String unit = request.convertRangeUnit(APIEnums.Units.KILOMETRES); Assert.assertEquals("km", unit); unit = request.convertRangeUnit(APIEnums.Units.METRES); Assert.assertEquals("m", unit); unit = request.convertRangeUnit(APIEnums.Units.MILES); Assert.assertEquals("mi", unit); } @Test public void convertSingleCoordinate() throws ParameterValueException { Coordinate coord = request.convertSingleCoordinate(new Double[]{123.4, 321.0}); Assert.assertEquals(123.4, coord.x, 0.0001); Assert.assertEquals(321.0, coord.y, 0.0001); } @Test(expected = ParameterValueException.class) public void convertSingleCoordinateInvalidLengthShort() throws ParameterValueException { request.convertSingleCoordinate(new Double[]{123.4}); } @Test(expected = ParameterValueException.class) public void convertSingleCoordinateInvalidLengthLong() throws ParameterValueException { request.convertSingleCoordinate(new Double[]{123.4, 123.4, 123.4}); } @Test public void setRangeAndIntervals() throws ParameterValueException, ParameterOutOfRangeException { TravellerInfo info = new TravellerInfo(); List<Double> rangeValues = new ArrayList<>(); rangeValues.add(20.0); double intervalValue = 10; request.setRangeAndIntervals(info, rangeValues, intervalValue); Assert.assertEquals(10.0, info.getRanges()[0], 0.0f); Assert.assertEquals(20.0, info.getRanges()[1], 0.0f); info = new TravellerInfo(); rangeValues = new ArrayList<>(); rangeValues.add(15.0); rangeValues.add(30.0); request.setRangeAndIntervals(info, rangeValues, intervalValue); Assert.assertEquals(15.0, info.getRanges()[0], 0.0f); Assert.assertEquals(30.0, info.getRanges()[1], 0.0f); } @Test public void convertAttributes() { IsochronesRequestEnums.Attributes[] atts = new IsochronesRequestEnums.Attributes[]{IsochronesRequestEnums.Attributes.AREA, IsochronesRequestEnums.Attributes.REACH_FACTOR, IsochronesRequestEnums.Attributes.TOTAL_POPULATION}; String[] attStr = request.convertAttributes(atts); Assert.assertEquals("area", attStr[0]); Assert.assertEquals("reachfactor", attStr[1]); Assert.assertEquals("total_pop", attStr[2]); } @Test public void convertCalcMethod() throws ParameterValueException { String calcMethod = request.convertCalcMethod(IsochronesRequestEnums.CalculationMethod.CONCAVE_BALLS); Assert.assertEquals("concaveballs", calcMethod); calcMethod = request.convertCalcMethod(IsochronesRequestEnums.CalculationMethod.GRID); Assert.assertEquals("grid", calcMethod); } @Test public void convertIsochroneRequest() throws Exception { IsochronesRequest request = new IsochronesRequest(); Double[][] locations = {{9.676034, 50.409675}, {9.676034, 50.409675}}; Coordinate coord0 = new Coordinate(); coord0.x = 9.676034; coord0.y = 50.409675; request.setLocations(locations); request.setProfile(APIEnums.Profile.DRIVING_CAR); List<Double> range = new ArrayList<>(); range.add(300.0); range.add(600.0); request.setRange(range); IsochroneRequest isochroneRequest = request.convertIsochroneRequest(); Assert.assertNotNull(isochroneRequest); Assert.assertFalse(isochroneRequest.getIncludeIntersections()); Assert.assertNull(request.getAttributes()); Assert.assertFalse(request.hasSmoothing()); Assert.assertNull(request.getSmoothing()); Assert.assertNull(request.getId()); Assert.assertEquals(coord0.x, isochroneRequest.getLocations()[0].x, 0); Assert.assertEquals(coord0.y, isochroneRequest.getLocations()[0].y, 0); Assert.assertEquals(coord0.x, isochroneRequest.getLocations()[1].x, 0); Assert.assertEquals(coord0.y, isochroneRequest.getLocations()[1].y, 0); Assert.assertEquals(2, isochroneRequest.getTravellers().size()); for (int i = 0; i < isochroneRequest.getTravellers().size(); i++) { TravellerInfo travellerInfo = isochroneRequest.getTravellers().get(i); Assert.assertEquals(String.valueOf(i), travellerInfo.getId()); Assert.assertEquals(coord0, travellerInfo.getLocation()); Assert.assertEquals(IsochronesRequestEnums.LocationType.START.toString(), travellerInfo.getLocationType()); Assert.assertNotNull(travellerInfo.getRanges()); Assert.assertEquals(TravelRangeType.TIME, travellerInfo.getRangeType()); Assert.assertNotNull(travellerInfo.getRouteSearchParameters()); } } @Test public void constructTravellerInfo() throws Exception { Double[][] coordinates = {{1.0, 3.0}, {1.0, 3.0}}; Double[] coordinate = {1.0, 3.0}; Coordinate realCoordinate = new Coordinate(); realCoordinate.x = 1.0; realCoordinate.y = 3.0; IsochronesRequest request = new IsochronesRequest(); request.setProfile(APIEnums.Profile.DRIVING_CAR); request.setLocations(coordinates); List<Double> range = new ArrayList<>(); range.add(300.0); range.add(600.0); request.setRange(range); TravellerInfo travellerInfo = request.constructTravellerInfo(coordinate); Assert.assertEquals(String.valueOf(0), travellerInfo.getId()); Assert.assertEquals(realCoordinate, travellerInfo.getLocation()); Assert.assertEquals("start", travellerInfo.getLocationType()); Assert.assertEquals(range.toString(), Arrays.toString(travellerInfo.getRanges())); Assert.assertEquals(TravelRangeType.TIME, travellerInfo.getRangeType()); } @Test public void constructRouteSearchParametersTest() throws Exception { Double[][] coordinates = {{1.0, 3.0}, {1.0, 3.0}}; IsochronesRequest request = new IsochronesRequest(); request.setProfile(APIEnums.Profile.DRIVING_CAR); request.setLocations(coordinates); RouteSearchParameters routeSearchParameters = request.constructRouteSearchParameters(); Assert.assertEquals(RoutingProfileType.DRIVING_CAR, routeSearchParameters.getProfileType()); Assert.assertEquals(WeightingMethod.FASTEST, routeSearchParameters.getWeightingMethod()); Assert.assertFalse(routeSearchParameters.getConsiderTurnRestrictions()); Assert.assertNull(routeSearchParameters.getAvoidAreas()); Assert.assertEquals(0, routeSearchParameters.getAvoidFeatureTypes()); Assert.assertEquals(0, routeSearchParameters.getVehicleType()); Assert.assertFalse(routeSearchParameters.getFlexibleMode()); Assert.assertEquals(BordersExtractor.Avoid.NONE, routeSearchParameters.getAvoidBorders()); Assert.assertNull(routeSearchParameters.getProfileParameters()); Assert.assertNull(routeSearchParameters.getBearings()); Assert.assertNull(routeSearchParameters.getMaximumRadiuses()); Assert.assertNull(routeSearchParameters.getAvoidCountries()); Assert.assertNull(routeSearchParameters.getOptions()); } @Test public void processIsochronesRequestOptionsTest() throws Exception { RouteSearchParameters routeSearchParameters = request.constructRouteSearchParameters(); Assert.assertEquals(RoutingProfileType.DRIVING_CAR, routeSearchParameters.getProfileType()); Assert.assertEquals(WeightingMethod.FASTEST, routeSearchParameters.getWeightingMethod()); Assert.assertFalse(routeSearchParameters.getConsiderTurnRestrictions()); checkPolygon(routeSearchParameters.getAvoidAreas(), geoJsonPolygon); Assert.assertEquals(16, routeSearchParameters.getAvoidFeatureTypes()); Assert.assertEquals(0, routeSearchParameters.getVehicleType()); Assert.assertFalse(routeSearchParameters.getFlexibleMode()); Assert.assertEquals(BordersExtractor.Avoid.CONTROLLED, routeSearchParameters.getAvoidBorders()); Assert.assertNull(routeSearchParameters.getBearings()); Assert.assertNull(routeSearchParameters.getMaximumRadiuses()); Assert.assertNull(routeSearchParameters.getOptions()); Assert.assertEquals(115, routeSearchParameters.getAvoidCountries()[0]); ProfileWeightingCollection weightings = routeSearchParameters.getProfileParameters().getWeightings(); ProfileWeighting weighting; Iterator<ProfileWeighting> iter = weightings.getIterator(); while (iter.hasNext() && (weighting = iter.next()) != null) { if (weighting.getName().equals("green")) { Assert.assertEquals(0.5, weighting.getParameters().getDouble("factor", -1), 0); } if (weighting.getName().equals("quiet")) { Assert.assertEquals(0.2, weighting.getParameters().getDouble("factor", -1), 0); } if (weighting.getName().equals("steepness_difficulty")) { Assert.assertEquals(3, weighting.getParameters().getInt("level", -1), 0); } } } @Test public void getIsoMapsTest() { Assert.assertNull(request.getIsoMaps()); } @Test public void getIsochroneRequestTest() { Assert.assertNull(request.getIsochroneRequest()); } private void checkPolygon(Polygon[] requestPolys, JSONObject apiPolys) { Assert.assertEquals(1, requestPolys.length); JSONArray jsonCoords = (JSONArray) ((JSONArray) apiPolys.get("coordinates")).get(0); for (int i = 0; i < jsonCoords.size(); i++) { Double[] coordPair = (Double[]) jsonCoords.get(i); Coordinate c = new Coordinate(coordPair[0], coordPair[1]); compareCoordinates(c, requestPolys[0].getCoordinates()[i]); } } private void compareCoordinates(Coordinate c1, Coordinate c2) { Assert.assertEquals(c1.x, c2.x, 0); Assert.assertEquals(c1.y, c2.y, 0); } }
package aceim.protocol.snuk182.icq.inner.dataprocessing; import java.io.UnsupportedEncodingException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Calendar; import java.util.Date; import java.util.Random; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import aceim.protocol.snuk182.icq.inner.ICQConstants; import aceim.protocol.snuk182.icq.inner.ICQException; import aceim.protocol.snuk182.icq.inner.ICQServiceInternal; import aceim.protocol.snuk182.icq.inner.ICQServiceResponse; import aceim.protocol.snuk182.icq.inner.dataentity.Flap; import aceim.protocol.snuk182.icq.inner.dataentity.ICBMMessage; import aceim.protocol.snuk182.icq.inner.dataentity.ICQFileInfo; import aceim.protocol.snuk182.icq.inner.dataentity.ICQOnlineInfo; import aceim.protocol.snuk182.icq.inner.dataentity.Snac; import aceim.protocol.snuk182.icq.inner.dataentity.TLV; import aceim.protocol.snuk182.icq.utils.ProtocolUtils; public class ICBMMessagingEngine { private ICQServiceInternal service; private MessageParser parser; private static final DateFormat OFFLINE_DATE_FORMATTER = new SimpleDateFormat("dd MMMM yyyy, HH:mm:ss"); static final Random RANDOM = new Random(); private ScheduledFuture<?> task; public ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(4); public ICBMMessagingEngine(ICQServiceInternal icqServiceInternal) { parser = new MessageParser(); this.service = icqServiceInternal; } public void parseMessage(Snac snac) { if (snac.plainData == null) { return; } parser.parseMessage(snac.plainData); } public void parsePluginMessage(Snac snac, boolean isAck) { if (snac.plainData == null) { return; } parser.parsePluginMessage(snac.plainData, isAck); } public void parseOfflineMessage(byte[] tailData) { parser.parseOfflineMessage(tailData); } private byte[] getAnswerXStatusSuffix(String title, String value) { byte[] header = new byte[81]; System.arraycopy(ProtocolUtils.short2ByteLE((short) 79), 0, header, 0, 2); System.arraycopy(ICQConstants.GUID_XSTATUSMSG, 0, header, 2, 16); System.arraycopy(ProtocolUtils.short2ByteLE((short) 0x8), 0, header, 18, 2); System.arraycopy(ProtocolUtils.int2ByteLE(42), 0, header, 20, 4); byte[] headerStrBytes = new String("Script Plug-in: Remote Notification Arrive").getBytes(); System.arraycopy(headerStrBytes, 0, header, 24, 42); System.arraycopy(ProtocolUtils.int2ByteLE(0x10000), 0, header, 66, 4); System.arraycopy(ProtocolUtils.int2ByteLE(0), 0, header, 70, 4); System.arraycopy(ProtocolUtils.int2ByteLE(0), 0, header, 74, 4); System.arraycopy(ProtocolUtils.short2ByteLE((short) 0), 0, header, 78, 2); header[80] = 0; StringBuilder reqStrBu = new StringBuilder(); reqStrBu.append("<NR><RES>"); reqStrBu.append(ProtocolUtils.xmlToParameter("<ret event='OnRemoteNotification'><srv><id>cAwaySrv</id><val srv_id='cAwaySrv'><Root><CASXtraSetAwayMessage></CASXtraSetAwayMessage><uin>")); reqStrBu.append(service.getUn()); reqStrBu.append(ProtocolUtils.xmlToParameter("</uin><index>1</index><title>")); reqStrBu.append(title != null ? title : ""); reqStrBu.append(ProtocolUtils.xmlToParameter("</title><desc>")); reqStrBu.append(value != null ? value : ""); reqStrBu.append(ProtocolUtils.xmlToParameter("</desc></Root></val></srv></ret>")); reqStrBu.append("</RES></NR>"); String reqStr = reqStrBu.toString(); byte[] reqBytes = reqStr.getBytes(); byte[] body = new byte[8 + reqBytes.length]; System.arraycopy(ProtocolUtils.int2ByteLE(reqBytes.length + 4), 0, body, 0, 4); System.arraycopy(ProtocolUtils.int2ByteLE(reqBytes.length), 0, body, 4, 4); System.arraycopy(reqBytes, 0, body, 8, reqBytes.length); byte[] total = new byte[header.length + body.length]; System.arraycopy(header, 0, total, 0, header.length); System.arraycopy(body, 0, total, header.length, body.length); return total; } private byte[] getAskXStatusSuffix(String uin) { byte[] header = new byte[81]; System.arraycopy(ProtocolUtils.short2ByteLE((short) 79), 0, header, 0, 2); System.arraycopy(ICQConstants.GUID_XSTATUSMSG, 0, header, 2, 16); System.arraycopy(ProtocolUtils.short2ByteLE((short) 0x8), 0, header, 18, 2); System.arraycopy(ProtocolUtils.int2ByteLE(42), 0, header, 20, 4); byte[] headerStrBytes = new String("Script Plug-in: Remote Notification Arrive").getBytes(); System.arraycopy(headerStrBytes, 0, header, 24, 42); System.arraycopy(ProtocolUtils.int2ByteLE(0x100), 0, header, 66, 4); System.arraycopy(ProtocolUtils.int2ByteLE(0), 0, header, 70, 4); System.arraycopy(ProtocolUtils.int2ByteLE(0), 0, header, 74, 4); System.arraycopy(ProtocolUtils.short2ByteLE((short) 0), 0, header, 78, 2); header[80] = 0; String reqStr = "<N><QUERY>" + ProtocolUtils.xmlToParameter("<Q><PluginID>srvMng</PluginID></Q>") + "</QUERY><NOTIFY>" + ProtocolUtils.xmlToParameter("<srv><id>cAwaySrv</id><req><id>AwayStat</id><trans>") + 0 + ProtocolUtils.xmlToParameter("</trans><senderId>" + uin + "</senderId></req></srv>") + "</NOTIFY></N>"; byte[] reqBytes = reqStr.getBytes(); byte[] body = new byte[8 + reqBytes.length]; System.arraycopy(ProtocolUtils.int2ByteLE(reqBytes.length + 4), 0, body, 0, 4); System.arraycopy(ProtocolUtils.int2ByteLE(reqBytes.length), 0, body, 4, 4); System.arraycopy(reqBytes, 0, body, 8, reqBytes.length); byte[] total = new byte[header.length + body.length]; System.arraycopy(header, 0, total, 0, header.length); System.arraycopy(body, 0, total, header.length, body.length); return total; } public void askForXStatus(String uin) { ICBMMessage message = new ICBMMessage(); message.pluginSpecificData = getAskXStatusSuffix(message.senderId); message.receiverId = uin; message.text = ""; message.messageType = ICQConstants.MTYPE_PLUGIN; sendChannel2Message(message); } private byte[] getPlainMessageSuffix() { byte[] guidBytes; try { guidBytes = new String(ICQConstants.GUID_UTF8).getBytes("ASCII"); } catch (UnsupportedEncodingException e) { guidBytes = new String(ICQConstants.GUID_UTF8).getBytes(); } byte[] suffix = new byte[12 + guidBytes.length]; System.arraycopy(new byte[] { 0, 0, 0, 0 }, 0, suffix, 0, 4); System.arraycopy(new byte[] { (byte) 0xff, (byte) 0xff, (byte) 0xff, 0 }, 0, suffix, 4, 4); System.arraycopy(ProtocolUtils.int2ByteLE(guidBytes.length), 0, suffix, 8, 4); System.arraycopy(guidBytes, 0, suffix, 12, guidBytes.length); return suffix; } private void sendChannel2PluginMessage(ICBMMessage message) { if (message.messageId == null) { message.messageId = ProtocolUtils.long2ByteBE(new Random().nextLong()); } short msgSeq = (short) 0xfffe; Flap flap = new Flap(); flap.channel = ICQConstants.FLAP_CHANNELL_DATA; Snac data = new Snac(); data.serviceId = ICQConstants.SNAC_FAMILY_MESSAGING; data.subtypeId = ICQConstants.SNAC_MESSAGING_PLUGINMSG; data.requestId = ICQConstants.SNAC_MESSAGING_PLUGINMSG; byte[] uidBytes; try { uidBytes = message.receiverId.getBytes("ASCII"); } catch (UnsupportedEncodingException e) { uidBytes = message.receiverId.getBytes(); } byte[] block1 = new byte[13 + uidBytes.length]; System.arraycopy(message.messageId, 0, block1, 0, 8); System.arraycopy(ProtocolUtils.short2ByteBE((short) 2), 0, block1, 8, 2); block1[10] = (byte) uidBytes.length; System.arraycopy(uidBytes, 0, block1, 11, uidBytes.length); System.arraycopy(ProtocolUtils.short2ByteBE((short) 3), 0, block1, 11 + uidBytes.length, 2); byte[] tlv2711data; if (message.messageType == ICQConstants.MTYPE_FILEREQ) { tlv2711data = new byte[] { 0, 2, 0, 1 }; } else { byte[] textBytes = new byte[0]; // dummy byte[] suffix = message.pluginSpecificData != null ? message.pluginSpecificData : getPlainMessageSuffix(); byte[] msgByteBlock = new byte[8 + textBytes.length + 1 + suffix.length]; msgByteBlock[0] = message.messageType; // !!! msgByteBlock[1] = 0; System.arraycopy(ProtocolUtils.short2ByteLE((short) 0), 0, msgByteBlock, 2, 2); System.arraycopy(ProtocolUtils.short2ByteLE((short) 0), 0, msgByteBlock, 4, 2); System.arraycopy(ProtocolUtils.short2ByteLE((short) (textBytes.length + 1)), 0, msgByteBlock, 6, 2); System.arraycopy(textBytes, 0, msgByteBlock, 8, textBytes.length); msgByteBlock[8 + textBytes.length] = 0; System.arraycopy(suffix, 0, msgByteBlock, 9 + textBytes.length, suffix.length); tlv2711data = new byte[2 + 2 + 16 + 2 + 4 + 1 + 2 + 2 + 2 + 12 + msgByteBlock.length]; System.arraycopy(ProtocolUtils.short2ByteLE((short) 27), 0, tlv2711data, 0, 2); System.arraycopy(ProtocolUtils.short2ByteLE((short) 9), 0, tlv2711data, 2, 2); byte[] zeros = new byte[16]; Arrays.fill(zeros, (byte) 0); System.arraycopy(zeros, 0, tlv2711data, 4, 16); System.arraycopy(ProtocolUtils.short2ByteLE((short) 0), 0, tlv2711data, 20, 2); System.arraycopy(ProtocolUtils.int2ByteLE(1), 0, tlv2711data, 22, 4); tlv2711data[26] = 0; System.arraycopy(ProtocolUtils.short2ByteLE(msgSeq), 0, tlv2711data, 27, 2); System.arraycopy(ProtocolUtils.short2ByteLE((short) 14), 0, tlv2711data, 29, 2); System.arraycopy(ProtocolUtils.short2ByteLE(msgSeq), 0, tlv2711data, 31, 2); zeros = new byte[12]; Arrays.fill(zeros, (byte) 0); System.arraycopy(zeros, 0, tlv2711data, 33, 12); System.arraycopy(msgByteBlock, 0, tlv2711data, 45, msgByteBlock.length); } byte[] total = new byte[block1.length + tlv2711data.length]; System.arraycopy(block1, 0, total, 0, block1.length); System.arraycopy(tlv2711data, 0, total, block1.length, tlv2711data.length); data.plainData = total; flap.data = data; service.getRunnableService().sendToSocket(flap); } private void sendChannel2Message(ICBMMessage message) { if (message.messageId == null) { message.messageId = ProtocolUtils.long2ByteBE(new Random().nextLong()); } short msgSeq = (short) 0xfffe; Flap flap = new Flap(); flap.channel = ICQConstants.FLAP_CHANNELL_DATA; Snac data = new Snac(); data.serviceId = ICQConstants.SNAC_FAMILY_MESSAGING; data.subtypeId = ICQConstants.SNAC_MESSAGING_SENDTHROUGHSERVER; data.requestId = ICQConstants.SNAC_MESSAGING_SENDTHROUGHSERVER; /* * TLV internalIpTLV = new TLV(); internalIpTLV.setType(0x03); byte[] * buffer; try { buffer = InetAddress.getLocalHost().getAddress(); } * catch (UnknownHostException e) { buffer = new byte[]{0,0,0,0}; } * internalIpTLV.setValue(buffer); * * TLV portTLV = new TLV(); portTLV.setType(0x05); * portTLV.setValue(Utils.short2ByteBE(ICQConstants.ICBM_PORT)); */ TLV unknownA = new TLV(); unknownA.type = 0xa; unknownA.value = new byte[] { 0, 1 }; TLV unknownF = new TLV(); unknownF.type = 0xf; TLV msgTLV = new TLV(); msgTLV.type = 0x2711; TLV[] tlv5content; byte[] clsid; if (message.messageType != ICQConstants.MTYPE_FILEREQ) { tlv5content = new TLV[] { unknownA, unknownF, msgTLV }; clsid = ICQConstants.CLSID_ICQUTF; byte[] textBytes; try { textBytes = message.text.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { textBytes = message.text.getBytes(); } byte[] suffix = null; switch (message.messageType) { case ICQConstants.MTYPE_PLAIN: suffix = getPlainMessageSuffix(); break; case ICQConstants.MTYPE_PLUGIN: suffix = message.pluginSpecificData; break; default: suffix = new byte[0]; break; } byte[] msgByteBlock = new byte[8 + textBytes.length + 1 + suffix.length]; msgByteBlock[0] = message.messageType; // !!! msgByteBlock[1] = 0; System.arraycopy(ProtocolUtils.short2ByteLE((short) 0), 0, msgByteBlock, 2, 2); System.arraycopy(ProtocolUtils.short2ByteLE((short) 1), 0, msgByteBlock, 4, 2); System.arraycopy(ProtocolUtils.short2ByteLE((short) (textBytes.length + 1)), 0, msgByteBlock, 6, 2); System.arraycopy(textBytes, 0, msgByteBlock, 8, textBytes.length); msgByteBlock[8 + textBytes.length] = 0; System.arraycopy(suffix, 0, msgByteBlock, 9 + textBytes.length, suffix.length); byte[] tlv2711data = new byte[2 + 2 + 16 + 2 + 4 + 1 + 2 + 2 + 2 + 12 + msgByteBlock.length]; System.arraycopy(ProtocolUtils.short2ByteLE((short) 27), 0, tlv2711data, 0, 2); System.arraycopy(ProtocolUtils.short2ByteLE((short) 9), 0, tlv2711data, 2, 2); byte[] zeros = new byte[16]; Arrays.fill(zeros, (byte) 0); System.arraycopy(zeros, 0, tlv2711data, 4, 16); System.arraycopy(ProtocolUtils.short2ByteLE((short) 0), 0, tlv2711data, 20, 2); System.arraycopy(ProtocolUtils.int2ByteLE(3), 0, tlv2711data, 22, 4); tlv2711data[26] = 0; System.arraycopy(ProtocolUtils.short2ByteLE(msgSeq), 0, tlv2711data, 27, 2); System.arraycopy(ProtocolUtils.short2ByteLE((short) 14), 0, tlv2711data, 29, 2); System.arraycopy(ProtocolUtils.short2ByteLE(msgSeq), 0, tlv2711data, 31, 2); zeros = new byte[12]; Arrays.fill(zeros, (byte) 0); System.arraycopy(zeros, 0, tlv2711data, 33, 12); System.arraycopy(msgByteBlock, 0, tlv2711data, 45, msgByteBlock.length); msgTLV.value = tlv2711data; } else { clsid = ICQConstants.CLSID_AIM_FILESEND; if (message.rvMessageType != 0) { tlv5content = new TLV[] { unknownA, unknownF, msgTLV }; msgTLV.value = new byte[0]; } else { // dummy tlv5content = new TLV[] { unknownA, unknownF, msgTLV }; msgTLV.value = new byte[0]; } } byte[] tlv5data = service.getDataParser().tlvs2Bytes(tlv5content); byte[] tlv5fullData = new byte[26 + tlv5data.length]; System.arraycopy(ProtocolUtils.short2ByteBE(message.rvMessageType), 0, tlv5fullData, 0, 2); System.arraycopy(message.messageId, 0, tlv5fullData, 2, 8); System.arraycopy(clsid, 0, tlv5fullData, 10, 16); System.arraycopy(tlv5data, 0, tlv5fullData, 26, tlv5data.length); TLV ch2messageTLV = new TLV(); ch2messageTLV.type = 0x5; ch2messageTLV.value = tlv5fullData; TLV confirmAckTLV = new TLV(); confirmAckTLV.type = 0x3; byte[] uidBytes; try { uidBytes = message.receiverId.getBytes("ASCII"); } catch (UnsupportedEncodingException e) { uidBytes = message.receiverId.getBytes(); } byte[] snacRawData = new byte[11 + uidBytes.length]; System.arraycopy(message.messageId, 0, snacRawData, 0, 8); System.arraycopy(ProtocolUtils.short2ByteBE((short) 2), 0, snacRawData, 8, 2); snacRawData[10] = (byte) message.receiverId.length(); System.arraycopy(uidBytes, 0, snacRawData, 11, uidBytes.length); data.data = new TLV[] { ch2messageTLV, confirmAckTLV }; data.plainData = snacRawData; flap.data = data; service.getRunnableService().sendToSocket(flap); } public long sendMessage(ICBMMessage message) { if (message == null) { service.log("msg to send is null " + new Date()); } if (message.messageId == null) { message.messageId = new byte[8]; RANDOM.nextBytes(message.messageId); } for (ICQOnlineInfo info : service.getBuddyList().buddyInfos) { if (info != null && info.uin.equals(message.receiverId) && info.capabilities != null) { for (String cap : info.capabilities) { if (cap.equals(ProtocolUtils.getHexString(ICQConstants.CLSID_ICQUTF))) { sendChannel2Message(message); return ProtocolUtils.bytes2LongBE(message.messageId); } } break; } } sendChannel1Message(message); return ProtocolUtils.bytes2LongBE(message.messageId); } public void sendFileMessage(ICBMMessage message) { for (ICQOnlineInfo info : service.getBuddyList().buddyInfos) { if (info != null && info.uin.equals(message.receiverId)) { for (String cap : info.capabilities) { if (cap.equals(ProtocolUtils.getHexString(ICQConstants.CLSID_AIM_FILESEND))) { sendChannel2Message(message); return; } } break; } } } private void sendChannel1Message(ICBMMessage message) { Flap flap = new Flap(); flap.channel = ICQConstants.FLAP_CHANNELL_DATA; Snac data = new Snac(); data.serviceId = ICQConstants.SNAC_FAMILY_MESSAGING; data.subtypeId = ICQConstants.SNAC_MESSAGING_SENDTHROUGHSERVER; data.requestId = 0; byte[] textBytes; try { textBytes = message.text.getBytes("windows-1251"); } catch (UnsupportedEncodingException e) { textBytes = message.text.getBytes(); } byte[] caps = new byte[] { 5, 1, 0, 1, 1 }; byte[] text = new byte[8 + textBytes.length]; text[1] = text[0] = 1; byte[] textLength = ProtocolUtils.short2ByteBE((short) (textBytes.length + 4)); System.arraycopy(textLength, 0, text, 2, 2); text[5] = text[4] = 0; text[7] = text[6] = (byte) 0xff; System.arraycopy(textBytes, 0, text, 8, textBytes.length); TLV msgTLV = new TLV(); msgTLV.type = 2; byte[] msgTLVBytes = new byte[caps.length + text.length]; System.arraycopy(caps, 0, msgTLVBytes, 0, caps.length); System.arraycopy(text, 0, msgTLVBytes, caps.length, text.length); msgTLV.value = msgTLVBytes; TLV confirmAckTLV = new TLV(); confirmAckTLV.type = 0x3; TLV storeMsgTLV = new TLV(); storeMsgTLV.type = 0x6; byte[] uidBytes; try { uidBytes = message.receiverId.getBytes("ASCII"); } catch (UnsupportedEncodingException e) { uidBytes = message.receiverId.getBytes(); } byte[] snacRawData = new byte[11 + uidBytes.length]; System.arraycopy(message.messageId, 0, snacRawData, 0, 8); System.arraycopy(ProtocolUtils.short2ByteBE((short) 1), 0, snacRawData, 8, 2); snacRawData[10] = (byte) message.receiverId.length(); System.arraycopy(uidBytes, 0, snacRawData, 11, uidBytes.length); data.data = new TLV[] { msgTLV, confirmAckTLV, storeMsgTLV }; data.plainData = snacRawData; flap.data = data; service.getRunnableService().sendToSocket(flap); } class MessageParser { String encoding = "windows-1251"; void parseMessage(byte[] data) { ICBMMessage message = new ICBMMessage(); System.arraycopy(data, 0, message.messageId, 0, 8); message.channel = ProtocolUtils.bytes2ShortBE(data, 8); message.receivingTime = new Date(); String uin = new String(data, 11, data[10]); message.senderId = uin; @SuppressWarnings("unused") short warningLevel = ProtocolUtils.bytes2ShortBE(data, 11 + data[10]); int fixedPartTlvCount = ProtocolUtils.bytes2ShortBE(data, 13 + data[10]); int tlvDataLength = data.length - 15 - data[10]; byte[] tlvData = new byte[tlvDataLength]; System.arraycopy(data, 15 + data[10], tlvData, 0, tlvDataLength); service.log("message from " + message.senderId + " id " + ProtocolUtils.getHexString(message.messageId)); ICQOnlineInfo info = new ICQOnlineInfo(); try { TLV[] tlvs = service.getDataParser().parseTLV(tlvData); for (int i = 0; i < fixedPartTlvCount; i++) { service.getOnlineInfoEngine().onlineInfoTLVMap(tlvs[i], info); } for (int i = fixedPartTlvCount; i < tlvs.length; i++) { messageTLVMap(tlvs[i], message); } service.log("message type " + message.messageType); //if (service.checkFileTransferEngineCreated() && service.getFileTransferEngine().findMessageByMessageId(message.messageId)!=null){ if (!message.senderId.equals(service.getUn()) && message.capability != null && message.capability.equals(ProtocolUtils.getHexString(ICQConstants.CLSID_AIM_FILESEND))) { switch (message.messageType) { case 0: if (!message.connectFTPeer && !message.connectFTProxy) { service.getFileTransferEngine().getMessages().add(message); service.getServiceResponse().respond(ICQServiceResponse.RES_FILEMESSAGE, message); } else { message.receiverId = message.senderId; message.senderId = service.getUn(); service.getFileTransferEngine().redirectRequest(message); } break; case 1: service.getFileTransferEngine().transferFailed(new ICQException("Cancelled"), "", message, uin); break; case 2: service.getFileTransferEngine().fireTransfer(message); break; } } } catch (ICQException e) { service.log(e); } } void parsePluginMessage(byte[] plainData, boolean isAck) { ICBMMessage message = new ICBMMessage(); int pos = 0; System.arraycopy(plainData, 0, message.messageId, 0, 8); pos += 8; short channel = ProtocolUtils.bytes2ShortBE(plainData, pos); message.channel = channel; pos += 2; int uinBytes = plainData[pos]; pos += 1; message.senderId = new String(plainData, pos, uinBytes); pos += uinBytes; if (isAck) { service.getServiceResponse().respond(ICQServiceResponse.RES_MESSAGEACK, message.senderId, ProtocolUtils.bytes2LongBE(message.messageId, 0), (byte)1); return; } short reasonId = ProtocolUtils.bytes2ShortBE(plainData, pos); pos += 2; switch (reasonId) { case 3: byte[] data = new byte[plainData.length - pos]; System.arraycopy(plainData, pos, data, 0, data.length); if (data.length < 5) { service.getFileTransferEngine().cancel(ProtocolUtils.bytes2LongBE(message.messageId, 0)); return; } else { channel2TextMessage(data, message, true); } break; } } void parseOfflineMessage(byte[] tailData) { ICBMMessage message = new ICBMMessage(); int senderUinInt = ProtocolUtils.bytes2IntLE(tailData, 0); message.senderId = senderUinInt + ""; short year = ProtocolUtils.bytes2ShortLE(tailData, 4); byte month = tailData[6]; byte day = tailData[7]; byte hour = tailData[8]; byte minute = tailData[9]; Calendar sendingDate = Calendar.getInstance(); sendingDate.set(year, month, day, hour, minute); message.sendingTime = sendingDate.getTime(); message.receivingTime = new Date(); byte mType = tailData[10]; @SuppressWarnings("unused") byte mFlag = tailData[11]; switch (mType) { case ICQConstants.MTYPE_PLAIN: int textLength = ProtocolUtils.bytes2ShortLE(tailData, 12) - 1; String text; try { text = new String(tailData, 14, textLength, "windows-1251"); } catch (UnsupportedEncodingException e) { text = new String(tailData, 14, textLength); } message.text = "(Sent at "+OFFLINE_DATE_FORMATTER.format(message.sendingTime)+") "+text; service.log(message.senderId + " says: " + text); if (text.length() > 0) notifyMessageReceived(message); break; } } private void messageTLVMap(TLV tlv, ICBMMessage message) { switch (tlv.type) { case 0x5: switch (message.channel) { // message channel 2 case 0x2: if (tlv.value == null) { return; } message.messageType = (byte) ProtocolUtils.bytes2ShortBE(tlv.value, 0); // eliminate message id - 8 bytes byte[] capability = new byte[16]; System.arraycopy(tlv.value, 10, capability, 0, 16); String strCap = ProtocolUtils.getHexString(capability); message.capability = strCap; byte[] tailData = new byte[tlv.value.length - 26]; System.arraycopy(tlv.value, 26, tailData, 0, tailData.length); try { TLV[] channel2Tlvs = service.getDataParser().parseTLV(tailData); for (TLV ch2tlv : channel2Tlvs) { channel2MessageTLVMap(ch2tlv, message); } if (service.getFileTransferEngine().findMessageByMessageId(ProtocolUtils.bytes2LongBE(message.messageId, 0)) != null) { message.connectFTPeer = true; } } catch (ICQException e) { service.log(e); } break; case 0x4: // message channel 4 channel4MessageTLVMap(tlv, message); break; } break; case 0x2: switch (message.channel) { // message channel 1 case 0x1: try { TLV[] channel1Tlvs = service.getDataParser().parseTLV(tlv.value); for (TLV ch1Tlv : channel1Tlvs) { channel1MessageTLVMap(ch1Tlv, message); } } catch (ICQException e) { service.log(e); } break; } break; case 0x24: service.log("0x24 unk cap - " + new String(tlv.value)); break; case 0x13: service.log("0x13 unk cap - " + ProtocolUtils.getHexString(tlv.value)); break; } } private void channel4MessageTLVMap(TLV tlv, ICBMMessage message) { int uinBytes = ProtocolUtils.bytes2IntLE(tlv.value, 0); String uin = new String(uinBytes + ""); message.senderId = uin; byte mType = tlv.value[4]; @SuppressWarnings("unused") byte mFlag = tlv.value[5]; switch (mType) { case ICQConstants.MTYPE_PLAIN: int textLength = ProtocolUtils.bytes2ShortLE(tlv.value, 6) - 1; String text; try { text = new String(tlv.value, 8, textLength, "ASCII"); } catch (UnsupportedEncodingException e) { text = new String(tlv.value, 8, textLength); } message.text = text; service.log(message.senderId + " says " + text); if (text.length() > 0) notifyMessageReceived(message); break; } } private void channel1MessageTLVMap(TLV tlv, ICBMMessage message) { byte[] bytes = ProtocolUtils.int2ByteBE(tlv.type); switch (bytes[2]) { case 0x5: byte[] capsArray = tlv.value; service.log(ProtocolUtils.getSpacedHexString(capsArray)); /* * if (capsArray.length > 0 && capsArray[capsArray.length - 1] * == 6) { encoding = "UTF-16"; } else { encoding = * "windows-1251"; } * service.log(" channel 1 message require caps: "+encoding); */ break; case 0x1: int charsetType = ProtocolUtils.bytes2ShortBE(tlv.value, 0); int charsetSubtype = ProtocolUtils.bytes2ShortBE(tlv.value, 2); switch (charsetType) { case 0: encoding = "windows-1251"; break; case 2: encoding = "UTF-16"; break; default: encoding = "UTF-8"; break; } service.log("charset type " + charsetType + "| charset subtype " + charsetSubtype); int textBytes = tlv.value.length - 4; String text;// = Utils.getEncodedString(textBytes); try { // text = new String(textBytes, "UTF-16"); text = new String(tlv.value, 4, textBytes, encoding); } catch (UnsupportedEncodingException e) { text = new String(tlv.value, 4, textBytes); } message.text = text; service.log(message.senderId + " says " + text); if ((message.senderId.equals(service.getUn())) || text.length() > 0) notifyMessageReceived(message); break; } } private void channel2MessageTLVMap(TLV tlv, ICBMMessage message) { switch (tlv.type) { case 0x2711: if (message.capability.equals(ProtocolUtils.getHexString(ICQConstants.CLSID_SRV_RELAY))) { channel2TextMessage(tlv.value, message, false); } if (message.capability.equals(ProtocolUtils.getHexString(ICQConstants.CLSID_AIM_FILESEND))) { channel2FileMessage(tlv.value, message); } break; case 0xa: service.log("seq number " + tlv.value); break; case 0xf: service.log("host check " + ProtocolUtils.getHexString(tlv.value)); break; case 0xd: service.log("mime " + new String(tlv.value)); break; case 0xc: String text; try { text = new String(tlv.value, "UTF-16"); } catch (UnsupportedEncodingException e) { text = new String(tlv.value); } message.invitation = ProtocolUtils.xmlFromParameter(text); service.log("invitation " + message.invitation); break; case 0x2: message.rvIp = ProtocolUtils.getIPString(tlv.value); service.log("rendezvouz ip " + message.rvIp); break; case 0x3: message.internalIp = ProtocolUtils.getIPString(tlv.value); service.log("internal ip " + message.internalIp); break; case 0x4: message.externalIp = ProtocolUtils.getIPString(tlv.value); service.log("external ip " + message.externalIp); break; case 0x5: message.externalPort = ProtocolUtils.unsignedShort2Int(ProtocolUtils.bytes2ShortBE(tlv.value)); service.log("external port " + message.externalPort); break; case 0x10: service.log("connect FT proxy request"); message.connectFTProxy = true; break; case 0x2712: service.log("kinda encoding " + new String(tlv.value)); break; } if ((message.senderId.equals(service.getUn())) || (message.text != null && message.text.length() > 0 && message.capability.equals(ProtocolUtils.getHexString(ICQConstants.CLSID_SRV_RELAY)))) { notifyMessageReceived(message); message.receiverId = message.senderId; // message.text = ""; message.senderId = service.getUn(); if ((service.getOnlineInfo().userStatus & ICQConstants.STATUS_INVISIBLE) < 1) { message.messageType = ICQConstants.MTYPE_PLAIN; sendChannel2PluginMessage(message); } } } @SuppressWarnings("unused") private void channel2FileMessage(byte[] in, ICBMMessage message) { if (in == null) { return; } int pos = 0; int type = ProtocolUtils.bytes2ShortBE(in, pos); pos += 2; int count = ProtocolUtils.bytes2ShortBE(in, pos); pos += 2; long filesize = ProtocolUtils.unsignedInt2Long(ProtocolUtils.bytes2IntBE(in, pos)); pos += 4; // message.messageType = ICQConstants.MTYPE_FILEREQ; int filenameBytes = in.length - 9; for (int i = 0; i < count; i++) { ICQFileInfo file = new ICQFileInfo(); file.size = filesize; try { file.filename = new String(in, pos, filenameBytes, "UTF-8"); } catch (UnsupportedEncodingException e) { service.log(e); file.filename = new String(in, pos, filenameBytes); } message.files.add(file); } } @SuppressWarnings("unused") private void channel2TextMessage(byte[] data, ICBMMessage message, boolean isAck) { short block1Length = ProtocolUtils.bytes2ShortLE(data, 0); byte[] pluginGUID = new byte[16]; System.arraycopy(data, 4, pluginGUID, 0, 16); String strGUID = ProtocolUtils.getHexString(pluginGUID); if (strGUID.equals(ICQConstants.GUID_RTF_TEXT)) { int pos = 2 + block1Length; short block2Length = ProtocolUtils.bytes2ShortLE(data, pos); pos = 4 + block1Length + block2Length; byte mType = data[pos]; byte mFlag = data[pos + 1]; short statusCode = ProtocolUtils.bytes2ShortLE(data, pos + 2); short priorityCode = ProtocolUtils.bytes2ShortLE(data, pos + 4); int textLength = ProtocolUtils.unsignedShort2Int(ProtocolUtils.bytes2ShortLE(data, pos + 6)); byte[] textBytes = null; if (textLength > 1) { textBytes = new byte[textLength - 1]; System.arraycopy(data, pos + 8, textBytes, 0, textLength - 1); } pos += (8 + textLength); String encoding = "windows-1251"; switch (mType) { case ICQConstants.MTYPE_ACK: case ICQConstants.MTYPE_PLAIN: if (!message.senderId.equals(service.getUn())) { service.getServiceResponse().respond(ICQServiceResponse.RES_MESSAGEACK, message.senderId, ProtocolUtils.bytes2LongBE(message.messageId, 0), (byte)2); } int color = ProtocolUtils.bytes2IntLE(data, pos); pos += 4; int bgColor = ProtocolUtils.bytes2IntLE(data, pos); pos += 4; if (data.length >= pos + 4) { int guidLen = ProtocolUtils.bytes2IntLE(data, pos); pos += 4; if (guidLen == 38) { String guid = ProtocolUtils.getEncodedString(data, pos, guidLen); if (guid.equals(ICQConstants.GUID_UTF8)) { encoding = "UTF-8"; } pos += guidLen; } } break; case ICQConstants.MTYPE_PLUGIN: parsePluginData(message, data, pos, message.senderId); break; } if (textBytes != null) { String text = ProtocolUtils.getEncodedString(textBytes, encoding); service.log(message.senderId + " says something " + text); message.text = text; } else { message.text = ""; } } } private void parsePluginData(ICBMMessage message, byte[] data, int pos, String uid) { int headerLength = ProtocolUtils.unsignedShort2Int(ProtocolUtils.bytes2ShortLE(data, pos)); byte[] pluginGuid = new byte[16]; pos += 2; System.arraycopy(data, pos, pluginGuid, 0, 16); if (new String(pluginGuid).equals(new String(ICQConstants.GUID_XSTATUSMSG))) { pos += headerLength + 4; int dataLength = ProtocolUtils.bytes2IntLE(data, pos); pos += 4; byte[] xmlDataBytes = new byte[dataLength]; System.arraycopy(data, pos, xmlDataBytes, 0, dataLength); String xmlData = ProtocolUtils.getEncodedString(xmlDataBytes); int i; if ((i = xmlData.indexOf("<NR><RES>")) < 0) { //service.log(message.senderId + " asks xstatus "); service.getServiceResponse().respond(ICQServiceResponse.RES_ACCOUNT_ACTIVITY, message.senderId + " asks xstatus "); if ((service.getOnlineInfo().userStatus & ICQConstants.STATUS_INVISIBLE) < 1){ answerOwnXStatus(message, uid); } return; } ; int j; if ((j = xmlData.indexOf("</RES></NR>")) < 0) return; String s2; if (((s2 = ProtocolUtils.xmlFromParameter(xmlData.substring(i + 9, j))).indexOf("<val srv_id='")) < 0) return; int j2; int k2; String xstatusName = ""; if ((j2 = s2.indexOf("<title>")) > 0 && (k2 = s2.indexOf("/title>")) > 0) { xstatusName = s2.substring(j2 + 7, k2 - 1); } ; int l2; int i3; String xstatusValue = ""; if ((l2 = s2.indexOf("<desc>")) > 0 && (i3 = s2.indexOf("</desc>")) > 0) { xstatusValue = s2.substring(l2 + 6, i3); } ; service.log(uid + " has xstatus: " + xstatusName + ": " + xstatusValue); ICQOnlineInfo info = service.getBuddyList().getByUin(uid); if (info != null) { info.personalText = xstatusName; info.extendedStatus = xstatusValue; service.getServiceResponse().respond(ICQServiceResponse.RES_BUDDYSTATECHANGED, info, true); } } } } public Flap getOfflineMessagesRequestFlap() { Flap flap = new Flap(); flap.channel = ICQConstants.FLAP_CHANNELL_DATA; Snac data = new Snac(); data.serviceId = ICQConstants.SNAC_FAMILY_MESSAGING; data.subtypeId = ICQConstants.SNAC_MESSAGING_OFFLINE; data.requestId = ICQConstants.SNAC_MESSAGING_OFFLINE; flap.data = data; return flap; } private void answerOwnXStatus(ICBMMessage askMessage, String receiverUid) { ICBMMessage message = new ICBMMessage(); message.messageId = askMessage.messageId; message.pluginSpecificData = getAnswerXStatusSuffix(service.getOnlineInfo().personalText, service.getOnlineInfo().extendedStatus); message.receiverId = receiverUid; message.text = ""; message.messageType = ICQConstants.MTYPE_PLUGIN; sendChannel2PluginMessage(message); } protected void notifyMessageReceived(ICBMMessage message) { service.getServiceResponse().respond(ICQServiceResponse.RES_MESSAGE, message); } public void sendFileMessageReject(ICBMMessage message) { sendChannel2PluginMessage(message); } public void parseTyping(Snac snac) { if (snac.plainData == null || snac.plainData.length == 0) { return; } int pos = 10; byte screennameLength = snac.plainData[pos]; pos++; String screenname = new String(snac.plainData, pos, screennameLength); pos += screennameLength; short type = ProtocolUtils.bytes2ShortBE(snac.plainData, pos); if (type != 0) { service.getServiceResponse().respond(ICQServiceResponse.RES_TYPING, screenname); } } public void sendTyping(String uin) { if (task != null && !task.isCancelled()) { task.cancel(false); } sendTyping(uin, false); } private void sendTyping(final String uin, boolean typingEnds) { short channel = 1; for (ICQOnlineInfo info : service.getBuddyList().buddyInfos) { if (info != null && info.capabilities != null && info.uin.equals(uin)) { for (String cap : info.capabilities) { if (cap.equals(ProtocolUtils.getHexString(ICQConstants.CLSID_ICQUTF))) { channel = 2; break; } } break; } } Flap flap = new Flap(); flap.channel = ICQConstants.FLAP_CHANNELL_DATA; Snac data = new Snac(); data.serviceId = ICQConstants.SNAC_FAMILY_MESSAGING; data.subtypeId = ICQConstants.SNAC_MESSAGING_TYPINGNOTIFICATION; data.requestId = ICQConstants.SNAC_MESSAGING_TYPINGNOTIFICATION; byte[] uinBytes = uin.getBytes(); byte[] raw = new byte[13 + uinBytes.length]; int pos = 0; System.arraycopy(ProtocolUtils.long2ByteBE(RANDOM.nextLong()), 0, raw, pos, 8); pos += 8; System.arraycopy(ProtocolUtils.short2ByteBE(channel), 0, raw, pos, 2); pos += 2; raw[pos] = (byte) uinBytes.length; pos++; System.arraycopy(uinBytes, 0, raw, pos, uinBytes.length); pos += uinBytes.length; raw[pos] = 0; pos++; if (typingEnds) { raw[pos] = 0; } else { raw[pos] = 2; } pos++; data.plainData = raw; flap.data = data; if (service.getRunnableService().sendToSocket(flap) && !typingEnds){ task = executor.schedule(new Runnable() { @Override public void run() { sendTyping(uin, true); } }, 4, TimeUnit.SECONDS); } } }
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.usages; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.util.NlsContexts; import com.intellij.openapi.util.NlsSafe; import com.intellij.openapi.util.text.StringUtil; import com.intellij.usageView.UsageViewBundle; import org.jetbrains.annotations.Nls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Objects; import java.util.regex.Pattern; import static org.jetbrains.annotations.Nls.Capitalization.Title; public class UsageViewPresentation { private static final Logger LOG = Logger.getInstance(UsageViewPresentation.class); private @NlsContexts.TabTitle String myTabText; private @NlsSafe String myScopeText = ""; // Default value. to be overwritten in most cases. private @NlsSafe String myUsagesString; private @NlsSafe String mySearchString; private @NlsContexts.ListItem String myTargetsNodeText = UsageViewBundle.message("node.targets"); // Default value. to be overwritten in most cases. private @NlsContexts.ListItem String myNonCodeUsagesString = UsageViewBundle.message("node.non.code.usages"); private @NlsContexts.ListItem String myCodeUsagesString = UsageViewBundle.message("node.found.usages"); private boolean myShowReadOnlyStatusAsRed; private boolean myShowCancelButton; private boolean myOpenInNewTab = true; private int myRerunHash;//this value shouldn't be copied and doesn't affect equals/hashcode methods private boolean myCodeUsages = true; private boolean myUsageTypeFilteringAvailable; private @NlsContexts.TabTitle String myTabName; private @NlsContexts.TabTitle String myToolwindowTitle; private boolean myDetachedMode; // no UI will be shown private @NlsContexts.ListItem String myDynamicCodeUsagesString; private boolean myMergeDupLinesAvailable = true; private boolean myExcludeAvailable = true; private Pattern mySearchPattern; private Pattern myReplacePattern; private boolean myReplaceMode; public @NlsContexts.TabTitle String getTabText() { return myTabText; } public void setTabText(@NlsContexts.TabTitle String tabText) { myTabText = tabText; } @NotNull @NlsSafe public String getScopeText() { return myScopeText; } public void setScopeText(@NotNull @NlsSafe String scopeText) { myScopeText = scopeText; } public boolean isShowReadOnlyStatusAsRed() { return myShowReadOnlyStatusAsRed; } public void setShowReadOnlyStatusAsRed(boolean showReadOnlyStatusAsRed) { myShowReadOnlyStatusAsRed = showReadOnlyStatusAsRed; } /** * @deprecated use {@link #setSearchString} */ @Deprecated public void setUsagesString(@Nls String usagesString) { myUsagesString = usagesString; } public @Nls(capitalization = Title) @NotNull String getSearchString() { String searchString = mySearchString; if (searchString != null) { return searchString; } String usagesString = myUsagesString; if (usagesString != null) { return StringUtil.capitalize(myUsagesString); } LOG.error("search string must be set"); return ""; } public void setSearchString(@Nls(capitalization = Title) @NotNull String searchString) { mySearchString = searchString; } @NlsContexts.ListItem @Nullable("null means the targets node must not be visible") public String getTargetsNodeText() { return myTargetsNodeText; } public void setTargetsNodeText(@NlsContexts.ListItem String targetsNodeText) { myTargetsNodeText = targetsNodeText; } public boolean isShowCancelButton() { return myShowCancelButton; } public void setShowCancelButton(boolean showCancelButton) { myShowCancelButton = showCancelButton; } @NotNull public @NlsContexts.ListItem String getNonCodeUsagesString() { return myNonCodeUsagesString; } public void setNonCodeUsagesString(@NotNull @NlsContexts.ListItem String nonCodeUsagesString) { myNonCodeUsagesString = nonCodeUsagesString; } @NotNull public @NlsContexts.ListItem String getCodeUsagesString() { return myCodeUsagesString; } public void setCodeUsagesString(@NotNull @NlsContexts.ListItem String codeUsagesString) { myCodeUsagesString = codeUsagesString; } public boolean isOpenInNewTab() { return myOpenInNewTab; } public void setOpenInNewTab(boolean openInNewTab) { myOpenInNewTab = openInNewTab; } public int getRerunHash() { return myRerunHash; } public void setRerunHash(int rerunHash) { myRerunHash = rerunHash; } public boolean isCodeUsages() { return myCodeUsages; } public void setCodeUsages(final boolean codeUsages) { myCodeUsages = codeUsages; } /** * @deprecated please avoid using this method, because it leads to string concatenations that are shown in UI */ @Deprecated(forRemoval = true) @NotNull public @Nls String getUsagesWord() { return UsageViewBundle.message("usage.name", 1); } /** * @deprecated no-op */ @Deprecated(forRemoval = true) public void setUsagesWord(@NotNull @Nls String usagesWord) {} public @NlsContexts.TabTitle String getTabName() { return myTabName; } public void setTabName(final @NlsContexts.TabTitle String tabName) { myTabName = tabName; } public @NlsContexts.TabTitle String getToolwindowTitle() { return myToolwindowTitle; } public void setToolwindowTitle(final @NlsContexts.TabTitle String toolwindowTitle) { myToolwindowTitle = toolwindowTitle; } public boolean isDetachedMode() { return myDetachedMode; } public void setDetachedMode(boolean detachedMode) { myDetachedMode = detachedMode; } public void setDynamicUsagesString(@NlsContexts.ListItem String dynamicCodeUsagesString) { myDynamicCodeUsagesString = dynamicCodeUsagesString; } public @NlsContexts.ListItem String getDynamicCodeUsagesString() { return myDynamicCodeUsagesString; } public boolean isMergeDupLinesAvailable() { return myMergeDupLinesAvailable; } public void setMergeDupLinesAvailable(boolean mergeDupLinesAvailable) { myMergeDupLinesAvailable = mergeDupLinesAvailable; } public boolean isUsageTypeFilteringAvailable() { return myCodeUsages || myUsageTypeFilteringAvailable; } public void setUsageTypeFilteringAvailable(boolean usageTypeFilteringAvailable) { myUsageTypeFilteringAvailable = usageTypeFilteringAvailable; } public boolean isExcludeAvailable() { return myExcludeAvailable; } public void setExcludeAvailable(boolean excludeAvailable) { myExcludeAvailable = excludeAvailable; } public void setSearchPattern(Pattern searchPattern) { mySearchPattern = searchPattern; } public Pattern getSearchPattern() { return mySearchPattern; } public void setReplacePattern(Pattern replacePattern) { myReplacePattern = replacePattern; } public Pattern getReplacePattern() { return myReplacePattern; } public boolean isReplaceMode() { return myReplaceMode; } public void setReplaceMode(boolean replaceMode) { myReplaceMode = replaceMode; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; UsageViewPresentation that = (UsageViewPresentation)o; return myCodeUsages == that.myCodeUsages && myDetachedMode == that.myDetachedMode && myMergeDupLinesAvailable == that.myMergeDupLinesAvailable && myOpenInNewTab == that.myOpenInNewTab && myShowCancelButton == that.myShowCancelButton && myShowReadOnlyStatusAsRed == that.myShowReadOnlyStatusAsRed && myUsageTypeFilteringAvailable == that.myUsageTypeFilteringAvailable && myExcludeAvailable == that.myExcludeAvailable && myReplaceMode == that.myReplaceMode && Objects.equals(myCodeUsagesString, that.myCodeUsagesString) && Objects.equals(myDynamicCodeUsagesString, that.myDynamicCodeUsagesString) && Objects.equals(myNonCodeUsagesString, that.myNonCodeUsagesString) && Objects.equals(myScopeText, that.myScopeText) && Objects.equals(myTabName, that.myTabName) && Objects.equals(myTabText, that.myTabText) && Objects.equals(myTargetsNodeText, that.myTargetsNodeText) && Objects.equals(myToolwindowTitle, that.myToolwindowTitle) && Objects.equals(myUsagesString, that.myUsagesString) && Objects.equals(mySearchString, that.mySearchString) && arePatternsEqual(mySearchPattern, that.mySearchPattern) && arePatternsEqual(myReplacePattern, that.myReplacePattern); } public static boolean arePatternsEqual(Pattern p1, Pattern p2) { if (p1 == null) return p2 == null; if (p2 == null) return false; return Objects.equals(p1.pattern(), p2.pattern()) && p1.flags() == p2.flags(); } public static int getHashCode(Pattern pattern) { if (pattern == null) return 0; String s = pattern.pattern(); return (s != null ? s.hashCode() : 0) * 31 + pattern.flags(); } @Override public int hashCode() { int result = Objects.hash( myTabText, myScopeText, myUsagesString, mySearchString, myTargetsNodeText, myNonCodeUsagesString, myCodeUsagesString, myShowReadOnlyStatusAsRed, myShowCancelButton, myOpenInNewTab, myCodeUsages, myUsageTypeFilteringAvailable, myExcludeAvailable, myTabName, myToolwindowTitle, myDetachedMode, myDynamicCodeUsagesString, myMergeDupLinesAvailable, myReplaceMode ); result = 31 * result + getHashCode(mySearchPattern); result = 31 * result + getHashCode(myReplacePattern); return result; } public UsageViewPresentation copy() { UsageViewPresentation copyInstance = new UsageViewPresentation(); copyInstance.myTabText = myTabText; copyInstance.myScopeText = myScopeText; copyInstance.myUsagesString = myUsagesString; copyInstance.mySearchString = mySearchString; copyInstance.myTargetsNodeText = myTargetsNodeText; copyInstance.myNonCodeUsagesString = myNonCodeUsagesString; copyInstance.myCodeUsagesString = myCodeUsagesString; copyInstance.myShowReadOnlyStatusAsRed = myShowReadOnlyStatusAsRed; copyInstance.myShowCancelButton = myShowCancelButton; copyInstance.myOpenInNewTab = myOpenInNewTab; copyInstance.myCodeUsages = myCodeUsages; copyInstance.myUsageTypeFilteringAvailable = myUsageTypeFilteringAvailable; copyInstance.myTabName = myTabName; copyInstance.myToolwindowTitle = myToolwindowTitle; copyInstance.myDetachedMode = myDetachedMode; copyInstance.myDynamicCodeUsagesString = myDynamicCodeUsagesString; copyInstance.myMergeDupLinesAvailable = myMergeDupLinesAvailable; copyInstance.myExcludeAvailable = myExcludeAvailable; copyInstance.mySearchPattern = mySearchPattern; copyInstance.myReplacePattern = myReplacePattern; copyInstance.myReplaceMode = myReplaceMode; return copyInstance; } }
/* ************************************************************************ # # DivConq # # http://divconq.com/ # # Copyright: # Copyright 2014 eTimeline, LLC. All rights reserved. # # License: # See the license.txt file in the project's top-level directory for details. # # Authors: # * Andy White # ************************************************************************ */ package divconq.struct; import groovy.lang.GroovyObject; import groovy.lang.MetaClass; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import org.codehaus.groovy.runtime.InvokerHelper; import org.joda.time.DateTime; import org.joda.time.LocalDate; import org.joda.time.LocalTime; import divconq.lang.BigDateTime; import divconq.lang.Memory; import divconq.lang.op.FuncResult; import divconq.lang.op.OperationContext; import divconq.lang.op.OperationResult; import divconq.schema.DataType; import divconq.schema.Field; import divconq.script.ExecuteState; import divconq.script.StackEntry; import divconq.struct.builder.BuilderStateException; import divconq.struct.builder.ICompositeBuilder; import divconq.struct.scalar.BooleanStruct; import divconq.struct.scalar.NullStruct; import divconq.struct.scalar.StringStruct; import divconq.util.ClassicIterableAdapter; import divconq.util.IAsyncIterable; import divconq.util.StringUtil; import divconq.xml.XElement; /** * DivConq uses a specialized type system that provides type consistency across services * (including web services), database fields and stored procedures, as well as scripting. * * All scalars (including primitives) and composites (collections) are wrapped by some * subclass of Struct. Map collections are expressed by this class - records have fields * and fields are a name value pair. This class is analogous to an Object in JSON but may * contain type information as well, similar to Yaml. * * TODO link to blog entries. * * @author Andy * */ public class RecordStruct extends CompositeStruct implements IItemCollection, GroovyObject /*, JSObject */ { // this defines valid field name pattern (same as json) static protected final Pattern FIELD_NAME_PATTERN = Pattern.compile("(^[a-zA-Z][a-zA-Z0-9\\$_\\-]*$)|(^[\\$_][a-zA-Z][a-zA-Z0-9\\$_\\-]*$)"); // TODO check field names inside of "set field" etc. static public boolean validateFieldName(String v) { if (StringUtil.isEmpty(v)) return false; return RecordStruct.FIELD_NAME_PATTERN.matcher(v).matches(); } protected Map<String,FieldStruct> fields = new HashMap<String,FieldStruct>(); @Override public DataType getType() { if (this.explicitType != null) return super.getType(); // implied only, not explicit return OperationContext.get().getSchema().getType("AnyRecord"); } /** * Provide data type info (schema for fields) and a list of initial fields * * @param type field schema * @param fields initial pairs */ public RecordStruct(DataType type, FieldStruct... fields) { super(type); this.setField(fields); } /** * Optionally provide a list of initial fields * * @param fields initial pairs */ public RecordStruct(FieldStruct... fields) { // this is necessary so that Hub can start an initial context (setField causes a allocate guest) if (fields.length > 0) this.setField(fields); } /* (non-Javadoc) * @see divconq.struct.CompositeStruct#select(divconq.struct.PathPart[]) */ @Override public Struct select(PathPart... path) { if (path.length == 0) return this; PathPart part = path[0]; if (!part.isField()) { OperationResult log = part.getLog(); if (log != null) log.warnTr(504, this); return NullStruct.instance; } String fld = part.getField(); if (!this.fields.containsKey(fld)) { //OperationResult log = part.getLog(); //if (log != null) // log.warnTr(505, fld); return NullStruct.instance; } Struct o = this.getField(fld); if (path.length == 1) return (o != null) ? o : NullStruct.instance; if (o instanceof CompositeStruct) return ((CompositeStruct)o).select(Arrays.copyOfRange(path, 1, path.length)); OperationResult log = part.getLog(); if (log != null) log.warnTr(503, o); return NullStruct.instance; } /* (non-Javadoc) * @see divconq.struct.CompositeStruct#isEmpty() */ @Override public boolean isEmpty() { return (this.fields.size() == 0); } @Override public void toBuilder(ICompositeBuilder builder) throws BuilderStateException { builder.startRecord(); for (FieldStruct f : this.fields.values()) f.toBuilder(builder); builder.endRecord(); } /** * Adds or replaces a list of fields within the record. * * @param fields to add or replace * @return a log of messages about success of the call */ public void setField(FieldStruct... fields) { for (FieldStruct f : fields) { Struct svalue = f.getValue(); if (!f.prepped) { // take the original value and convert to a struct, fields hold structures Object value = f.orgvalue; if (value instanceof ICompositeBuilder) value = ((ICompositeBuilder)value).toLocal(); if (this.explicitType != null) { Field fld = this.explicitType.getField(f.getName()); if (fld != null) { Struct sv = fld.wrap(value); if (sv != null) svalue = sv; } } if (svalue == null) svalue = Struct.objectToStruct(value); f.setValue(svalue); f.prepped = true; } //FieldStruct old = this.fields.get(f.getName()); //if (old != null) // old.dispose(); this.fields.put(f.getName(), f); } } /** * Add or replace a specific field with a value. * * @param name of field * @param value to store with field * @return a log of messages about success of the call */ public void setField(String name, Object value) { this.setField(new FieldStruct(name, value)); } public RecordStruct withField(String name, Object value) { this.setField(new FieldStruct(name, value)); return this; } /** * * @return collection of all the fields this record holds */ public Iterable<FieldStruct> getFields() { return this.fields.values(); } /** * * @param name of the field desired * @return the struct for that field */ public Struct getField(String name) { if (!this.fields.containsKey(name)) return null; FieldStruct fs = this.fields.get(name); if (fs == null) return null; return fs.value; } /** * * @param name of the field desired * @return the struct for that field */ public FieldStruct getFieldStruct(String name) { if (!this.fields.containsKey(name)) return null; return this.fields.get(name); } /** * * @param from original name of the field * @param to new name for field */ public void renameField(String from, String to) { FieldStruct f = this.fields.remove(from); if (f != null) { f.setName(to); this.fields.put(to, f); } } /** * Unlike getField, this returns the value (inner) rather than struct wrapping * the value. * * @param name of the field desired * @return field's "inner" value as an Object */ public Object getFieldAsAny(String name) { Struct st = this.getField(name); if (st == null) return null; if (st instanceof ScalarStruct) return ((ScalarStruct)st).getGenericValue(); if (st instanceof CompositeStruct) return ((CompositeStruct)st).toString(); return null; } /** * If the record has schema, lookup the schema for a given field. * * @param name of the field desired * @return field's schema */ public DataType getFieldType(String name) { // look first at the field value, if it has schema return Struct fs = this.getField(name); if ((fs != null) && (fs.hasExplicitType())) return fs.getType(); // look next at this records schema if (this.explicitType != null) { Field fld = this.explicitType.getField(name); if (fld != null) return fld.getPrimaryType(); } // give up, we don't know the schema return null; } /** * Like getField, except if the field does not exist it will be created and added * to the Record (unless that field name violates the schema). * * @param name of the field desired * @return log of messages from call plus the requested structure */ public FuncResult<Struct> getOrAllocateField(String name) { FuncResult<Struct> fr = new FuncResult<Struct>(); if (!this.fields.containsKey(name)) { Struct value = null; if (this.explicitType != null) { Field fld = this.explicitType.getField(name); if (fld != null) return fld.create(); if (this.explicitType.isAnyRecord()) value = NullStruct.instance; } else value = NullStruct.instance; if (value != null) { FieldStruct f = new FieldStruct(name, value); f.value = value; this.fields.put(name, f); fr.setResult(value); } } else { Struct value = this.getField(name); if (value == null) value = NullStruct.instance; fr.setResult(value); } return fr; } /** * * @param name of field * @return true if field exists */ public boolean hasField(String name) { return this.fields.containsKey(name); } /** * * @param name of field * @return true if field does not exist or if field is string and its value is empty */ public boolean isFieldEmpty(String name) { Struct f = this.getField(name); if (f == null) return true; return f.isEmpty(); } /** * Unlike getField, this returns the value (inner) rather than struct wrapping * the value. * * @param name of the field desired * @return field's "inner" value as Integer (DivConq thinks of integers as 64bit) */ public Long getFieldAsInteger(String name) { return Struct.objectToInteger(this.getField(name)); } public long getFieldAsInteger(String name, long defaultval) { Long x = Struct.objectToInteger(this.getField(name)); if (x == null) return defaultval; return x; } /** * Unlike getField, this returns the value (inner) rather than struct wrapping * the value. * * @param name of the field desired * @return field's "inner" value as BigInteger */ public BigInteger getFieldAsBigInteger(String name) { return Struct.objectToBigInteger(this.getField(name)); } public BigInteger getFieldAsBigInteger(String name, BigInteger defaultval) { BigInteger x = Struct.objectToBigInteger(this.getField(name)); if (x == null) return defaultval; return x; } /** * Unlike getField, this returns the value (inner) rather than struct wrapping * the value. * * @param name of the field desired * @return field's "inner" value as BigDecimal */ public BigDecimal getFieldAsDecimal(String name) { return Struct.objectToDecimal(this.getField(name)); } public BigDecimal getFieldAsDecimal(String name, BigDecimal defaultval) { BigDecimal x = Struct.objectToDecimal(this.getField(name)); if (x == null) return defaultval; return x; } /** * Unlike getField, this returns the value (inner) rather than struct wrapping * the value. * * @param name of the field desired * @return field's "inner" value as Boolean */ public Boolean getFieldAsBoolean(String name) { return Struct.objectToBoolean(this.getField(name)); } public boolean getFieldAsBooleanOrFalse(String name) { Boolean b = Struct.objectToBoolean(this.getField(name)); return (b == null) ? false : b.booleanValue(); } /** * Unlike getField, this returns the value (inner) rather than struct wrapping * the value. * * @param name of the field desired * @return field's "inner" value as DateTime */ public DateTime getFieldAsDateTime(String name) { return Struct.objectToDateTime(this.getField(name)); } /** * Unlike getField, this returns the value (inner) rather than struct wrapping * the value. * * @param name of the field desired * @return field's "inner" value as BigDateTime */ public BigDateTime getFieldAsBigDateTime(String name) { return Struct.objectToBigDateTime(this.getField(name)); } /** * Unlike getField, this returns the value (inner) rather than struct wrapping * the value. * * @param name of the field desired * @return field's "inner" value as Date */ public LocalDate getFieldAsDate(String name) { return Struct.objectToDate(this.getField(name)); } /** * Unlike getField, this returns the value (inner) rather than struct wrapping * the value. * * @param name of the field desired * @return field's "inner" value as Time */ public LocalTime getFieldAsTime(String name) { return Struct.objectToTime(this.getField(name)); } /** * Unlike getField, this returns the value (inner) rather than struct wrapping * the value. * * @param name of the field desired * @return field's "inner" value as a String */ public String getFieldAsString(String name) { return Struct.objectToString(this.getField(name)); } /** * Unlike getField, this returns the value (inner) rather than struct wrapping * the value. * * @param name of the field desired * @return field's "inner" value as Memory */ public Memory getFieldAsBinary(String name) { return Struct.objectToBinary(this.getField(name)); } /** * Unlike getField, this returns the value (inner) rather than struct wrapping * the value. * * @param name of the field desired * @return field's "inner" value as a Record */ public RecordStruct getFieldAsRecord(String name) { return Struct.objectToRecord(this.getField(name)); } /** * Unlike getField, this returns the value (inner) rather than struct wrapping * the value. * * @param name of the field desired * @return field's "inner" value as a List */ public ListStruct getFieldAsList(String name) { return Struct.objectToList(this.getField(name)); } /** * Unlike getField, this returns the value (inner) rather than struct wrapping * the value. * * @param name of the field desired * @return field's "inner" value as CompositeStruct */ public CompositeStruct getFieldAsComposite(String name) { return Struct.objectToComposite(this.getField(name)); } /** * Unlike getField, this returns the value (inner) rather than struct wrapping * the value. * * @param name of the field desired * @return field's "inner" value as Struct */ public Struct getFieldAsStruct(String name) { return Struct.objectToStruct(this.getField(name)); } public <T extends Object> T getFieldAsStruct(String name, Class<T> type) { Struct s = this.getField(name); if (type.isAssignableFrom(s.getClass())) return type.cast(s); return null; } /** * Unlike getField, this returns the value (inner) rather than struct wrapping * the value. * * @param name of the field desired * @return field's "inner" value as Xml (will parse if value is string) */ public XElement getFieldAsXml(String name) { return Struct.objectToXml(this.getField(name)); } /** * * @return number of fields held by this record */ public int getFieldCount() { return this.fields.size(); } /* public String checkRequiredFields(String... fields) { for (String fld : fields) { if (this.isFieldBlank(fld)) return fld; } return null; } public String checkRequiredIfPresentFields(String... fields) { for (String fld : fields) { if (this.hasField(fld) && this.isFieldBlank(fld)) return fld; } return null; } public String checkFieldRange(String... fields) { for (FieldStruct fld : this.getFields()) { boolean fnd = false; for (String fname : fields) { if (fld.getName().equals(fname)) { fnd = true; break; } } if (!fnd) return fld.getName(); } return null; } */ /** * * @param name of field to remove */ public FieldStruct removeField(String name) { return this.fields.remove(name); } public Struct sliceField(String name) { FieldStruct fld = this.fields.get(name); this.fields.remove(name); return fld.sliceValue(); } @Override protected void doCopy(Struct n) { super.doCopy(n); RecordStruct nn = (RecordStruct)n; for (FieldStruct fld : this.fields.values()) nn.setField(fld.deepCopy()); } @Override public Struct deepCopy() { RecordStruct cp = new RecordStruct(); this.doCopy(cp); return cp; } public RecordStruct deepCopyFields(String... include) { RecordStruct cp = new RecordStruct(); super.doCopy(cp); for (String fld : include) { if (this.hasField(fld)) cp.setField(this.fields.get(fld).deepCopy()); } return cp; } public RecordStruct deepCopyExclude(String... exclude) { RecordStruct cp = new RecordStruct(); super.doCopy(cp); for (FieldStruct fld : this.fields.values()) { boolean fnd = false; for (String x : exclude) if (fld.getName().equals(x)) { fnd = true; break; } if (!fnd) cp.setField(fld.deepCopy()); } return cp; } /** * Remove all child fields. */ @Override public void clear() { this.fields.clear(); } @Override public void operation(StackEntry stack, XElement code) { if ("Set".equals(code.getName())) { this.clear(); String json = stack.resolveValueToString(code.getText()); if (StringUtil.isNotEmpty(json)) { RecordStruct pjson = (RecordStruct) CompositeParser.parseJson(" { " + json + " } ").getResult(); this.copyFields(pjson); } stack.resume(); return; } if ("SetField".equals(code.getName())) { String def = stack.stringFromElement(code, "Type"); String name = stack.stringFromElement(code, "Name"); if (StringUtil.isEmpty(name)) { // TODO log stack.resume(); return; } Struct var = null; if (StringUtil.isNotEmpty(def)) var = stack.getActivity().createStruct(def); if (code.hasAttribute("Value")) { Struct var3 = stack.refFromElement(code, "Value"); if (var == null) var = stack.getActivity().createStruct(var3.getType().getId()); if (var instanceof ScalarStruct) ((ScalarStruct) var).adaptValue(var3); else var = var3; } if (var == null) { stack.setState(ExecuteState.Done); OperationContext.get().errorTr(520); stack.resume(); return; } this.setField(name, var); stack.resume(); return; } if ("RemoveField".equals(code.getName())) { String name = stack.stringFromElement(code, "Name"); if (StringUtil.isEmpty(name)) { // TODO log stack.resume(); return; } this.removeField(name); stack.resume(); return; } if ("NewList".equals(code.getName())) { String name = stack.stringFromElement(code, "Name"); if (StringUtil.isEmpty(name)) { // TODO log stack.resume(); return; } this.removeField(name); this.setField(name, new ListStruct()); stack.resume(); return; } if ("NewRecord".equals(code.getName())) { String name = stack.stringFromElement(code, "Name"); if (StringUtil.isEmpty(name)) { // TODO log stack.resume(); return; } this.removeField(name); this.setField(name, new RecordStruct()); stack.resume(); return; } if ("HasField".equals(code.getName())) { String name = stack.stringFromElement(code, "Name"); if (StringUtil.isEmpty(name)) { // TODO log stack.resume(); return; } String handle = stack.stringFromElement(code, "Handle"); if (handle != null) stack.addVariable(handle, new BooleanStruct(this.hasField(name))); stack.resume(); return; } if ("IsFieldEmpty".equals(code.getName())) { String name = stack.stringFromElement(code, "Name"); if (StringUtil.isEmpty(name)) { // TODO log stack.resume(); return; } String handle = stack.stringFromElement(code, "Handle"); if (handle != null) stack.addVariable(handle, new BooleanStruct(this.isFieldEmpty(name))); stack.resume(); return; } super.operation(stack, code); } public void copyFields(RecordStruct src, String... except) { if (src != null) for (FieldStruct fld : src.getFields()) { boolean fnd = false; for (String x : except) if (fld.getName().equals(x)) { fnd = true; break; } if (!fnd) this.setField(fld); } } @Override public Iterable<Struct> getItems() { List<String> tkeys = new ArrayList<String>(); for (String key : this.fields.keySet()) tkeys.add(key); Collections.sort(tkeys); List<Struct> keys = new ArrayList<Struct>(); for (String key : tkeys) keys.add(new StringStruct(key)); return keys; } @Override public IAsyncIterable<Struct> getItemsAsync() { return new ClassicIterableAdapter<Struct>(this.getItems()); } @Override public boolean equals(Object obj) { // TODO go deep if (obj instanceof RecordStruct) { RecordStruct data = (RecordStruct) obj; for (FieldStruct fld : this.fields.values()) { if (!data.hasField(fld.name)) return false; Struct ds = data.getField(fld.name); Struct ts = fld.value; if ((ds == null) && (ts == null)) continue; if ((ds == null) && (ts != null)) return false; if ((ds != null) && (ts == null)) return false; if (!ts.equals(ds)) return false; } // don't need to check match the other way around, we already know matching fields have good values for (FieldStruct fld : data.fields.values()) { if (!this.hasField(fld.name)) return false; } return true; } return super.equals(obj); } @Override public Object getProperty(String name) { Struct v = this.getField(name); if (v == null) return null; if (v instanceof CompositeStruct) return v; return ((ScalarStruct) v).getGenericValue(); } @Override public void setProperty(String name, Object value) { this.setField(name, value); } // TODO generate only on request private transient MetaClass metaClass = null; @Override public void setMetaClass(MetaClass v) { this.metaClass = v; } @Override public MetaClass getMetaClass() { if (this.metaClass == null) this.metaClass = InvokerHelper.getMetaClass(getClass()); return this.metaClass; } @Override public Object invokeMethod(String name, Object arg1) { // is really an object array Object[] args = (Object[])arg1; if (args.length > 0) System.out.println("G2: " + name + " - " + args[0]); else System.out.println("G2: " + name); // TODO Auto-generated method stub return null; } /* @Override public boolean hasMember(String name) { return this.hasField(name); } @Override public Object getMember(String name) { // TODO there is probably a better way... if ("getFieldAsInteger".equals(name)) { return new AbstractJSObject() { @Override public Object call(Object thiz, Object... args) { return RecordStruct.this.getFieldAsInteger((String)args[0]); // TODO saftey } }; } // TODO there is probably a better way... if ("cbTest".equals(name)) { return new AbstractJSObject() { @Override public Object call(Object thiz, Object... args) { System.out.println(args[0]); //ScriptFunction x = null; new Thread(() -> { try { ((ScriptFunction)args[0]).getBoundInvokeHandle(args[0]).invoke(new RecordStruct(new FieldStruct("Data", "atad"))); } catch (Throwable x) { System.out.println("Invoke Error: " + x); x.printStackTrace(); } }).start(); return null; } }; } Struct v = this.getField(name); if (v instanceof CompositeStruct) return v; return ((ScalarStruct) v).getGenericValue(); } @Override public void removeMember(String name) { this.removeField(name); } @Override public void setMember(String name, Object value) { this.setField(name, value); } @Override public Collection<Object> values() { System.out.println("call to values..."); return null; //this.fields.values(); TODO } @Override public Set<String> keySet() { System.out.println("call to keyset..."); return this.fields.keySet(); } @Override public Object call(Object thiz, Object... args) { System.out.println("call to call... " + thiz); return null; //super.call(thiz, args); TODO } @Override public Object eval(String s) { System.out.println("a"); // TODO Auto-generated method stub return null; } @Override public boolean isArray() { System.out.println("b"); // TODO Auto-generated method stub return false; } @Override public boolean isFunction() { System.out.println("c"); // TODO Auto-generated method stub return false; } @Override public Object newObject(Object... args) { System.out.println("d"); // TODO Auto-generated method stub return null; } @Override public String getClassName() { System.out.println("e"); // TODO Auto-generated method stub return null; } @Override public Object getSlot(int arg0) { System.out.println("f"); // TODO Auto-generated method stub return null; } @Override public boolean hasSlot(int arg0) { System.out.println("g"); // TODO Auto-generated method stub return false; } @Override public boolean isInstance(Object arg0) { System.out.println("h"); // TODO Auto-generated method stub return false; } @Override public boolean isInstanceOf(Object arg0) { System.out.println("i"); // TODO Auto-generated method stub return false; } @Override public boolean isStrictFunction() { System.out.println("j"); // TODO Auto-generated method stub return false; } @Override public void setSlot(int arg0, Object arg1) { System.out.println("k"); // TODO Auto-generated method stub } @Override public double toNumber() { System.out.println("l"); // TODO Auto-generated method stub return 0; } */ }
/* * Swift Parallel Scripting Language (http://swift-lang.org) * Code from Java CoG Kit Project (see notice below) with modifications. * * Copyright 2005-2014 University of Chicago * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // ---------------------------------------------------------------------- // This code is developed as part of the Java CoG Kit project // The terms of the license can be found at http://www.cogkit.org/license // This message may not be removed or altered. // ---------------------------------------------------------------------- /* * Created on Jun 18, 2003 */ package org.globus.cog.karajan.util; import java.util.HashMap; import java.util.Map; import org.globus.cog.abstraction.impl.common.task.ServiceContactImpl; import org.globus.cog.abstraction.impl.common.task.ServiceImpl; import org.globus.cog.abstraction.interfaces.Service; import org.globus.cog.abstraction.interfaces.ServiceContact; import org.globus.cog.abstraction.interfaces.TaskHandler; /** * This class sub-classes {@link Contact} and adds concrete * contact information, such as a {@link #getHost host} and * a set of {@link #getServices services}. * * @author Mihael Hategan * */ public class BoundContact extends Contact { private Map<TypeProviderPair,Service> services; private String name; private int cpus; private int activeTasks; private Map<String, Object> properties; public static final BoundContact LOCALHOST = new Localhost(); public BoundContact() { super(); services = new HashMap<TypeProviderPair, Service>(); cpus = 1; } public BoundContact(String name) { this(); this.name = name; } public void setName(String name) { this.name = name; } public String getName() { return name; } public void addService(Service sc) { services.put(new TypeProviderPair(sc.getType(), sc.getProvider()), sc); TypeProviderPair first = new TypeProviderPair(sc.getType(), null); if (!services.containsKey(first)) { services.put(first, sc); } if (getName() == null) { if (sc.getServiceContact().getHost() != null) { setName(sc.getServiceContact().getHost()); } } } public void removeService(int type, String provider) { services.remove(new TypeProviderPair(type, provider)); } public boolean hasService(int type, String provider) { return services.containsKey(new TypeProviderPair(type, provider)); } public boolean hasService(TaskHandlerWrapper handler) { return hasService(getServiceType(handler.getType()), handler.getProvider()); } public Service getService(int type, String provider) { return services.get(new TypeProviderPair(type, provider)); } public Service getService(TaskHandlerWrapper handler) { return getService(getServiceType(handler.getType()), handler.getProvider()); } public Service findService(int type) { Service found = null; for (Map.Entry<TypeProviderPair, Service> e : services.entrySet()) { if (e.getKey().type == type) { if (found != null) { throw new IllegalStateException("More than one service of type " + type + " exists for host '" + this.getName() + "'"); } found = e.getValue(); } } return found; } public static int getServiceType(int handlerType) { if (handlerType == TaskHandler.EXECUTION) { return Service.EXECUTION; } else if (handlerType == TaskHandler.FILE_TRANSFER) { return Service.FILE_OPERATION; } else if (handlerType == TaskHandler.FILE_OPERATION) { return Service.FILE_OPERATION; } else { throw new RuntimeException("Unknown handler type: " + handlerType); } } public static int getServiceType(String type) { if (type == null) { return Service.EXECUTION; } if (type.equalsIgnoreCase("execution") || type.equalsIgnoreCase("job-submission")) { return Service.EXECUTION; } if (type.equalsIgnoreCase("file")) { return Service.FILE_OPERATION; } return Service.EXECUTION; } public Map<TypeProviderPair, Service> getServices() { return services; } public int getCpus() { return this.cpus; } public void setCpus(int cpus) { this.cpus = cpus; } public boolean isVirtual() { return false; } public int getActiveTasks() { return activeTasks; } public void setActiveTasks(int activeTasks) { this.activeTasks = activeTasks; } public String toString() { return name; } public boolean equals(Object obj) { if (obj instanceof BoundContact) { BoundContact bc = (BoundContact) obj; if (name == null) { return bc.getName() == null; } return name.equals(bc.getName()); } return false; } public int hashCode() { if (name != null) { return name.hashCode(); } else { return System.identityHashCode(this); } } public static class TypeProviderPair { public final int type; public final String provider; public TypeProviderPair(int type, String provider) { this.type = type; this.provider = provider; } public boolean equals(Object obj) { if (obj instanceof TypeProviderPair) { TypeProviderPair other = (TypeProviderPair) obj; if (type != other.type) { return false; } if (provider == null) { return other.provider == null; } return provider.equals(other.provider); } return false; } public int hashCode() { return (provider == null ? 0 : provider.hashCode()); } public String toString() { return type + ":" + provider; } } public static class Localhost extends BoundContact { public static final ServiceContact LOCALHOST = new ServiceContactImpl("localhost"); private final Service fileService = new ServiceImpl("local", new ServiceContactImpl("localhost"), null); private final Service transferService = new ServiceImpl("local", new ServiceContactImpl( "localhost"), null); private final Service executionService = new ServiceImpl("local", new ServiceContactImpl( "localhost"), null); public Localhost() { fileService.setType(Service.FILE_OPERATION); transferService.setType(Service.FILE_TRANSFER); executionService.setType(Service.EXECUTION); addService(fileService); addService(transferService); addService(executionService); //TODO A better way to avoid this being equal to a host who happens //to have the same name should be implemented setName("_localhost"); } public Service getService(int type, String provider) { if (type == Service.FILE_OPERATION || type == Service.FILE_TRANSFER || type == Service.EXECUTION) { return new ServiceImpl(provider, LOCALHOST, null); } else { return super.getService(type, provider); } } } public Map<String, Object> getProperties() { return properties; } public void setProperties(Map<String,Object> properties) { this.properties = properties; } public boolean hasProperty(String name) { return properties != null && properties.containsKey(name); } public Object getProperty(String name) { if (properties == null) { return null; } else { return properties.get(name); } } public void setProperty(String name, Object value) { if (properties == null) { properties = new HashMap<String, Object>(); } properties.put(name, value); } }
/* * Copyright 2014-2018 Groupon, Inc * Copyright 2014-2018 The Billing Project, LLC * * The Billing Project licenses this file to you under the Apache License, version 2.0 * (the "License"); you may not use this file except in compliance with the * License. You may obtain a copy of the License at: * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package org.killbill.billing.beatrix.integration; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; import java.util.UUID; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.IllegalInstantException; import org.joda.time.LocalDate; import org.killbill.billing.account.api.Account; import org.killbill.billing.account.api.AccountData; import org.killbill.billing.api.TestApiListener.NextEvent; import org.killbill.billing.beatrix.util.InvoiceChecker.ExpectedInvoiceItemCheck; import org.killbill.billing.catalog.api.BillingPeriod; import org.killbill.billing.catalog.api.Currency; import org.killbill.billing.catalog.api.PlanPhaseSpecifier; import org.killbill.billing.catalog.api.ProductCategory; import org.killbill.billing.entitlement.api.DefaultEntitlement; import org.killbill.billing.entitlement.api.DefaultEntitlementSpecifier; import org.killbill.billing.entitlement.api.Entitlement; import org.killbill.billing.entitlement.api.SubscriptionEventType; import org.killbill.billing.invoice.api.DryRunType; import org.killbill.billing.invoice.api.Invoice; import org.killbill.billing.invoice.api.InvoiceItemType; import org.killbill.billing.mock.MockAccountBuilder; import org.killbill.billing.payment.api.PluginProperty; import org.testng.Assert; import org.testng.annotations.Test; import com.google.common.collect.ImmutableList; import static org.testng.Assert.assertEquals; public class TestWithTimeZones extends TestIntegrationBase { // Verify that recurring invoice items are correctly computed although we went through and out of daylight saving transitions @Test(groups = "slow") public void testWithDayLightSaving() throws Exception { // Start with a date in daylight saving period and make sure we use a time of 8 hour so that we we reach standard time // the next month where the difference is 9 hours, a transformation from DateTime to LocalDate with the account time zone would bring us a day earlier clock.setTime(new DateTime("2015-09-01T08:01:01.000Z")); final DateTimeZone tz = DateTimeZone.forID("America/Juneau"); final AccountData accountData = new MockAccountBuilder().name(UUID.randomUUID().toString().substring(1, 8)) .firstNameLength(6) .email(UUID.randomUUID().toString().substring(1, 8)) .phone(UUID.randomUUID().toString().substring(1, 8)) .migrated(false) .externalKey(UUID.randomUUID().toString().substring(1, 8)) .billingCycleDayLocal(1) .currency(Currency.USD) .paymentMethodId(UUID.randomUUID()) .referenceTime(clock.getUTCNow()) .timeZone(tz) .build(); final Account account = createAccountWithNonOsgiPaymentMethod(accountData); accountChecker.checkAccount(account.getId(), accountData, callContext); final List<ExpectedInvoiceItemCheck> expectedInvoices = new ArrayList<ExpectedInvoiceItemCheck>(); final TestDryRunArguments dryRun = new TestDryRunArguments(DryRunType.SUBSCRIPTION_ACTION, "Shotgun", ProductCategory.BASE, BillingPeriod.MONTHLY, null, null, SubscriptionEventType.START_BILLING, null, null, null, null); final Invoice dryRunInvoice = invoiceUserApi.triggerDryRunInvoiceGeneration(account.getId(), clock.getUTCToday(), dryRun, callContext); expectedInvoices.add(new ExpectedInvoiceItemCheck(new LocalDate(2015, 9, 1), null, InvoiceItemType.FIXED, new BigDecimal("0"))); invoiceChecker.checkInvoiceNoAudits(dryRunInvoice, expectedInvoices); final DefaultEntitlement bpSubscription = createBaseEntitlementAndCheckForCompletion(account.getId(), "bundleKey", "Shotgun", ProductCategory.BASE, BillingPeriod.MONTHLY, NextEvent.CREATE, NextEvent.BLOCK, NextEvent.INVOICE); // Check bundle after BP got created otherwise we get an error from auditApi. subscriptionChecker.checkSubscriptionCreated(bpSubscription.getId(), internalCallContext); invoiceChecker.checkInvoice(account.getId(), 1, callContext, expectedInvoices); expectedInvoices.clear(); busHandler.pushExpectedEvents(NextEvent.PHASE, NextEvent.INVOICE, NextEvent.PAYMENT, NextEvent.INVOICE_PAYMENT); clock.addDays(30); assertListenerStatus(); invoiceChecker.checkInvoice(account.getId(), 2, callContext, new ExpectedInvoiceItemCheck(new LocalDate(2015, 10, 1), new LocalDate(2015, 11, 1), InvoiceItemType.RECURRING, new BigDecimal("249.95"))); LocalDate startDate = new LocalDate(2015, 11, 1); // We loop 18 times to go over a year and transitions several times between winter and summer (daylight saving) for (int i = 0; i < 18; i++) { final LocalDate endDate = startDate.plusMonths(1); busHandler.pushExpectedEvents(NextEvent.INVOICE, NextEvent.PAYMENT, NextEvent.INVOICE_PAYMENT); clock.addMonths(1); assertListenerStatus(); invoiceChecker.checkInvoice(account.getId(), i + 3, callContext, new ExpectedInvoiceItemCheck(startDate, endDate, InvoiceItemType.RECURRING, new BigDecimal("249.95"))); startDate = endDate; } } // Verify cancellation logic when we exit daylight saving period @Test(groups = "slow") public void testCancellationFrom_PDT_to_PST() throws Exception { // Start with a date in daylight saving period (PDT) and make sure we use a time of 7 hour so that we we reach standard time (PST) // the next month where the difference is 8 hours, a transformation from DateTime to LocalDate with the account time zone would bring us a day earlier // (e.g new LocalDate("2015-12-01T07:01:01.000Z", tz) -> "2015-11-30. clock.setTime(new DateTime("2015-11-01T07:01:01.000Z")); final DateTimeZone tz = DateTimeZone.forID("America/Los_Angeles"); final AccountData accountData = new MockAccountBuilder().name(UUID.randomUUID().toString().substring(1, 8)) .firstNameLength(6) .email(UUID.randomUUID().toString().substring(1, 8)) .phone(UUID.randomUUID().toString().substring(1, 8)) .migrated(false) .externalKey(UUID.randomUUID().toString().substring(1, 8)) .billingCycleDayLocal(1) .currency(Currency.USD) .paymentMethodId(UUID.randomUUID()) .referenceTime(clock.getUTCNow()) .timeZone(tz) .build(); final Account account = createAccountWithNonOsgiPaymentMethod(accountData); accountChecker.checkAccount(account.getId(), accountData, callContext); busHandler.pushExpectedEvents(NextEvent.CREATE, NextEvent.BLOCK, NextEvent.INVOICE, NextEvent.PAYMENT, NextEvent.INVOICE_PAYMENT); final PlanPhaseSpecifier spec = new PlanPhaseSpecifier("Blowdart", BillingPeriod.MONTHLY, "notrial", null); UUID entitlementId = entitlementApi.createBaseEntitlement(account.getId(), new DefaultEntitlementSpecifier(spec), "Something", null, null, false, true, ImmutableList.<PluginProperty>of(), callContext); assertListenerStatus(); Entitlement entitlement = entitlementApi.getEntitlementForId(entitlementId, callContext); // Cancel the next month specifying just a LocalDate final LocalDate cancellationDate = new LocalDate("2015-12-01", tz); entitlement = entitlement.cancelEntitlementWithDate(cancellationDate, true, ImmutableList.<PluginProperty>of(), callContext); assertListenerStatus(); // Verify first entitlement is correctly cancelled on the right date Assert.assertEquals(entitlement.getEffectiveEndDate(), cancellationDate); // We now move the clock to the date of the cancellation, which match the cancellation day from the client point of view busHandler.pushExpectedEvents(NextEvent.NULL_INVOICE, NextEvent.CANCEL, NextEvent.BLOCK, NextEvent.NULL_INVOICE); clock.setTime(new DateTime("2015-12-01T07:01:02Z")); assertListenerStatus(); // Verify second that there was no repair (so the cancellation did correctly happen on the "2015-12-01") final List<Invoice> invoices = invoiceUserApi.getInvoicesByAccount(account.getId(), false, false, callContext); Assert.assertEquals(invoices.size(), 1); } // Same test as previous test but this time going from PST -> PDT (somehow not too interesting in that direction because we start with // an offset of 8 hours and then go through 7 hours so anyway we would stay in the same day. @Test(groups = "slow") public void testCancellationFrom_PST_to_PDT() throws Exception { clock.setTime(new DateTime("2015-02-01T08:01:01.000Z")); final DateTimeZone tz = DateTimeZone.forID("America/Los_Angeles"); final AccountData accountData = new MockAccountBuilder().name(UUID.randomUUID().toString().substring(1, 8)) .firstNameLength(6) .email(UUID.randomUUID().toString().substring(1, 8)) .phone(UUID.randomUUID().toString().substring(1, 8)) .migrated(false) .externalKey(UUID.randomUUID().toString().substring(1, 8)) .billingCycleDayLocal(1) .currency(Currency.USD) .paymentMethodId(UUID.randomUUID()) .referenceTime(clock.getUTCNow()) .timeZone(tz) .build(); final Account account = createAccountWithNonOsgiPaymentMethod(accountData); accountChecker.checkAccount(account.getId(), accountData, callContext); busHandler.pushExpectedEvents(NextEvent.CREATE, NextEvent.BLOCK, NextEvent.INVOICE, NextEvent.PAYMENT, NextEvent.INVOICE_PAYMENT); final PlanPhaseSpecifier spec = new PlanPhaseSpecifier("Blowdart", BillingPeriod.MONTHLY, "notrial", null); UUID entitlementId = entitlementApi.createBaseEntitlement(account.getId(), new DefaultEntitlementSpecifier(spec), "Something", null, null, false, true, ImmutableList.<PluginProperty>of(), callContext); assertListenerStatus(); Entitlement entitlement = entitlementApi.getEntitlementForId(entitlementId, callContext); // Cancel the next month specifying just a LocalDate final LocalDate cancellationDate = new LocalDate("2015-03-01", tz); entitlement = entitlement.cancelEntitlementWithDate(cancellationDate, true, ImmutableList.<PluginProperty>of(), callContext); // Verify first entitlement is correctly cancelled on the right date Assert.assertEquals(entitlement.getEffectiveEndDate(), cancellationDate); // We now move the clock to the date of the cancellation which match the cancellation day from the client point of view busHandler.pushExpectedEvents(NextEvent.CANCEL, NextEvent.BLOCK, NextEvent.NULL_INVOICE, NextEvent.NULL_INVOICE); clock.setTime(new DateTime("2015-03-01T08:01:02")); assertListenerStatus(); // Verify second that there was no repair (so the cancellation did correctly happen on the "2015-12-01" final List<Invoice> invoices = invoiceUserApi.getInvoicesByAccount(account.getId(), false, false, callContext); Assert.assertEquals(invoices.size(), 1); } @Test(groups = "slow") public void testReferenceTimeInDSTGap() throws Exception { final DateTimeZone tz = DateTimeZone.forID("America/Los_Angeles"); clock.setTime(new DateTime(2015, 3, 7, 2, 0, 0, tz)); final AccountData accountData = new MockAccountBuilder().currency(Currency.USD) .referenceTime(clock.getUTCNow()) .timeZone(tz) .build(); final Account account = createAccountWithNonOsgiPaymentMethod(accountData); accountChecker.checkAccount(account.getId(), accountData, callContext); Assert.assertEquals(account.getTimeZone(), tz); Assert.assertEquals(account.getFixedOffsetTimeZone(), DateTimeZone.forOffsetHours(-8)); // Note the gap: 2015-03-07T02:00:00.000-08:00 to 2015-03-08T03:00:00.000-07:00 clock.addDays(1); try { // See TimeAwareContext#toUTCDateTime (which uses account.getFixedOffsetTimeZone() instead) new DateTime(clock.getUTCToday().getYear(), clock.getUTCToday().getMonthOfYear(), clock.getUTCToday().getDayOfMonth(), account.getReferenceTime().toDateTime(tz).getHourOfDay(), account.getReferenceTime().toDateTime(tz).getMinuteOfHour(), account.getReferenceTime().toDateTime(tz).getSecondOfMinute(), account.getTimeZone()); Assert.fail(); } catch (final IllegalInstantException e) { // Illegal instant due to time zone offset transition (daylight savings time 'gap'): 2015-03-08T10:00:00.000 (America/Los_Angeles) } busHandler.pushExpectedEvents(NextEvent.CREATE, NextEvent.BLOCK, NextEvent.INVOICE, NextEvent.PAYMENT, NextEvent.INVOICE_PAYMENT); final PlanPhaseSpecifier spec = new PlanPhaseSpecifier("Blowdart", BillingPeriod.MONTHLY, "notrial", null); // Pass a date of today, to trigger TimeAwareContext#toUTCDateTime final UUID entitlementId = entitlementApi.createBaseEntitlement(account.getId(), new DefaultEntitlementSpecifier(spec), "Something", clock.getUTCToday(), clock.getUTCToday(), false, true, ImmutableList.<PluginProperty>of(), callContext); assertListenerStatus(); final Entitlement entitlement = entitlementApi.getEntitlementForId(entitlementId, callContext); Assert.assertEquals(entitlement.getEffectiveStartDate().compareTo(new LocalDate("2015-03-08")), 0); Assert.assertEquals(((DefaultEntitlement) entitlement).getBasePlanSubscriptionBase().getStartDate().compareTo(new DateTime("2015-03-08T02:00:00.000-08:00")), 0); invoiceChecker.checkChargedThroughDate(entitlement.getId(), new LocalDate("2015-04-08"), callContext); busHandler.pushExpectedEvents(NextEvent.INVOICE, NextEvent.PAYMENT, NextEvent.INVOICE_PAYMENT); clock.addDays(31); assertListenerStatus(); invoiceChecker.checkChargedThroughDate(entitlement.getId(), new LocalDate("2015-05-08"), callContext); for (int i = 0; i < 25 ; i++) { busHandler.pushExpectedEvents(NextEvent.INVOICE, NextEvent.PAYMENT, NextEvent.INVOICE_PAYMENT); clock.addMonths(1); assertListenerStatus(); invoiceChecker.checkChargedThroughDate(entitlement.getId(), new LocalDate("2015-03-08").plusMonths(3 + i), callContext); } } @Test(groups = "slow") public void testIntoDaylightSavingTransition() throws Exception { // Daylight saving happened on March 12th. // // Because we use 30 days trial, we start a bit before and that way we can check that computation of BCD crossing into daylight saving works as expected. // final DateTimeZone tz = DateTimeZone.forID("America/Los_Angeles"); clock.setTime(new DateTime(2017, 3, 1, 23, 30, 0, tz)); final AccountData accountData = new MockAccountBuilder().currency(Currency.USD) .referenceTime(clock.getUTCNow()) .timeZone(tz) .build(); // Create account with non BCD to force junction BCD logic to activate final Account account = createAccountWithNonOsgiPaymentMethod(accountData); createBaseEntitlementAndCheckForCompletion(account.getId(), "bundleKey", "Pistol", ProductCategory.BASE, BillingPeriod.MONTHLY, NextEvent.CREATE, NextEvent.BLOCK, NextEvent.INVOICE); final Account accountWithBCD = accountUserApi.getAccountById(account.getId(), callContext); assertEquals(accountWithBCD.getBillCycleDayLocal().intValue(), 31); busHandler.pushExpectedEvents(NextEvent.PHASE, NextEvent.INVOICE, NextEvent.PAYMENT, NextEvent.INVOICE_PAYMENT); clock.addDays(30); assertListenerStatus(); final List<ExpectedInvoiceItemCheck> expectedInvoices = new ArrayList<ExpectedInvoiceItemCheck>(); expectedInvoices.add(new ExpectedInvoiceItemCheck(new LocalDate(2017, 3, 31), new LocalDate(2017, 4, 30), InvoiceItemType.RECURRING, new BigDecimal("29.95"))); invoiceChecker.checkInvoice(account.getId(), 2, callContext, expectedInvoices); expectedInvoices.clear(); } @Test(groups = "slow") public void testIntoDaylightSavingTransition2() throws Exception { // // Nov 6th Transition date from DST -> ST // // Because we use 30 days trial, we start a bit before and that way we can check that computation of BCD crossing into daylight saving works as expected. // final DateTimeZone tz = DateTimeZone.forID("America/Los_Angeles"); clock.setTime(new DateTime(2016, 11, 5, 23, 30, 0, tz)); final AccountData accountData = new MockAccountBuilder().currency(Currency.USD) .referenceTime(clock.getUTCNow()) .timeZone(tz) .build(); // Create account with non BCD to force junction BCD logic to activate final Account account = createAccountWithNonOsgiPaymentMethod(accountData); clock.setTime(new DateTime(2017, 3, 1, 23, 30, 0, tz)); createBaseEntitlementAndCheckForCompletion(account.getId(), "bundleKey", "Pistol", ProductCategory.BASE, BillingPeriod.MONTHLY, NextEvent.CREATE, NextEvent.BLOCK, NextEvent.INVOICE); final Account accountWithBCD = accountUserApi.getAccountById(account.getId(), callContext); // // Ok, it's a little bit tricky here: // // Intuitively we would expect a BCD of 31 (same as previous test testIntoDaylightSavingTransition1), however our implementation relies on TimeAwareContext for all TZ // computation. This context stores an offset from UTC which is then used as a reference and because we created an account before Nov 6 (DST), the offest is (-7) // so the result is different than previous test (where offset was -8) // What 's important is the fact that BCD and invoiceDate align in such a way that: // 1. we see no leading pro-ration // 2. Invoice is correctly generated (don't miss it because too early or don't invoice loop) // assertEquals(accountWithBCD.getBillCycleDayLocal().intValue(), 1); busHandler.pushExpectedEvents(NextEvent.PHASE, NextEvent.INVOICE, NextEvent.PAYMENT, NextEvent.INVOICE_PAYMENT); clock.addDays(30); assertListenerStatus(); final List<ExpectedInvoiceItemCheck> expectedInvoices = new ArrayList<ExpectedInvoiceItemCheck>(); expectedInvoices.add(new ExpectedInvoiceItemCheck(new LocalDate(2017, 4, 1), new LocalDate(2017, 5, 1), InvoiceItemType.RECURRING, new BigDecimal("29.95"))); invoiceChecker.checkInvoice(account.getId(), 2, callContext, expectedInvoices); expectedInvoices.clear(); } @Test(groups = "slow") public void testIntoDaylightSavingTransition3() throws Exception { final DateTimeZone tz = DateTimeZone.forID("America/Los_Angeles"); clock.setTime(new DateTime(2017, 3, 1, 23, 30, 0, tz)); final AccountData accountData = new MockAccountBuilder().currency(Currency.USD) .timeZone(tz) .referenceTime(clock.getUTCNow()) .build(); // Create account with non BCD to force junction BCD logic to activate final Account account = createAccountWithNonOsgiPaymentMethod(accountData); final PlanPhaseSpecifier spec = new PlanPhaseSpecifier("pistol-monthly-notrial",null); busHandler.pushExpectedEvents(NextEvent.CREATE, NextEvent.BLOCK, NextEvent.INVOICE, NextEvent.INVOICE_PAYMENT, NextEvent.PAYMENT); entitlementApi.createBaseEntitlement(account.getId(), new DefaultEntitlementSpecifier(spec), "bundleExternalKey", null, null, false, true, ImmutableList.<PluginProperty>of(), callContext); assertListenerStatus(); busHandler.pushExpectedEvents(NextEvent.INVOICE, NextEvent.PAYMENT, NextEvent.INVOICE_PAYMENT); // Technically, we should see the invoice at the end of day in the account timezone, but this is not the case, the invoice comes slightly after (30') // clock.setTime(new DateTime(2017, 4, 1, 23, 59, 0, tz)); // // But this is really not very important as long as invoicing is correct clock.addMonths(1); // Add one hour to hit the notification date of 2017-04-02T07:30:00.000Z clock.addDeltaFromReality(3600 * 1000); assertListenerStatus(); } @Test(groups = "slow") public void testOutOfDaylightSavingTransition1() throws Exception { // Transition out of daylight saving is set for Nov 5 // // Because we use 30 days trial, we start a bit before and that way we can check that computation of BCD crossing out of of daylight saving works as expected. // final DateTimeZone tz = DateTimeZone.forID("America/Los_Angeles"); clock.setTime(new DateTime(2017, 11, 1, 00, 30, 0, tz)); final AccountData accountData = new MockAccountBuilder().currency(Currency.USD) .timeZone(tz) .referenceTime(clock.getUTCNow()) .build(); // Create account with non BCD to force junction BCD logic to activate final Account account = createAccountWithNonOsgiPaymentMethod(accountData); createBaseEntitlementAndCheckForCompletion(account.getId(), "bundleKey", "Pistol", ProductCategory.BASE, BillingPeriod.MONTHLY, NextEvent.CREATE, NextEvent.BLOCK, NextEvent.INVOICE); final Account accountWithBCD = accountUserApi.getAccountById(account.getId(), callContext); assertEquals(accountWithBCD.getBillCycleDayLocal().intValue(), 1); busHandler.pushExpectedEvents(NextEvent.PHASE, NextEvent.INVOICE, NextEvent.PAYMENT, NextEvent.INVOICE_PAYMENT); clock.addDays(30); assertListenerStatus(); final List<ExpectedInvoiceItemCheck> expectedInvoices = new ArrayList<ExpectedInvoiceItemCheck>(); expectedInvoices.add(new ExpectedInvoiceItemCheck(new LocalDate(2017, 12, 1), new LocalDate(2018, 1, 1), InvoiceItemType.RECURRING, new BigDecimal("29.95"))); invoiceChecker.checkInvoice(account.getId(), 2, callContext, expectedInvoices); expectedInvoices.clear(); } }
package de.lalo5.particleeffectlib.util; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import org.bukkit.Bukkit; /** * <b>ReflectionUtils</b> * <p> * This class provides useful methods which makes dealing with reflection much easier, especially when working with Bukkit * <p> * You are welcome to use it, modify it and redistribute it under the following conditions: * <ul> * <li>Don't claim this class as your own * <li>Don't remove this disclaimer * </ul> * <p> * <i>It would be nice if you provide credit to me if you use this class in a published project</i> * * @author DarkBlade12 * @version 1.1 */ @SuppressWarnings({"WeakerAccess", "unused", "ConfusingArgumentToVarargsMethod"}) public final class ReflectionUtils { // Prevent accidental construction private ReflectionUtils() { } /** * Returns the constructor of a given class with the given parameter types * * @param clazz Target class * @param parameterTypes Parameter types of the desired constructor * @return The constructor of the target class with the specified parameter types * @throws NoSuchMethodException If the desired constructor with the specified parameter types cannot be found * @see DataType * @see DataType#getPrimitive(Class[]) * @see DataType#compare(Class[], Class[]) */ public static Constructor<?> getConstructor(Class<?> clazz, Class<?>... parameterTypes) throws NoSuchMethodException { Class<?>[] primitiveTypes = DataType.getPrimitive(parameterTypes); for (Constructor<?> constructor : clazz.getConstructors()) { if (!DataType.compare(DataType.getPrimitive(constructor.getParameterTypes()), primitiveTypes)) { continue; } return constructor; } throw new NoSuchMethodException("There is no such constructor in this class with the specified parameter types"); } /** * Returns the constructor of a desired class with the given parameter types * * @param className Name of the desired target class * @param packageType Package where the desired target class is located * @param parameterTypes Parameter types of the desired constructor * @return The constructor of the desired target class with the specified parameter types * @throws NoSuchMethodException If the desired constructor with the specified parameter types cannot be found * @throws ClassNotFoundException ClassNotFoundException If the desired target class with the specified name and package cannot be found * @see #getConstructor(Class, Class...) */ public static Constructor<?> getConstructor(String className, PackageType packageType, Class<?>... parameterTypes) throws NoSuchMethodException, ClassNotFoundException { return getConstructor(packageType.getClass(className), parameterTypes); } /** * Returns an instance of a class with the given arguments * * @param clazz Target class * @param arguments Arguments which are used to construct an object of the target class * @return The instance of the target class with the specified arguments * @throws InstantiationException If you cannot create an instance of the target class due to certain circumstances * @throws IllegalAccessException If the desired constructor cannot be accessed due to certain circumstances * @throws IllegalArgumentException If the types of the arguments do not match the parameter types of the constructor (this should not occur since it searches for a constructor with the types of the arguments) * @throws InvocationTargetException If the desired constructor cannot be invoked * @throws NoSuchMethodException If the desired constructor with the specified arguments cannot be found */ public static Object instantiateObject(Class<?> clazz, Object... arguments) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException { return getConstructor(clazz, DataType.getPrimitive(arguments)).newInstance(arguments); } /** * Returns an instance of a desired class with the given arguments * * @param className Name of the desired target class * @param packageType Package where the desired target class is located * @param arguments Arguments which are used to construct an object of the desired target class * @return The instance of the desired target class with the specified arguments * @throws InstantiationException If you cannot create an instance of the desired target class due to certain circumstances * @throws IllegalAccessException If the desired constructor cannot be accessed due to certain circumstances * @throws IllegalArgumentException If the types of the arguments do not match the parameter types of the constructor (this should not occur since it searches for a constructor with the types of the arguments) * @throws InvocationTargetException If the desired constructor cannot be invoked * @throws NoSuchMethodException If the desired constructor with the specified arguments cannot be found * @throws ClassNotFoundException If the desired target class with the specified name and package cannot be found * @see #instantiateObject(Class, Object...) */ public static Object instantiateObject(String className, PackageType packageType, Object... arguments) throws InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, ClassNotFoundException { return instantiateObject(packageType.getClass(className), arguments); } /** * Returns a method of a class with the given parameter types * * @param clazz Target class * @param methodName Name of the desired method * @param parameterTypes Parameter types of the desired method * @return The method of the target class with the specified name and parameter types * @throws NoSuchMethodException If the desired method of the target class with the specified name and parameter types cannot be found * @see DataType#getPrimitive(Class[]) * @see DataType#compare(Class[], Class[]) */ public static Method getMethod(Class<?> clazz, String methodName, Class<?>... parameterTypes) throws NoSuchMethodException { Class<?>[] primitiveTypes = DataType.getPrimitive(parameterTypes); for (Method method : clazz.getMethods()) { if (!method.getName().equals(methodName) || !DataType.compare(DataType.getPrimitive(method.getParameterTypes()), primitiveTypes)) { continue; } return method; } throw new NoSuchMethodException("There is no such method in this class with the specified name and parameter types"); } /** * Returns a method of a desired class with the given parameter types * * @param className Name of the desired target class * @param packageType Package where the desired target class is located * @param methodName Name of the desired method * @param parameterTypes Parameter types of the desired method * @return The method of the desired target class with the specified name and parameter types * @throws NoSuchMethodException If the desired method of the desired target class with the specified name and parameter types cannot be found * @throws ClassNotFoundException If the desired target class with the specified name and package cannot be found * @see #getMethod(Class, String, Class...) */ public static Method getMethod(String className, PackageType packageType, String methodName, Class<?>... parameterTypes) throws NoSuchMethodException, ClassNotFoundException { return getMethod(packageType.getClass(className), methodName, parameterTypes); } /** * Invokes a method on an object with the given arguments * * @param instance Target object * @param methodName Name of the desired method * @param arguments Arguments which are used to invoke the desired method * @return The result of invoking the desired method on the target object * @throws IllegalAccessException If the desired method cannot be accessed due to certain circumstances * @throws IllegalArgumentException If the types of the arguments do not match the parameter types of the method (this should not occur since it searches for a method with the types of the arguments) * @throws InvocationTargetException If the desired method cannot be invoked on the target object * @throws NoSuchMethodException If the desired method of the class of the target object with the specified name and arguments cannot be found * @see #getMethod(Class, String, Class...) * @see DataType#getPrimitive(Object[]) */ public static Object invokeMethod(Object instance, String methodName, Object... arguments) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException { return getMethod(instance.getClass(), methodName, DataType.getPrimitive(arguments)).invoke(instance, arguments); } /** * Invokes a method of the target class on an object with the given arguments * * @param instance Target object * @param clazz Target class * @param methodName Name of the desired method * @param arguments Arguments which are used to invoke the desired method * @return The result of invoking the desired method on the target object * @throws IllegalAccessException If the desired method cannot be accessed due to certain circumstances * @throws IllegalArgumentException If the types of the arguments do not match the parameter types of the method (this should not occur since it searches for a method with the types of the arguments) * @throws InvocationTargetException If the desired method cannot be invoked on the target object * @throws NoSuchMethodException If the desired method of the target class with the specified name and arguments cannot be found * @see #getMethod(Class, String, Class...) * @see DataType#getPrimitive(Object[]) */ public static Object invokeMethod(Object instance, Class<?> clazz, String methodName, Object... arguments) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException { return getMethod(clazz, methodName, DataType.getPrimitive(arguments)).invoke(instance, arguments); } /** * Invokes a method of a desired class on an object with the given arguments * * @param instance Target object * @param className Name of the desired target class * @param packageType Package where the desired target class is located * @param methodName Name of the desired method * @param arguments Arguments which are used to invoke the desired method * @return The result of invoking the desired method on the target object * @throws IllegalAccessException If the desired method cannot be accessed due to certain circumstances * @throws IllegalArgumentException If the types of the arguments do not match the parameter types of the method (this should not occur since it searches for a method with the types of the arguments) * @throws InvocationTargetException If the desired method cannot be invoked on the target object * @throws NoSuchMethodException If the desired method of the desired target class with the specified name and arguments cannot be found * @throws ClassNotFoundException If the desired target class with the specified name and package cannot be found * @see #invokeMethod(Object, Class, String, Object...) */ public static Object invokeMethod(Object instance, String className, PackageType packageType, String methodName, Object... arguments) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException, ClassNotFoundException { return invokeMethod(instance, packageType.getClass(className), methodName, arguments); } /** * Returns a field of the target class with the given name * * @param clazz Target class * @param declared Whether the desired field is declared or not * @param fieldName Name of the desired field * @return The field of the target class with the specified name * @throws NoSuchFieldException If the desired field of the given class cannot be found * @throws SecurityException If the desired field cannot be made accessible */ public static Field getField(Class<?> clazz, boolean declared, String fieldName) throws NoSuchFieldException, SecurityException { Field field = declared ? clazz.getDeclaredField(fieldName) : clazz.getField(fieldName); field.setAccessible(true); return field; } /** * Returns a field of a desired class with the given name * * @param className Name of the desired target class * @param packageType Package where the desired target class is located * @param declared Whether the desired field is declared or not * @param fieldName Name of the desired field * @return The field of the desired target class with the specified name * @throws NoSuchFieldException If the desired field of the desired class cannot be found * @throws SecurityException If the desired field cannot be made accessible * @throws ClassNotFoundException If the desired target class with the specified name and package cannot be found * @see #getField(Class, boolean, String) */ public static Field getField(String className, PackageType packageType, boolean declared, String fieldName) throws NoSuchFieldException, SecurityException, ClassNotFoundException { return getField(packageType.getClass(className), declared, fieldName); } /** * Returns the value of a field of the given class of an object * * @param instance Target object * @param clazz Target class * @param declared Whether the desired field is declared or not * @param fieldName Name of the desired field * @return The value of field of the target object * @throws IllegalArgumentException If the target object does not feature the desired field * @throws IllegalAccessException If the desired field cannot be accessed * @throws NoSuchFieldException If the desired field of the target class cannot be found * @throws SecurityException If the desired field cannot be made accessible * @see #getField(Class, boolean, String) */ public static Object getValue(Object instance, Class<?> clazz, boolean declared, String fieldName) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { return getField(clazz, declared, fieldName).get(instance); } /** * Returns the value of a field of a desired class of an object * * @param instance Target object * @param className Name of the desired target class * @param packageType Package where the desired target class is located * @param declared Whether the desired field is declared or not * @param fieldName Name of the desired field * @return The value of field of the target object * @throws IllegalArgumentException If the target object does not feature the desired field * @throws IllegalAccessException If the desired field cannot be accessed * @throws NoSuchFieldException If the desired field of the desired class cannot be found * @throws SecurityException If the desired field cannot be made accessible * @throws ClassNotFoundException If the desired target class with the specified name and package cannot be found * @see #getValue(Object, Class, boolean, String) */ public static Object getValue(Object instance, String className, PackageType packageType, boolean declared, String fieldName) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException, ClassNotFoundException { return getValue(instance, packageType.getClass(className), declared, fieldName); } /** * Returns the value of a field with the given name of an object * * @param instance Target object * @param declared Whether the desired field is declared or not * @param fieldName Name of the desired field * @return The value of field of the target object * @throws IllegalArgumentException If the target object does not feature the desired field (should not occur since it searches for a field with the given name in the class of the object) * @throws IllegalAccessException If the desired field cannot be accessed * @throws NoSuchFieldException If the desired field of the target object cannot be found * @throws SecurityException If the desired field cannot be made accessible * @see #getValue(Object, Class, boolean, String) */ public static Object getValue(Object instance, boolean declared, String fieldName) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { return getValue(instance, instance.getClass(), declared, fieldName); } /** * Sets the value of a field of the given class of an object * * @param instance Target object * @param clazz Target class * @param declared Whether the desired field is declared or not * @param fieldName Name of the desired field * @param value New value * @throws IllegalArgumentException If the type of the value does not match the type of the desired field * @throws IllegalAccessException If the desired field cannot be accessed * @throws NoSuchFieldException If the desired field of the target class cannot be found * @throws SecurityException If the desired field cannot be made accessible * @see #getField(Class, boolean, String) */ public static void setValue(Object instance, Class<?> clazz, boolean declared, String fieldName, Object value) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { getField(clazz, declared, fieldName).set(instance, value); } /** * Sets the value of a field of a desired class of an object * * @param instance Target object * @param className Name of the desired target class * @param packageType Package where the desired target class is located * @param declared Whether the desired field is declared or not * @param fieldName Name of the desired field * @param value New value * @throws IllegalArgumentException If the type of the value does not match the type of the desired field * @throws IllegalAccessException If the desired field cannot be accessed * @throws NoSuchFieldException If the desired field of the desired class cannot be found * @throws SecurityException If the desired field cannot be made accessible * @throws ClassNotFoundException If the desired target class with the specified name and package cannot be found * @see #setValue(Object, Class, boolean, String, Object) */ public static void setValue(Object instance, String className, PackageType packageType, boolean declared, String fieldName, Object value) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException, ClassNotFoundException { setValue(instance, packageType.getClass(className), declared, fieldName, value); } /** * Sets the value of a field with the given name of an object * * @param instance Target object * @param declared Whether the desired field is declared or not * @param fieldName Name of the desired field * @param value New value * @throws IllegalArgumentException If the type of the value does not match the type of the desired field * @throws IllegalAccessException If the desired field cannot be accessed * @throws NoSuchFieldException If the desired field of the target object cannot be found * @throws SecurityException If the desired field cannot be made accessible * @see #setValue(Object, Class, boolean, String, Object) */ public static void setValue(Object instance, boolean declared, String fieldName, Object value) throws IllegalArgumentException, IllegalAccessException, NoSuchFieldException, SecurityException { setValue(instance, instance.getClass(), declared, fieldName, value); } /** * Represents an enumeration of dynamic packages of NMS and CraftBukkit * <p> * This class is part of the <b>ReflectionUtils</b> and follows the same usage conditions * * @author DarkBlade12 * @since 1.0 */ @SuppressWarnings("UnnecessaryEnumModifier") public enum PackageType { MINECRAFT_SERVER("net.minecraft.server." + getServerVersion()), CRAFTBUKKIT("org.bukkit.craftbukkit." + getServerVersion()), CRAFTBUKKIT_BLOCK(CRAFTBUKKIT, "block"), CRAFTBUKKIT_CHUNKIO(CRAFTBUKKIT, "chunkio"), CRAFTBUKKIT_COMMAND(CRAFTBUKKIT, "command"), CRAFTBUKKIT_CONVERSATIONS(CRAFTBUKKIT, "conversations"), CRAFTBUKKIT_ENCHANTMENS(CRAFTBUKKIT, "enchantments"), CRAFTBUKKIT_ENTITY(CRAFTBUKKIT, "entity"), CRAFTBUKKIT_EVENT(CRAFTBUKKIT, "event"), CRAFTBUKKIT_GENERATOR(CRAFTBUKKIT, "generator"), CRAFTBUKKIT_HELP(CRAFTBUKKIT, "help"), CRAFTBUKKIT_INVENTORY(CRAFTBUKKIT, "inventory"), CRAFTBUKKIT_MAP(CRAFTBUKKIT, "map"), CRAFTBUKKIT_METADATA(CRAFTBUKKIT, "metadata"), CRAFTBUKKIT_POTION(CRAFTBUKKIT, "potion"), CRAFTBUKKIT_PROJECTILES(CRAFTBUKKIT, "projectiles"), CRAFTBUKKIT_SCHEDULER(CRAFTBUKKIT, "scheduler"), CRAFTBUKKIT_SCOREBOARD(CRAFTBUKKIT, "scoreboard"), CRAFTBUKKIT_UPDATER(CRAFTBUKKIT, "updater"), CRAFTBUKKIT_UTIL(CRAFTBUKKIT, "util"); private final String path; /** * Construct a new package type * * @param path Path of the package */ private PackageType(String path) { this.path = path; } /** * Construct a new package type * * @param parent Parent package of the package * @param path Path of the package */ private PackageType(PackageType parent, String path) { this(parent + "." + path); } /** * Returns the path of this package type * * @return The path */ public String getPath() { return path; } /** * Returns the class with the given name * * @param className Name of the desired class * @return The class with the specified name * @throws ClassNotFoundException If the desired class with the specified name and package cannot be found */ public Class<?> getClass(String className) throws ClassNotFoundException { return Class.forName(this + "." + className); } // Override for convenience @Override public String toString() { return path; } /** * Returns the version of your server * * @return The server version */ public static String getServerVersion() { return Bukkit.getServer().getClass().getPackage().getName().substring(23); } } /** * Represents an enumeration of Java data types with corresponding classes * <p> * This class is part of the <b>ReflectionUtils</b> and follows the same usage conditions * * @author DarkBlade12 * @since 1.0 */ @SuppressWarnings("UnnecessaryEnumModifier") public enum DataType { BYTE(byte.class, Byte.class), SHORT(short.class, Short.class), INTEGER(int.class, Integer.class), LONG(long.class, Long.class), CHARACTER(char.class, Character.class), FLOAT(float.class, Float.class), DOUBLE(double.class, Double.class), BOOLEAN(boolean.class, Boolean.class); private static final Map<Class<?>, DataType> CLASS_MAP = new HashMap<>(); private final Class<?> primitive; private final Class<?> reference; // Initialize map for quick class lookup static { for (DataType type : values()) { CLASS_MAP.put(type.primitive, type); CLASS_MAP.put(type.reference, type); } } /** * Construct a new data type * * @param primitive Primitive class of this data type * @param reference Reference class of this data type */ private DataType(Class<?> primitive, Class<?> reference) { this.primitive = primitive; this.reference = reference; } /** * Returns the primitive class of this data type * * @return The primitive class */ public Class<?> getPrimitive() { return primitive; } /** * Returns the reference class of this data type * * @return The reference class */ public Class<?> getReference() { return reference; } /** * Returns the data type with the given primitive/reference class * * @param clazz Primitive/Reference class of the data type * @return The data type */ public static DataType fromClass(Class<?> clazz) { return CLASS_MAP.get(clazz); } /** * Returns the primitive class of the data type with the given reference class * * @param clazz Reference class of the data type * @return The primitive class */ public static Class<?> getPrimitive(Class<?> clazz) { DataType type = fromClass(clazz); return type == null ? clazz : type.getPrimitive(); } /** * Returns the reference class of the data type with the given primitive class * * @param clazz Primitive class of the data type * @return The reference class */ public static Class<?> getReference(Class<?> clazz) { DataType type = fromClass(clazz); return type == null ? clazz : type.getReference(); } /** * Returns the primitive class array of the given class array * * @param classes Given class array * @return The primitive class array */ public static Class<?>[] getPrimitive(Class<?>[] classes) { int length = classes == null ? 0 : classes.length; Class<?>[] types = new Class<?>[length]; for (int index = 0; index < length; index++) { types[index] = getPrimitive(classes[index]); } return types; } /** * Returns the reference class array of the given class array * * @param classes Given class array * @return The reference class array */ public static Class<?>[] getReference(Class<?>[] classes) { int length = classes == null ? 0 : classes.length; Class<?>[] types = new Class<?>[length]; for (int index = 0; index < length; index++) { types[index] = getReference(classes[index]); } return types; } /** * Returns the primitive class array of the given object array * * @param objects Given object array * @return The primitive class array */ public static Class<?>[] getPrimitive(Object[] objects) { int length = objects == null ? 0 : objects.length; Class<?>[] types = new Class<?>[length]; for (int index = 0; index < length; index++) { types[index] = getPrimitive(objects[index].getClass()); } return types; } /** * Returns the reference class array of the given object array * * @param objects Given object array * @return The reference class array */ public static Class<?>[] getReference(Object[] objects) { int length = objects == null ? 0 : objects.length; Class<?>[] types = new Class<?>[length]; for (int index = 0; index < length; index++) { types[index] = getReference(objects[index].getClass()); } return types; } /** * Compares two class arrays on equivalence * * @param primary Primary class array * @param secondary Class array which is compared to the primary array * @return Whether these arrays are equal or not */ public static boolean compare(Class<?>[] primary, Class<?>[] secondary) { if (primary == null || secondary == null || primary.length != secondary.length) { return false; } for (int index = 0; index < primary.length; index++) { Class<?> primaryClass = primary[index]; Class<?> secondaryClass = secondary[index]; if (primaryClass.equals(secondaryClass) || primaryClass.isAssignableFrom(secondaryClass)) { continue; } return false; } return true; } } }
/* * Copyright 2000-2016 Vaadin Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.vaadin.server; import java.net.URL; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import com.vaadin.ui.LegacyWindow; import com.vaadin.ui.UI; /** * A special application designed to help migrating applications from Vaadin 6 * to Vaadin 7. The legacy application supports setting a main window, adding * additional browser level windows and defining the theme for the entire * application. * * @deprecated As of 7.0. This class is only intended to ease migration and * should not be used for new projects. * * @since 7.0 */ @Deprecated public abstract class LegacyApplication implements ErrorHandler { private LegacyWindow mainWindow; private String theme = "reindeer"; private final Map<String, LegacyWindow> legacyUINames = new HashMap<>(); private boolean isRunning = true; /** * URL where the user is redirected to on application close, or null if * application is just closed without redirection. */ private String logoutURL = null; private URL url; /** * Sets the main window of this application. Setting window as a main window * of this application also adds the window to this application. * * @param mainWindow * the UI to set as the default window */ public void setMainWindow(LegacyWindow mainWindow) { if (this.mainWindow != null) { throw new IllegalStateException("mainWindow has already been set"); } if (mainWindow.isAttached()) { throw new IllegalStateException( "mainWindow is attached to another application"); } if (UI.getCurrent() == null) { // Assume setting a main window from Application.init if there's // no current UI -> set the main window as the current UI UI.setCurrent(mainWindow); } addWindow(mainWindow); this.mainWindow = mainWindow; } public void doInit(URL url) { this.url = url; VaadinSession.getCurrent().setErrorHandler(this); init(); } protected abstract void init(); /** * Gets the mainWindow of the application. * * <p> * The main window is the window attached to the application URL ( * {@link #getURL()}) and thus which is show by default to the user. * </p> * <p> * Note that each application must have at least one main window. * </p> * * @return the UI used as the default window */ public LegacyWindow getMainWindow() { return mainWindow; } /** * Sets the application's theme. * <p> * The default theme for {@link LegacyApplication} is reindeer, unlike for * {@link UI} the default theme is valo. * <p> * Note that this theme can be overridden for a specific UI with * {@link VaadinSession#getThemeForUI(UI)}. Setting theme to be * <code>null</code> selects the default theme. For the available theme * names, see the contents of the VAADIN/themes directory. * </p> * * @param theme * the new theme for this application. */ public void setTheme(String theme) { this.theme = theme; } /** * Gets the application's theme. The application's theme is the default * theme used by all the uIs for which a theme is not explicitly defined. If * the application theme is not explicitly set, <code>null</code> is * returned. * * @return the name of the application's theme. */ public String getTheme() { return theme; } /** * <p> * Gets a UI by name. Returns <code>null</code> if the application is not * running or it does not contain a window corresponding to the name. * </p> * * @param name * the name of the requested window * @return a UI corresponding to the name, or <code>null</code> to use the * default window */ public LegacyWindow getWindow(String name) { return legacyUINames.get(name); } /** * Counter to get unique names for windows with no explicit name */ private int namelessUIIndex = 0; /** * Adds a new browser level window to this application. * * @param uI * the UI window to add to the application */ public void addWindow(LegacyWindow uI) { if (uI.getName() == null) { String name = Integer.toString(namelessUIIndex++); uI.setName(name); } uI.setApplication(this); legacyUINames.put(uI.getName(), uI); uI.setSession(VaadinSession.getCurrent()); } /** * Removes the specified window from the application. This also removes all * name mappings for the window (see {@link #addWindow(LegacyWindow)} and * #getWindowName(UI)}. * * <p> * Note that removing window from the application does not close the browser * window - the window is only removed from the server-side. * </p> * * @param uI * the UI to remove */ public void removeWindow(LegacyWindow uI) { for (Entry<String, LegacyWindow> entry : legacyUINames.entrySet()) { if (entry.getValue() == uI) { legacyUINames.remove(entry.getKey()); } } } /** * Gets the set of windows contained by the application. * * <p> * Note that the returned set of windows can not be modified. * </p> * * @return the unmodifiable collection of windows. */ public Collection<LegacyWindow> getWindows() { return Collections.unmodifiableCollection(legacyUINames.values()); } @Override public void error(ErrorEvent event) { DefaultErrorHandler.doDefault(event); } public VaadinSession getContext() { return VaadinSession.getCurrent(); } public void close() { isRunning = false; Collection<LegacyWindow> windows = getWindows(); for (LegacyWindow legacyWindow : windows) { String logoutUrl = getLogoutURL(); if (logoutUrl == null) { URL url = getURL(); if (url != null) { logoutUrl = url.toString(); } } if (logoutUrl != null) { legacyWindow.getPage().setLocation(logoutUrl); } legacyWindow.close(); } } public boolean isRunning() { return isRunning; } public URL getURL() { return url; } /** * Returns the URL user is redirected to on application close. If the URL is * <code>null</code>, the application is closed normally as defined by the * application running environment. * <p> * Desktop application just closes the application window and * web-application redirects the browser to application main URL. * </p> * * @return the URL. */ public String getLogoutURL() { return logoutURL; } /** * Sets the URL user is redirected to on application close. If the URL is * <code>null</code>, the application is closed normally as defined by the * application running environment: Desktop application just closes the * application window and web-application redirects the browser to * application main URL. * * @param logoutURL * the logoutURL to set. */ public void setLogoutURL(String logoutURL) { this.logoutURL = logoutURL; } }
/* * Copyright 2007 Macquarie E-Learning Centre Of Excellence * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.fcrepo.server.security.xacml.pdp.data; import java.io.File; import java.net.URISyntaxException; import java.util.HashMap; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import org.fcrepo.server.security.xacml.pdp.finder.policy.PolicyReader; import org.fcrepo.server.security.xacml.util.AttributeBean; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.sleepycat.dbxml.XmlDocument; import com.sleepycat.dbxml.XmlDocumentConfig; import com.sleepycat.dbxml.XmlException; import com.sleepycat.dbxml.XmlQueryContext; import com.sleepycat.dbxml.XmlQueryExpression; import com.sleepycat.dbxml.XmlResults; import com.sleepycat.dbxml.XmlValue; import com.sun.xacml.AbstractPolicy; import com.sun.xacml.EvaluationCtx; import com.sun.xacml.ParsingException; import com.sun.xacml.finder.PolicyFinder; /** * Encapsulates indexed access to policies stored in DbXml. * * See DbXmlPolicyStore for CRUD operations on policies in DbXml. * * @author Stephen Bayliss * @version $Id$ */ public class DbXmlPolicyIndex extends XPathPolicyIndex implements PolicyIndex { private static final Logger log = LoggerFactory.getLogger(DbXmlPolicyIndex.class.getName()); private String m_databaseDirectory = null; private String m_container = null; private DbXmlManager m_dbXmlManager = null; private volatile long m_lastUpdate; private PolicyUtils m_utils; private Map<String, XmlQueryExpression> m_queries = null; public DbXmlPolicyIndex(PolicyReader policyReader) throws PolicyIndexException { super(policyReader); } public void setDatabaseDirectory(String databaseDirectory) { m_databaseDirectory = databaseDirectory; } public void setContainer(String container) { m_container = container; } public void init() throws PolicyIndexException { try { m_dbXmlManager = new DbXmlManager(m_databaseDirectory, m_container); m_dbXmlManager.indexMap = this.indexMap; } catch (PolicyStoreException pse) { throw new PolicyIndexException(pse.getMessage(),pse); } m_queries = new ConcurrentHashMap<String, XmlQueryExpression>(); m_utils = new PolicyUtils(); } public void close() { m_dbXmlManager.close(); m_queries.clear(); } /* * (non-Javadoc) * @seemelcoe.xacml.pdp.data.PolicyDataManager#getPolicies(com.sun.xacml. * EvaluationCtx) */ @Override public Map<String, AbstractPolicy> getPolicies(EvaluationCtx eval, PolicyFinder policyFinder) throws PolicyIndexException { long a = 0; long b = 0; long total = 0; Map<String, AbstractPolicy> documents = new HashMap<String, AbstractPolicy>(); XmlQueryExpression qe = null; XmlQueryContext context = null; try { // Get the query (query gets prepared if necesary) a = System.nanoTime(); Map<String, Set<AttributeBean>> attributeMap = getAttributeMap(eval); context = m_dbXmlManager.manager.createQueryContext(); context.setDefaultCollection(m_dbXmlManager.CONTAINER); for (String prefix : namespaces.keySet()) { context.setNamespace(prefix, namespaces.get(prefix)); } // not clear why this is needed.... but it is used in hashing the queries int resourceComponentCount = 0; Map<String, String> variables = getXpathVariables(attributeMap); for (String variable : variables.keySet()) { context.setVariableValue(variable, new XmlValue(variables.get(variable))); if (variable.equals(XACML_RESOURCE_ID)) { resourceComponentCount++; } } qe = getQuery(attributeMap, context, resourceComponentCount); } catch (XmlException xe) { throw new PolicyIndexException("Error while constructing query", xe); } catch (URISyntaxException e) { throw new PolicyIndexException("Error while constructing query", e); } DbXmlManager.readLock.lock(); try { b = System.nanoTime(); total += b - a; if (log.isDebugEnabled()) { log.debug("Query prep. time: " + (b - a) + "ns"); } // execute the query a = System.nanoTime(); XmlResults results = qe.execute(context); b = System.nanoTime(); total += b - a; if (log.isDebugEnabled()) { log.debug("Query exec. time: " + (b - a) + "ns"); } // process results while (results.hasNext()) { XmlValue value = results.next(); byte[] content = value.asDocument().getContent(); if (content.length > 0) { documents.put(value.asDocument().getName(), handleDocument(m_policyReader.readPolicy(content),policyFinder)); } else { throw new PolicyIndexException("Zero-length result found"); } } results.delete(); } catch (XmlException xe) { log.error("Error getting query results." + xe.getMessage()); throw new PolicyIndexException("Error getting query results." + xe.getMessage(), xe); } catch (ParsingException pe) { log.error("Error getting query results." + pe.getMessage()); throw new PolicyIndexException("Error getting query results." + pe.getMessage(), pe); } finally { DbXmlManager.readLock.unlock(); } if (log.isDebugEnabled()) { log.debug("Total exec. time: " + total + "ns"); } return documents; } /** * Either returns a query that has previously been generated, or generates a * new one if it has not. * * @param attributeMap * the Map of attributes, type and values upon which this query is * based * @param context * the context for the query * @return an XmlQueryExpression that can be executed * @throws XmlException * @throws XmlException * @throws PolicyIndexException */ private XmlQueryExpression getQuery(Map<String, Set<AttributeBean>> attributeMap, XmlQueryContext context, int r) throws XmlException { // The dimensions for this query. StringBuilder sb = new StringBuilder(); for (Set<AttributeBean> attributeBeans : attributeMap.values()) { sb.append(attributeBeans.size() + ":"); for (AttributeBean bean : attributeBeans) { sb.append(bean.getValues().size() + "-"); } } // If a query of these dimensions already exists, then just return it. String hash = sb.toString() + r; XmlQueryExpression result = m_queries.get(hash); if (result != null) { return result; } // We do not have a query of those dimensions. We must make one. String query = createQuery(attributeMap); if (log.isDebugEnabled()) { log.debug("Query [" + hash + "]:\n" + query); } // Once we have created a query, we can parse it and store the // execution plan. This is an expensive operation that we do // not want to have to do more than once for each dimension result = m_dbXmlManager.manager.prepare(query, context); m_queries.put(hash, result); return result; } /** * Given a set of attributes this method generates a DBXML XPath query based * on those attributes to extract a subset of policies from the database. * * @param attributeMap * the Map of Attributes from which to generate the query * @param r * the number of components in the resource id * @return the query as a String */ private String createQuery(Map<String, Set<AttributeBean>> attributeMap) { return "collection('" + m_dbXmlManager.CONTAINER + "')" + getXpath(attributeMap); } /* * (non-Javadoc) * @see * org.fcrepo.server.security.xacml.pdp.data.PolicyDataManager#addPolicy * (java.lang.String, java.lang.String) */ @Override public String addPolicy(String name, String document) throws PolicyIndexException { String docName = null; DbXmlManager.writeLock.lock(); try { XmlDocument doc = makeDocument(name, document); docName = doc.getName(); log.debug("Adding document: " + docName); m_dbXmlManager.container.putDocument(doc, m_dbXmlManager.updateContext); setLastUpdate(System.currentTimeMillis()); } catch (XmlException xe) { if (xe.getErrorCode() == XmlException.UNIQUE_ERROR) { throw new PolicyIndexException("Document already exists: " + docName); } else { throw new PolicyIndexException("Error adding policy: " + xe.getMessage(), xe); } } finally { DbXmlManager.writeLock.unlock(); } return docName; } /* * (non-Javadoc) * @see * org.fcrepo.server.security.xacml.pdp.data.PolicyDataManager#deletePolicy * (java.lang.String) */ @Override public boolean deletePolicy(String name) throws PolicyIndexException { log.debug("Deleting document: " + name); DbXmlManager.writeLock.lock(); try { m_dbXmlManager.container.deleteDocument(name, m_dbXmlManager.updateContext); setLastUpdate(System.currentTimeMillis()); } catch (XmlException xe) { // safe delete - only warn if not found if (xe.getDbError() == XmlException.DOCUMENT_NOT_FOUND){ log.warn("Error deleting document: " + name + " - document does not exist"); } else { throw new PolicyIndexException("Error deleting document: " + name + xe.getMessage(), xe); } } finally { DbXmlManager.writeLock.unlock(); } return true; } /* * (non-Javadoc) * @see * org.fcrepo.server.security.xacml.pdp.data.PolicyDataManager#updatePolicy * (java.lang.String, java.lang.String) */ @Override public boolean updatePolicy(String name, String newDocument) throws PolicyIndexException { log.debug("Updating document: " + name); // FIXME: DBXML container.updateDocument is failing to update document metadata (this tested on DBXML ver 2.5.13) // specifically anySubject, anyResource metadata elements are not changing // if Subjects and Resources elements are added/deleted from document. // FIXME: this will acquire and release write locks for each operation // should instead do this just once for an update deletePolicy(name); addPolicy(name, newDocument); // FIXME: code below would also need updating for transactions, deadlocks, single thread updates... /* original code below works apart from metadata update not happening try { utils.validate(newDocument, name); } catch (MelcoePDPException e) { throw new PolicyIndexException(e); } XmlTransaction txn = null; try { try { txn = dbXmlManager.manager.createTransaction(); XmlDocument doc = makeDocument(name, newDocument); dbXmlManager.container.updateDocument(txn, doc, dbXmlManager.updateContext); txn.commit(); setLastUpdate(System.currentTimeMillis()); } catch (XmlException xe) { txn.abort(); throw new PolicyIndexException("Error updating document: " + name, xe); } } catch (XmlException xe) { throw new PolicyIndexException("Error aborting transaction: " + xe.getMessage(), xe); } */ return true; } /* * (non-Javadoc) * @see * org.fcrepo.server.security.xacml.pdp.data.PolicyDataManager#getPolicy * (java.lang.String) */ @Override public AbstractPolicy getPolicy(String name, PolicyFinder policyFinder) throws PolicyIndexException { log.debug("Getting document: " + name); XmlDocument doc = null; DbXmlManager.readLock.lock(); try { doc = m_dbXmlManager.container.getDocument(name); return handleDocument(m_policyReader.readPolicy(doc.getContent()), policyFinder); } catch (XmlException xe) { throw new PolicyIndexException("Error getting Policy: " + name + xe.getMessage() + " - " + xe.getDatabaseException().getMessage(), xe); } catch (ParsingException pe) { throw new PolicyIndexException("Error getting Policy: " + name + pe.getMessage(), pe); } finally { DbXmlManager.readLock.unlock(); } } /** * Check if the policy identified by policyName exists. * * @param policyName * @return true iff the policy store contains a policy identified as * policyName * @throws PolicyStoreException */ @Override public boolean contains(String policyName) throws PolicyIndexException { log.debug("Determining if document exists: " + policyName); DbXmlManager.readLock.lock(); try { m_dbXmlManager.container.getDocument(policyName, new XmlDocumentConfig().setLazyDocs(true)); } catch (XmlException e) { if (e.getErrorCode() == XmlException.DOCUMENT_NOT_FOUND) { return false; } else { throw new PolicyIndexException("Error executing contains. " + e.getMessage(), e); } } finally { DbXmlManager.readLock.unlock(); } return true; } /** * Creates an instance of an XmlDocument for storage in the database. * * @param name * the name of the document (policy) * @param document * the document data as a String * @return the XmlDocument instance * @throws XmlException * @throws PolicyStoreException */ private XmlDocument makeDocument(String name, String document) throws XmlException, PolicyIndexException { Map<String, String> metadata = m_utils.getDocumentMetadata(document .getBytes()); XmlDocument doc = m_dbXmlManager.manager.createDocument(); String docName = name; if (docName == null || "".equals(docName)) { docName = metadata.get("PolicyId"); } if (docName == null || "".equals(docName)) { throw new PolicyIndexException("Could not extract PolicyID from document."); } doc.setMetaData("metadata", "PolicyId", new XmlValue(XmlValue.STRING, docName)); doc.setContent(document); doc.setName(docName); // FIXME: // this is probably redundant as the xpath queries now directly query the policy // for the "any" scenarios String item = null; item = metadata.get("anySubject"); if (item != null) { doc.setMetaData("metadata", "anySubject", new XmlValue(XmlValue.STRING, item)); } item = metadata.get("anyResource"); if (item != null) { doc.setMetaData("metadata", "anyResource", new XmlValue(XmlValue.STRING, item)); } item = metadata.get("anyAction"); if (item != null) { doc.setMetaData("metadata", "anyAction", new XmlValue(XmlValue.STRING, item)); } item = metadata.get("anyEnvironment"); if (item != null) { doc.setMetaData("metadata", "anyEnvironment", new XmlValue(XmlValue.STRING, item)); } return doc; } /* * (non-Javadoc) * @see * org.fcrepo.server.security.xacml.pdp.data.PolicyDataManager#getLastUpdate * () */ public long getLastUpdate() { return m_lastUpdate; } /** * @param lastUpdate * the lastUpdate to set */ public void setLastUpdate(long lastUpdate) { this.m_lastUpdate = lastUpdate; } @Override public boolean clear() throws PolicyIndexException { m_dbXmlManager.deleteDatabase(); m_dbXmlManager.close(); m_dbXmlManager = null; // and init will create a new database (by creating a new dbXmlManager) init(); return true; } private boolean deleteDirectory(String directory) { boolean result = false; if (directory != null) { File file = new File(directory); if (file.exists() && file.isDirectory()) { // 1. delete content of directory: File[] files = file.listFiles(); result = true; //init result flag int count = files.length; for (int i = 0; i < count; i++) { //for each file: File f = files[i]; if (f.isFile()) { result = result && f.delete(); } else if (f.isDirectory()) { result = result && deleteDirectory(f.getAbsolutePath()); } }//next file file.delete(); //finally delete (empty) input directory }//else: input directory does not exist or is not a directory }//else: no input value return result; }//deleteDirectory() }
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.search.fields; import org.apache.lucene.util.BytesRef; import org.elasticsearch.action.index.IndexRequestBuilder; import org.elasticsearch.action.search.SearchPhaseExecutionException; import org.elasticsearch.action.search.SearchRequestBuilder; import org.elasticsearch.action.search.SearchResponse; import org.elasticsearch.common.Base64; import org.elasticsearch.common.Priority; import org.elasticsearch.common.bytes.BytesArray; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.collect.MapBuilder; import org.elasticsearch.common.joda.Joda; import org.elasticsearch.common.settings.ImmutableSettings; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.rest.RestStatus; import org.elasticsearch.search.SearchHit; import org.elasticsearch.search.SearchHitField; import org.elasticsearch.search.sort.SortOrder; import org.elasticsearch.test.ElasticsearchIntegrationTest; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.concurrent.ExecutionException; import static org.elasticsearch.client.Requests.refreshRequest; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.index.query.QueryBuilders.matchAllQuery; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertFailures; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertHitCount; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertNoFailures; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertSearchResponse; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.Matchers.nullValue; /** * */ public class SearchFieldsTests extends ElasticsearchIntegrationTest { @Test public void testStoredFields() throws Exception { createIndex("test"); client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForYellowStatus().execute().actionGet(); String mapping = XContentFactory.jsonBuilder().startObject().startObject("type1") // _timestamp and _size are randomly enabled via templates but we don't want it here to test stored fields behaviour .startObject("_timestamp").field("enabled", false).endObject() .startObject("_size").field("enabled", false).endObject() .startObject("properties") .startObject("field1").field("type", "string").field("store", "yes").endObject() .startObject("field2").field("type", "string").field("store", "no").endObject() .startObject("field3").field("type", "string").field("store", "yes").endObject() .endObject().endObject().endObject().string(); client().admin().indices().preparePutMapping().setType("type1").setSource(mapping).execute().actionGet(); client().prepareIndex("test", "type1", "1").setSource(jsonBuilder().startObject() .field("field1", "value1") .field("field2", "value2") .field("field3", "value3") .endObject()).execute().actionGet(); client().admin().indices().prepareRefresh().execute().actionGet(); SearchResponse searchResponse = client().prepareSearch().setQuery(matchAllQuery()).addField("field1").execute().actionGet(); assertThat(searchResponse.getHits().getTotalHits(), equalTo(1l)); assertThat(searchResponse.getHits().hits().length, equalTo(1)); assertThat(searchResponse.getHits().getAt(0).fields().size(), equalTo(1)); assertThat(searchResponse.getHits().getAt(0).fields().get("field1").value().toString(), equalTo("value1")); // field2 is not stored, check that it gets extracted from source searchResponse = client().prepareSearch().setQuery(matchAllQuery()).addField("field2").execute().actionGet(); assertThat(searchResponse.getHits().getTotalHits(), equalTo(1l)); assertThat(searchResponse.getHits().hits().length, equalTo(1)); assertThat(searchResponse.getHits().getAt(0).fields().size(), equalTo(1)); assertThat(searchResponse.getHits().getAt(0).fields().get("field2").value().toString(), equalTo("value2")); searchResponse = client().prepareSearch().setQuery(matchAllQuery()).addField("field3").execute().actionGet(); assertThat(searchResponse.getHits().getTotalHits(), equalTo(1l)); assertThat(searchResponse.getHits().hits().length, equalTo(1)); assertThat(searchResponse.getHits().getAt(0).fields().size(), equalTo(1)); assertThat(searchResponse.getHits().getAt(0).fields().get("field3").value().toString(), equalTo("value3")); searchResponse = client().prepareSearch().setQuery(matchAllQuery()).addField("*").execute().actionGet(); assertThat(searchResponse.getHits().getTotalHits(), equalTo(1l)); assertThat(searchResponse.getHits().hits().length, equalTo(1)); assertThat(searchResponse.getHits().getAt(0).source(), nullValue()); assertThat(searchResponse.getHits().getAt(0).fields().size(), equalTo(2)); assertThat(searchResponse.getHits().getAt(0).fields().get("field1").value().toString(), equalTo("value1")); assertThat(searchResponse.getHits().getAt(0).fields().get("field3").value().toString(), equalTo("value3")); searchResponse = client().prepareSearch().setQuery(matchAllQuery()).addField("*").addField("_source").execute().actionGet(); assertThat(searchResponse.getHits().getTotalHits(), equalTo(1l)); assertThat(searchResponse.getHits().hits().length, equalTo(1)); assertThat(searchResponse.getHits().getAt(0).source(), notNullValue()); assertThat(searchResponse.getHits().getAt(0).fields().size(), equalTo(2)); assertThat(searchResponse.getHits().getAt(0).fields().get("field1").value().toString(), equalTo("value1")); assertThat(searchResponse.getHits().getAt(0).fields().get("field3").value().toString(), equalTo("value3")); } @Test public void testScriptDocAndFields() throws Exception { createIndex("test"); client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForYellowStatus().execute().actionGet(); String mapping = XContentFactory.jsonBuilder().startObject().startObject("type1").startObject("properties") .startObject("num1").field("type", "double").field("store", "yes").endObject() .endObject().endObject().endObject().string(); client().admin().indices().preparePutMapping().setType("type1").setSource(mapping).execute().actionGet(); client().prepareIndex("test", "type1", "1") .setSource(jsonBuilder().startObject().field("test", "value beck").field("num1", 1.0f).field("date", "1970-01-01T00:00:00").endObject()) .execute().actionGet(); client().admin().indices().prepareFlush().execute().actionGet(); client().prepareIndex("test", "type1", "2") .setSource(jsonBuilder().startObject().field("test", "value beck").field("num1", 2.0f).field("date", "1970-01-01T00:00:25").endObject()) .execute().actionGet(); client().admin().indices().prepareFlush().execute().actionGet(); client().prepareIndex("test", "type1", "3") .setSource(jsonBuilder().startObject().field("test", "value beck").field("num1", 3.0f).field("date", "1970-01-01T00:02:00").endObject()) .execute().actionGet(); client().admin().indices().refresh(refreshRequest()).actionGet(); logger.info("running doc['num1'].value"); SearchResponse response = client().prepareSearch() .setQuery(matchAllQuery()) .addSort("num1", SortOrder.ASC) .addScriptField("sNum1", "doc['num1'].value") .addScriptField("sNum1_field", "_fields['num1'].value") .addScriptField("date1", "doc['date'].date.millis") .execute().actionGet(); assertNoFailures(response); assertThat(response.getHits().totalHits(), equalTo(3l)); assertThat(response.getHits().getAt(0).isSourceEmpty(), equalTo(true)); assertThat(response.getHits().getAt(0).id(), equalTo("1")); assertThat(response.getHits().getAt(0).fields().size(), equalTo(3)); assertThat((Double) response.getHits().getAt(0).fields().get("sNum1").values().get(0), equalTo(1.0)); assertThat((Double) response.getHits().getAt(0).fields().get("sNum1_field").values().get(0), equalTo(1.0)); assertThat((Long) response.getHits().getAt(0).fields().get("date1").values().get(0), equalTo(0l)); assertThat(response.getHits().getAt(1).id(), equalTo("2")); assertThat(response.getHits().getAt(1).fields().size(), equalTo(3)); assertThat((Double) response.getHits().getAt(1).fields().get("sNum1").values().get(0), equalTo(2.0)); assertThat((Double) response.getHits().getAt(1).fields().get("sNum1_field").values().get(0), equalTo(2.0)); assertThat((Long) response.getHits().getAt(1).fields().get("date1").values().get(0), equalTo(25000l)); assertThat(response.getHits().getAt(2).id(), equalTo("3")); assertThat(response.getHits().getAt(2).fields().size(), equalTo(3)); assertThat((Double) response.getHits().getAt(2).fields().get("sNum1").values().get(0), equalTo(3.0)); assertThat((Double) response.getHits().getAt(2).fields().get("sNum1_field").values().get(0), equalTo(3.0)); assertThat((Long) response.getHits().getAt(2).fields().get("date1").values().get(0), equalTo(120000l)); logger.info("running doc['num1'].value * factor"); Map<String, Object> params = MapBuilder.<String, Object>newMapBuilder().put("factor", 2.0).map(); response = client().prepareSearch() .setQuery(matchAllQuery()) .addSort("num1", SortOrder.ASC) .addScriptField("sNum1", "doc['num1'].value * factor", params) .execute().actionGet(); assertThat(response.getHits().totalHits(), equalTo(3l)); assertThat(response.getHits().getAt(0).id(), equalTo("1")); assertThat(response.getHits().getAt(0).fields().size(), equalTo(1)); assertThat((Double) response.getHits().getAt(0).fields().get("sNum1").values().get(0), equalTo(2.0)); assertThat(response.getHits().getAt(1).id(), equalTo("2")); assertThat(response.getHits().getAt(1).fields().size(), equalTo(1)); assertThat((Double) response.getHits().getAt(1).fields().get("sNum1").values().get(0), equalTo(4.0)); assertThat(response.getHits().getAt(2).id(), equalTo("3")); assertThat(response.getHits().getAt(2).fields().size(), equalTo(1)); assertThat((Double) response.getHits().getAt(2).fields().get("sNum1").values().get(0), equalTo(6.0)); } @Test public void testUidBasedScriptFields() throws Exception { prepareCreate("test").addMapping("type1", "num1", "type=long").execute().actionGet(); ensureYellow(); int numDocs = randomIntBetween(1, 30); IndexRequestBuilder[] indexRequestBuilders = new IndexRequestBuilder[numDocs]; for (int i = 0; i < numDocs; i++) { indexRequestBuilders[i] = client().prepareIndex("test", "type1", Integer.toString(i)) .setSource(jsonBuilder().startObject().field("num1", i).endObject()); } indexRandom(true, indexRequestBuilders); SearchResponse response = client().prepareSearch() .setQuery(matchAllQuery()).addSort("num1", SortOrder.ASC).setSize(numDocs) .addScriptField("uid", "_fields._uid.value").get(); assertNoFailures(response); assertThat(response.getHits().totalHits(), equalTo((long)numDocs)); for (int i = 0; i < numDocs; i++) { assertThat(response.getHits().getAt(i).id(), equalTo(Integer.toString(i))); assertThat(response.getHits().getAt(i).fields().size(), equalTo(1)); assertThat((String)response.getHits().getAt(i).fields().get("uid").value(), equalTo("type1#" + Integer.toString(i))); } response = client().prepareSearch() .setQuery(matchAllQuery()).addSort("num1", SortOrder.ASC).setSize(numDocs) .addScriptField("id", "_fields._id.value").get(); assertNoFailures(response); assertThat(response.getHits().totalHits(), equalTo((long)numDocs)); for (int i = 0; i < numDocs; i++) { assertThat(response.getHits().getAt(i).id(), equalTo(Integer.toString(i))); assertThat(response.getHits().getAt(i).fields().size(), equalTo(1)); assertThat((String)response.getHits().getAt(i).fields().get("id").value(), equalTo(Integer.toString(i))); } response = client().prepareSearch() .setQuery(matchAllQuery()).addSort("num1", SortOrder.ASC).setSize(numDocs) .addScriptField("type", "_fields._type.value").get(); assertNoFailures(response); assertThat(response.getHits().totalHits(), equalTo((long)numDocs)); for (int i = 0; i < numDocs; i++) { assertThat(response.getHits().getAt(i).id(), equalTo(Integer.toString(i))); assertThat(response.getHits().getAt(i).fields().size(), equalTo(1)); assertThat((String)response.getHits().getAt(i).fields().get("type").value(), equalTo("type1")); } response = client().prepareSearch() .setQuery(matchAllQuery()).addSort("num1", SortOrder.ASC).setSize(numDocs) .addScriptField("id", "_fields._id.value") .addScriptField("uid", "_fields._uid.value") .addScriptField("type", "_fields._type.value").get(); assertNoFailures(response); assertThat(response.getHits().totalHits(), equalTo((long)numDocs)); for (int i = 0; i < numDocs; i++) { assertThat(response.getHits().getAt(i).id(), equalTo(Integer.toString(i))); assertThat(response.getHits().getAt(i).fields().size(), equalTo(3)); assertThat((String)response.getHits().getAt(i).fields().get("uid").value(), equalTo("type1#" + Integer.toString(i))); assertThat((String)response.getHits().getAt(i).fields().get("type").value(), equalTo("type1")); assertThat((String)response.getHits().getAt(i).fields().get("id").value(), equalTo(Integer.toString(i))); } } @Test public void testScriptFieldUsingSource() throws Exception { createIndex("test"); client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForYellowStatus().execute().actionGet(); client().prepareIndex("test", "type1", "1") .setSource(jsonBuilder().startObject() .startObject("obj1").field("test", "something").endObject() .startObject("obj2").startArray("arr2").value("arr_value1").value("arr_value2").endArray().endObject() .startArray("arr3").startObject().field("arr3_field1", "arr3_value1").endObject().endArray() .endObject()) .execute().actionGet(); client().admin().indices().refresh(refreshRequest()).actionGet(); SearchResponse response = client().prepareSearch() .setQuery(matchAllQuery()) .addScriptField("s_obj1", "_source.obj1") .addScriptField("s_obj1_test", "_source.obj1.test") .addScriptField("s_obj2", "_source.obj2") .addScriptField("s_obj2_arr2", "_source.obj2.arr2") .addScriptField("s_arr3", "_source.arr3") .execute().actionGet(); assertThat("Failures " + Arrays.toString(response.getShardFailures()), response.getShardFailures().length, equalTo(0)); assertThat(response.getHits().getAt(0).field("s_obj1_test").value().toString(), equalTo("something")); Map<String, Object> sObj1 = response.getHits().getAt(0).field("s_obj1").value(); assertThat(sObj1.get("test").toString(), equalTo("something")); assertThat(response.getHits().getAt(0).field("s_obj1_test").value().toString(), equalTo("something")); Map<String, Object> sObj2 = response.getHits().getAt(0).field("s_obj2").value(); List sObj2Arr2 = (List) sObj2.get("arr2"); assertThat(sObj2Arr2.size(), equalTo(2)); assertThat(sObj2Arr2.get(0).toString(), equalTo("arr_value1")); assertThat(sObj2Arr2.get(1).toString(), equalTo("arr_value2")); sObj2Arr2 = response.getHits().getAt(0).field("s_obj2_arr2").values(); assertThat(sObj2Arr2.size(), equalTo(2)); assertThat(sObj2Arr2.get(0).toString(), equalTo("arr_value1")); assertThat(sObj2Arr2.get(1).toString(), equalTo("arr_value2")); List sObj2Arr3 = response.getHits().getAt(0).field("s_arr3").values(); assertThat(((Map) sObj2Arr3.get(0)).get("arr3_field1").toString(), equalTo("arr3_value1")); } @Test public void testPartialFields() throws Exception { createIndex("test"); client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForYellowStatus().execute().actionGet(); client().prepareIndex("test", "type1", "1").setSource(XContentFactory.jsonBuilder().startObject() .field("field1", "value1") .startObject("obj1") .startArray("arr1") .startObject().startObject("obj2").field("field2", "value21").endObject().endObject() .startObject().startObject("obj2").field("field2", "value22").endObject().endObject() .endArray() .endObject() .endObject()) .execute().actionGet(); client().admin().indices().prepareRefresh().execute().actionGet(); } @Test public void testStoredFieldsWithoutSource() throws Exception { createIndex("test"); client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForYellowStatus().execute().actionGet(); String mapping = XContentFactory.jsonBuilder().startObject().startObject("type1").startObject("properties") .startObject("_source").field("enabled", false).endObject() .startObject("byte_field").field("type", "byte").field("store", "yes").endObject() .startObject("short_field").field("type", "short").field("store", "yes").endObject() .startObject("integer_field").field("type", "integer").field("store", "yes").endObject() .startObject("long_field").field("type", "long").field("store", "yes").endObject() .startObject("float_field").field("type", "float").field("store", "yes").endObject() .startObject("double_field").field("type", "double").field("store", "yes").endObject() .startObject("date_field").field("type", "date").field("store", "yes").endObject() .startObject("boolean_field").field("type", "boolean").field("store", "yes").endObject() .startObject("binary_field").field("type", "binary").field("store", "yes").endObject() .endObject().endObject().endObject().string(); client().admin().indices().preparePutMapping().setType("type1").setSource(mapping).execute().actionGet(); client().prepareIndex("test", "type1", "1").setSource(jsonBuilder().startObject() .field("byte_field", (byte) 1) .field("short_field", (short) 2) .field("integer_field", 3) .field("long_field", 4l) .field("float_field", 5.0f) .field("double_field", 6.0d) .field("date_field", Joda.forPattern("dateOptionalTime").printer().print(new DateTime(2012, 3, 22, 0, 0, DateTimeZone.UTC))) .field("boolean_field", true) .field("binary_field", Base64.encodeBytes("testing text".getBytes("UTF8"))) .endObject()).execute().actionGet(); client().admin().indices().prepareRefresh().execute().actionGet(); SearchResponse searchResponse = client().prepareSearch().setQuery(matchAllQuery()) .addField("byte_field") .addField("short_field") .addField("integer_field") .addField("long_field") .addField("float_field") .addField("double_field") .addField("date_field") .addField("boolean_field") .addField("binary_field") .execute().actionGet(); assertThat(searchResponse.getHits().getTotalHits(), equalTo(1l)); assertThat(searchResponse.getHits().hits().length, equalTo(1)); assertThat(searchResponse.getHits().getAt(0).fields().size(), equalTo(9)); assertThat(searchResponse.getHits().getAt(0).fields().get("byte_field").value().toString(), equalTo("1")); assertThat(searchResponse.getHits().getAt(0).fields().get("short_field").value().toString(), equalTo("2")); assertThat(searchResponse.getHits().getAt(0).fields().get("integer_field").value(), equalTo((Object) 3)); assertThat(searchResponse.getHits().getAt(0).fields().get("long_field").value(), equalTo((Object) 4l)); assertThat(searchResponse.getHits().getAt(0).fields().get("float_field").value(), equalTo((Object) 5.0f)); assertThat(searchResponse.getHits().getAt(0).fields().get("double_field").value(), equalTo((Object) 6.0d)); String dateTime = Joda.forPattern("dateOptionalTime").printer().print(new DateTime(2012, 3, 22, 0, 0, DateTimeZone.UTC)); assertThat(searchResponse.getHits().getAt(0).fields().get("date_field").value(), equalTo((Object) dateTime)); assertThat(searchResponse.getHits().getAt(0).fields().get("boolean_field").value(), equalTo((Object) Boolean.TRUE)); assertThat(((BytesReference) searchResponse.getHits().getAt(0).fields().get("binary_field").value()).toBytesArray(), equalTo((BytesReference) new BytesArray("testing text".getBytes("UTF8")))); } @Test public void testSearchFields_metaData() throws Exception { client().prepareIndex("my-index", "my-type1", "1") .setRouting("1") .setSource(jsonBuilder().startObject().field("field1", "value").endObject()) .setRefresh(true) .get(); SearchResponse searchResponse = client().prepareSearch("my-index") .setTypes("my-type1") .addField("field1").addField("_routing") .get(); assertThat(searchResponse.getHits().totalHits(), equalTo(1l)); assertThat(searchResponse.getHits().getAt(0).field("field1").isMetadataField(), equalTo(false)); assertThat(searchResponse.getHits().getAt(0).field("field1").getValue().toString(), equalTo("value")); assertThat(searchResponse.getHits().getAt(0).field("_routing").isMetadataField(), equalTo(true)); assertThat(searchResponse.getHits().getAt(0).field("_routing").getValue().toString(), equalTo("1")); } @Test public void testSearchFields_nonLeafField() throws Exception { client().prepareIndex("my-index", "my-type1", "1") .setSource(jsonBuilder().startObject().startObject("field1").field("field2", "value1").endObject().endObject()) .setRefresh(true) .get(); assertFailures(client().prepareSearch("my-index").setTypes("my-type1").addField("field1"), RestStatus.BAD_REQUEST, containsString("field [field1] isn't a leaf field")); } @Test public void testGetFields_complexField() throws Exception { client().admin().indices().prepareCreate("my-index") .setSettings(ImmutableSettings.settingsBuilder().put("index.refresh_interval", -1)) .addMapping("my-type2", jsonBuilder().startObject().startObject("my-type2").startObject("properties") .startObject("field1").field("type", "object").startObject("properties") .startObject("field2").field("type", "object").startObject("properties") .startObject("field3").field("type", "object").startObject("properties") .startObject("field4").field("type", "string").field("store", "yes") .endObject().endObject() .endObject().endObject() .endObject().endObject() .endObject().endObject().endObject()) .get(); BytesReference source = jsonBuilder().startObject() .startArray("field1") .startObject() .startObject("field2") .startArray("field3") .startObject() .field("field4", "value1") .endObject() .endArray() .endObject() .endObject() .startObject() .startObject("field2") .startArray("field3") .startObject() .field("field4", "value2") .endObject() .endArray() .endObject() .endObject() .endArray() .endObject().bytes(); client().prepareIndex("my-index", "my-type1", "1").setSource(source).get(); client().prepareIndex("my-index", "my-type2", "1").setRefresh(true).setSource(source).get(); String field = "field1.field2.field3.field4"; SearchResponse searchResponse = client().prepareSearch("my-index").setTypes("my-type1").addField(field).get(); assertThat(searchResponse.getHits().totalHits(), equalTo(1l)); assertThat(searchResponse.getHits().getAt(0).field(field).isMetadataField(), equalTo(false)); assertThat(searchResponse.getHits().getAt(0).field(field).getValues().size(), equalTo(2)); assertThat(searchResponse.getHits().getAt(0).field(field).getValues().get(0).toString(), equalTo("value1")); assertThat(searchResponse.getHits().getAt(0).field(field).getValues().get(1).toString(), equalTo("value2")); searchResponse = client().prepareSearch("my-index").setTypes("my-type2").addField(field).get(); assertThat(searchResponse.getHits().totalHits(), equalTo(1l)); assertThat(searchResponse.getHits().getAt(0).field(field).isMetadataField(), equalTo(false)); assertThat(searchResponse.getHits().getAt(0).field(field).getValues().size(), equalTo(2)); assertThat(searchResponse.getHits().getAt(0).field(field).getValues().get(0).toString(), equalTo("value1")); assertThat(searchResponse.getHits().getAt(0).field(field).getValues().get(1).toString(), equalTo("value2")); } @Test // see #8203 public void testSingleValueFieldDatatField() throws ExecutionException, InterruptedException { createIndex("test"); indexRandom(true, client().prepareIndex("test", "type", "1").setSource("test_field", "foobar")); refresh(); SearchResponse searchResponse = client().prepareSearch("test").setTypes("type").setSource(new BytesArray(new BytesRef("{\"query\":{\"match_all\":{}},\"fielddata_fields\": \"test_field\"}"))).get(); assertHitCount(searchResponse, 1); Map<String,SearchHitField> fields = searchResponse.getHits().getHits()[0].getFields(); assertThat((String)fields.get("test_field").value(), equalTo("foobar")); } @Test(expected = SearchPhaseExecutionException.class) public void testInvalidFieldDataField() throws ExecutionException, InterruptedException { createIndex("test"); if (randomBoolean()) { client().prepareSearch("test").setTypes("type").setSource(new BytesArray(new BytesRef("{\"query\":{\"match_all\":{}},\"fielddata_fields\": {}}"))).get(); } else { client().prepareSearch("test").setTypes("type").setSource(new BytesArray(new BytesRef("{\"query\":{\"match_all\":{}},\"fielddata_fields\": 1.0}"))).get(); } } @Test public void testFieldsPulledFromFieldData() throws Exception { createIndex("test"); client().admin().cluster().prepareHealth().setWaitForEvents(Priority.LANGUID).setWaitForYellowStatus().execute().actionGet(); String mapping = XContentFactory.jsonBuilder().startObject().startObject("type1").startObject("properties") .startObject("_source").field("enabled", false).endObject() .startObject("string_field").field("type", "string").endObject() .startObject("byte_field").field("type", "byte").endObject() .startObject("short_field").field("type", "short").endObject() .startObject("integer_field").field("type", "integer").endObject() .startObject("long_field").field("type", "long").endObject() .startObject("float_field").field("type", "float").endObject() .startObject("double_field").field("type", "double").endObject() .startObject("date_field").field("type", "date").endObject() .startObject("boolean_field").field("type", "boolean").endObject() .startObject("binary_field").field("type", "binary").endObject() .endObject().endObject().endObject().string(); client().admin().indices().preparePutMapping().setType("type1").setSource(mapping).execute().actionGet(); client().prepareIndex("test", "type1", "1").setSource(jsonBuilder().startObject() .field("string_field", "foo") .field("byte_field", (byte) 1) .field("short_field", (short) 2) .field("integer_field", 3) .field("long_field", 4l) .field("float_field", 5.0f) .field("double_field", 6.0d) .field("date_field", Joda.forPattern("dateOptionalTime").printer().print(new DateTime(2012, 3, 22, 0, 0, DateTimeZone.UTC))) .field("boolean_field", true) .endObject()).execute().actionGet(); client().admin().indices().prepareRefresh().execute().actionGet(); SearchRequestBuilder builder = client().prepareSearch().setQuery(matchAllQuery()) .addFieldDataField("string_field") .addFieldDataField("byte_field") .addFieldDataField("short_field") .addFieldDataField("integer_field") .addFieldDataField("long_field") .addFieldDataField("float_field") .addFieldDataField("double_field") .addFieldDataField("date_field") .addFieldDataField("boolean_field"); SearchResponse searchResponse = builder.execute().actionGet(); assertThat(searchResponse.getHits().getTotalHits(), equalTo(1l)); assertThat(searchResponse.getHits().hits().length, equalTo(1)); assertThat(searchResponse.getHits().getAt(0).fields().size(), equalTo(9)); assertThat(searchResponse.getHits().getAt(0).fields().get("byte_field").value().toString(), equalTo("1")); assertThat(searchResponse.getHits().getAt(0).fields().get("short_field").value().toString(), equalTo("2")); assertThat(searchResponse.getHits().getAt(0).fields().get("integer_field").value(), equalTo((Object) 3l)); assertThat(searchResponse.getHits().getAt(0).fields().get("long_field").value(), equalTo((Object) 4l)); assertThat(searchResponse.getHits().getAt(0).fields().get("float_field").value(), equalTo((Object) 5.0)); assertThat(searchResponse.getHits().getAt(0).fields().get("double_field").value(), equalTo((Object) 6.0d)); assertThat(searchResponse.getHits().getAt(0).fields().get("date_field").value(), equalTo((Object) 1332374400000L)); assertThat(searchResponse.getHits().getAt(0).fields().get("boolean_field").value().toString(), equalTo("T")); } public void testScriptFields() throws Exception { assertAcked(prepareCreate("index").addMapping("type", "s", "type=string,index=not_analyzed", "l", "type=long", "d", "type=double", "ms", "type=string,index=not_analyzed", "ml", "type=long", "md", "type=double").get()); final int numDocs = randomIntBetween(3, 8); List<IndexRequestBuilder> reqs = new ArrayList<>(); for (int i = 0; i < numDocs; ++i) { reqs.add(client().prepareIndex("index", "type", Integer.toString(i)).setSource( "s", Integer.toString(i), "ms", new String[] {Integer.toString(i), Integer.toString(i+1)}, "l", i, "ml", new long[] {i, i+1}, "d", i, "md", new double[] {i, i+1})); } indexRandom(true, reqs); ensureSearchable(); SearchRequestBuilder req = client().prepareSearch("index"); for (String field : Arrays.asList("s", "ms", "l", "ml", "d", "md")) { req.addScriptField(field, "doc['" + field + "'].values"); } SearchResponse resp = req.get(); assertSearchResponse(resp); for (SearchHit hit : resp.getHits().getHits()) { final int id = Integer.parseInt(hit.getId()); Map<String, SearchHitField> fields = hit.getFields(); assertThat(fields.get("s").getValues(), equalTo(Collections.<Object>singletonList(Integer.toString(id)))); assertThat(fields.get("l").getValues(), equalTo(Collections.<Object>singletonList((long) id))); assertThat(fields.get("d").getValues(), equalTo(Collections.<Object>singletonList((double) id))); assertThat(fields.get("ms").getValues(), equalTo(Arrays.<Object>asList(Integer.toString(id), Integer.toString(id + 1)))); assertThat(fields.get("ml").getValues(), equalTo(Arrays.<Object>asList((long) id, id+1L))); assertThat(fields.get("md").getValues(), equalTo(Arrays.<Object>asList((double) id, id+1d))); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.pig.test; import static org.junit.Assert.assertTrue; import java.io.File; import java.util.ArrayList; import java.util.Iterator; import org.apache.pig.ExecType; import org.apache.pig.PigServer; import org.apache.pig.backend.executionengine.ExecException; import org.apache.pig.builtin.PigStorage; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class TestStreamingLocal { private TupleFactory tf = TupleFactory.getInstance(); PigServer pigServer; private static final String simpleEchoStreamingCommand; static { String quote = "'"; if (Util.WINDOWS) { quote= "\""; } simpleEchoStreamingCommand = "perl -ne "+quote+"print $_"+quote; } @Before public void setUp() throws Exception { pigServer = new PigServer(ExecType.LOCAL); } @After public void tearDown() throws Exception { pigServer.shutdown(); } private Tuple[] setupExpectedResults(Object[] firstField, Object[] secondField) throws ExecException { Assert.assertEquals(firstField.length, secondField.length); Tuple[] expectedResults = new Tuple[firstField.length]; for (int i=0; i < expectedResults.length; ++i) { expectedResults[i] = tf.newTuple(2); expectedResults[i].set(0, firstField[i]); expectedResults[i].set(1, secondField[i]); } return expectedResults; } @Test public void testSimpleMapSideStreaming() throws Exception { File input = Util.createInputFile("tmp", "", new String[] {"A,1", "B,2", "C,3", "D,2", "A,5", "B,5", "C,8", "A,8", "D,8", "A,9"}); // Expected results String[] expectedFirstFields = new String[] {"A", "B", "C", "A", "D", "A"}; Integer[] expectedSecondFields = new Integer[] {5, 5, 8, 8, 8, 9}; boolean[] withTypes = {true, false}; for (int i = 0; i < withTypes.length; i++) { Tuple[] expectedResults = null; if(withTypes[i] == true) { expectedResults = setupExpectedResults(expectedFirstFields, expectedSecondFields); } else { expectedResults = setupExpectedResults(Util .toDataByteArrays(expectedFirstFields), Util .toDataByteArrays(expectedSecondFields)); } // Pig query to run pigServer.registerQuery("IP = load '" + Util.generateURI(input.toString(), pigServer.getPigContext()) + "' using " + PigStorage.class.getName() + "(',');"); pigServer.registerQuery("FILTERED_DATA = filter IP by $1 > '3';"); pigServer.registerQuery("S1 = stream FILTERED_DATA through `" + simpleEchoStreamingCommand + "`;"); if(withTypes[i] == true) { pigServer.registerQuery("OP = stream S1 through `" + simpleEchoStreamingCommand + "` as (f0:chararray, f1:int);"); } else { pigServer.registerQuery("OP = stream S1 through `" + simpleEchoStreamingCommand + "`;"); } // Run the query and check the results Util.checkQueryOutputs(pigServer.openIterator("OP"), expectedResults); } } @Test public void testSimpleMapSideStreamingWithOutputSchema() throws Exception { File input = Util.createInputFile("tmp", "", new String[] {"A,1", "B,2", "C,3", "D,2", "A,5", "B,5", "C,8", "A,8", "D,8", "A,9"}); // Expected results Object[] expectedFirstFields = new String[] {"C", "A", "D", "A"}; Object[] expectedSecondFields = new Integer[] {8, 8, 8, 9}; boolean[] withTypes = {true, false}; for (int i = 0; i < withTypes.length; i++) { Tuple[] expectedResults = null; if(withTypes[i] == true) { expectedResults = setupExpectedResults(expectedFirstFields, expectedSecondFields); } else { expectedResults = setupExpectedResults(Util .toDataByteArrays(expectedFirstFields), Util .toDataByteArrays(expectedSecondFields)); } // Pig query to run pigServer.registerQuery("IP = load '" + Util.generateURI(input.toString(), pigServer.getPigContext()) + "' using " + PigStorage.class.getName() + "(',');"); pigServer.registerQuery("FILTERED_DATA = filter IP by $1 > '3';"); if(withTypes[i] == true) { pigServer.registerQuery("STREAMED_DATA = stream FILTERED_DATA through `" + simpleEchoStreamingCommand + "` as (f0:chararray, f1:int);"); } else { pigServer.registerQuery("STREAMED_DATA = stream FILTERED_DATA through `" + simpleEchoStreamingCommand + "` as (f0, f1);"); } pigServer.registerQuery("OP = filter STREAMED_DATA by f1 > 6;"); // Run the query and check the results Util.checkQueryOutputs(pigServer.openIterator("OP"), expectedResults); } } @Test public void testSimpleReduceSideStreamingAfterFlatten() throws Exception { File input = Util.createInputFile("tmp", "", new String[] {"A,1", "B,2", "C,3", "D,2", "A,5", "B,5", "C,8", "A,8", "D,8", "A,9"}); // Expected results String[] expectedFirstFields = new String[] {"A", "A", "A", "B", "C", "D"}; Integer[] expectedSecondFields = new Integer[] {5, 8, 9, 5, 8, 8}; boolean[] withTypes = {true, false}; for (int i = 0; i < withTypes.length; i++) { Tuple[] expectedResults = null; if(withTypes[i] == true) { expectedResults = setupExpectedResults(expectedFirstFields, expectedSecondFields); } else { expectedResults = setupExpectedResults(Util .toDataByteArrays(expectedFirstFields), Util .toDataByteArrays(expectedSecondFields)); } // Pig query to run pigServer.registerQuery("IP = load '" + Util.generateURI(input.toString(), pigServer.getPigContext()) + "' using " + PigStorage.class.getName() + "(',');"); pigServer.registerQuery("FILTERED_DATA = filter IP by $1 > '3';"); pigServer.registerQuery("GROUPED_DATA = group FILTERED_DATA by $0;"); pigServer.registerQuery("FLATTENED_GROUPED_DATA = foreach GROUPED_DATA " + "generate flatten($1);"); pigServer.registerQuery("S1 = stream FLATTENED_GROUPED_DATA through `" + simpleEchoStreamingCommand + "`;"); if(withTypes[i] == true) { pigServer.registerQuery("OP = stream S1 through `" + simpleEchoStreamingCommand + "` as (f0:chararray, f1:int);"); } else { pigServer.registerQuery("OP = stream S1 through `" + simpleEchoStreamingCommand + "`;"); } // Run the query and check the results Util.checkQueryOutputsAfterSort(pigServer.openIterator("OP"), expectedResults); } } @Test public void testSimpleOrderedReduceSideStreamingAfterFlatten() throws Exception { File input = Util.createInputFile("tmp", "", new String[] {"A,1,2,3", "B,2,4,5", "C,3,1,2", "D,2,5,2", "A,5,5,1", "B,5,7,4", "C,8,9,2", "A,8,4,5", "D,8,8,3", "A,9,2,5"} ); // Expected results String[] expectedFirstFields = new String[] {"A", "A", "A", "A", "B", "B", "C", "C", "D", "D"}; Integer[] expectedSecondFields = new Integer[] {1, 9, 8, 5, 2, 5, 3, 8, 2, 8}; Integer[] expectedThirdFields = new Integer[] {2, 2, 4, 5, 4, 7, 1, 9, 5, 8}; Integer[] expectedFourthFields = new Integer[] {3, 5, 5, 1, 5, 4, 2, 2, 2, 3}; Tuple[] expectedResults = new Tuple[10]; for (int i = 0; i < expectedResults.length; ++i) { expectedResults[i] = tf.newTuple(4); expectedResults[i].set(0, expectedFirstFields[i]); expectedResults[i].set(1, expectedSecondFields[i]); expectedResults[i].set(2, expectedThirdFields[i]); expectedResults[i].set(3, expectedFourthFields[i]); } //setupExpectedResults(expectedFirstFields, expectedSecondFields); // Pig query to run pigServer.registerQuery("IP = load '" + Util.generateURI(input.toString(), pigServer.getPigContext()) + "' using " + PigStorage.class.getName() + "(',');"); pigServer.registerQuery("FILTERED_DATA = filter IP by $1 > '3';"); pigServer.registerQuery("S1 = stream FILTERED_DATA through `" + simpleEchoStreamingCommand + "`;"); pigServer.registerQuery("S2 = stream S1 through `" + simpleEchoStreamingCommand + "`;"); pigServer.registerQuery("GROUPED_DATA = group IP by $0;"); pigServer.registerQuery("ORDERED_DATA = foreach GROUPED_DATA { " + " D = order IP BY $2, $3;" + " generate flatten(D);" + "};"); pigServer.registerQuery("S3 = stream ORDERED_DATA through `" + simpleEchoStreamingCommand + "`;"); pigServer.registerQuery("OP = stream S3 through `" + simpleEchoStreamingCommand + "` as (f0:chararray, f1:int, f2:int, f3:int);"); // Run the query and check the results Util.checkQueryOutputs(pigServer.openIterator("OP"), expectedResults); } @Test public void testSimpleMapSideStreamingWithUnixPipes() throws Exception { File input = Util.createInputFile("tmp", "", new String[] {"A,1", "B,2", "C,3", "D,2", "A,5", "B,5", "C,8", "A,8", "D,8", "A,9"}); // Expected results String[] expectedFirstFields = new String[] {"A", "B", "C", "D", "A", "B", "C", "A", "D", "A"}; Integer[] expectedSecondFields = new Integer[] {1, 2, 3, 2, 5, 5, 8, 8, 8, 9}; boolean[] withTypes = {true, false}; for (int i = 0; i < withTypes.length; i++) { Tuple[] expectedResults = null; if(withTypes[i] == true) { expectedResults = setupExpectedResults(expectedFirstFields, expectedSecondFields); } else { expectedResults = setupExpectedResults(Util.toDataByteArrays(expectedFirstFields), Util.toDataByteArrays(expectedSecondFields)); } // Pig query to run pigServer.registerQuery("define CMD `" + simpleEchoStreamingCommand + " | " + simpleEchoStreamingCommand + "`;"); pigServer.registerQuery("IP = load '" + Util.generateURI(input.toString(), pigServer.getPigContext()) + "' using " + PigStorage.class.getName() + "(',');"); if(withTypes[i] == true) { pigServer.registerQuery("OP = stream IP through CMD as (f0:chararray, f1:int);"); } else { pigServer.registerQuery("OP = stream IP through CMD;"); } // Run the query and check the results Util.checkQueryOutputs(pigServer.openIterator("OP"), expectedResults); } } @Test public void testJoinTwoStreamingRelations() throws Exception { ArrayList<String> list = new ArrayList<String>(); for (int i=0; i<10000; i++) { list.add("A," + i); } File input = Util.createInputFile("tmp", "", list.toArray(new String[0])); // Expected results Tuple expected = TupleFactory.getInstance().newTuple(4); expected.set(0, "A"); expected.set(1, 0); expected.set(2, "A"); expected.set(3, 0); pigServer.registerQuery("A = load '" + Util.generateURI(input.toString(), pigServer.getPigContext()) + "' using " + PigStorage.class.getName() + "(',') as (a0, a1);"); pigServer.registerQuery("B = stream A through `head -1` as (a0, a1);"); pigServer.registerQuery("C = load '" + Util.generateURI(input.toString(), pigServer.getPigContext()) + "' using " + PigStorage.class.getName() + "(',') as (a0, a1);"); pigServer.registerQuery("D = stream C through `head -1` as (a0, a1);"); pigServer.registerQuery("E = join B by a0, D by a0;"); Iterator<Tuple> iter = pigServer.openIterator("E"); int count = 0; while (iter.hasNext()) { Assert.assertEquals(expected.toString(), iter.next().toString()); count++; } Assert.assertTrue(count == 1); } @Test public void testLocalNegativeLoadStoreOptimization() throws Exception { testNegativeLoadStoreOptimization(ExecType.LOCAL); } private void testNegativeLoadStoreOptimization(ExecType execType) throws Exception { File input = Util.createInputFile("tmp", "", new String[] {"A,1", "B,2", "C,3", "D,2", "A,5", "B,5", "C,8", "A,8", "D,8", "A,9"}); // Expected results String[] expectedFirstFields = new String[] {"A", "B", "C", "A", "D", "A"}; Integer[] expectedSecondFields = new Integer[] {5, 5, 8, 8, 8, 9}; boolean[] withTypes = {true, false}; for (int i = 0; i < withTypes.length; i++) { Tuple[] expectedResults = null; if(withTypes[i] == true) { expectedResults = setupExpectedResults(expectedFirstFields, expectedSecondFields); } else { expectedResults = setupExpectedResults(Util .toDataByteArrays(expectedFirstFields), Util .toDataByteArrays(expectedSecondFields)); } // Pig query to run pigServer.registerQuery("define CMD `"+ simpleEchoStreamingCommand + "` input(stdin);"); pigServer.registerQuery("IP = load '" + Util.generateURI(input.toString(), pigServer.getPigContext()) + "' using " + PigStorage.class.getName() + "(',');"); pigServer.registerQuery("FILTERED_DATA = filter IP by $1 > '3';"); if(withTypes[i] == true) { pigServer.registerQuery("OP = stream FILTERED_DATA through `" + simpleEchoStreamingCommand + "` as (f0:chararray, f1:int);"); } else { pigServer.registerQuery("OP = stream FILTERED_DATA through `" + simpleEchoStreamingCommand + "`;"); } // Run the query and check the results Util.checkQueryOutputs(pigServer.openIterator("OP"), expectedResults); } } }
/* ****************************************************************** Copyright (c) 2001-2013, Jeff Martin, Tim Bacon All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the xmlunit.sourceforge.net nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ****************************************************************** */ package org.custommonkey.xmlunit; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.Reader; import java.util.HashSet; import java.util.Set; import junit.framework.TestCase; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.Text; /** * Test a Diff */ public class test_Diff extends TestCase{ private static final String[] control = new String[]{ "<test/>", "<test></test>", "<test>test</test>", "<test test=\"test\">test</test>", "<test/>", "<test>test</test>", "<test test=\"test\"/>", "<test><test><test></test></test></test>", "<test test=\"test\"><test>test<test>test</test></test></test>", "<test test=\"test\"><test>test<test>test</test></test></test>", "<html>Yo this is a test!</html>", "<java></java>" }; private static final String[] test = new String[]{ "<fail/>", "<fail/>", "<fail>test</fail>", "<test>test</test>", "<fail/>", "<test>fail</test>", "<test test=\"fail\"/>", "<test><test><test>test</test></test></test>", "<test test=\"test\"><test>fail<test>test</test></test></test>", "<test test=\"fail\"><test>test<test>test</test></test></test>", "<html>Yo this isn't a test!</html>", "<java><package-def><ident>org</ident><dot/><ident>apache</ident><dot/><ident>test</ident></package-def></java>" }; private Document aDocument; public void setUp() throws Exception { aDocument = XMLUnit.newControlParser().newDocument(); } public void testToString(){ Diff diff = buildDiff(aDocument, aDocument); String[] animals = {"Monkey", "Chicken"}; String tag = "tag"; Element elemA = aDocument.createElement(tag); Text textA = aDocument.createTextNode(animals[0]); elemA.appendChild(textA); Element elemB = aDocument.createElement(tag); Difference difference = new Difference(DifferenceConstants.HAS_CHILD_NODES, new NodeDetail(Boolean.TRUE.toString(), elemA, "/tag"), new NodeDetail(Boolean.FALSE.toString(),elemB, "/tag")); diff.differenceFound(difference); assertEquals(diff.getClass().getName() +"\n[different] Expected " + DifferenceConstants.HAS_CHILD_NODES.getDescription() + " 'true' but was 'false' - comparing <tag...> at /tag to <tag...> at /tag\n", diff.toString()); diff = buildDiff(aDocument, aDocument); Text textB = aDocument.createTextNode(animals[1]); elemB.appendChild(textB); difference = new Difference(DifferenceConstants.TEXT_VALUE, new NodeDetail(animals[0], textA, "/tag/text()"), new NodeDetail(animals[1], textB, "/tag/text()")); diff.differenceFound(difference); assertEquals(diff.getClass().getName() +"\n[different] Expected " + DifferenceConstants.TEXT_VALUE.getDescription() + " 'Monkey' but was 'Chicken' - comparing <tag ...>Monkey</tag> " + "at /tag/text() to <tag ...>Chicken</tag> at /tag/text()\n", diff.toString()); } /** * Tests the compare method */ public void testSimilar() throws Exception { for(int i=0;i<control.length;i++){ assertEquals("XMLUnit.compare().similar() test case "+i+" failed", true, buildDiff(control[i], control[i]).similar()); assertEquals("!XMLUnit.compare().similar() test case "+i+" failed", false, (buildDiff(control[i], test[i])).similar()); } } public void testIdentical() throws Exception { String control="<control><test>test1</test><test>test2</test></control>"; String test="<control><test>test2</test><test>test1</test></control>"; assertEquals("Documents are identical, when they are not", false, buildDiff(control, test).identical()); } public void testFiles() throws Exception { FileReader control = new FileReader(test_Constants.BASEDIR + "/tests/etc/test.blame.html"); FileReader test = new FileReader(test_Constants.BASEDIR + "/tests/etc/test.blame.html"); Diff diff = buildDiff(control, test); assertEquals(diff.toString(), true, diff.identical()); } public void testSameTwoStrings() throws Exception { Diff diff = buildDiff("<same>pass</same>", "<same>pass</same>"); assertEquals("same should be identical", true, diff.identical()); assertEquals("same should be similar", true, diff.similar()); } public void testMissingElement() throws Exception { Diff diff = buildDiff("<root></root>", "<root><node/></root>"); assertEquals("should not be identical", false, diff.identical()); assertEquals("and should not be similar", false, diff.similar()); } public void testExtraElement() throws Exception { Diff diff = buildDiff("<root><node/></root>", "<root></root>"); assertEquals("should not be identical", false, diff.identical()); assertEquals("and should not be similar", false, diff.similar()); } public void testElementsInReverseOrder() throws Exception { Diff diff = buildDiff("<root><same/><pass/></root>", "<root><pass/><same/></root>"); assertEquals("should not be identical", false, diff.identical()); assertEquals("but should be similar", true, diff.similar()); } public void testMissingAttribute() throws Exception { Diff diff = buildDiff("<same>pass</same>", "<same except=\"this\">pass</same>"); assertEquals("should not be identical", false, diff.identical()); assertEquals("and should not be similar", false, diff.similar()); } public void testExtraAttribute() throws Exception { Diff diff = buildDiff("<same except=\"this\">pass</same>", "<same>pass</same>"); assertEquals("should not be identical", false, diff.identical()); assertEquals("and should not be similar", false, diff.similar()); } public void testAttributesInReverseOrder() throws Exception { Diff diff = buildDiff("<same zzz=\"qwerty\" aaa=\"uiop\">pass</same>", "<same aaa=\"uiop\" zzz=\"qwerty\">pass</same>" ); if (diff.identical()) { System.out.println(getName() + " - should not ideally be identical " + "but JAXP implementations can reorder attributes inside NamedNodeMap"); } assertEquals(diff.toString() + ": but should be similar", true, diff.similar()); } public void testDiffStringWithAttributes() throws Exception { final String fruitBat = "<bat type=\"fruit\"/>", longEaredBat = "<bat type=\"longeared\"/>"; Diff diff = buildDiff(fruitBat, longEaredBat); assertEquals(diff.getClass().getName() +"\n[different] Expected " + DifferenceConstants.ATTR_VALUE.getDescription() + " 'fruit' but was 'longeared' - comparing " + "<bat type=\"fruit\"...> at /bat[1]/@type to <bat type=\"longeared\"...> at /bat[1]/@type\n", diff.toString()); } public void testXMLWithDTD() throws Exception { String aDTDpart = "<!DOCTYPE test [" + "<!ELEMENT assertion EMPTY>" + "<!ATTLIST assertion result (pass|fail) \"fail\">" + "<!ELEMENT test (assertion)*>"; String aDTD = aDTDpart + "]>"; String xmlWithoutDTD = "<test>" + "<assertion result=\"pass\"/>" + "<assertion result=\"fail\"/>" + "</test>"; String xmlWithDTD = aDTD + xmlWithoutDTD; Diff diff = buildDiff(xmlWithDTD, xmlWithoutDTD); assertTrue("similar. " + diff.toString(), diff.similar()); assertTrue("not identical. " + diff.toString(), !diff.identical()); File tempDtdFile = File.createTempFile(getName(), "dtd"); tempDtdFile.deleteOnExit(); FileWriter dtdWriter = new FileWriter(tempDtdFile); dtdWriter.write(aDTD); try { String xmlWithExternalDTD = "<!DOCTYPE test SYSTEM \"" + tempDtdFile.toURL().toExternalForm() + "\">" + xmlWithoutDTD; diff = buildDiff(xmlWithDTD, xmlWithExternalDTD); assertTrue("similar again. " + diff.toString(), diff.similar()); assertTrue("not identical again. " + diff.toString(), !diff.identical()); } finally { tempDtdFile.delete(); } String anotherDTD = aDTDpart + "<!ELEMENT comment (ANY)>" + "]>"; String xmlWithAnotherDTD = anotherDTD + xmlWithoutDTD; diff = buildDiff(xmlWithDTD, xmlWithAnotherDTD); assertTrue("similar. " + diff.toString(), diff.similar()); assertTrue("amd identical as DTD content is not compared. " + diff.toString(), diff.identical()); } /** * Raised by aakture 25.04.2002 * Despite the name under which this defect was raised the issue is really * about managing redundant whitespace */ public void testXMLUnitDoesNotWorkWellWithFiles() throws Exception { // to avoid test sequencing issues we need to restore whitespace setting boolean startValueIgnoreWhitespace = XMLUnit.getIgnoreWhitespace(); try { XMLUnit.setIgnoreWhitespace(false); Diff whitespaceAwareDiff = buildDiff(test_Constants.XML_WITHOUT_WHITESPACE, test_Constants.XML_WITH_WHITESPACE); assertTrue(whitespaceAwareDiff.toString(), !whitespaceAwareDiff.similar()); XMLUnit.setIgnoreWhitespace(true); Diff whitespaceIgnoredDiff = buildDiff(test_Constants.XML_WITHOUT_WHITESPACE, test_Constants.XML_WITH_WHITESPACE); assertTrue(whitespaceIgnoredDiff.toString(), whitespaceIgnoredDiff.similar()); } finally { XMLUnit.setIgnoreWhitespace(startValueIgnoreWhitespace); } } public void testCommentHandlingDoesntAffectWhitespaceHandling() throws Exception { try { XMLUnit.setIgnoreComments(true); testXMLUnitDoesNotWorkWellWithFiles(); } finally { XMLUnit.setIgnoreComments(false); } } public void testNormalizationDoesntAffectWhitespaceHandling() throws Exception { try { XMLUnit.setNormalize(true); testXMLUnitDoesNotWorkWellWithFiles(); } finally { XMLUnit.setNormalize(false); } } /** * Raised 15.05.2002 */ public void testNamespaceIssues() throws Exception { String control = "<control:abc xmlns:control=\"http://yada.com\">" + "<control:xyz>text</control:xyz></control:abc>"; Replacement replace = new Replacement("control", "test"); String test = replace.replace(control); Diff diff = buildDiff(control, test); assertTrue("a-"+diff.toString(), diff.similar()); assertTrue("b-"+diff.toString(), !diff.identical()); Diff reverseDiff = buildDiff(test, control); assertTrue("c-"+reverseDiff.toString(), reverseDiff.similar()); assertTrue("d-"+reverseDiff.toString(), !reverseDiff.identical()); } /** * Raised 16.05.2002 */ public void testDefaultNamespace() throws Exception { String control = "<control:abc xmlns:control=\"http://yada.com\">" + "<control:xyz>text</control:xyz></control:abc>"; Replacement replace = new Replacement("control:", ""); Replacement trim = new Replacement("xmlns:control", "xmlns"); String test = trim.replace(replace.replace(control)); Diff diff = buildDiff(control, test); assertTrue("a-"+diff.toString(), diff.similar()); assertTrue("b-"+diff.toString(), !diff.identical()); Diff reverseDiff = buildDiff(test, control); assertTrue("c-"+reverseDiff.toString(), reverseDiff.similar()); assertTrue("d-"+reverseDiff.toString(), !reverseDiff.identical()); } public void testSameNameDifferentQName() throws Exception { String control = "<ns1:root xmlns:ns1=\"http://example.org/ns1\" xmlns:ns2=\"http://example.org/ns2\">" + "<ns1:branch>In namespace 1</ns1:branch>" + "<ns2:branch>In namespace 2</ns2:branch>" + "</ns1:root>"; String test = "<ns1:root xmlns:ns1=\"http://example.org/ns1\" xmlns:ns2=\"http://example.org/ns2\">" + "<ns2:branch>In namespace 2</ns2:branch>" + "<ns1:branch>In namespace 1</ns1:branch>" + "</ns1:root>"; Diff diff = buildDiff(control, test); assertTrue("a-"+diff.toString(), diff.similar()); assertTrue("b-"+diff.toString(), !diff.identical()); Diff reverseDiff = buildDiff(test, control); assertTrue("c-"+reverseDiff.toString(), reverseDiff.similar()); assertTrue("d-"+reverseDiff.toString(), !reverseDiff.identical()); } public void testOverrideDifferenceListener() throws Exception { String control = "<vehicles><car colour=\"white\">ford fiesta</car>" +"<car colour=\"red\">citroen xsara</car></vehicles>"; String test = "<vehicles><car colour=\"white\">nissan primera</car>" +"<car colour=\"blue\">peugot 206</car></vehicles>"; Diff diff = buildDiff(control, test); assertTrue("initially " + diff.toString(), !diff.similar()); Diff diffWithIdenticalOverride = buildDiff(control, test); diffWithIdenticalOverride.overrideDifferenceListener( new OverrideDifferenceListener( DifferenceListener.RETURN_IGNORE_DIFFERENCE_NODES_IDENTICAL)); assertTrue("now identical" + diffWithIdenticalOverride.toString(), diffWithIdenticalOverride.identical()); Diff diffWithSimilarOverride = buildDiff(control, test); diffWithSimilarOverride.overrideDifferenceListener( new OverrideDifferenceListener( DifferenceListener.RETURN_IGNORE_DIFFERENCE_NODES_SIMILAR)); assertTrue("no longer identical" + diffWithSimilarOverride.toString(), !diffWithSimilarOverride.identical()); assertTrue("but still similar" + diffWithSimilarOverride.toString(), diffWithSimilarOverride.similar()); Diff diffWithOverride = buildDiff(control, test); diffWithOverride.overrideDifferenceListener( new OverrideDifferenceListener( DifferenceListener.RETURN_ACCEPT_DIFFERENCE)); assertTrue("default behaviour" + diffWithOverride.toString(), !diffWithOverride.similar()); } public void testNamespacedAttributes() throws Exception { FileReader control = new FileReader(test_Constants.BASEDIR + "/tests/etc/controlNamespaces.xml"); FileReader test = new FileReader(test_Constants.BASEDIR + "/tests/etc/testNamespaces.xml"); Diff diff = buildDiff(control, test); diff.overrideDifferenceListener( new ExpectedDifferenceListener(DifferenceConstants.NAMESPACE_PREFIX_ID)); assertEquals(diff.toString(), false, diff.identical()); assertEquals(diff.toString(), true, diff.similar()); } public void testDifferentStructure() throws Exception { String control = "<root><node>text</node></root>"; String test = "<root><node><inner-node>text</inner-node></node></root>"; Diff myDiff = buildDiff(control, test); assertEquals(myDiff.toString(), false, myDiff.similar()); } public void testRepeatedElementNamesWithAttributeQualification1() throws Exception { Diff diff = buildDiff("<root><node id=\"1\"/><node id=\"2\"/></root>", "<root><node id=\"2\"/><node id=\"1\"/></root>"); diff.overrideElementQualifier(new ElementNameAndAttributeQualifier("id")); assertFalse("should not be identical: " + diff.toString(), diff.identical()); assertTrue("should be similar: " + diff.toString(), diff.similar()); } public void testRepeatedElementNamesWithAttributeQualification2() throws Exception { Diff diff = buildDiff("<root><node id=\"1\" val=\"4\"/><node id=\"2\" val=\"3\"/></root>", "<root><node id=\"2\" val=\"4\"/><node id=\"1\" val=\"3\"/></root>"); diff.overrideElementQualifier(new ElementNameAndAttributeQualifier("id")); assertFalse("should not be identical: " + diff.toString(), diff.identical()); assertFalse("should not be similar: " + diff.toString(), diff.similar()); } public void testRepeatedElementNamesWithAttributeQualification3() throws Exception { Diff diff = buildDiff("<root><node id=\"1\" val=\"4\"/><node id=\"2\" val=\"3\"/></root>", "<root><node id=\"2\" val=\"3\"/><node id=\"1\" val=\"4\"/></root>"); diff.overrideElementQualifier(new ElementNameAndAttributeQualifier()); assertFalse("should not be identical: " + diff.toString(), diff.identical()); assertTrue("should be similar: " + diff.toString(), diff.similar()); } public void testRepeatedElementNamesWithAttributeQualification4() throws Exception { Diff diff = buildDiff("<root><node id=\"1\" val=\"4\"/><node id=\"2\" val=\"3\"/></root>", "<root><node id=\"2\" val=\"4\"/><node id=\"1\" val=\"3\"/></root>"); diff.overrideElementQualifier(new ElementNameAndAttributeQualifier()); assertFalse("should not be identical: " + diff.toString(), diff.identical()); assertFalse("should not be similar: " + diff.toString(), diff.similar()); } public void testRepeatedElementNamesWithNamespacedAttributeQualification() throws Exception { Diff diff = buildDiff("<root xmlns:a=\"http://a.com\" xmlns:b=\"http://b.com\">" + "<node id=\"1\" a:val=\"a\" b:val=\"b\"/><node id=\"2\" a:val=\"a2\" b:val=\"b2\"/></root>", "<root xmlns:c=\"http://a.com\" xmlns:d=\"http://b.com\">" + "<node id=\"2\" c:val=\"a2\" d:val=\"b2\"/><node id=\"1\" c:val=\"a\" d:val=\"b\"/></root>"); diff.overrideElementQualifier(new ElementNameAndAttributeQualifier()); diff.overrideDifferenceListener(new ExpectedDifferenceListener( new int[] {DifferenceConstants.NAMESPACE_PREFIX_ID, DifferenceConstants.CHILD_NODELIST_SEQUENCE_ID})); assertFalse("should not be identical: " + diff.toString(), diff.identical()); assertTrue("should be similar: " + diff.toString(), diff.similar()); } public void testRepeatedElementNamesWithTextQualification() throws Exception { Diff diff = buildDiff("<root><node>1</node><node>2</node></root>", "<root><node>2</node><node>1</node></root>"); diff.overrideElementQualifier(new ElementNameAndTextQualifier()); diff.overrideDifferenceListener( new ExaminingExpectedDifferenceListener(DifferenceConstants.CHILD_NODELIST_SEQUENCE_ID) { private int i=0; protected void examineDifferenceContents(Difference difference) { ++i; assertEquals("/root[1]/node[" + i +"]", difference.getControlNodeDetail().getXpathLocation()); } }); assertFalse("should not be identical: " + diff.toString(), diff.identical()); assertTrue("should be similar: " + diff.toString(), diff.similar()); } // defect raised by Kevin Krouse Jan 2003 public void testXMLNSNumberOfAttributes() throws Exception { Diff diff = buildDiff("<root xmlns=\"qwerty\"><node/></root>", "<root xmlns=\"qwerty\" xmlns:qwerty=\"qwerty\"><qwerty:node/></root>"); assertTrue(diff.toString(), diff.similar()); assertFalse(diff.toString(), diff.identical()); } protected Diff buildDiff(Document control, Document test) { return new Diff(control, test); } protected Diff buildDiff(String control, String test) throws Exception { return new Diff(control, test); } protected Diff buildDiff(Reader control, Reader test) throws Exception { return new Diff(control, test); } protected Diff buildDiff(String control, String test, DifferenceEngine engine) throws Exception { return new Diff(XMLUnit.buildControlDocument(control), XMLUnit.buildTestDocument(test), engine); } /** * Construct a test * @param name Test name */ public test_Diff(String name){ super(name); } private class OverrideDifferenceListener implements DifferenceListener { private final int overrideValue; private OverrideDifferenceListener(int overrideValue) { this.overrideValue = overrideValue; } public int differenceFound(Difference difference) { return overrideValue; } public void skippedComparison(Node control, Node test) { } } private class ExpectedDifferenceListener implements DifferenceListener { private final Set expectedIds; private ExpectedDifferenceListener(int expectedIdValue) { this(new int[] {expectedIdValue}); } private ExpectedDifferenceListener(int[] expectedIdValues) { this.expectedIds = new HashSet(expectedIdValues.length); for (int i=0; i < expectedIdValues.length; ++i) { expectedIds.add(new Integer(expectedIdValues[i])); } } public int differenceFound(Difference difference) { assertTrue(difference.toString(), expectedIds.contains(new Integer(difference.getId()))); examineDifferenceContents(difference); return RETURN_ACCEPT_DIFFERENCE; } public void skippedComparison(Node control, Node test) { } protected void examineDifferenceContents(Difference difference) { } } private abstract class ExaminingExpectedDifferenceListener extends ExpectedDifferenceListener { private ExaminingExpectedDifferenceListener(int expectedIdValue) { super(expectedIdValue); } protected abstract void examineDifferenceContents(Difference difference) ; } public void testIssue1189681() throws Exception { String left = "" + "<farm>\n" + "<size>100</size>\n" + " <animal>\n" + "<name>Cow</name>\n" + " </animal>\n" + " <animal>\n" + "<name>Sheep</name>\n" + " </animal>\n" + "</farm>"; String right = "" + "<farm>\n" + " <animal>\n" + "<name>Sheep</name>\n" + " </animal>\n" + " <size>100</size>\n" + " <animal>\n" + " <name>Cow</name>\n" + " </animal>\n" + "</farm>"; assertFalse(buildDiff(left, right).similar()); } public void testCDATANoIgnore() throws Exception { String expected = "<a>Hello</a>"; String actual = "<a><![CDATA[Hello]]></a>"; assertFalse(buildDiff(expected, actual).similar()); assertFalse(buildDiff(expected, actual).identical()); } public void testCDATAIgnore() throws Exception { try { XMLUnit.setIgnoreDiffBetweenTextAndCDATA(true); String expected = "<a>Hello</a>"; String actual = "<a><![CDATA[Hello]]></a>"; assertTrue(buildDiff(expected, actual).similar()); assertTrue(buildDiff(expected, actual).identical()); } finally { XMLUnit.setIgnoreDiffBetweenTextAndCDATA(false); } } public void testCommentHandling() throws Exception { String xml1 = "<foo><!-- test --><bar a=\"b\"/> </foo>"; String xml2 = "<foo><bar a=\"b\"><!-- test --></bar> </foo>"; try { assertFalse(buildDiff(xml1, xml2).identical()); assertFalse(buildDiff(xml1, xml2).similar()); XMLUnit.setIgnoreComments(true); assertTrue(buildDiff(xml1, xml2).identical()); assertTrue(buildDiff(xml1, xml2).similar()); } finally { XMLUnit.setIgnoreComments(false); } } public void testWhitespaceHandlingDoesntAffectCommentHandling() throws Exception { try { XMLUnit.setIgnoreWhitespace(true); testCommentHandling(); } finally { XMLUnit.setIgnoreWhitespace(false); } } public void testNormalizationDoesntAffectCommentHandling() throws Exception { try { XMLUnit.setNormalize(true); testCommentHandling(); } finally { XMLUnit.setNormalize(false); } } public void testNormalization() throws Exception { Document control = XMLUnit.newControlParser().newDocument(); Element root = control.createElement("root"); control.appendChild(root); root.appendChild(control.createTextNode("Text 1")); root.appendChild(control.createTextNode(" and 2")); Element inner = control.createElement("inner"); root.appendChild(inner); inner.appendChild(control.createTextNode("Text 3 and 4")); Document test = XMLUnit.newTestParser().newDocument(); root = test.createElement("root"); test.appendChild(root); root.appendChild(test.createTextNode("Text 1 and 2")); inner = test.createElement("inner"); root.appendChild(inner); inner.appendChild(test.createTextNode("Text 3")); inner.appendChild(test.createTextNode(" and 4")); assertFalse(buildDiff(control, test).identical()); try { XMLUnit.setNormalize(true); assertTrue(buildDiff(control, test).identical()); assertTrue(buildDiff(control, test).similar()); } finally { XMLUnit.setNormalize(false); } assertFalse(buildDiff(control, test).similar()); } // fails with Java 5 and later public void XtestWhitespaceHandlingDoesntAffectNormalization() throws Exception { try { XMLUnit.setIgnoreWhitespace(true); testNormalization(); } finally { XMLUnit.setIgnoreWhitespace(false); } } // fails with Java 5 and later public void XtestCommentHandlingDoesntAffectNormalization() throws Exception { try { XMLUnit.setIgnoreComments(true); testNormalization(); } finally { XMLUnit.setIgnoreComments(false); } } public void testNormalizedWhitespace() throws Exception { String xml1 = "<foo>a = b;</foo>"; String xml2 = "<foo>\r\n\ta =\tb; \r\n</foo>"; try { assertFalse(buildDiff(xml1, xml2).identical()); assertFalse(buildDiff(xml1, xml2).similar()); XMLUnit.setNormalizeWhitespace(true); assertTrue(buildDiff(xml1, xml2).identical()); assertTrue(buildDiff(xml1, xml2).similar()); } finally { XMLUnit.setNormalizeWhitespace(false); } } /** * inspired by {@link * http://day-to-day-stuff.blogspot.com/2007/05/comparing-xml-in-junit-test.html * Erik von Oosten's Weblog}, made us implement special handling * of schemaLocation. */ public void testNamespacePrefixDiff() throws Exception { String xml1 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<Message xmlns=\"http://www.a.nl/a10.xsd\"" + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" + " xsi:schemaLocation=\"C:/longpath/a10.xsd\"" + ">" + "<MessageHeader/>" + "</Message>"; String xml2 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<a:Message xmlns:a=\"http://www.a.nl/a10.xsd\">" + "<a:MessageHeader/>" + "</a:Message>"; Diff d = buildDiff(xml1, xml2); assertFalse(d.toString(), d.identical()); assertTrue(d.toString(), d.similar()); } /** * Bug Report 1779701 * @see http://sourceforge.net/tracker/index.php?func=detail&amp;aid=1779701&amp;group_id=23187&amp;atid=377768 */ public void testWhitespaceAndNamespaces() throws Exception { String control = "<env:Envelope xmlns:env='http://schemas.xmlsoap.org/soap/envelope/'>" + "\r\n <env:Header/>" + "\r\n </env:Envelope>"; String test = "<env:Envelope xmlns:env='http://schemas.xmlsoap.org/soap/envelope/'>" + "<env:Header/>" + "</env:Envelope>"; XMLUnit.setIgnoreWhitespace(true); try { Diff diff = buildDiff(control, test); assertTrue(diff.toString(), diff.identical()); } finally { XMLUnit.setIgnoreWhitespace(false); } } /** * Bug Report 1863632 * @see http://sourceforge.net/tracker/index.php?func=detail&amp;aid=1863632&amp;group_id=23187&amp;atid=377768 */ public void testBasicWhitespaceHandling() throws Exception { String control = "<a><b/></a>"; String test = "<a>\r\n <b/>\r\n</a>"; XMLUnit.setIgnoreWhitespace(true); try { Diff diff = buildDiff(control, test); assertTrue(diff.toString(), diff.identical()); } finally { XMLUnit.setIgnoreWhitespace(false); } } public void testUpgradingOfRecoverableDifference() throws Exception { String control = "<foo:bar xmlns:foo='urn:foo'/>"; String test = "<bar xmlns='urn:foo'/>"; Diff diff = buildDiff(control, test); assertFalse(diff.toString(), diff.identical()); assertTrue(diff.toString(), diff.similar()); diff = buildDiff(control, test); diff.overrideDifferenceListener(new DifferenceListener() { public int differenceFound(Difference d) { return RETURN_UPGRADE_DIFFERENCE_NODES_DIFFERENT; } public void skippedComparison(Node c, Node t) { fail("skippedComparison shouldn't get invoked"); } }); assertFalse(diff.toString(), diff.identical()); assertFalse(diff.toString(), diff.similar()); } public void testMatchTrackerSetViaOverride() throws Exception { Diff diff = buildDiff("<foo/>", "<foo/>"); final int[] count = new int[1]; diff.overrideMatchTracker(new MatchTracker() { public void matchFound(Difference d) { count[0]++; } }); assertTrue(diff.identical()); // NODE_TYPE (not null), NODE_TYPE(Document), NAMESPACE_URI(none), // NAMESPACE_PREFIX(none), HAS_DOCTYPE_DECLARATION(no), // HAS_CHILD_NODES(true) // // NODE_TYPE(Element), NAMESPACE_URI(none), // NAMESPACE_PREFIX(none), ELEMENT_TAG_NAME(foo), // ELEMENT_NUM_ATTRIBUTE(none), HAS_CHILD_NODES(false), // CHILD_NODELIST_LENGTH(0) assertEquals(13, count[0]); } public void testMatchTrackerSetViaEngine() throws Exception { final int[] count = new int[1]; DifferenceEngine engine = new DifferenceEngine(new ComparisonController() { public boolean haltComparison(Difference afterDifference) { fail("haltComparison invoked"); // NOTREACHED return false; } }, new MatchTracker() { public void matchFound(Difference d) { count[0]++; } }); Diff diff = buildDiff("<foo/>", "<foo/>", engine); assertTrue(diff.identical()); // NODE_TYPE (not null), NODE_TYPE(Document), NAMESPACE_URI(none), // NAMESPACE_PREFIX(none), HAS_DOCTYPE_DECLARATION(no), // HAS_CHILD_NODES(true) // // NODE_TYPE(Element), NAMESPACE_URI(none), // NAMESPACE_PREFIX(none), ELEMENT_TAG_NAME(foo), // ELEMENT_NUM_ATTRIBUTE(none), HAS_CHILD_NODES(false), // CHILD_NODELIST_LENGTH(0) assertEquals(13, count[0]); } public void testMatchTrackerSetViaOverrideOnEngine() throws Exception { DifferenceEngine engine = new DifferenceEngine(new ComparisonController() { public boolean haltComparison(Difference afterDifference) { fail("haltComparison invoked"); // NOTREACHED return false; } }); Diff diff = buildDiff("<foo/>", "<foo/>", engine); final int[] count = new int[1]; diff.overrideMatchTracker(new MatchTracker() { public void matchFound(Difference d) { count[0]++; } }); assertTrue(diff.identical()); // NODE_TYPE (not null), NODE_TYPE(Document), NAMESPACE_URI(none), // NAMESPACE_PREFIX(none), HAS_DOCTYPE_DECLARATION(no), // HAS_CHILD_NODES(true) // // NODE_TYPE(Element), NAMESPACE_URI(none), // NAMESPACE_PREFIX(none), ELEMENT_TAG_NAME(foo), // ELEMENT_NUM_ATTRIBUTE(none), HAS_CHILD_NODES(false) // CHILD_NODELIST_LENGTH(0) assertEquals(13, count[0]); } public void testCDATAAndIgnoreWhitespace() throws Exception { String control = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + "<Data><Person><Name><![CDATA[JOE]]></Name></Person></Data>"; String test = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +"<Data>" +" <Person>" +" <Name>" +" <![CDATA[JOE]]>" +" </Name>" +" </Person>" +"</Data>"; XMLUnit.setIgnoreWhitespace(true); XMLUnit.setIgnoreDiffBetweenTextAndCDATA(true); try { Diff diff = buildDiff(control, test); assertTrue(diff.toString(), diff.similar()); } finally { XMLUnit.setIgnoreWhitespace(false); XMLUnit.setIgnoreDiffBetweenTextAndCDATA(false); } } /** * Not a real test. Need something that actually fails unless I * set the flag. */ public void testEntityExpansion() throws Exception { String control = "<root>bla&#13;bla</root>"; String test = "<root>bla&#xD;bla</root>"; //XMLUnit.setExpandEntityReferences(true); try { Diff diff = buildDiff(control, test); assertTrue(diff.toString(), diff.similar()); } finally { XMLUnit.setExpandEntityReferences(false); } } /** * @see https://sourceforge.net/tracker/?func=detail&aid=2807167&group_id=23187&atid=377768 */ public void testIssue2807167() throws Exception { String test = "<tag>" + "<child amount=\"100\" />" + "<child amount=\"100\" />" + "<child amount=\"100\" />" + "<child amount=\"250\" />" + "<child amount=\"100\" />" + "</tag>"; String control = "<tag>" + "<child amount=\"100\" />" + "<child amount=\"100\" />" + "<child amount=\"250\" />" + "<child amount=\"100\" />" + "<child amount=\"100\" />" + "</tag>"; Diff diff = new Diff(control, test); diff.overrideElementQualifier(new ElementNameAndAttributeQualifier()); assertTrue(diff.toString(), diff.similar()); } /** * @see http://sourceforge.net/tracker/?func=detail&atid=377768&aid=3602981&group_id=23187 */ public void testXsiTypeSpecialCase() throws Exception { String test = "<ns1:Square xsi:type=\"ns1:Shape\" " + "xmlns:ns1=\"http://example.com/\" " + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"/>"; String control = "<ns2:Square xsi:type=\"ns2:Shape\" " + "xmlns:ns2=\"http://example.com/\" " + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"/>"; Diff diff = new Diff(control, test); assertTrue(diff.toString(), diff.similar()); } public void testXsiTypeSpecialCaseShortLocalName() throws Exception { String test = "<ns1:Square xsi:type=\"ns1:a\" " + "xmlns:ns1=\"http://example.com/\" " + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"/>"; String control = "<ns2:Square xsi:type=\"ns2:a\" " + "xmlns:ns2=\"http://example.com/\" " + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"/>"; Diff diff = new Diff(control, test); assertTrue(diff.toString(), diff.similar()); } public void testXsiTypeSpecialCaseWorksWithDefaultNs() throws Exception { String test = "<Square xsi:type=\"Shape\" " + "xmlns=\"http://example.com/\" " + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"/>"; String control = "<ns2:Square xsi:type=\"ns2:Shape\" " + "xmlns:ns2=\"http://example.com/\" " + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"/>"; Diff diff = new Diff(control, test); assertTrue(diff.toString(), diff.similar()); } public void testXsiTypeSpecialCaseInheritsParentNs() throws Exception { String test = "<ns1:Shapes xmlns:ns1=\"http://example.com/\">" + "<ns1:Square xsi:type=\"ns1:Shape\" " + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"/>" + "</ns1:Shapes>"; String control = "<ns2:Shapes xmlns:ns2=\"http://example.com/\">" + "<ns2:Square xsi:type=\"ns2:Shape\" " + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"/>" + "</ns2:Shapes>"; Diff diff = new Diff(control, test); assertTrue(diff.toString(), diff.similar()); } public void testXsiTypeSpecialCaseDoesntIgnorePrefix() throws Exception { String test = "<ns1:Square xsi:type=\"ns1:Shape\" " + "xmlns:ns1=\"http://example.com/\" " + "xmlns:ns2=\"http://example.com/another-uri/\" " + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"/>"; String control = "<ns1:Square xsi:type=\"ns2:Shape\" " + "xmlns:ns1=\"http://example.com/\" " + "xmlns:ns2=\"http://example.com/another-uri/\" " + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"/>"; Diff diff = new Diff(control, test); assertFalse(diff.toString(), diff.similar()); } public void testXsiNil() throws Exception { String test = "<foo xsi:nil=\"true\" " + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"/>"; String control = "<foo xsi:nil=\"false\" " + "xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"/>"; Diff diff = new Diff(control, test); assertFalse(diff.toString(), diff.similar()); } }
/* Copyright 2022 The Kubernetes Authors. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package io.kubernetes.client.openapi.models; /** Generated */ public class V1NamespaceFluentImpl< A extends io.kubernetes.client.openapi.models.V1NamespaceFluent<A>> extends io.kubernetes.client.fluent.BaseFluent<A> implements io.kubernetes.client.openapi.models.V1NamespaceFluent<A> { public V1NamespaceFluentImpl() {} public V1NamespaceFluentImpl(io.kubernetes.client.openapi.models.V1Namespace instance) { this.withApiVersion(instance.getApiVersion()); this.withKind(instance.getKind()); this.withMetadata(instance.getMetadata()); this.withSpec(instance.getSpec()); this.withStatus(instance.getStatus()); } private java.lang.String apiVersion; private java.lang.String kind; private io.kubernetes.client.openapi.models.V1ObjectMetaBuilder metadata; private io.kubernetes.client.openapi.models.V1NamespaceSpecBuilder spec; private io.kubernetes.client.openapi.models.V1NamespaceStatusBuilder status; public java.lang.String getApiVersion() { return this.apiVersion; } public A withApiVersion(java.lang.String apiVersion) { this.apiVersion = apiVersion; return (A) this; } public java.lang.Boolean hasApiVersion() { return this.apiVersion != null; } /** Method is deprecated. use withApiVersion instead. */ @java.lang.Deprecated public A withNewApiVersion(java.lang.String original) { return (A) withApiVersion(new String(original)); } public java.lang.String getKind() { return this.kind; } public A withKind(java.lang.String kind) { this.kind = kind; return (A) this; } public java.lang.Boolean hasKind() { return this.kind != null; } /** Method is deprecated. use withKind instead. */ @java.lang.Deprecated public A withNewKind(java.lang.String original) { return (A) withKind(new String(original)); } /** * This method has been deprecated, please use method buildMetadata instead. * * @return The buildable object. */ @java.lang.Deprecated public io.kubernetes.client.openapi.models.V1ObjectMeta getMetadata() { return this.metadata != null ? this.metadata.build() : null; } public io.kubernetes.client.openapi.models.V1ObjectMeta buildMetadata() { return this.metadata != null ? this.metadata.build() : null; } public A withMetadata(io.kubernetes.client.openapi.models.V1ObjectMeta metadata) { _visitables.get("metadata").remove(this.metadata); if (metadata != null) { this.metadata = new io.kubernetes.client.openapi.models.V1ObjectMetaBuilder(metadata); _visitables.get("metadata").add(this.metadata); } return (A) this; } public java.lang.Boolean hasMetadata() { return this.metadata != null; } public io.kubernetes.client.openapi.models.V1NamespaceFluent.MetadataNested<A> withNewMetadata() { return new io.kubernetes.client.openapi.models.V1NamespaceFluentImpl.MetadataNestedImpl(); } public io.kubernetes.client.openapi.models.V1NamespaceFluent.MetadataNested<A> withNewMetadataLike(io.kubernetes.client.openapi.models.V1ObjectMeta item) { return new io.kubernetes.client.openapi.models.V1NamespaceFluentImpl.MetadataNestedImpl(item); } public io.kubernetes.client.openapi.models.V1NamespaceFluent.MetadataNested<A> editMetadata() { return withNewMetadataLike(getMetadata()); } public io.kubernetes.client.openapi.models.V1NamespaceFluent.MetadataNested<A> editOrNewMetadata() { return withNewMetadataLike( getMetadata() != null ? getMetadata() : new io.kubernetes.client.openapi.models.V1ObjectMetaBuilder().build()); } public io.kubernetes.client.openapi.models.V1NamespaceFluent.MetadataNested<A> editOrNewMetadataLike(io.kubernetes.client.openapi.models.V1ObjectMeta item) { return withNewMetadataLike(getMetadata() != null ? getMetadata() : item); } /** * This method has been deprecated, please use method buildSpec instead. * * @return The buildable object. */ @java.lang.Deprecated public io.kubernetes.client.openapi.models.V1NamespaceSpec getSpec() { return this.spec != null ? this.spec.build() : null; } public io.kubernetes.client.openapi.models.V1NamespaceSpec buildSpec() { return this.spec != null ? this.spec.build() : null; } public A withSpec(io.kubernetes.client.openapi.models.V1NamespaceSpec spec) { _visitables.get("spec").remove(this.spec); if (spec != null) { this.spec = new io.kubernetes.client.openapi.models.V1NamespaceSpecBuilder(spec); _visitables.get("spec").add(this.spec); } return (A) this; } public java.lang.Boolean hasSpec() { return this.spec != null; } public io.kubernetes.client.openapi.models.V1NamespaceFluent.SpecNested<A> withNewSpec() { return new io.kubernetes.client.openapi.models.V1NamespaceFluentImpl.SpecNestedImpl(); } public io.kubernetes.client.openapi.models.V1NamespaceFluent.SpecNested<A> withNewSpecLike( io.kubernetes.client.openapi.models.V1NamespaceSpec item) { return new io.kubernetes.client.openapi.models.V1NamespaceFluentImpl.SpecNestedImpl(item); } public io.kubernetes.client.openapi.models.V1NamespaceFluent.SpecNested<A> editSpec() { return withNewSpecLike(getSpec()); } public io.kubernetes.client.openapi.models.V1NamespaceFluent.SpecNested<A> editOrNewSpec() { return withNewSpecLike( getSpec() != null ? getSpec() : new io.kubernetes.client.openapi.models.V1NamespaceSpecBuilder().build()); } public io.kubernetes.client.openapi.models.V1NamespaceFluent.SpecNested<A> editOrNewSpecLike( io.kubernetes.client.openapi.models.V1NamespaceSpec item) { return withNewSpecLike(getSpec() != null ? getSpec() : item); } /** * This method has been deprecated, please use method buildStatus instead. * * @return The buildable object. */ @java.lang.Deprecated public io.kubernetes.client.openapi.models.V1NamespaceStatus getStatus() { return this.status != null ? this.status.build() : null; } public io.kubernetes.client.openapi.models.V1NamespaceStatus buildStatus() { return this.status != null ? this.status.build() : null; } public A withStatus(io.kubernetes.client.openapi.models.V1NamespaceStatus status) { _visitables.get("status").remove(this.status); if (status != null) { this.status = new io.kubernetes.client.openapi.models.V1NamespaceStatusBuilder(status); _visitables.get("status").add(this.status); } return (A) this; } public java.lang.Boolean hasStatus() { return this.status != null; } public io.kubernetes.client.openapi.models.V1NamespaceFluent.StatusNested<A> withNewStatus() { return new io.kubernetes.client.openapi.models.V1NamespaceFluentImpl.StatusNestedImpl(); } public io.kubernetes.client.openapi.models.V1NamespaceFluent.StatusNested<A> withNewStatusLike( io.kubernetes.client.openapi.models.V1NamespaceStatus item) { return new io.kubernetes.client.openapi.models.V1NamespaceFluentImpl.StatusNestedImpl(item); } public io.kubernetes.client.openapi.models.V1NamespaceFluent.StatusNested<A> editStatus() { return withNewStatusLike(getStatus()); } public io.kubernetes.client.openapi.models.V1NamespaceFluent.StatusNested<A> editOrNewStatus() { return withNewStatusLike( getStatus() != null ? getStatus() : new io.kubernetes.client.openapi.models.V1NamespaceStatusBuilder().build()); } public io.kubernetes.client.openapi.models.V1NamespaceFluent.StatusNested<A> editOrNewStatusLike( io.kubernetes.client.openapi.models.V1NamespaceStatus item) { return withNewStatusLike(getStatus() != null ? getStatus() : item); } public boolean equals(java.lang.Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; V1NamespaceFluentImpl that = (V1NamespaceFluentImpl) o; if (apiVersion != null ? !apiVersion.equals(that.apiVersion) : that.apiVersion != null) return false; if (kind != null ? !kind.equals(that.kind) : that.kind != null) return false; if (metadata != null ? !metadata.equals(that.metadata) : that.metadata != null) return false; if (spec != null ? !spec.equals(that.spec) : that.spec != null) return false; if (status != null ? !status.equals(that.status) : that.status != null) return false; return true; } public int hashCode() { return java.util.Objects.hash(apiVersion, kind, metadata, spec, status, super.hashCode()); } public class MetadataNestedImpl<N> extends io.kubernetes.client.openapi.models.V1ObjectMetaFluentImpl< io.kubernetes.client.openapi.models.V1NamespaceFluent.MetadataNested<N>> implements io.kubernetes.client.openapi.models.V1NamespaceFluent.MetadataNested<N>, io.kubernetes.client.fluent.Nested<N> { MetadataNestedImpl(io.kubernetes.client.openapi.models.V1ObjectMeta item) { this.builder = new io.kubernetes.client.openapi.models.V1ObjectMetaBuilder(this, item); } MetadataNestedImpl() { this.builder = new io.kubernetes.client.openapi.models.V1ObjectMetaBuilder(this); } io.kubernetes.client.openapi.models.V1ObjectMetaBuilder builder; public N and() { return (N) V1NamespaceFluentImpl.this.withMetadata(builder.build()); } public N endMetadata() { return and(); } } public class SpecNestedImpl<N> extends io.kubernetes.client.openapi.models.V1NamespaceSpecFluentImpl< io.kubernetes.client.openapi.models.V1NamespaceFluent.SpecNested<N>> implements io.kubernetes.client.openapi.models.V1NamespaceFluent.SpecNested<N>, io.kubernetes.client.fluent.Nested<N> { SpecNestedImpl(io.kubernetes.client.openapi.models.V1NamespaceSpec item) { this.builder = new io.kubernetes.client.openapi.models.V1NamespaceSpecBuilder(this, item); } SpecNestedImpl() { this.builder = new io.kubernetes.client.openapi.models.V1NamespaceSpecBuilder(this); } io.kubernetes.client.openapi.models.V1NamespaceSpecBuilder builder; public N and() { return (N) V1NamespaceFluentImpl.this.withSpec(builder.build()); } public N endSpec() { return and(); } } public class StatusNestedImpl<N> extends io.kubernetes.client.openapi.models.V1NamespaceStatusFluentImpl< io.kubernetes.client.openapi.models.V1NamespaceFluent.StatusNested<N>> implements io.kubernetes.client.openapi.models.V1NamespaceFluent.StatusNested<N>, io.kubernetes.client.fluent.Nested<N> { StatusNestedImpl(io.kubernetes.client.openapi.models.V1NamespaceStatus item) { this.builder = new io.kubernetes.client.openapi.models.V1NamespaceStatusBuilder(this, item); } StatusNestedImpl() { this.builder = new io.kubernetes.client.openapi.models.V1NamespaceStatusBuilder(this); } io.kubernetes.client.openapi.models.V1NamespaceStatusBuilder builder; public N and() { return (N) V1NamespaceFluentImpl.this.withStatus(builder.build()); } public N endStatus() { return and(); } } }
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.index.get; import org.apache.lucene.index.Term; import org.elasticsearch.ElasticsearchException; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.collect.Tuple; import org.elasticsearch.common.lucene.uid.Versions; import org.elasticsearch.common.metrics.CounterMetric; import org.elasticsearch.common.metrics.MeanMetric; import org.elasticsearch.common.util.set.Sets; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentHelper; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.common.xcontent.support.XContentMapValues; import org.elasticsearch.index.IndexSettings; import org.elasticsearch.index.VersionType; import org.elasticsearch.index.engine.Engine; import org.elasticsearch.index.fieldvisitor.CustomFieldsVisitor; import org.elasticsearch.index.fieldvisitor.FieldsVisitor; import org.elasticsearch.index.mapper.DocumentMapper; import org.elasticsearch.index.mapper.FieldMapper; import org.elasticsearch.index.mapper.MapperService; import org.elasticsearch.index.mapper.Uid; import org.elasticsearch.index.mapper.internal.ParentFieldMapper; import org.elasticsearch.index.mapper.internal.RoutingFieldMapper; import org.elasticsearch.index.mapper.internal.SourceFieldMapper; import org.elasticsearch.index.mapper.internal.TTLFieldMapper; import org.elasticsearch.index.mapper.internal.TimestampFieldMapper; import org.elasticsearch.index.mapper.internal.UidFieldMapper; import org.elasticsearch.index.shard.AbstractIndexShardComponent; import org.elasticsearch.index.shard.IndexShard; import org.elasticsearch.index.translog.Translog; import org.elasticsearch.search.fetch.parent.ParentFieldSubFetchPhase; import org.elasticsearch.search.fetch.source.FetchSourceContext; import org.elasticsearch.search.lookup.LeafSearchLookup; import org.elasticsearch.search.lookup.SearchLookup; import java.io.IOException; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.TimeUnit; /** */ public final class ShardGetService extends AbstractIndexShardComponent { private final MapperService mapperService; private final MeanMetric existsMetric = new MeanMetric(); private final MeanMetric missingMetric = new MeanMetric(); private final CounterMetric currentMetric = new CounterMetric(); private final IndexShard indexShard; public ShardGetService(IndexSettings indexSettings, IndexShard indexShard, MapperService mapperService) { super(indexShard.shardId(), indexSettings); this.mapperService = mapperService; this.indexShard = indexShard; } public GetStats stats() { return new GetStats(existsMetric.count(), TimeUnit.NANOSECONDS.toMillis(existsMetric.sum()), missingMetric.count(), TimeUnit.NANOSECONDS.toMillis(missingMetric.sum()), currentMetric.count()); } public GetResult get(String type, String id, String[] gFields, boolean realtime, long version, VersionType versionType, FetchSourceContext fetchSourceContext, boolean ignoreErrorsOnGeneratedFields) { currentMetric.inc(); try { long now = System.nanoTime(); GetResult getResult = innerGet(type, id, gFields, realtime, version, versionType, fetchSourceContext, ignoreErrorsOnGeneratedFields); if (getResult.isExists()) { existsMetric.inc(System.nanoTime() - now); } else { missingMetric.inc(System.nanoTime() - now); } return getResult; } finally { currentMetric.dec(); } } /** * Returns {@link GetResult} based on the specified {@link org.elasticsearch.index.engine.Engine.GetResult} argument. * This method basically loads specified fields for the associated document in the engineGetResult. * This method load the fields from the Lucene index and not from transaction log and therefore isn't realtime. * <p> * Note: Call <b>must</b> release engine searcher associated with engineGetResult! */ public GetResult get(Engine.GetResult engineGetResult, String id, String type, String[] fields, FetchSourceContext fetchSourceContext) { if (!engineGetResult.exists()) { return new GetResult(shardId.getIndexName(), type, id, -1, false, null, null); } currentMetric.inc(); try { long now = System.nanoTime(); fetchSourceContext = normalizeFetchSourceContent(fetchSourceContext, fields); GetResult getResult = innerGetLoadFromStoredFields(type, id, fields, fetchSourceContext, engineGetResult, mapperService); if (getResult.isExists()) { existsMetric.inc(System.nanoTime() - now); } else { missingMetric.inc(System.nanoTime() - now); // This shouldn't happen... } return getResult; } finally { currentMetric.dec(); } } /** * decides what needs to be done based on the request input and always returns a valid non-null FetchSourceContext */ private FetchSourceContext normalizeFetchSourceContent(@Nullable FetchSourceContext context, @Nullable String[] gFields) { if (context != null) { return context; } if (gFields == null) { return FetchSourceContext.FETCH_SOURCE; } for (String field : gFields) { if (SourceFieldMapper.NAME.equals(field)) { return FetchSourceContext.FETCH_SOURCE; } } return FetchSourceContext.DO_NOT_FETCH_SOURCE; } private GetResult innerGet(String type, String id, String[] gFields, boolean realtime, long version, VersionType versionType, FetchSourceContext fetchSourceContext, boolean ignoreErrorsOnGeneratedFields) { fetchSourceContext = normalizeFetchSourceContent(fetchSourceContext, gFields); Engine.GetResult get = null; if (type == null || type.equals("_all")) { for (String typeX : mapperService.types()) { get = indexShard.get(new Engine.Get(realtime, new Term(UidFieldMapper.NAME, Uid.createUidAsBytes(typeX, id))) .version(version).versionType(versionType)); if (get.exists()) { type = typeX; break; } else { get.release(); } } if (get == null) { return new GetResult(shardId.getIndexName(), type, id, -1, false, null, null); } if (!get.exists()) { // no need to release here as well..., we release in the for loop for non exists return new GetResult(shardId.getIndexName(), type, id, -1, false, null, null); } } else { get = indexShard.get(new Engine.Get(realtime, new Term(UidFieldMapper.NAME, Uid.createUidAsBytes(type, id))) .version(version).versionType(versionType)); if (!get.exists()) { get.release(); return new GetResult(shardId.getIndexName(), type, id, -1, false, null, null); } } try { // break between having loaded it from translog (so we only have _source), and having a document to load if (get.docIdAndVersion() != null) { return innerGetLoadFromStoredFields(type, id, gFields, fetchSourceContext, get, mapperService); } else { Translog.Source source = get.source(); Map<String, GetField> fields = null; SearchLookup searchLookup = null; // we can only load scripts that can run against the source Set<String> neededFields = new HashSet<>(); // add meta fields neededFields.add(RoutingFieldMapper.NAME); DocumentMapper docMapper = mapperService.documentMapper(type); if (docMapper.parentFieldMapper().active()) { neededFields.add(ParentFieldMapper.NAME); } if (docMapper.timestampFieldMapper().enabled()) { neededFields.add(TimestampFieldMapper.NAME); } if (docMapper.TTLFieldMapper().enabled()) { neededFields.add(TTLFieldMapper.NAME); } // add requested fields if (gFields != null) { neededFields.addAll(Arrays.asList(gFields)); } for (String field : neededFields) { if (SourceFieldMapper.NAME.equals(field)) { // dealt with when normalizing fetchSourceContext. continue; } Object value = null; if (field.equals(RoutingFieldMapper.NAME)) { value = source.routing; } else if (field.equals(ParentFieldMapper.NAME) && docMapper.parentFieldMapper().active()) { value = source.parent; } else if (field.equals(TimestampFieldMapper.NAME) && docMapper.timestampFieldMapper().enabled()) { value = source.timestamp; } else if (field.equals(TTLFieldMapper.NAME) && docMapper.TTLFieldMapper().enabled()) { // Call value for search with timestamp + ttl here to display the live remaining ttl value and be consistent with the search result display if (source.ttl > 0) { value = docMapper.TTLFieldMapper().valueForSearch(source.timestamp + source.ttl); } } else { if (searchLookup == null) { searchLookup = new SearchLookup(mapperService, null, new String[]{type}); searchLookup.source().setSource(source.source); } FieldMapper fieldMapper = docMapper.mappers().smartNameFieldMapper(field); if (fieldMapper == null) { if (docMapper.objectMappers().get(field) != null) { // Only fail if we know it is a object field, missing paths / fields shouldn't fail. throw new IllegalArgumentException("field [" + field + "] isn't a leaf field"); } } else if (shouldGetFromSource(ignoreErrorsOnGeneratedFields, docMapper, fieldMapper)) { List<Object> values = searchLookup.source().extractRawValues(field); if (!values.isEmpty()) { value = values; } } } if (value != null) { if (fields == null) { fields = new HashMap<>(2); } if (value instanceof List) { fields.put(field, new GetField(field, (List) value)); } else { fields.put(field, new GetField(field, Collections.singletonList(value))); } } } // deal with source, but only if it's enabled (we always have it from the translog) BytesReference sourceToBeReturned = null; SourceFieldMapper sourceFieldMapper = docMapper.sourceMapper(); if (fetchSourceContext.fetchSource() && sourceFieldMapper.enabled()) { sourceToBeReturned = source.source; // Cater for source excludes/includes at the cost of performance // We must first apply the field mapper filtering to make sure we get correct results // in the case that the fetchSourceContext white lists something that's not included by the field mapper boolean sourceFieldFiltering = sourceFieldMapper.includes().length > 0 || sourceFieldMapper.excludes().length > 0; boolean sourceFetchFiltering = fetchSourceContext.includes().length > 0 || fetchSourceContext.excludes().length > 0; if (sourceFieldFiltering || sourceFetchFiltering) { // TODO: The source might parsed and available in the sourceLookup but that one uses unordered maps so different. Do we care? Tuple<XContentType, Map<String, Object>> typeMapTuple = XContentHelper.convertToMap(source.source, true); XContentType sourceContentType = typeMapTuple.v1(); Map<String, Object> sourceAsMap = typeMapTuple.v2(); if (sourceFieldFiltering) { sourceAsMap = XContentMapValues.filter(sourceAsMap, sourceFieldMapper.includes(), sourceFieldMapper.excludes()); } if (sourceFetchFiltering) { sourceAsMap = XContentMapValues.filter(sourceAsMap, fetchSourceContext.includes(), fetchSourceContext.excludes()); } try { sourceToBeReturned = XContentFactory.contentBuilder(sourceContentType).map(sourceAsMap).bytes(); } catch (IOException e) { throw new ElasticsearchException("Failed to get type [" + type + "] and id [" + id + "] with includes/excludes set", e); } } } return new GetResult(shardId.getIndexName(), type, id, get.version(), get.exists(), sourceToBeReturned, fields); } } finally { get.release(); } } protected boolean shouldGetFromSource(boolean ignoreErrorsOnGeneratedFields, DocumentMapper docMapper, FieldMapper fieldMapper) { if (!fieldMapper.isGenerated()) { //if the field is always there we check if either source mapper is enabled, in which case we get the field // from source, or, if the field is stored, in which case we have to get if from source here also (we are in the translog phase, doc not indexed yet, we annot access the stored fields) return docMapper.sourceMapper().enabled() || fieldMapper.fieldType().stored(); } else { if (!fieldMapper.fieldType().stored()) { //if it is not stored, user will not get the generated field back return false; } else { if (ignoreErrorsOnGeneratedFields) { return false; } else { throw new ElasticsearchException("Cannot access field " + fieldMapper.name() + " from transaction log. You can only get this field after refresh() has been called."); } } } } private GetResult innerGetLoadFromStoredFields(String type, String id, String[] gFields, FetchSourceContext fetchSourceContext, Engine.GetResult get, MapperService mapperService) { Map<String, GetField> fields = null; BytesReference source = null; Versions.DocIdAndVersion docIdAndVersion = get.docIdAndVersion(); FieldsVisitor fieldVisitor = buildFieldsVisitors(gFields, fetchSourceContext); if (fieldVisitor != null) { try { docIdAndVersion.context.reader().document(docIdAndVersion.docId, fieldVisitor); } catch (IOException e) { throw new ElasticsearchException("Failed to get type [" + type + "] and id [" + id + "]", e); } source = fieldVisitor.source(); if (!fieldVisitor.fields().isEmpty()) { fieldVisitor.postProcess(mapperService); fields = new HashMap<>(fieldVisitor.fields().size()); for (Map.Entry<String, List<Object>> entry : fieldVisitor.fields().entrySet()) { fields.put(entry.getKey(), new GetField(entry.getKey(), entry.getValue())); } } } DocumentMapper docMapper = mapperService.documentMapper(type); if (docMapper.parentFieldMapper().active()) { String parentId = ParentFieldSubFetchPhase.getParentId(docMapper.parentFieldMapper(), docIdAndVersion.context.reader(), docIdAndVersion.docId); if (fields == null) { fields = new HashMap<>(1); } fields.put(ParentFieldMapper.NAME, new GetField(ParentFieldMapper.NAME, Collections.singletonList(parentId))); } // now, go and do the script thingy if needed if (gFields != null && gFields.length > 0) { SearchLookup searchLookup = null; for (String field : gFields) { Object value = null; FieldMapper fieldMapper = docMapper.mappers().smartNameFieldMapper(field); if (fieldMapper == null) { if (docMapper.objectMappers().get(field) != null) { // Only fail if we know it is a object field, missing paths / fields shouldn't fail. throw new IllegalArgumentException("field [" + field + "] isn't a leaf field"); } } else if (!fieldMapper.fieldType().stored() && !fieldMapper.isGenerated()) { if (searchLookup == null) { searchLookup = new SearchLookup(mapperService, null, new String[]{type}); LeafSearchLookup leafSearchLookup = searchLookup.getLeafSearchLookup(docIdAndVersion.context); searchLookup.source().setSource(source); leafSearchLookup.setDocument(docIdAndVersion.docId); } List<Object> values = searchLookup.source().extractRawValues(field); if (!values.isEmpty()) { for (int i = 0; i < values.size(); i++) { values.set(i, fieldMapper.fieldType().valueForSearch(values.get(i))); } value = values; } } if (value != null) { if (fields == null) { fields = new HashMap<>(2); } if (value instanceof List) { fields.put(field, new GetField(field, (List) value)); } else { fields.put(field, new GetField(field, Collections.singletonList(value))); } } } } if (!fetchSourceContext.fetchSource()) { source = null; } else if (fetchSourceContext.includes().length > 0 || fetchSourceContext.excludes().length > 0) { Map<String, Object> sourceAsMap; XContentType sourceContentType = null; // TODO: The source might parsed and available in the sourceLookup but that one uses unordered maps so different. Do we care? Tuple<XContentType, Map<String, Object>> typeMapTuple = XContentHelper.convertToMap(source, true); sourceContentType = typeMapTuple.v1(); sourceAsMap = typeMapTuple.v2(); sourceAsMap = XContentMapValues.filter(sourceAsMap, fetchSourceContext.includes(), fetchSourceContext.excludes()); try { source = XContentFactory.contentBuilder(sourceContentType).map(sourceAsMap).bytes(); } catch (IOException e) { throw new ElasticsearchException("Failed to get type [" + type + "] and id [" + id + "] with includes/excludes set", e); } } return new GetResult(shardId.getIndexName(), type, id, get.version(), get.exists(), source, fields); } private static FieldsVisitor buildFieldsVisitors(String[] fields, FetchSourceContext fetchSourceContext) { if (fields == null || fields.length == 0) { return fetchSourceContext.fetchSource() ? new FieldsVisitor(true) : null; } return new CustomFieldsVisitor(Sets.newHashSet(fields), fetchSourceContext.fetchSource()); } }
package demoGui; import gui.CancelThread; import gui.UnicastListThread; import java.awt.BasicStroke; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.FlowLayout; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.awt.image.BufferedImage; import javax.imageio.ImageIO; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import javax.swing.BorderFactory; import javax.swing.Box; import javax.swing.BoxLayout; import javax.swing.GroupLayout; import javax.swing.GroupLayout.Alignment; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.JTextPane; import javax.swing.JTree; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeNode; import javax.swing.tree.TreePath; import javax.swing.border.Border; import javax.swing.border.LineBorder; import javax.swing.event.TreeSelectionEvent; import javax.swing.event.TreeSelectionListener; import javax.swing.tree.TreeSelectionModel; import java.util.ArrayList; import java.util.Arrays; import java.util.Enumeration; import java.util.concurrent.ExecutionException; import org.apache.log4j.PropertyConfigurator; public class DemoUI { private JFrame frame; protected ArrayList<String> mpGriList = new ArrayList<String>(); // List for displaying all existing MP group GRIs protected ArrayList<String> griList = new ArrayList<String>(); //List for displaying all existing non-MP GRIs protected JTree griTree = new JTree(); protected UnicastListThread listingThread; // Parallel thread used to populate list of Unicast requests. Made global so it can be accessed in CreateThread. protected DemoGuiController mpUIController; // Controller for this GUI. List models are modified here. // Also responsible for submitting requests to MultipathOSCARSClient.java protected JTextPane outputConsole; protected BackgroundPanel topology; protected ArrayList<Node> nodes = new ArrayList<Node>(); protected ArrayList<String> nodeNames = new ArrayList<String>(); protected boolean creatingRequest = false; protected boolean sourceSelection = false; protected boolean destinationSelection = false; protected boolean pathSelection = false; protected String currentSource = ""; protected String currentDestination = ""; protected int numDisjointPaths = 0; protected String srcUrn = ""; protected String dstUrn = ""; protected static DemoUI window; protected Node currentSrcNode = null; protected Node previousSrcNode = null; protected Node currentDstNode = null; protected Node previousDstNode = null; JButton createButton; JButton modifyResButton; JButton cancelResButton; JButton closeDemoButton; JButton confirm; JComboBox numPaths; /** * Launch the application. */ public static void main(String[] args) { PropertyConfigurator.configure("lib/log4j.properties"); // Eliminate Logger warnings. try { UIManager.setLookAndFeel ("com.sun.java.swing.plaf.windows.WindowsLookAndFeel"); } catch (ClassNotFoundException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (InstantiationException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (IllegalAccessException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } catch (UnsupportedLookAndFeelException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } EventQueue.invokeLater(new Runnable() { public void run() { try { window = new DemoUI(); window.frame.setExtendedState(JFrame.MAXIMIZED_BOTH); // Should maximize the window but not cover the taskbar window.frame.setVisible(true); } catch (Exception e) { e.printStackTrace(); } } }); } /** * Create the application. */ public DemoUI() { mpUIController = new DemoGuiController(); mpUIController.getAllUnicastGRIs(); // Invoke a request to List all unicast GRIs mpUIController.refreshMPGriLists(); // Invoke a request to obtain all Multipath group GRIs initialize(); // Constantly auto-refresh query output every 7 seconds in parallel (to eliminate lag/freezing) // DemoRefreshThread refresher = new DemoRefreshThread(this); refresher.execute(); } /** * Initialize the contents of the frame. */ private void initialize() { frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(1500, 790); frame.setResizable(true); frame.setTitle("Multipath OSCARS Demo"); JPanel panel = new JPanel(); panel.setPreferredSize(new Dimension(150, 480)); frame.getContentPane().add(panel, BorderLayout.WEST); createButton = new JButton("Create Request"); createButton.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent arg0) { if(creatingRequest){ cancelCreation(); } else{ modifyResButton.setEnabled(false); cancelResButton.setEnabled(false); closeDemoButton.setEnabled(false); createReservation(); } }}); createButton.setMinimumSize(new Dimension(110, 80)); createButton.setMaximumSize(new Dimension(110, 80)); modifyResButton = new JButton("Modify Request"); modifyResButton.setEnabled(false); modifyResButton.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent arg0) { createButton.setEnabled(false); modifyResButton.setEnabled(false); cancelResButton.setEnabled(false); closeDemoButton.setEnabled(false); modifyReservation(); }}); modifyResButton.setMinimumSize(new Dimension(110, 80)); modifyResButton.setMaximumSize(new Dimension(110, 80)); cancelResButton = new JButton("Cancel Request"); cancelResButton.setEnabled(false); cancelResButton.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent arg0) { createButton.setEnabled(false); modifyResButton.setEnabled(false); cancelResButton.setEnabled(false); closeDemoButton.setEnabled(false); cancelReservation(); }}); cancelResButton.setMinimumSize(new Dimension(110, 80)); cancelResButton.setMaximumSize(new Dimension(110, 80)); closeDemoButton = new JButton("Close Demo"); closeDemoButton.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent arg0) { createButton.setEnabled(false); modifyResButton.setEnabled(false); cancelResButton.setEnabled(false); closeDemoButton.setEnabled(false); System.exit(0); }}); closeDemoButton.setMinimumSize(new Dimension(110, 40)); closeDemoButton.setMaximumSize(new Dimension(110, 40)); panel.setLayout(new BoxLayout(panel, BoxLayout.PAGE_AXIS)); panel.setBorder(BorderFactory.createEmptyBorder(10,15,10,10)); panel.add(Box.createRigidArea(new Dimension(0,50))); panel.add(createButton); panel.add(Box.createRigidArea(new Dimension(0,75))); panel.add(modifyResButton); panel.add(Box.createRigidArea(new Dimension(0,75))); panel.add(cancelResButton); panel.add(Box.createRigidArea(new Dimension(0,75))); panel.add(closeDemoButton); JSplitPane splitPane = new JSplitPane(); frame.getContentPane().add(splitPane, BorderLayout.CENTER); splitPane.setEnabled( false ); topology = new BackgroundPanel(); splitPane.setRightComponent(topology); topology.setLayout(null); placeImages(topology); drawLinks(topology); handleGriTree(); JScrollPane scrollPane = new JScrollPane(griTree); scrollPane.setMinimumSize(new Dimension(150, 500)); splitPane.setLeftComponent(scrollPane); JPanel panel2 = new JPanel(); frame.getContentPane().add(panel2, BorderLayout.SOUTH); panel2.setLayout(new FlowLayout(FlowLayout.RIGHT, 5, 5)); outputConsole = new JTextPane(); outputConsole.setText("Welcome to the Multipath Client User Interface!"); outputConsole.setEditable(false); outputConsole.setPreferredSize(new Dimension(1210, 100)); outputConsole.setMaximumSize(new Dimension(1210, 100)); JScrollPane outputScrollPane = new JScrollPane(outputConsole); panel2.add(outputScrollPane); } protected void cancelCreation() { creatingRequest = false; createButton.setText("Create Request"); createButton.setBorder(null); currentSource = ""; currentDestination = ""; numDisjointPaths = 0; sourceSelection = false; destinationSelection = false; pathSelection = false; topology.resetNodes(); topology.remove(numPaths); topology.remove(confirm); topology.validate(); topology.repaint(); outputConsole.setText("Request Creation Process Cancelled"); } /** MODIFY RESERVATION **/ protected void modifyReservation() { Object griSelected = griTree.getLastSelectedPathComponent(); if(griSelected == null) { return; } createButton.setEnabled(false); closeDemoButton.setEnabled(false); cancelResButton.setEnabled(false); String griSelectedString = griSelected.toString(); if(!outputConsole.getText().contains("ACTIVE") && !outputConsole.getText().contains("RESERVED")) { JOptionPane.showMessageDialog(frame,"Inactive reservations cannot be modified!"); handleGriTree(); selectARequest(griSelectedString); cancelResButton.setEnabled(true); modifyResButton.setEnabled(true); createButton.setEnabled(true); closeDemoButton.setEnabled(true); return; } Object options[]; // Pop-up dialog // if(griSelectedString.contains("MP-")) options = new Object[]{"Add New Path to Group", "Never Mind"}; else options = new Object[]{"Add New Path to Group", "Remove Path from Group"}; int choice = JOptionPane.showOptionDialog(frame, "How would you like to modify \'" + griSelectedString + "\'?", "Modify Reservation?", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[1]); if(choice == 0) { outputConsole.setText("Attempting to create new reservation..."); String groupGRI = mpUIController.addToGroup(griSelectedString); handleGriTree(); if(groupGRI.equals("IMPOSSIBLE")) { JOptionPane.showMessageDialog(frame,"Current network state does not support adding an additional disjoint reservation to " + griSelectedString + "!"); groupGRI = griSelectedString; selectARequest(griSelectedString); } else if(!griSelectedString.contains("MP-")) { outputConsole.setText("Reservation \'" + griSelectedString + "\' and new path added to new group \'" + groupGRI + "\'."); selectARequest(groupGRI); } else { outputConsole.setText("New path added to group \'" + groupGRI + "\'."); selectARequest(groupGRI); } } else if((choice == 1) && (griSelectedString.contains("MP-"))) { handleGriTree(); selectARequest(griSelectedString); cancelResButton.setEnabled(true); modifyResButton.setEnabled(true); createButton.setEnabled(true); closeDemoButton.setEnabled(true); return; } else if(choice == 1) { BufferedReader br = null; boolean isPartOfMPGroup = false; String whichMPGroup = null; String line = null; try { br = new BufferedReader(new FileReader("mp_gri_lookup.txt")); while((line = br.readLine()) != null) { if(line.contains(griSelectedString)) { isPartOfMPGroup = true; String[] groupDecomp = line.split("_=_"); whichMPGroup = groupDecomp[0]; System.out.println(whichMPGroup); break; } } br.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } if(!isPartOfMPGroup) { JOptionPane.showMessageDialog(frame, griSelectedString + " does not belong to a Multipath group, and cannot be removed!"); handleGriTree(); selectARequest(griSelectedString); cancelResButton.setEnabled(true); modifyResButton.setEnabled(true); createButton.setEnabled(true); closeDemoButton.setEnabled(true); return; } else { Object options2[] = {"Remove", "Cancel"}; int choice2 = JOptionPane.showOptionDialog(frame, "WARNING! Removing \'" + griSelectedString + "\' from group \'" + whichMPGroup + "\' will not cancel the reservation in OSCARS. Would you like to proceed with removal?", "WARNING!", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null, options2, options2[1]); if(choice2 == 1) { handleGriTree(); selectARequest(whichMPGroup); cancelResButton.setEnabled(true); modifyResButton.setEnabled(true); createButton.setEnabled(true); closeDemoButton.setEnabled(true); return; } else { outputConsole.setText("Attempting to remove reservation from group..."); String groupGRI = mpUIController.subFromGroup(whichMPGroup, griSelectedString); outputConsole.setText("Removal operation complete."); handleGriTree(); TreePath tp = null; DefaultMutableTreeNode root = (DefaultMutableTreeNode)griTree.getModel().getRoot(); Enumeration<DefaultMutableTreeNode> e = root.depthFirstEnumeration(); while (e.hasMoreElements()) { DefaultMutableTreeNode node = e.nextElement(); if (node.toString().equalsIgnoreCase(groupGRI)) { tp = new TreePath(node.getPath()); } } if(tp!= null) { selectARequest(groupGRI); } else { topology.resetLinks(); topology.resetNodes(); } } } } handleGriTree(); cancelResButton.setEnabled(true); modifyResButton.setEnabled(true); createButton.setEnabled(true); closeDemoButton.setEnabled(true); } /***************************************************************************** * This is what happens when you click the "Cancel Reservation" button. * - Submits the request to OSCARS. *****************************************************************************/ protected void cancelReservation() { Object griSelected = griTree.getLastSelectedPathComponent(); if(griSelected == null){ return; } createButton.setEnabled(false); closeDemoButton.setEnabled(false); String griSelectedString = griSelected.toString(); if(!outputConsole.getText().contains("ACTIVE") && !outputConsole.getText().contains("RESERVED")) { JOptionPane.showMessageDialog(frame,"Inactive reservations cannot be cancelled!"); handleGriTree(); selectARequest(griSelectedString); cancelResButton.setEnabled(true); modifyResButton.setEnabled(true); createButton.setEnabled(true); closeDemoButton.setEnabled(true); return; } DemoCancelThread cancellationThread; // Parallel thread in which to perform the cancellation to prevent lag/freezing // Cancel Unicast request if(!griSelectedString.contains("MP")) { // Confirm cancellation with pop-up warning dialog // Object options[] = {"Cancel Request", "Never Mind"}; int choice = JOptionPane.showOptionDialog(frame,"Are you sure you want to cancel the unicast request \'" + griSelectedString + "\'?", "Confirm Cancel?", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[1]); if(choice == 0) // User confirmed cancellation { outputConsole.setText("Cancelling reservation..."); //mpUIController.cancelExistingReservation(uniGriSelected); cancellationThread = new DemoCancelThread(this, griSelectedString, false, true, false, 1); cancellationThread.execute(); } } // Cancel Group Request else if(griSelectedString.contains("MP")) { // Confirm cancellation with pop-up warning dialog // Object options[] = {"Cancel Group", "Never Mind"}; int choice = JOptionPane.showOptionDialog(frame,"Are you sure you want to cancel Group \'" + griSelectedString + "\'?", "Confirm Cancel?", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE, null, options, options[1]); if(choice == 0) // User confirmed cancellation { int numRequests = ((DefaultMutableTreeNode)griSelected).getChildCount(); outputConsole.setText("Cancelling reservation..."); cancellationThread = new DemoCancelThread(this, griSelectedString, true, false, true, numRequests); cancellationThread.execute(); } } handleGriTree(); selectARequest(griSelectedString); cancelResButton.setEnabled(false); modifyResButton.setEnabled(false); } /***************************************************************************** * This is what happens when you click the "Create Reservation" button. * - Submits the request to OSCARS. *****************************************************************************/ protected void createReservation() { currentSource = ""; currentDestination = ""; outputConsole.setForeground(Color.BLACK); outputConsole.setText(""); outputConsole.setText("Creating reservation..."); topology.resetLinks(); topology.resetNodes(); griTree.setSelectionPath(null); creatingRequest = true; createButton.setText("Cancel Creation"); Border roundedBorder = new LineBorder(Color.RED, 4, true); createButton.setBorder(roundedBorder); // First get the appropriate URNs for the selected src/destination // sourceSelection = true; outputConsole.setText("Select a Source Node for this Request"); Object[] numPathsArray = {"1 Path", "2 Paths", "3 Paths", "4 Paths", "5 Paths"}; numPaths = new JComboBox(numPathsArray); confirm = new JButton("Confirm Selection"); numPaths.setSelectedIndex(0); numPaths.setEditable(false); topology.add(numPaths); numPaths.setBounds(300, 530, 75, 40); numPaths.setVisible(false); numPaths.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent arg0) { String selectedValue = ((JComboBox)arg0.getSource()).getSelectedItem().toString(); selectedValue = selectedValue.substring(0, selectedValue.indexOf("Path")-1); System.out.println("Value = [" + selectedValue + "]"); numDisjointPaths = Integer.parseInt(selectedValue); outputConsole.setText(numDisjointPaths + " Paths Selected"); pathSelection = true; } }); confirm.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent arg0) { String startTime = "2016-01-01 00:00"; String endTime = "2016-01-01 01:00"; int bandwidth = 10; DemoCreateThread creationThread; if(!confirmSelection()) return; else { if(sourceSelection) { sourceSelection = false; destinationSelection = true; outputConsole.setText("Select a Destination node for this Request"); return; } if(destinationSelection) { if(currentDestination.equals(currentSource)) { outputConsole.setText("Cannot have the same node as both Source and Destination for one Request. Reselect a new Destination"); return; } destinationSelection = false; //Source and Destination Chosen, now create URNs srcUrn = currentSource + " : " + "port-1" + " : " + "link1"; dstUrn = currentDestination + " : " + "port-1" + " : " + "link1"; //Select Number of Paths outputConsole.setText("Select the number of Paths for this Request"); numPaths.setVisible(true); numPaths.setSelectedIndex(0); return; } if(pathSelection) { pathSelection = false; outputConsole.setText("Creating Request..."); topology.remove(numPaths); topology.remove(confirm); topology.validate(); topology.repaint(); creationThread = new DemoCreateThread(window, srcUrn, dstUrn, startTime, endTime, bandwidth, numDisjointPaths); creationThread.execute(); createButton.setText("Create Request"); createButton.setEnabled(false); creatingRequest = false; return; } } }}); } protected boolean confirmSelection() { if(sourceSelection){ if(currentSource != ""){ return true; } else{ return false; } } if(destinationSelection){ if(currentDestination != ""){ return true; } else{ return false; } } if(pathSelection){ return true; } return false; } /** Node click action handler **/ protected void handleNodeSelection(Node node) { topology.add(confirm); confirm.setBounds(675, 530, 130, 40); if(sourceSelection) { if(node.isClickedAsSource()) // Don't do any source management if this node is already selected as source return; currentSource = node.getName(); outputConsole.setText(node.getName() + " selected as Source"); this.placeSourceNode(topology, node, previousSrcNode); previousSrcNode = node; return; } if(destinationSelection) { if(node.isClickedAsDestination()) // Don't do any destination management if this node is already selected as destination return; if(node.isClickedAsSource()) // Don't do any destination management if this node is already selected as source return; currentDestination = node.getName(); outputConsole.setText(node.getName() + " selected as Destination"); this.placeDestinationNode(topology, node, previousDstNode); previousDstNode = node; return; } } protected void handleGriTree() { // TODO Auto-generated method stub mpUIController.refreshMPGriLists(); mpUIController.getAllUnicastGRIs(); mpGriList = mpUIController.getMPGRIsAsStrings(); griList = mpUIController.getUngroupedGRIs(mpGriList); DefaultMutableTreeNode root = new DefaultMutableTreeNode("Requests"); for(int i = 0; i < mpGriList.size(); i++){ DefaultMutableTreeNode mpNode = new DefaultMutableTreeNode(mpGriList.get(i)); Object[] uniGriObjects = mpUIController.getGroupedGRIs(mpGriList.get(i)); for(int j = 0; j < uniGriObjects.length; j++){ mpNode.add(new DefaultMutableTreeNode(uniGriObjects[j].toString())); } root.add(mpNode); } for(int i = 0; i < griList.size(); i++){ DefaultMutableTreeNode ungroupedNode = new DefaultMutableTreeNode(griList.get(i)); root.add(ungroupedNode); } griTree.setModel(new DefaultTreeModel(root)); griTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); ((DefaultTreeModel)griTree.getModel()).reload(); griTree.addTreeSelectionListener(new TreeSelectionListener() { @Override public void valueChanged(TreeSelectionEvent e) { //Returns the last path element of the selection. //This method is useful only when the selection model allows a single selection. JTree tree = (JTree)e.getSource(); DefaultMutableTreeNode node = (DefaultMutableTreeNode)tree.getLastSelectedPathComponent(); if (node == null) { cancelResButton.setEnabled(false); modifyResButton.setEnabled(false); return; } //if(((String)node.getUserObject()).equals("Requests") || creatingRequest){ // tree.setSelectionPath(null); // cancelResButton.setEnabled(false); // modifyResButton.setEnabled(false); // return; //} Object nodeInfo = node.getUserObject(); ArrayList<String> queryOutput = queryGRI((String)nodeInfo); ArrayList<String> requestStrings = new ArrayList<String>(); ArrayList<String> requestStatuses = new ArrayList<String>(); for(int i = 0; i < queryOutput.size(); i++) { if (queryOutput.get(i).contains("Hops")) { requestStrings.add(queryOutput.get(i)); if(queryOutput.get(i).contains("CANCELLED")) { requestStatuses.add("CANCELLED"); } else if(queryOutput.get(i).contains("RESERVED")) { requestStatuses.add("RESERVED"); } else if(queryOutput.get(i).contains("ACTIVE")) { requestStatuses.add("ACTIVE"); } else if(queryOutput.get(i).contains("FAILED")) { requestStatuses.add("FAILED"); } else { requestStatuses.add("OTHER"); } } else if(queryOutput.get(i).contains("FAILED")) { topology.resetLinks(); requestStrings.add("FAILED"); requestStatuses.add("FAILED"); } } ArrayList<ArrayList<String>> pathStrings = new ArrayList<ArrayList<String>>(); for(int i = 0; i < requestStrings.size(); i++) { if(requestStrings.equals("FAILED")) { ArrayList<String> linkStrings = new ArrayList<String>(); linkStrings.add("FAILED"); pathStrings.add(linkStrings); } String[] splitRequest = requestStrings.get(i).split("Hops in Path:"); if(splitRequest.length > 1) { String linksInPath = splitRequest[1]; linksInPath = linksInPath.trim(); String[] links = linksInPath.split(" --> "); ArrayList<String> linkStrings = new ArrayList<String>(Arrays.asList(links)); pathStrings.add(linkStrings); } } for(int xx = 0; xx < pathStrings.size(); xx++) { if(pathStrings.get(xx).equals("FAILED")){ continue; } String[] partsOfFirstHop = pathStrings.get(xx).get(0).split("_"); String[] partsOfLastHop = pathStrings.get(xx).get(pathStrings.get(xx).size()-1).split("_"); String reservationSource = partsOfFirstHop[0]; String reservationDestination = partsOfLastHop[1]; ArrayList<Node> allTopoNodes = topology.getNodes(); Node reservationSrcNode = null; Node reservationDstNode = null; for(Node oneNode : allTopoNodes) { if(oneNode.getName().equals(reservationSource)) reservationSrcNode = oneNode; if(oneNode.getName().equals(reservationDestination)) reservationDstNode = oneNode; } currentSrcNode = reservationSrcNode; currentDstNode = reservationDstNode; placeSourceNode(topology,reservationSrcNode,previousSrcNode); placeDestinationNode(topology,reservationDstNode,previousDstNode); previousSrcNode = reservationSrcNode; previousDstNode = reservationDstNode; } if(pathStrings.size() > 0) { if(pathStrings.size() > 1) //MP { colorLinksMP(pathStrings, requestStatuses); } else //One path { colorLinks(pathStrings.get(0), requestStatuses); } } cancelResButton.setEnabled(true); modifyResButton.setEnabled(true); closeDemoButton.setEnabled(true); } }); } /***************************************************************************** * This is what happens when user or another method selects an item in the * Multipath/Subrequest/Unicast GRI lists. * - Submit the selected item for immediate Querying in OSCARS. * - Print query results to output console. * * @param isGroup, TRUE if an item in the MP-GRI list is selected, * FALSE if an item in the Subrequest GRI list is selected. *****************************************************************************/ protected ArrayList<String> queryGRI(String gri) { DemoQueryThread queryThread; // Query the GRI in a parallel thread to eliminate lag/freezing outputConsole.setForeground(Color.BLACK); outputConsole.setText(""); outputConsole.setText("Querying reservation..."); queryThread = new DemoQueryThread(gri, this); queryThread.execute(); // Perform the actual query try { queryThread.get(); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } return queryThread.getAllQueryOutput(); } void colorLinks(ArrayList<String> links, ArrayList<String> requestStatuses){ ArrayList<Link> allLinks = topology.getLinks(); for(int i = 0; i < allLinks.size(); i++){ topology.changeColor(Color.black, allLinks.get(i).getID1()); } if(requestStatuses.get(0).equals("FAILED") && links.get(0).equals("FAILED")){ topology.resetLinks(); return; } for(int i = 0; i < allLinks.size(); i++){ if(links.contains(allLinks.get(i).getID1()) || links.contains(allLinks.get(i).getID2())){ if(requestStatuses.get(0).equals("RESERVED") || requestStatuses.get(0).equals("ACTIVE") || requestStatuses.get(0).equals("OTHER")) topology.changeColor(Color.red, allLinks.get(i).getID1()); else if(requestStatuses.get(0).equals("CANCELLED") || requestStatuses.get(0).equals("FAILED")) topology.changeColor(Color.gray, allLinks.get(i).getID1()); } } return; } private void colorLinksMP(ArrayList<ArrayList<String>> pathStrings, ArrayList<String> requestStatuses) { ArrayList<Link> allLinks = topology.getLinks(); for(int i = 0; i < allLinks.size(); i++){ topology.changeColor(Color.black, allLinks.get(i).getID1()); } for(int i = 0; i < pathStrings.size(); i++){ ArrayList<String> links = pathStrings.get(i); for(int j = 0; j < allLinks.size(); j++){ if(links.contains(allLinks.get(j).getID1()) || links.contains(allLinks.get(j).getID2())){ if(requestStatuses.get(i).equals("RESERVED") || requestStatuses.get(i).equals("ACTIVE") || requestStatuses.get(i).equals("OTHER")){ switch(i){ case 0: topology.changeColor(Color.red, allLinks.get(j).getID1()); break; case 1: topology.changeColor(Color.blue, allLinks.get(j).getID1()); break; case 2: topology.changeColor(Color.green, allLinks.get(j).getID1()); break; case 3: topology.changeColor(Color.MAGENTA, allLinks.get(j).getID1()); break; } } else if(requestStatuses.get(i).equals("CANCELLED") || requestStatuses.get(i).equals("FAILED")){ topology.changeColor(Color.gray, allLinks.get(j).getID1()); } else{ //FAILED } } } } } void placeImages(BackgroundPanel panel){ Object[] topologyNodes = mpUIController.getTopologyNodes(); BufferedImage[] nodeImages; for(int i = 0; i < topologyNodes.length; i++) { String nodeName = topologyNodes[i].toString().split(" ")[0]; if(!nodeNames.contains(nodeName)){ nodeNames.add(nodeName); } } nodeImages = new BufferedImage[nodeNames.size()]; for(int i = 0; i < nodeNames.size(); i++) { nodeImages[i] = null; try { nodeImages[i] = ImageIO.read(new File("images/UnselectedNode.fw.png")); nodeImages[i] = resize(nodeImages[i],60,60); } catch (IOException e) { System.out.println("Image File not found"); } } for(int i =0; i < nodeNames.size(); i++){ Node n = new Node(nodeNames.get(i), assignCoords(i), nodeImages[i]); n.addMouseListener(new MouseAdapter() { @Override public void mousePressed(MouseEvent e) { Node node = (Node)e.getSource(); handleNodeSelection(node); return; } }); nodes.add(n); placeNodes(n, panel); } return; } /** Draw source node -- JJ Added **/ void placeSourceNode(BackgroundPanel topoMap, Node srcNode, Node previousSelection) { if(previousSelection != null) { if(previousSelection.equals(srcNode)) return; try { BufferedImage deselectedNodeImage; deselectedNodeImage = ImageIO.read(new File("images/UnselectedNode.fw.png")); deselectedNodeImage = resize(deselectedNodeImage, 60, 60); previousSelection.setImageIcon(deselectedNodeImage); } catch (IOException e) { System.out.println("Image File not found"); } previousSelection.unclickAsSource(); } try { BufferedImage srcNodeImage; srcNodeImage = ImageIO.read(new File("images/SourceNode.fw.png")); srcNodeImage = resize(srcNodeImage, 60, 60); srcNode.setImageIcon(srcNodeImage); } catch (IOException e) { System.out.println("Image File not found"); } srcNode.clickAsSource(); topoMap.repaint(); return; } /** Draw destination node -- JJ Added **/ void placeDestinationNode(BackgroundPanel topoMap, Node dstNode, Node previousSelection) { if(previousSelection != null) { if(previousSelection.equals(dstNode)) return; try { BufferedImage deselectedNodeImage; deselectedNodeImage = ImageIO.read(new File("images/UnselectedNode.fw.png")); deselectedNodeImage = resize(deselectedNodeImage, 60, 60); previousSelection.setImageIcon(deselectedNodeImage); } catch (IOException e) { System.out.println("Image File not found"); } previousSelection.unclickAsDestination(); } try { BufferedImage dstNodeImage; dstNodeImage = ImageIO.read(new File("images/DestinationNode.fw.png")); dstNodeImage = resize(dstNodeImage, 60, 60); dstNode.setImageIcon(dstNodeImage); } catch (IOException e) { System.out.println("Image File not found"); } dstNode.clickAsDestination(); topoMap.repaint(); return; } /** ReDraw node in its default state -- JJ Added **/ void clearNode(Node n) { try { BufferedImage nodeImage; nodeImage = ImageIO.read(new File("images/UnselectedNode.fw.png")); nodeImage = resize(nodeImage, 60, 60); n.setImageIcon(nodeImage); } catch (IOException e) { System.out.println("Image File not found"); } topology.repaint(); } protected Coord assignCoords(int position){ Coord c = null; switch(position){ case 0: //ALBU c = new Coord(350, 420); break; case 1: //AOFA c = new Coord(960, 160); break; case 2: //ATLA c = new Coord(800, 450); break; case 3: //CHIC c = new Coord(700, 300); break; case 4: //CLEV c = new Coord(820, 230); break; case 5: //DENV c = new Coord(375, 300); break; case 6: //ELPA c = new Coord(390, 500); break; case 7: //HOUS c = new Coord(550, 525); break; case 8: //KANS c = new Coord(520, 335); break; case 9: //NASH c = new Coord(740, 380); break; case 10: //NEWY c = new Coord(975, 250); break; case 11: //PNWG c = new Coord(124, 50); break; case 12: //SDSC c = new Coord(100, 400); break; case 13: //STAR c = new Coord(680, 220); break; case 14: //SUNN c = new Coord(65, 275); break; case 15: //WASH c = new Coord(910, 300); break; } return c; } void placeNodes(Node node, BackgroundPanel panel){ node.setBounds(node.getCoords().getX(), node.getCoords().getY(), 60, 60); panel.add(node); panel.addNode(node); return; } void drawLinks(BackgroundPanel topology){ // 0 - ALBU, 1 - AOFA, 2 - ATLA, 3 - CHIC, 4 - CLEV, 5 - DENV, 6 - ELPA, 7 - HOUS, 8 - KANS, 9 - NASH, 10 - NEWY, 11 - PNWG, 12 - SDSC, 13 - STAR, 14 - SUNN, 15 - WASH int PNWG_X = nodes.get(nodeNames.indexOf("PNWG")).getCenterCoords().getX(); int PNWG_Y = nodes.get(nodeNames.indexOf("PNWG")).getCenterCoords().getY(); int SUNN_X = nodes.get(nodeNames.indexOf("SUNN")).getCenterCoords().getX(); int SUNN_Y = nodes.get(nodeNames.indexOf("SUNN")).getCenterCoords().getY(); int ALBU_X = nodes.get(nodeNames.indexOf("ALBU")).getCenterCoords().getX(); int ALBU_Y = nodes.get(nodeNames.indexOf("ALBU")).getCenterCoords().getY(); int AOFA_X = nodes.get(nodeNames.indexOf("AOFA")).getCenterCoords().getX(); int AOFA_Y = nodes.get(nodeNames.indexOf("AOFA")).getCenterCoords().getY(); int ATLA_X = nodes.get(nodeNames.indexOf("ATLA")).getCenterCoords().getX(); int ATLA_Y = nodes.get(nodeNames.indexOf("ATLA")).getCenterCoords().getY(); int CHIC_X = nodes.get(nodeNames.indexOf("CHIC")).getCenterCoords().getX(); int CHIC_Y = nodes.get(nodeNames.indexOf("CHIC")).getCenterCoords().getY(); int CLEV_X = nodes.get(nodeNames.indexOf("CLEV")).getCenterCoords().getX(); int CLEV_Y = nodes.get(nodeNames.indexOf("CLEV")).getCenterCoords().getY(); int DENV_X = nodes.get(nodeNames.indexOf("DENV")).getCenterCoords().getX(); int DENV_Y = nodes.get(nodeNames.indexOf("DENV")).getCenterCoords().getY(); int ELPA_X = nodes.get(nodeNames.indexOf("ELPA")).getCenterCoords().getX(); int ELPA_Y = nodes.get(nodeNames.indexOf("ELPA")).getCenterCoords().getY(); int HOUS_X = nodes.get(nodeNames.indexOf("HOUS")).getCenterCoords().getX(); int HOUS_Y = nodes.get(nodeNames.indexOf("HOUS")).getCenterCoords().getY(); int KANS_X = nodes.get(nodeNames.indexOf("KANS")).getCenterCoords().getX(); int KANS_Y = nodes.get(nodeNames.indexOf("KANS")).getCenterCoords().getY(); int NASH_X = nodes.get(nodeNames.indexOf("NASH")).getCenterCoords().getX(); int NASH_Y = nodes.get(nodeNames.indexOf("NASH")).getCenterCoords().getY(); int NEWY_X = nodes.get(nodeNames.indexOf("NEWY")).getCenterCoords().getX(); int NEWY_Y = nodes.get(nodeNames.indexOf("NEWY")).getCenterCoords().getY(); int SDSC_X = nodes.get(nodeNames.indexOf("SDSC")).getCenterCoords().getX(); int SDSC_Y = nodes.get(nodeNames.indexOf("SDSC")).getCenterCoords().getY(); int STAR_X = nodes.get(nodeNames.indexOf("STAR")).getCenterCoords().getX(); int STAR_Y = nodes.get(nodeNames.indexOf("STAR")).getCenterCoords().getY(); int WASH_X = nodes.get(nodeNames.indexOf("WASH")).getCenterCoords().getX(); int WASH_Y = nodes.get(nodeNames.indexOf("WASH")).getCenterCoords().getY(); //(PNWG, SUNN) topology.addLink(PNWG_X-7, PNWG_Y-7, SUNN_X-7, SUNN_Y-7, Color.black, "PNWG_SUNN_port-1_port-1", "SUNN_PNWG_port-1_port-1"); topology.addLink(PNWG_X+7, PNWG_Y+7, SUNN_X+7, SUNN_Y+7, Color.black, "PNWG_SUNN_port-2_port-2", "SUNN_PNWG_port-2_port-2"); //(PNWG, STAR) topology.addLink(PNWG_X, PNWG_Y, STAR_X, STAR_Y, Color.black, "PNWG_STAR_port-4_port-1", "STAR_PNWG_port-1_port-4"); //(PNWG, DENV) topology.addLink(PNWG_X, PNWG_Y, DENV_X, DENV_Y, Color.black, "PNWG_DENV_port-3_port-1", "DENV_PNWG_port-1_port-3"); //(SUNN, SDSC) topology.addLink(SUNN_X, SUNN_Y, SDSC_X, SDSC_Y, Color.black, "SDSC_SUNN_port-1_port-3", "SUNN_SDSC_port-3_port-1"); //(SUNN, DENV) topology.addLink(SUNN_X, SUNN_Y, DENV_X, DENV_Y, Color.black, "DENV_SUNN_port-2_port-4", "SUNN_DENV_port-4_port-2"); //(SUNN, ELPA) topology.addLink(SUNN_X, SUNN_Y, ELPA_X, ELPA_Y, Color.black, "ELPA_SUNN_port-1_port-5", "SUNN_ELPA_port-5_port-1"); //(DENV, KANS) topology.addLink(DENV_X-10, DENV_Y-10, KANS_X-10, KANS_Y-10, Color.black, "DENV_KANS_port-4_port-1", "KANS_DENV_port-1_port-4"); topology.addLink(DENV_X+10, DENV_Y+10, KANS_X+10, KANS_Y+10, Color.black, "DENV_KANS_port-5_port-2", "KANS_DENV_port-2_port-5"); //(DENV, ALBU) topology.addLink(DENV_X, DENV_Y, ALBU_X, ALBU_Y, Color.black, "DENV_ALBU_port-3_port-1", "ALBU_DENV_port-1_port-3"); //(ALBU, ELPA) topology.addLink(ALBU_X, ALBU_Y, ELPA_X, ELPA_Y, Color.black, "ALBU_ELPA_port-2_port-2", "ELPA_ALBU_port-2_port-2"); //(ELPA, HOUS) topology.addLink(HOUS_X, HOUS_Y, ELPA_X, ELPA_Y, Color.black, "ELPA_HOUS_port-3_port-1", "HOUS_ELPA_port-1_port-3"); //(HOUS, KANS) topology.addLink(HOUS_X, HOUS_Y, KANS_X, KANS_Y, Color.black, "HOUS_KANS_port-2_port-3", "KANS_HOUS_port-3_port-2"); //(HOUS, ATLA) topology.addLink(HOUS_X, HOUS_Y, ATLA_X, ATLA_Y, Color.black, "HOUS_ATLA_port-3_port-3", "ATLA_HOUS_port-3_port-3"); //(ATLA, NASH) topology.addLink(NASH_X, NASH_Y-12, ATLA_X, ATLA_Y-12, Color.black, "ATLA_NASH_port-1_port-3", "NASH_ATLA_port-3_port-1"); topology.addLink(NASH_X, NASH_Y+12, ATLA_X, ATLA_Y+12, Color.black, "ATLA_NASH_port-2_port-4", "NASH_ATLA_port-4_port-2"); //(NASH, CHIC) topology.addLink(NASH_X-17, NASH_Y-17, CHIC_X-17, CHIC_Y-17, Color.black, "NASH_CHIC_port-1_port-5", "CHIC_NASH_port-5_port-1"); topology.addLink(NASH_X+17, NASH_Y+17, CHIC_X+17, CHIC_Y+17, Color.black, "NASH_CHIC_port-2_port-6", "CHIC_NASH_port-6_port-2"); //(CHIC, KANS) topology.addLink(KANS_X-7, KANS_Y-7, CHIC_X-7, CHIC_Y-7, Color.black, "CHIC_KANS_port-3_port-4", "KANS_CHIC_port-4_port-3"); topology.addLink(KANS_X+7, KANS_Y+7, CHIC_X+7, CHIC_Y+7, Color.black, "CHIC_KANS_port-4_port-5", "KANS_CHIC_port-5_port-4"); //(CHIC, CLEV) topology.addLink(CLEV_X-7, CLEV_Y-7, CHIC_X-7, CHIC_Y-7, Color.black, "CHIC_CLEV_port-7_port-1", "CLEV_CHIC_port-1_port-7"); topology.addLink(CLEV_X+7, CLEV_Y+7, CHIC_X+7, CHIC_Y+7, Color.black, "CHIC_CLEV_port-8_port-2", "CLEV_CHIC_port-2_port-8"); //(CHIC, STAR) topology.addLink(STAR_X-12, STAR_Y-12, CHIC_X-12, CHIC_Y-12, Color.black, "CHIC_STAR_port-1_port-2", "STAR_CHIC_port-2_port-1"); topology.addLink(STAR_X+12, STAR_Y+12, CHIC_X+12, CHIC_Y+12, Color.black, "CHIC_STAR_port-2_port-3", "STAR_CHIC_port-3_port-2"); //(CLEV, AOFA) topology.addLink(CLEV_X-7, CLEV_Y-7, AOFA_X-7, AOFA_Y-7, Color.black, "CLEV_AOFA_port-4_port-1", "AOFA_CLEV_port-1_port-4"); topology.addLink(CLEV_X+7, CLEV_Y+7, AOFA_X+7, AOFA_Y+7, Color.black, "CLEV_AOFA_port-5_port-2", "AOFA_CLEV_port-2_port-5"); //(NEWY, AOFA) topology.addLink(AOFA_X-10, AOFA_Y-10, NEWY_X-10, NEWY_Y-10, Color.black, "NEWY_AOFA_port-3_port-5", "AOFA_NEWY_port-5_port-3"); topology.addLink(AOFA_X+10, AOFA_Y+10, NEWY_X+10, NEWY_Y+10, Color.black, "NEWY_AOFA_port-2_port-4", "AOFA_NEWY_port-4_port-2"); //(NEWY, WASH) topology.addLink(NEWY_X, NEWY_Y, WASH_X, WASH_Y, Color.black, "NEWY_WASH_port-1_port-6", "WASH_NEWY_port-6_port-1"); //(WASH, ATLA) topology.addLink(ATLA_X-7, ATLA_Y-7, WASH_X-7, WASH_Y-7, Color.black, "WASH_ATLA_port-4_port-4", "ATLA_WASH_port-4_port-4"); topology.addLink(ATLA_X+7, ATLA_Y+7, WASH_X+7, WASH_Y+7, Color.black, "WASH_ATLA_port-5_port-5", "ATLA_WASH_port-5_port-5"); //(WASH, CLEV) topology.addLink(CLEV_X, CLEV_Y, WASH_X, WASH_Y, Color.black, "WASH_CLEV_port-1_port-3", "CLEV_WASH_port-3_port-1"); //(STAR, WASH) topology.addLink(STAR_X, STAR_Y, WASH_X, WASH_Y, Color.black, "STAR_WASH_port-4_port-2", "WASH_STAR_port-2_port-4"); //(WASH, AOFA) topology.addLink(AOFA_X, AOFA_Y, WASH_X, WASH_Y, Color.black, "AOFA_WASH_port-3_port-3", "WASH_AOFA_port-3_port-3"); } void updateRequestTree(JTree tree){ mpGriList = mpUIController.getMPGRIsAsStrings(); DefaultMutableTreeNode root = new DefaultMutableTreeNode("Requests"); for(int i = 0; i < mpGriList.size(); i++){ DefaultMutableTreeNode mpNode = new DefaultMutableTreeNode(mpGriList.get(i)); Object[] uniGriObjects = mpUIController.getGroupedGRIs(mpGriList.get(i)); for(int j = 0; j < uniGriObjects.length; j++){ mpNode.add(new DefaultMutableTreeNode(uniGriObjects[j].toString())); } root.add(mpNode); } tree.setModel(new DefaultTreeModel(root)); return; } public static BufferedImage resize(BufferedImage image, int width, int height) { BufferedImage bi = new BufferedImage(width, height, BufferedImage.TRANSLUCENT); Graphics2D g2d = (Graphics2D) bi.createGraphics(); g2d.addRenderingHints(new RenderingHints(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY)); g2d.drawImage(image, 0, 0, width, height, null); g2d.dispose(); return bi; } protected class Coord{ int x; int y; public Coord(int x, int y){ this.x = x; this.y = y; } public int getX(){ return this.x; } public int getY(){ return this.y; } } protected class Node extends JLabel{ private String name; private Coord coordinates; private ImageIcon imageIcon; private Coord centerCoordinates; private boolean srcClick = false; private boolean dstClick = false; public Node(String name, Coord coordinates, BufferedImage image){ this.name = name; this.coordinates = coordinates; this.imageIcon = new ImageIcon(image); this.setSize(new Dimension(this.imageIcon.getIconWidth(), this.imageIcon.getIconWidth())); this.setText(name); this.setIcon(imageIcon); this.setIconTextGap(-45); this.centerCoordinates = new Coord(coordinates.getX()+this.getIcon().getIconWidth()/2, coordinates.getY()+this.getIcon().getIconHeight()/2); } public Coord getCoords(){ return this.coordinates; } public String getName(){ return this.name; } public ImageIcon getImageIcon(){ return this.imageIcon; } public Coord getCenterCoords(){ return this.centerCoordinates; } public boolean isClickedAsSource() { return srcClick; } public void clickAsSource() { srcClick = true; } public void unclickAsSource() { srcClick = false; } public void clickAsDestination() { dstClick = true; } public void unclickAsDestination() { dstClick = false; } public boolean isClickedAsDestination() { return dstClick; } public void setImageIcon(BufferedImage newImage) { this.imageIcon = new ImageIcon(newImage); this.setIcon(imageIcon); } } protected class BackgroundPanel extends JPanel{ private ArrayList<Link> links = new ArrayList<Link>(); private ArrayList<Node> nodes = new ArrayList<Node>(); public void addLink(int x1, int x2, int x3, int x4, Color color, String id1, String id2) { links.add(new Link(x1,x2,x3,x4, color, id1, id2)); repaint(); } public void addNode(Node newNode) { nodes.add(newNode); } public void clearLinks() { links.clear(); repaint(); } public void resetLinks() { for(Link eachLink : this.links) { changeColor(Color.black, eachLink.getID1()); } } public void resetNodes() { previousSrcNode = null; previousDstNode = null; if(currentSrcNode != null) currentSrcNode.unclickAsSource(); if(currentDstNode != null) currentDstNode.unclickAsDestination(); for(Node eachNode : this.nodes) { clearNode(eachNode); } } public ArrayList<Link> getLinks(){ return this.links; } public ArrayList<Node> getNodes() { return this.nodes; } public void changeColor(Color color, String id){ for(int i = 0; i < links.size(); i++){ if(links.get(i).getID1().equals(id) || links.get(i).getID2().equals(id)){ links.get(i).setColor(color); } } repaint(); } @Override protected void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D) g; super.paintComponent(g2); try { g2.drawImage(ImageIO.read(new File("images/US.png")), 0, 0, null); g2.drawImage(ImageIO.read(new File("images/UML.png")), 50, 465, Color.WHITE, null); g2.drawImage(ImageIO.read(new File("images/Esnet_Logo.png")), 830, 520, Color.WHITE, null); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } for (Link link : links) { g2.setColor(link.color); g2.setStroke(new BasicStroke(5)); g2.drawLine(link.x1, link.y1, link.x2, link.y2); } } } protected class Link{ private int x1; private int y1; private int x2; private int y2; private Color color; private String id1; private String id2; public Link(int x1, int y1, int x2, int y2, Color color, String id1, String id2) { this.x1 = x1; this.y1 = y1; this.x2 = x2; this.y2 = y2; this.color = color; this.id1 = id1; this.id2 = id2; } public void setColor(Color color){ this.color = color; } public String getID1(){ return this.id1; } public String getID2(){ return this.id2; } } public void selectARequest(String gri) { // TODO Auto-generated method stub @SuppressWarnings("unchecked") TreePath tp = null; DefaultMutableTreeNode root = (DefaultMutableTreeNode)griTree.getModel().getRoot(); Enumeration<DefaultMutableTreeNode> e = root.depthFirstEnumeration(); while (e.hasMoreElements()) { DefaultMutableTreeNode node = e.nextElement(); if (node.toString().equalsIgnoreCase(gri)) { tp = new TreePath(node.getPath()); } } if(tp!= null){ griTree.setSelectionPath(tp); System.out.println(griTree.getSelectionPath()); } } }
package org.docksidestage.oracle.dbflute.bsbhv.pmbean; import java.util.*; import org.dbflute.outsidesql.ProcedurePmb; import org.dbflute.jdbc.*; import org.dbflute.outsidesql.PmbCustodial; import org.dbflute.util.DfTypeUtil; import org.docksidestage.oracle.dbflute.allcommon.*; import org.docksidestage.oracle.dbflute.exentity.customize.*; /** * The base class for procedure parameter-bean of SpResultSetParameterWith. <br> * This is related to "<span style="color: #AD4747">SP_RESULT_SET_PARAMETER_WITH</span>". * @author oracleman */ public class BsSpResultSetParameterWithPmb implements ProcedurePmb, FetchBean { // =================================================================================== // Definition // ========== // ----------------------------------------------------- // Procedure Parameter // ------------------- public static final String curMember_PROCEDURE_PARAMETER = "out, 0"; public static final String curMemberStatus_PROCEDURE_PARAMETER = "out, 1"; public static final String VInChar_PROCEDURE_PARAMETER = "in, 2"; public static final String VOutVarchar_PROCEDURE_PARAMETER = "out, 3"; public static final String VInoutVarchar_PROCEDURE_PARAMETER = "inout, 4"; public static final String VInNumber_PROCEDURE_PARAMETER = "in, 5"; public static final String VInDate_PROCEDURE_PARAMETER = "in, 6"; public static final String VInTimestamp_PROCEDURE_PARAMETER = "in, 7"; // =================================================================================== // Attribute // ========= /** The parameter of curMember: {REF CURSOR as Out}. */ protected List<SpResultSetParameterWithCurMember> _curMember; /** The parameter of curMemberStatus: {REF CURSOR as Out}. */ protected List<SpResultSetParameterWithCurMemberStatus> _curMemberStatus; /** The parameter of VInChar: {CHAR as In}. */ protected String _vInChar; /** The parameter of VOutVarchar: {VARCHAR2 as Out}. */ protected String _vOutVarchar; /** The parameter of VInoutVarchar: {VARCHAR2 as InOut}. */ protected String _vInoutVarchar; /** The parameter of VInNumber: {NUMBER(22) as In}. */ protected java.math.BigDecimal _vInNumber; /** The parameter of VInDate: {DATE as In}. */ protected java.time.LocalDate _vInDate; /** The parameter of VInTimestamp: {TIMESTAMP(6) as In}. */ protected java.time.LocalDateTime _vInTimestamp; /** The max size of safety result. */ protected int _safetyMaxResultSize; /** The time-zone for filtering e.g. from-to. (NullAllowed: if null, default zone) */ protected TimeZone _timeZone; // =================================================================================== // Constructor // =========== /** * Constructor for the procedure parameter-bean of SpResultSetParameterWith. <br> * This is related to "<span style="color: #AD4747">SP_RESULT_SET_PARAMETER_WITH</span>". */ public BsSpResultSetParameterWithPmb() { } // =================================================================================== // Procedure Implementation // ======================== /** * {@inheritDoc} */ public String getProcedureName() { return "SP_RESULT_SET_PARAMETER_WITH"; } /** * {@inheritDoc} */ public boolean isEscapeStatement() { return true; } // as default /** * {@inheritDoc} */ public boolean isCalledBySelect() { return false; } // resolved by generator // =================================================================================== // Safety Result // ============= /** * {@inheritDoc} */ public void checkSafetyResult(int safetyMaxResultSize) { _safetyMaxResultSize = safetyMaxResultSize; } /** * {@inheritDoc} */ public int getSafetyMaxResultSize() { return _safetyMaxResultSize; } // =================================================================================== // Assist Helper // ============= // ----------------------------------------------------- // String // ------ protected String filterStringParameter(String value) { return isEmptyStringParameterAllowed() ? value : convertEmptyToNull(value); } protected boolean isEmptyStringParameterAllowed() { return DBFluteConfig.getInstance().isEmptyStringParameterAllowed(); } protected String convertEmptyToNull(String value) { return PmbCustodial.convertEmptyToNull(value); } // ----------------------------------------------------- // Date // ---- protected Date toUtilDate(Object date) { return PmbCustodial.toUtilDate(date, _timeZone); } protected <DATE> DATE toLocalDate(Date date, Class<DATE> localType) { return PmbCustodial.toLocalDate(date, localType, chooseRealTimeZone()); } protected TimeZone chooseRealTimeZone() { return PmbCustodial.chooseRealTimeZone(_timeZone); } /** * Set time-zone, basically for LocalDate conversion. <br> * Normally you don't need to set this, you can adjust other ways. <br> * (DBFlute system's time-zone is used as default) * @param timeZone The time-zone for filtering. (NullAllowed: if null, default zone) */ public void zone(TimeZone timeZone) { _timeZone = timeZone; } // ----------------------------------------------------- // by Option Handling // ------------------ // might be called by option handling protected <NUMBER extends Number> NUMBER toNumber(Object obj, Class<NUMBER> type) { return PmbCustodial.toNumber(obj, type); } protected Boolean toBoolean(Object obj) { return PmbCustodial.toBoolean(obj); } @SuppressWarnings("unchecked") protected <ELEMENT> ArrayList<ELEMENT> newArrayList(ELEMENT... elements) { return PmbCustodial.newArrayList(elements); } // =================================================================================== // Basic Override // ============== /** * @return The display string of all parameters. (NotNull) */ @Override public String toString() { final StringBuilder sb = new StringBuilder(); sb.append(DfTypeUtil.toClassTitle(this)).append(":"); sb.append(xbuildColumnString()); return sb.toString(); } protected String xbuildColumnString() { final String dm = ", "; final StringBuilder sb = new StringBuilder(); sb.append(dm).append(_curMember); sb.append(dm).append(_curMemberStatus); sb.append(dm).append(_vInChar); sb.append(dm).append(_vOutVarchar); sb.append(dm).append(_vInoutVarchar); sb.append(dm).append(_vInNumber); sb.append(dm).append(_vInDate); sb.append(dm).append(_vInTimestamp); if (sb.length() > 0) { sb.delete(0, dm.length()); } sb.insert(0, "{").append("}"); return sb.toString(); } // =================================================================================== // Accessor // ======== /** * [get] curMember: {REF CURSOR as Out} <br> * @return The value of curMember. (NullAllowed, NotEmptyString(when String): if empty string, returns null) */ public List<SpResultSetParameterWithCurMember> getCurMember() { return _curMember; } /** * [set] curMember: {REF CURSOR as Out} <br> * @param curMember The value of curMember. (NullAllowed) */ public void setCurMember(List<SpResultSetParameterWithCurMember> curMember) { _curMember = curMember; } /** * [get] curMemberStatus: {REF CURSOR as Out} <br> * @return The value of curMemberStatus. (NullAllowed, NotEmptyString(when String): if empty string, returns null) */ public List<SpResultSetParameterWithCurMemberStatus> getCurMemberStatus() { return _curMemberStatus; } /** * [set] curMemberStatus: {REF CURSOR as Out} <br> * @param curMemberStatus The value of curMemberStatus. (NullAllowed) */ public void setCurMemberStatus(List<SpResultSetParameterWithCurMemberStatus> curMemberStatus) { _curMemberStatus = curMemberStatus; } /** * [get] VInChar: {CHAR as In} <br> * @return The value of VInChar. (NullAllowed, NotEmptyString(when String): if empty string, returns null) */ public String getVInChar() { return filterStringParameter(_vInChar); } /** * [set] VInChar: {CHAR as In} <br> * @param vInChar The value of VInChar. (NullAllowed) */ public void setVInChar(String vInChar) { _vInChar = vInChar; } /** * [get] VOutVarchar: {VARCHAR2 as Out} <br> * @return The value of VOutVarchar. (NullAllowed, NotEmptyString(when String): if empty string, returns null) */ public String getVOutVarchar() { return filterStringParameter(_vOutVarchar); } /** * [set] VOutVarchar: {VARCHAR2 as Out} <br> * @param vOutVarchar The value of VOutVarchar. (NullAllowed) */ public void setVOutVarchar(String vOutVarchar) { _vOutVarchar = vOutVarchar; } /** * [get] VInoutVarchar: {VARCHAR2 as InOut} <br> * @return The value of VInoutVarchar. (NullAllowed, NotEmptyString(when String): if empty string, returns null) */ public String getVInoutVarchar() { return filterStringParameter(_vInoutVarchar); } /** * [set] VInoutVarchar: {VARCHAR2 as InOut} <br> * @param vInoutVarchar The value of VInoutVarchar. (NullAllowed) */ public void setVInoutVarchar(String vInoutVarchar) { _vInoutVarchar = vInoutVarchar; } /** * [get] VInNumber: {NUMBER(22) as In} <br> * @return The value of VInNumber. (NullAllowed, NotEmptyString(when String): if empty string, returns null) */ public java.math.BigDecimal getVInNumber() { return _vInNumber; } /** * [set] VInNumber: {NUMBER(22) as In} <br> * @param vInNumber The value of VInNumber. (NullAllowed) */ public void setVInNumber(java.math.BigDecimal vInNumber) { _vInNumber = vInNumber; } /** * [get] VInDate: {DATE as In} <br> * @return The value of VInDate. (NullAllowed, NotEmptyString(when String): if empty string, returns null) */ public java.time.LocalDate getVInDate() { return _vInDate; } /** * [set] VInDate: {DATE as In} <br> * @param vInDate The value of VInDate. (NullAllowed) */ public void setVInDate(java.time.LocalDate vInDate) { _vInDate = vInDate; } /** * [get] VInTimestamp: {TIMESTAMP(6) as In} <br> * @return The value of VInTimestamp. (NullAllowed, NotEmptyString(when String): if empty string, returns null) */ public java.time.LocalDateTime getVInTimestamp() { return _vInTimestamp; } /** * [set] VInTimestamp: {TIMESTAMP(6) as In} <br> * @param vInTimestamp The value of VInTimestamp. (NullAllowed) */ public void setVInTimestamp(java.time.LocalDateTime vInTimestamp) { _vInTimestamp = vInTimestamp; } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.flink.test.runtime; import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.apache.flink.configuration.Configuration; import org.apache.flink.core.io.IOReadableWritable; import org.apache.flink.core.memory.DataInputView; import org.apache.flink.core.memory.DataOutputView; import org.apache.flink.runtime.io.network.api.RecordReader; import org.apache.flink.runtime.io.network.api.RecordWriter; import org.apache.flink.runtime.jobgraph.AbstractJobVertex; import org.apache.flink.runtime.jobgraph.DistributionPattern; import org.apache.flink.runtime.jobgraph.JobGraph; import org.apache.flink.runtime.jobgraph.tasks.AbstractInvokable; import org.apache.flink.runtime.jobmanager.scheduler.SlotSharingGroup; import org.apache.flink.test.util.RecordAPITestBase; import org.junit.After; public class NetworkStackThroughput { private static final Logger LOG = LoggerFactory.getLogger(NetworkStackThroughput.class); private static final String DATA_VOLUME_GB_CONFIG_KEY = "data.volume.gb"; private static final String USE_FORWARDER_CONFIG_KEY = "use.forwarder"; private static final String PARALLELISM_CONFIG_KEY = "num.subtasks"; private static final String NUM_SLOTS_PER_TM_CONFIG_KEY = "num.slots.per.tm"; private static final String IS_SLOW_SENDER_CONFIG_KEY = "is.slow.sender"; private static final String IS_SLOW_RECEIVER_CONFIG_KEY = "is.slow.receiver"; private static final int IS_SLOW_SLEEP_MS = 10; private static final int IS_SLOW_EVERY_NUM_RECORDS = (2 * 32 * 1024) / SpeedTestRecord.RECORD_SIZE; // ------------------------------------------------------------------------ // wrapper to reuse RecordAPITestBase code in runs via main() private static class TestBaseWrapper extends RecordAPITestBase { private int dataVolumeGb; private boolean useForwarder; private boolean isSlowSender; private boolean isSlowReceiver; private int parallelism; public TestBaseWrapper(Configuration config) { super(config); dataVolumeGb = config.getInteger(DATA_VOLUME_GB_CONFIG_KEY, 1); useForwarder = config.getBoolean(USE_FORWARDER_CONFIG_KEY, true); isSlowSender = config.getBoolean(IS_SLOW_SENDER_CONFIG_KEY, false); isSlowReceiver = config.getBoolean(IS_SLOW_RECEIVER_CONFIG_KEY, false); parallelism = config.getInteger(PARALLELISM_CONFIG_KEY, 1); int numSlots = config.getInteger(NUM_SLOTS_PER_TM_CONFIG_KEY, 1); if (parallelism % numSlots != 0) { throw new RuntimeException("The test case defines a parallelism that is not a multiple of the slots per task manager."); } setNumTaskManager(parallelism / numSlots); setTaskManagerNumSlots(numSlots); } @Override protected JobGraph getJobGraph() throws Exception { return createJobGraph(dataVolumeGb, useForwarder, isSlowSender, isSlowReceiver, parallelism); } private JobGraph createJobGraph(int dataVolumeGb, boolean useForwarder, boolean isSlowSender, boolean isSlowReceiver, int numSubtasks) { JobGraph jobGraph = new JobGraph("Speed Test"); SlotSharingGroup sharingGroup = new SlotSharingGroup(); AbstractJobVertex producer = new AbstractJobVertex("Speed Test Producer"); jobGraph.addVertex(producer); producer.setSlotSharingGroup(sharingGroup); producer.setInvokableClass(SpeedTestProducer.class); producer.setParallelism(numSubtasks); producer.getConfiguration().setInteger(DATA_VOLUME_GB_CONFIG_KEY, dataVolumeGb); producer.getConfiguration().setBoolean(IS_SLOW_SENDER_CONFIG_KEY, isSlowSender); AbstractJobVertex forwarder = null; if (useForwarder) { forwarder = new AbstractJobVertex("Speed Test Forwarder"); jobGraph.addVertex(forwarder); forwarder.setSlotSharingGroup(sharingGroup); forwarder.setInvokableClass(SpeedTestForwarder.class); forwarder.setParallelism(numSubtasks); } AbstractJobVertex consumer = new AbstractJobVertex("Speed Test Consumer"); jobGraph.addVertex(consumer); consumer.setSlotSharingGroup(sharingGroup); consumer.setInvokableClass(SpeedTestConsumer.class); consumer.setParallelism(numSubtasks); consumer.getConfiguration().setBoolean(IS_SLOW_RECEIVER_CONFIG_KEY, isSlowReceiver); if (useForwarder) { forwarder.connectNewDataSetAsInput(producer, DistributionPattern.BIPARTITE); consumer.connectNewDataSetAsInput(forwarder, DistributionPattern.BIPARTITE); } else { consumer.connectNewDataSetAsInput(producer, DistributionPattern.BIPARTITE); } return jobGraph; } @After public void calculateThroughput() { if (getJobExecutionResult() != null) { int dataVolumeGb = this.config.getInteger(DATA_VOLUME_GB_CONFIG_KEY, 1); double dataVolumeMbit = dataVolumeGb * 8192.0; double runtimeSecs = getJobExecutionResult().getNetRuntime() / 1000.0; int mbitPerSecond = (int) Math.round(dataVolumeMbit / runtimeSecs); LOG.info(String.format("Test finished with throughput of %d MBit/s (runtime [secs]: %.2f, " + "data volume [mbits]: %.2f)", mbitPerSecond, runtimeSecs, dataVolumeMbit)); } } } // ------------------------------------------------------------------------ public static class SpeedTestProducer extends AbstractInvokable { private RecordWriter<SpeedTestRecord> writer; @Override public void registerInputOutput() { this.writer = new RecordWriter<SpeedTestRecord>(this); } @Override public void invoke() throws Exception { this.writer.initializeSerializers(); // Determine the amount of data to send per subtask int dataVolumeGb = getTaskConfiguration().getInteger(NetworkStackThroughput.DATA_VOLUME_GB_CONFIG_KEY, 1); long dataMbPerSubtask = (dataVolumeGb * 1024) / getCurrentNumberOfSubtasks(); long numRecordsToEmit = (dataMbPerSubtask * 1024 * 1024) / SpeedTestRecord.RECORD_SIZE; LOG.info(String.format("%d/%d: Producing %d records (each record: %d bytes, total: %.2f GB)", getIndexInSubtaskGroup() + 1, getCurrentNumberOfSubtasks(), numRecordsToEmit, SpeedTestRecord.RECORD_SIZE, dataMbPerSubtask / 1024.0)); boolean isSlow = getTaskConfiguration().getBoolean(IS_SLOW_SENDER_CONFIG_KEY, false); int numRecords = 0; SpeedTestRecord record = new SpeedTestRecord(); for (long i = 0; i < numRecordsToEmit; i++) { if (isSlow && (numRecords++ % IS_SLOW_EVERY_NUM_RECORDS) == 0) { Thread.sleep(IS_SLOW_SLEEP_MS); } this.writer.emit(record); } this.writer.flush(); } } public static class SpeedTestForwarder extends AbstractInvokable { private RecordReader<SpeedTestRecord> reader; private RecordWriter<SpeedTestRecord> writer; @Override public void registerInputOutput() { this.reader = new RecordReader<SpeedTestRecord>(this, SpeedTestRecord.class); this.writer = new RecordWriter<SpeedTestRecord>(this); } @Override public void invoke() throws Exception { this.writer.initializeSerializers(); SpeedTestRecord record; while ((record = this.reader.next()) != null) { this.writer.emit(record); } this.writer.flush(); } } public static class SpeedTestConsumer extends AbstractInvokable { private RecordReader<SpeedTestRecord> reader; @Override public void registerInputOutput() { this.reader = new RecordReader<SpeedTestRecord>(this, SpeedTestRecord.class); } @Override public void invoke() throws Exception { boolean isSlow = getTaskConfiguration().getBoolean(IS_SLOW_RECEIVER_CONFIG_KEY, false); int numRecords = 0; while (this.reader.next() != null) { if (isSlow && (numRecords++ % IS_SLOW_EVERY_NUM_RECORDS) == 0) { Thread.sleep(IS_SLOW_SLEEP_MS); } } } } public static class SpeedTestRecord implements IOReadableWritable { private static final int RECORD_SIZE = 128; private final byte[] buf = new byte[RECORD_SIZE]; public SpeedTestRecord() { for (int i = 0; i < RECORD_SIZE; ++i) { this.buf[i] = (byte) (i % 128); } } @Override public void write(DataOutputView out) throws IOException { out.write(this.buf); } @Override public void read(DataInputView in) throws IOException { in.readFully(this.buf); } } // ------------------------------------------------------------------------ public void testThroughput() throws Exception { Object[][] configParams = new Object[][]{ new Object[]{1, false, false, false, 4, 2}, new Object[]{1, true, false, false, 4, 2}, new Object[]{1, true, true, false, 4, 2}, new Object[]{1, true, false, true, 4, 2}, new Object[]{2, true, false, false, 4, 2}, new Object[]{4, true, false, false, 4, 2}, new Object[]{4, true, false, false, 8, 4}, new Object[]{4, true, false, false, 16, 8}, }; for (Object[] p : configParams) { Configuration config = new Configuration(); config.setInteger(DATA_VOLUME_GB_CONFIG_KEY, (Integer) p[0]); config.setBoolean(USE_FORWARDER_CONFIG_KEY, (Boolean) p[1]); config.setBoolean(IS_SLOW_SENDER_CONFIG_KEY, (Boolean) p[2]); config.setBoolean(IS_SLOW_RECEIVER_CONFIG_KEY, (Boolean) p[3]); config.setInteger(PARALLELISM_CONFIG_KEY, (Integer) p[4]); config.setInteger(NUM_SLOTS_PER_TM_CONFIG_KEY, (Integer) p[5]); TestBaseWrapper test = new TestBaseWrapper(config); test.startCluster(); try { test.testJob(); test.calculateThroughput(); } finally { test.stopCluster(); } } } private void runAllTests() throws Exception { testThroughput(); System.out.println("Done."); } public static void main(String[] args) throws Exception { new NetworkStackThroughput().runAllTests(); } }
package com.mcxiaoke.next.ui.widget; /* * Copyright (C) 2006 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import android.content.Context; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.Filter; import android.widget.Filterable; import android.widget.ListView; import android.widget.Spinner; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * You can use this adapter to provide views for an {@link AdapterView}, * Returns a view for each object in a collection of data objects you * provide, and can be used with list-based user interface widgets such as * {@link ListView} or {@link Spinner}. * <p> * By default, the array adapter creates a view by calling {@link Object#toString()} on each * data object in the collection you provide, and places the result in a TextView. * You may also customize what type of view is used for the data object in the collection. * To customize what type of view is used for the data object, * override {@link #getView(int, View, ViewGroup)} * and inflate a view resource. * For a code example, see * the <a href="https://developer.android.com/samples/CustomChoiceList/index.html"> * CustomChoiceList</a> sample. * </p> * <p> * For an example of using an array adapter with a ListView, see the * <a href="{@docRoot}guide/topics/ui/declaring-layout.html#AdapterViews"> * Adapter Views</a> guide. * </p> * <p> * For an example of using an array adapter with a Spinner, see the * <a href="{@docRoot}guide/topics/ui/controls/spinner.html">Spinners</a> guide. * </p> * <p class="note"><strong>Note:</strong> * If you are considering using array adapter with a ListView, consider using * {@link androidx.recyclerview.widget.RecyclerView} instead. * RecyclerView offers similar features with better performance and more flexibility than * ListView provides. * See the * <a href="https://developer.android.com/guide/topics/ui/layout/recyclerview.html"> * Recycler View</a> guide.</p> */ public abstract class ArrayAdapterCompat2<T> extends BaseAdapter implements Filterable { /** * Lock used to modify the content of {@link #mObjects}. Any write operation * performed on the array should be synchronized on this lock. This lock is also * used by the filter (see {@link #getFilter()} to make a synchronized copy of * the original array of data. */ private final Object mLock = new Object(); private final LayoutInflater mInflater; private final Context mContext; /** * Contains the list of objects that represent the data of this ArrayAdapter. * The content of this list is referred to as "the array" in the documentation. */ private List<T> mObjects; /** * Indicates whether or not {@link #notifyDataSetChanged()} must be called whenever * {@link #mObjects} is modified. */ private boolean mNotifyOnChange = true; // A copy of the original mObjects array, initialized from and then used instead as soon as // the mFilter ArrayFilter is used. mObjects will then only contain the filtered values. private ArrayList<T> mOriginalValues; private ArrayFilter mFilter; public ArrayAdapterCompat2(@NonNull Context context) { this(context, new ArrayList<T>()); } /** * Constructor * * @param context The current context. * @param objects The objects to represent in the ListView. */ public ArrayAdapterCompat2(@NonNull Context context, @NonNull T[] objects) { this(context, Arrays.asList(objects)); } private ArrayAdapterCompat2(@NonNull Context context, @NonNull List<T> objects) { mContext = context; mInflater = LayoutInflater.from(context); mObjects = objects; } /** * Adds the specified object at the end of the array. * * @param object The object to add at the end of the array. */ public void add(@Nullable T object) { synchronized (mLock) { if (mOriginalValues != null) { mOriginalValues.add(object); } else { mObjects.add(object); } } if (mNotifyOnChange) notifyDataSetChanged(); } /** * Adds the specified Collection at the end of the array. * * @param collection The Collection to add at the end of the array. * @throws UnsupportedOperationException if the <tt>addAll</tt> operation * is not supported by this list * @throws ClassCastException if the class of an element of the specified * collection prevents it from being added to this list * @throws NullPointerException if the specified collection contains one * or more null elements and this list does not permit null * elements, or if the specified collection is null * @throws IllegalArgumentException if some property of an element of the * specified collection prevents it from being added to this list */ public void addAll(@NonNull Collection<? extends T> collection) { synchronized (mLock) { if (mOriginalValues != null) { mOriginalValues.addAll(collection); } else { mObjects.addAll(collection); } } if (mNotifyOnChange) notifyDataSetChanged(); } /** * Adds the specified items at the end of the array. * * @param items The items to add at the end of the array. */ public void addAll(T ... items) { synchronized (mLock) { if (mOriginalValues != null) { Collections.addAll(mOriginalValues, items); } else { Collections.addAll(mObjects, items); } } if (mNotifyOnChange) notifyDataSetChanged(); } /** * Inserts the specified object at the specified index in the array. * * @param object The object to insert into the array. * @param index The index at which the object must be inserted. */ public void insert(@Nullable T object, int index) { synchronized (mLock) { if (mOriginalValues != null) { mOriginalValues.add(index, object); } else { mObjects.add(index, object); } } if (mNotifyOnChange) notifyDataSetChanged(); } /** * Removes the specified object from the array. * * @param object The object to remove. */ public void remove(@Nullable T object) { synchronized (mLock) { if (mOriginalValues != null) { mOriginalValues.remove(object); } else { mObjects.remove(object); } } if (mNotifyOnChange) notifyDataSetChanged(); } /** * Remove all elements from the list. */ public void clear() { synchronized (mLock) { if (mOriginalValues != null) { mOriginalValues.clear(); } else { mObjects.clear(); } } if (mNotifyOnChange) notifyDataSetChanged(); } /** * Sorts the content of this adapter using the specified comparator. * * @param comparator The comparator used to sort the objects contained * in this adapter. */ public void sort(@NonNull Comparator<? super T> comparator) { synchronized (mLock) { if (mOriginalValues != null) { Collections.sort(mOriginalValues, comparator); } else { Collections.sort(mObjects, comparator); } } if (mNotifyOnChange) notifyDataSetChanged(); } @Override public void notifyDataSetChanged() { super.notifyDataSetChanged(); mNotifyOnChange = true; } /** * Control whether methods that change the list ({@link #add}, {@link #addAll(Collection)}, * {@link #addAll(Object[])}, {@link #insert}, {@link #remove}, {@link #clear}, * {@link #sort(Comparator)}) automatically call {@link #notifyDataSetChanged}. If set to * false, caller must manually call notifyDataSetChanged() to have the changes * reflected in the attached view. * * The default is true, and calling notifyDataSetChanged() * resets the flag to true. * * @param notifyOnChange if true, modifications to the list will * automatically call {@link * #notifyDataSetChanged} */ public void setNotifyOnChange(boolean notifyOnChange) { mNotifyOnChange = notifyOnChange; } /** * Returns the context associated with this array adapter. The context is used * to create views from the resource passed to the constructor. * * @return The Context associated with this adapter. */ public @NonNull Context getContext() { return mContext; } @Override public int getCount() { return mObjects.size(); } @Override public @Nullable T getItem(int position) { return mObjects.get(position); } /** * Returns the position of the specified item in the array. * * @param item The item to retrieve the position of. * * @return The position of the specified item. */ public int getPosition(@Nullable T item) { return mObjects.indexOf(item); } @Override public long getItemId(int position) { return position; } @Override public @NonNull Filter getFilter() { if (mFilter == null) { mFilter = new ArrayFilter(); } return mFilter; } /** * <p>An array filter constrains the content of the array adapter with * a prefix. Each item that does not start with the supplied prefix * is removed from the list.</p> */ private class ArrayFilter extends Filter { @Override protected FilterResults performFiltering(CharSequence prefix) { final FilterResults results = new FilterResults(); if (mOriginalValues == null) { synchronized (mLock) { mOriginalValues = new ArrayList<>(mObjects); } } if (prefix == null || prefix.length() == 0) { final ArrayList<T> list; synchronized (mLock) { list = new ArrayList<>(mOriginalValues); } results.values = list; results.count = list.size(); } else { final String prefixString = prefix.toString().toLowerCase(); final ArrayList<T> values; synchronized (mLock) { values = new ArrayList<>(mOriginalValues); } final int count = values.size(); final ArrayList<T> newValues = new ArrayList<>(); for (int i = 0; i < count; i++) { final T value = values.get(i); final String valueText = value.toString().toLowerCase(); // First match against the whole, non-splitted value if (valueText.startsWith(prefixString)) { newValues.add(value); } else { final String[] words = valueText.split(" "); for (String word : words) { if (word.startsWith(prefixString)) { newValues.add(value); break; } } } } results.values = newValues; results.count = newValues.size(); } return results; } @Override protected void publishResults(CharSequence constraint, FilterResults results) { //noinspection unchecked mObjects = (List<T>) results.values; if (results.count > 0) { notifyDataSetChanged(); } else { notifyDataSetInvalidated(); } } } }
/* * Copyright 2016 Tilmann Zaeschke * * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.tinspin.index.rtree; import java.util.Arrays; import org.tinspin.index.RectangleEntry; public class Entry<T> implements RectangleEntry<T>, Comparable<Entry<T>> { protected double[] min; protected double[] max; private T val; public Entry(double[] min, double[] max, T val) { this.min = min; this.max = max; this.val = val; } @Override public double[] lower() { return min; } @Override public double[] upper() { return max; } @Override public T value() { return val; } @Override public int compareTo(Entry<T> o) { return Double.compare(min[0], o.min[0]); } double calcOverlap(Entry<T> e) { double area = 1; for (int i = 0; i < min.length; i++) { double d = min(max[i], e.max[i]) - max(min[i], e.min[i]); if (d <= 0) { return 0; } area *= d; } return area; } /** * Check whether the current entry geometrically includes the * rectangle defined by min2 and max2. * @param min2 * @param max2 * @return WHether min2/max is included in the current entry. */ public boolean checkInclusion(double[] min2, double[] max2) { for (int i = 0; i < min.length; i++) { if (min[i] > min2[i] || max[i] < max2[i]) { return false; } } return true; } public boolean checkExactMatch(double[] min2, double[] max2) { for (int i = 0; i < min.length; i++) { if (min[i] != min2[i] || max[i] != max2[i]) { return false; } } return true; } public double calcArea() { double area = 1; for (int i = 0; i < min.length; i++) { double d = max[i] - min[i]; area *= d; } return area; } public void setToCover(Entry<T> e1, Entry<T> e2) { for (int i = 0; i < min.length; i++) { min[i] = min(e1.min[i], e2.min[i]); max[i] = max(e1.max[i], e2.max[i]); } } static double min(double d1, double d2) { return d1 < d2 ? d1 : d2; } static double max(double d1, double d2) { return d1 > d2 ? d1 : d2; } public static double calcVolume(Entry<?> e) { return calcVolume(e.min, e.max); } public static double calcVolume(double[] min, double[] max) { double v = 1; for (int d = 0; d < min.length; d++) { v *= max[d] - min[d]; } return v; } public static void calcBoundingBox(Entry<?>[] entries, int start, int end, double[] minOut, double[] maxOut) { System.arraycopy(entries[start].min, 0, minOut, 0, minOut.length); System.arraycopy(entries[start].max, 0, maxOut, 0, maxOut.length); for (int i = start+1; i < end; i++) { for (int d = 0; d < minOut.length; d++) { minOut[d] = min(minOut[d], entries[i].min[d]); maxOut[d] = max(maxOut[d], entries[i].max[d]); } } } public static double calcOverlap(double[] min1, double[] max1, double[] min2, double[] max2) { double area = 1; for (int i = 0; i < min1.length; i++) { double d = min(max1[i], max2[i]) - max(min1[i], min2[i]); if (d <= 0) { return 0; } area *= d; } return area; } public static boolean checkOverlap(double[] min, double[] max, Entry<?> e) { for (int i = 0; i < min.length; i++) { if (min[i] > e.max[i] || max[i] < e.min[i]) { return false; } } return true; } public static boolean calcIncludes(double[] minOut, double[] maxOut, double[] minIn, double[] maxIn) { for (int i = 0; i < minOut.length; i++) { if (minOut[i] > minIn[i] || maxOut[i] < maxIn[i]) { return false; } } return true; } /** * Calculates the bounding boxes and the estimated dead space. * @param entries * @param start * @param end * @param minOut * @param maxOut * @return estimated dead space */ public static double calcDeadspace(Entry<?>[] entries, int start, int end, double[] minOut, double[] maxOut) { Arrays.fill(minOut, Double.POSITIVE_INFINITY); Arrays.fill(maxOut, Double.NEGATIVE_INFINITY); double volumeSum = 0; for (int i = start; i < end; i++) { double v = 1; for (int d = 0; d < minOut.length; d++) { minOut[d] = min(minOut[d], entries[i].min[d]); maxOut[d] = max(maxOut[d], entries[i].max[d]); v *= entries[i].max[d]-entries[i].min[d]; } volumeSum += v; } //The dead volume does not consider overlapping boundary boxes of children. The //resulting deadspace estimate can therefore be negative. return calcVolume(minOut, maxOut) - volumeSum; } public static double calcMargin(double[] min2, double[] max2) { double d = 0; for (int i = 0; i < min2.length; i++) { d += max2[i] - min2[i]; } return d; } public static double calcCenterDistance(Entry<?> e1, Entry<?> e2) { double[] min1 = e1.min; double[] max1 = e1.max; double[] min2 = e2.min; double[] max2 = e2.max; double dist = 0; for (int i = 0; i < min1.length; i++) { double d = (min1[i]+max1[i])-(min2[i]+max2[i]); d *= 0.5; dist += d*d; } return Math.sqrt(dist); } @Override public String toString() { double[] len = new double[min.length]; Arrays.setAll(len, (i)->(max[i]-min[i])); return Arrays.toString(min) + "/" + Arrays.toString(max) + ";len=" + Arrays.toString(len) + ";v=" + val; } protected void set(Entry<T> e) { min = e.min; max = e.max; val = e.val; } public void set(double[] lower, double[] upper, T val) { this.min = lower; this.max = upper; this.val = val; } }
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.tools.rumen; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintStream; import java.util.ArrayList; import java.util.List; import java.util.Properties; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.io.IOUtils; import org.apache.hadoop.io.Text; import org.apache.hadoop.io.compress.CodecPool; import org.apache.hadoop.io.compress.CompressionCodec; import org.apache.hadoop.io.compress.CompressionCodecFactory; import org.apache.hadoop.io.compress.Compressor; import org.apache.hadoop.mapreduce.TaskAttemptID; import org.apache.hadoop.mapreduce.TaskID; import org.apache.hadoop.mapreduce.TaskType; import org.apache.hadoop.mapreduce.jobhistory.HistoryEvent; import org.apache.hadoop.mapreduce.jobhistory.TaskAttemptFinishedEvent; import org.apache.hadoop.mapreduce.jobhistory.TaskAttemptUnsuccessfulCompletionEvent; import org.apache.hadoop.mapreduce.jobhistory.TaskStartedEvent; import org.apache.hadoop.util.LineReader; import org.apache.hadoop.util.Tool; import org.apache.hadoop.util.ToolRunner; import org.junit.Test; import static org.junit.Assert.*; public class TestRumenJobTraces { @Test public void testSmallTrace() throws Exception { performSingleTest("sample-job-tracker-logs.gz", "job-tracker-logs-topology-output", "job-tracker-logs-trace-output.gz"); } @Test public void testTruncatedTask() throws Exception { performSingleTest("truncated-job-tracker-log", "truncated-topology-output", "truncated-trace-output"); } private void performSingleTest(String jtLogName, String goldTopology, String goldTrace) throws Exception { final Configuration conf = new Configuration(); final FileSystem lfs = FileSystem.getLocal(conf); final Path rootInputDir = new Path(System.getProperty("test.tools.input.dir", "")).makeQualified( lfs.getUri(), lfs.getWorkingDirectory()); final Path rootTempDir = new Path(System.getProperty("test.build.data", "/tmp")).makeQualified( lfs.getUri(), lfs.getWorkingDirectory()); final Path rootInputFile = new Path(rootInputDir, "rumen/small-trace-test"); final Path tempDir = new Path(rootTempDir, "TestRumenJobTraces"); lfs.delete(tempDir, true); final Path topologyFile = new Path(tempDir, jtLogName + "-topology.json"); final Path traceFile = new Path(tempDir, jtLogName + "-trace.json"); final Path inputFile = new Path(rootInputFile, jtLogName); System.out.println("topology result file = " + topologyFile); System.out.println("trace result file = " + traceFile); String[] args = new String[6]; args[0] = "-v1"; args[1] = "-write-topology"; args[2] = topologyFile.toString(); args[3] = "-write-job-trace"; args[4] = traceFile.toString(); args[5] = inputFile.toString(); final Path topologyGoldFile = new Path(rootInputFile, goldTopology); final Path traceGoldFile = new Path(rootInputFile, goldTrace); @SuppressWarnings("deprecation") HadoopLogsAnalyzer analyzer = new HadoopLogsAnalyzer(); int result = ToolRunner.run(analyzer, args); assertEquals("Non-zero exit", 0, result); TestRumenJobTraces .<LoggedNetworkTopology> jsonFileMatchesGold(conf, topologyFile, topologyGoldFile, LoggedNetworkTopology.class, "topology"); TestRumenJobTraces.<LoggedJob> jsonFileMatchesGold(conf, traceFile, traceGoldFile, LoggedJob.class, "trace"); } @Test public void testRumenViaDispatch() throws Exception { final Configuration conf = new Configuration(); final FileSystem lfs = FileSystem.getLocal(conf); final Path rootInputDir = new Path(System.getProperty("test.tools.input.dir", "")).makeQualified( lfs.getUri(), lfs.getWorkingDirectory()); final Path rootTempDir = new Path(System.getProperty("test.build.data", "/tmp")).makeQualified( lfs.getUri(), lfs.getWorkingDirectory()); final Path rootInputPath = new Path(rootInputDir, "rumen/small-trace-test"); final Path tempDir = new Path(rootTempDir, "TestRumenViaDispatch"); lfs.delete(tempDir, true); final Path topologyPath = new Path(tempDir, "dispatch-topology.json"); final Path tracePath = new Path(tempDir, "dispatch-trace.json"); final Path inputPath = new Path(rootInputPath, "dispatch-sample-v20-jt-log.gz"); System.out.println("topology result file = " + topologyPath); System.out.println("testRumenViaDispatch() trace result file = " + tracePath); String demuxerClassName = ConcatenatedInputFilesDemuxer.class.getName(); String[] args = { "-demuxer", demuxerClassName, tracePath.toString(), topologyPath.toString(), inputPath.toString() }; final Path topologyGoldFile = new Path(rootInputPath, "dispatch-topology-output.json.gz"); final Path traceGoldFile = new Path(rootInputPath, "dispatch-trace-output.json.gz"); Tool analyzer = new TraceBuilder(); int result = ToolRunner.run(analyzer, args); assertEquals("Non-zero exit", 0, result); TestRumenJobTraces .<LoggedNetworkTopology> jsonFileMatchesGold(conf, topologyPath, topologyGoldFile, LoggedNetworkTopology.class, "topology"); TestRumenJobTraces.<LoggedJob> jsonFileMatchesGold(conf, tracePath, traceGoldFile, LoggedJob.class, "trace"); } @Test public void testBracketedCounters() throws Exception { final Configuration conf = new Configuration(); final FileSystem lfs = FileSystem.getLocal(conf); final Path rootInputDir = new Path(System.getProperty("test.tools.input.dir", "")).makeQualified( lfs.getUri(), lfs.getWorkingDirectory()); final Path rootTempDir = new Path(System.getProperty("test.build.data", "/tmp")).makeQualified( lfs.getUri(), lfs.getWorkingDirectory()); final Path rootInputPath = new Path(rootInputDir, "rumen/small-trace-test"); final Path tempDir = new Path(rootTempDir, "TestBracketedCounters"); lfs.delete(tempDir, true); final Path topologyPath = new Path(tempDir, "dispatch-topology.json"); final Path tracePath = new Path(tempDir, "dispatch-trace.json"); final Path inputPath = new Path(rootInputPath, "counters-format-test-logs"); System.out.println("topology result file = " + topologyPath); System.out.println("testBracketedCounters() trace result file = " + tracePath); final Path goldPath = new Path(rootInputPath, "counters-test-trace.json.gz"); String[] args = { tracePath.toString(), topologyPath.toString(), inputPath.toString() }; Tool analyzer = new TraceBuilder(); int result = ToolRunner.run(analyzer, args); assertEquals("Non-zero exit", 0, result); TestRumenJobTraces.<LoggedJob> jsonFileMatchesGold(conf, tracePath, goldPath, LoggedJob.class, "trace"); } @Test public void testHadoop20JHParser() throws Exception { final Configuration conf = new Configuration(); final FileSystem lfs = FileSystem.getLocal(conf); boolean success = false; final Path rootInputDir = new Path(System.getProperty("test.tools.input.dir", "")).makeQualified( lfs.getUri(), lfs.getWorkingDirectory()); final Path rootTempDir = new Path(System.getProperty("test.build.data", "/tmp")).makeQualified( lfs.getUri(), lfs.getWorkingDirectory()); final Path rootInputPath = new Path(rootInputDir, "rumen/small-trace-test"); final Path tempDir = new Path(rootTempDir, "TestRumenViaDispatch"); lfs.delete(tempDir, true); final Path inputPath = new Path(rootInputPath, "v20-single-input-log.gz"); final Path goldPath = new Path(rootInputPath, "v20-single-input-log-event-classes.text.gz"); InputStream inputLogStream = new PossiblyDecompressedInputStream(inputPath, conf); InputStream inputGoldStream = new PossiblyDecompressedInputStream(goldPath, conf); BufferedInputStream bis = new BufferedInputStream(inputLogStream); bis.mark(10000); Hadoop20JHParser parser = new Hadoop20JHParser(bis); final Path resultPath = new Path(tempDir, "result.text"); System.out.println("testHadoop20JHParser sent its output to " + resultPath); Compressor compressor; FileSystem fs = resultPath.getFileSystem(conf); CompressionCodec codec = new CompressionCodecFactory(conf).getCodec(resultPath); OutputStream output; if (codec != null) { compressor = CodecPool.getCompressor(codec); output = codec.createOutputStream(fs.create(resultPath), compressor); } else { output = fs.create(resultPath); } PrintStream printStream = new PrintStream(output); try { assertEquals("Hadoop20JHParser can't parse the test file", true, Hadoop20JHParser.canParse(inputLogStream)); bis.reset(); HistoryEvent event = parser.nextEvent(); while (event != null) { printStream.println(event.getClass().getCanonicalName()); event = parser.nextEvent(); } printStream.close(); LineReader goldLines = new LineReader(inputGoldStream); LineReader resultLines = new LineReader(new PossiblyDecompressedInputStream(resultPath, conf)); int lineNumber = 1; try { Text goldLine = new Text(); Text resultLine = new Text(); int goldRead = goldLines.readLine(goldLine); int resultRead = resultLines.readLine(resultLine); while (goldRead * resultRead != 0) { if (!goldLine.equals(resultLine)) { assertEquals("Type mismatch detected", goldLine, resultLine); break; } goldRead = goldLines.readLine(goldLine); resultRead = resultLines.readLine(resultLine); ++lineNumber; } if (goldRead != resultRead) { assertEquals("the " + (goldRead > resultRead ? "gold" : resultRead) + " file contains more text at line " + lineNumber, goldRead, resultRead); } success = true; } finally { goldLines.close(); resultLines.close(); if (success) { lfs.delete(resultPath, false); } } } finally { if (parser == null) { inputLogStream.close(); } else { if (parser != null) { parser.close(); } } if (inputGoldStream != null) { inputGoldStream.close(); } // it's okay to do this twice [if we get an error on input] printStream.close(); } } @Test public void testJobConfigurationParser() throws Exception { String[] list1 = { "mapred.job.queue.name", "mapreduce.job.name", "mapred.child.java.opts" }; String[] list2 = { "mapred.job.queue.name", "mapred.child.java.opts" }; List<String> interested1 = new ArrayList<String>(); for (String interested : list1) { interested1.add(interested); } List<String> interested2 = new ArrayList<String>(); for (String interested : list2) { interested2.add(interested); } JobConfigurationParser jcp1 = new JobConfigurationParser(interested1); JobConfigurationParser jcp2 = new JobConfigurationParser(interested2); final Configuration conf = new Configuration(); final FileSystem lfs = FileSystem.getLocal(conf); @SuppressWarnings("deprecation") final Path rootInputDir = new Path(System.getProperty("test.tools.input.dir", "")) .makeQualified(lfs); final Path rootInputPath = new Path(rootInputDir, "rumen/small-trace-test"); final Path inputPath = new Path(rootInputPath, "sample-conf.file.xml"); InputStream inputConfStream = new PossiblyDecompressedInputStream(inputPath, conf); try { Properties props1 = jcp1.parse(inputConfStream); inputConfStream.close(); inputConfStream = new PossiblyDecompressedInputStream(inputPath, conf); Properties props2 = jcp2.parse(inputConfStream); assertEquals("testJobConfigurationParser: wrong number of properties", 3, props1.size()); assertEquals("testJobConfigurationParser: wrong number of properties", 2, props2.size()); assertEquals("prop test 1", "TheQueue", props1 .get("mapred.job.queue.name")); assertEquals("prop test 2", "job_0001", props1.get("mapreduce.job.name")); assertEquals("prop test 3", "-server -Xmx640m -Djava.net.preferIPv4Stack=true", props1 .get("mapred.child.java.opts")); assertEquals("prop test 4", "TheQueue", props2 .get("mapred.job.queue.name")); assertEquals("prop test 5", "-server -Xmx640m -Djava.net.preferIPv4Stack=true", props2 .get("mapred.child.java.opts")); } finally { inputConfStream.close(); } } @Test public void testTopologyBuilder() throws Exception { final TopologyBuilder subject = new TopologyBuilder(); // currently we extract no host names from the Properties subject.process(new Properties()); subject.process(new TaskAttemptFinishedEvent(TaskAttemptID .forName("attempt_200904211745_0003_m_000004_0"), TaskType .valueOf("MAP"), "STATUS", 1234567890L, "/194\\.6\\.134\\.64/cluster50261\\.secondleveldomain\\.com", "SUCCESS", null)); subject.process(new TaskAttemptUnsuccessfulCompletionEvent(TaskAttemptID .forName("attempt_200904211745_0003_m_000004_1"), TaskType .valueOf("MAP"), "STATUS", 1234567890L, "/194\\.6\\.134\\.80/cluster50262\\.secondleveldomain\\.com", "MACHINE_EXPLODED")); subject.process(new TaskAttemptUnsuccessfulCompletionEvent(TaskAttemptID .forName("attempt_200904211745_0003_m_000004_2"), TaskType .valueOf("MAP"), "STATUS", 1234567890L, "/194\\.6\\.134\\.80/cluster50263\\.secondleveldomain\\.com", "MACHINE_EXPLODED")); subject.process(new TaskStartedEvent(TaskID .forName("task_200904211745_0003_m_000004"), 1234567890L, TaskType .valueOf("MAP"), "/194\\.6\\.134\\.80/cluster50263\\.secondleveldomain\\.com")); final LoggedNetworkTopology topology = subject.build(); List<LoggedNetworkTopology> racks = topology.getChildren(); assertEquals("Wrong number of racks", 2, racks.size()); boolean sawSingleton = false; boolean sawDoubleton = false; for (LoggedNetworkTopology rack : racks) { List<LoggedNetworkTopology> nodes = rack.getChildren(); if (rack.getName().endsWith(".64")) { assertEquals("The singleton rack has the wrong number of elements", 1, nodes.size()); sawSingleton = true; } else if (rack.getName().endsWith(".80")) { assertEquals("The doubleton rack has the wrong number of elements", 2, nodes.size()); sawDoubleton = true; } else { assertTrue("Unrecognized rack name", false); } } assertTrue("Did not see singleton rack", sawSingleton); assertTrue("Did not see doubleton rack", sawDoubleton); } static private <T extends DeepCompare> void jsonFileMatchesGold( Configuration conf, Path result, Path gold, Class<? extends T> clazz, String fileDescription) throws IOException { JsonObjectMapperParser<T> goldParser = new JsonObjectMapperParser<T>(gold, clazz, conf); JsonObjectMapperParser<T> resultParser = new JsonObjectMapperParser<T>(result, clazz, conf); try { while (true) { DeepCompare goldJob = goldParser.getNext(); DeepCompare resultJob = resultParser.getNext(); if ((goldJob == null) || (resultJob == null)) { assertTrue(goldJob == resultJob); break; } try { resultJob.deepCompare(goldJob, new TreePath(null, "<root>")); } catch (DeepInequalityException e) { String error = e.path.toString(); assertFalse(fileDescription + " mismatches: " + error, true); } } } finally { IOUtils.cleanup(null, goldParser, resultParser); } } }
/* * $Id: TestLinkTag7.java 54929 2004-10-16 16:38:42Z germuska $ * * Copyright 1999-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.struts.taglib.html; import java.util.ArrayList; import java.util.HashMap; import java.util.Locale; import java.util.StringTokenizer; import javax.servlet.jsp.PageContext; import junit.framework.Test; import junit.framework.TestSuite; import org.apache.cactus.JspTestCase; import org.apache.struts.Globals; import org.apache.struts.taglib.SimpleBeanForTesting; /** * Suite of unit tests for the * <code>org.apache.struts.taglib.html.LinkTag</code> class. * */ public class TestLinkTag7 extends JspTestCase { /** * Defines the testcase name for JUnit. * * @param theName the testcase's name. */ public TestLinkTag7(String theName) { super(theName); } /** * Start the tests. * * @param theArgs the arguments. Not used */ public static void main(String[] theArgs) { junit.awtui.TestRunner.main(new String[] {TestLinkTag7.class.getName()}); } /** * @return a test suite (<code>TestSuite</code>) that includes all methods * starting with "test" */ public static Test suite() { // All methods starting with "test" will be executed in the test suite. return new TestSuite(TestLinkTag7.class); } private void runMyTest(String whichTest, String locale) throws Exception { pageContext.setAttribute(Globals.LOCALE_KEY, new Locale(locale, locale), PageContext.SESSION_SCOPE); request.setAttribute("runTest", whichTest); pageContext.forward("/test/org/apache/struts/taglib/html/TestLinkTag7.jsp"); } /* * Testing LinkTag. */ //--------Testing attributes using forward------ public void testLinkPage() throws Exception { runMyTest("testLinkPage", ""); } public void testLinkPageAccesskey() throws Exception { runMyTest("testLinkPageAccesskey", ""); } public void testLinkPageAnchor() throws Exception { runMyTest("testLinkPageAnchor", ""); } public void testLinkPageIndexedArray() throws Exception { ArrayList lst = new ArrayList(); lst.add("Test Message"); pageContext.setAttribute("lst", lst, PageContext.REQUEST_SCOPE); runMyTest("testLinkPageIndexedArray", ""); } public void testLinkPageIndexedArrayProperty() throws Exception { SimpleBeanForTesting sbft = new SimpleBeanForTesting(); ArrayList lst = new ArrayList(); lst.add("Test Message"); sbft.setList(lst); pageContext.setAttribute("lst", sbft, PageContext.REQUEST_SCOPE); runMyTest("testLinkPageIndexedArrayProperty", ""); } public void testLinkPageIndexedMap() throws Exception { HashMap map = new HashMap(); map.put("tst1", "Test Message"); pageContext.setAttribute("lst", map, PageContext.REQUEST_SCOPE); runMyTest("testLinkPageIndexedMap", ""); } public void testLinkPageIndexedMapProperty() throws Exception { SimpleBeanForTesting sbft = new SimpleBeanForTesting(); HashMap map = new HashMap(); map.put("tst1", "Test Message"); sbft.setMap(map); pageContext.setAttribute("lst", sbft, PageContext.REQUEST_SCOPE); runMyTest("testLinkPageIndexedMapProperty", ""); } public void testLinkPageIndexedEnumeration() throws Exception { StringTokenizer st = new StringTokenizer("Test Message"); pageContext.setAttribute("lst", st, PageContext.REQUEST_SCOPE); runMyTest("testLinkPageIndexedEnumeration", ""); } public void testLinkPageIndexedEnumerationProperty() throws Exception { SimpleBeanForTesting sbft = new SimpleBeanForTesting(); StringTokenizer st = new StringTokenizer("Test Message"); sbft.setEnumeration(st); pageContext.setAttribute("lst", sbft, PageContext.REQUEST_SCOPE); runMyTest("testLinkPageIndexedEnumerationProperty", ""); } public void testLinkPageIndexedAlternateIdArray() throws Exception { ArrayList lst = new ArrayList(); lst.add("Test Message"); pageContext.setAttribute("lst", lst, PageContext.REQUEST_SCOPE); runMyTest("testLinkPageIndexedAlternateIdArray", ""); } public void testLinkPageIndexedAlternateIdArrayProperty() throws Exception { SimpleBeanForTesting sbft = new SimpleBeanForTesting(); ArrayList lst = new ArrayList(); lst.add("Test Message"); sbft.setList(lst); pageContext.setAttribute("lst", sbft, PageContext.REQUEST_SCOPE); runMyTest("testLinkPageIndexedAlternateIdArrayProperty", ""); } public void testLinkPageIndexedAlternateIdMap() throws Exception { HashMap map = new HashMap(); map.put("tst1", "Test Message"); pageContext.setAttribute("lst", map, PageContext.REQUEST_SCOPE); runMyTest("testLinkPageIndexedAlternateIdMap", ""); } public void testLinkPageIndexedAlternateIdMapProperty() throws Exception { SimpleBeanForTesting sbft = new SimpleBeanForTesting(); HashMap map = new HashMap(); map.put("tst1", "Test Message"); sbft.setMap(map); pageContext.setAttribute("lst", sbft, PageContext.REQUEST_SCOPE); runMyTest("testLinkPageIndexedAlternateIdMapProperty", ""); } public void testLinkPageIndexedAlternateIdEnumeration() throws Exception { StringTokenizer st = new StringTokenizer("Test Message"); pageContext.setAttribute("lst", st, PageContext.REQUEST_SCOPE); runMyTest("testLinkPageIndexedAlternateIdEnumeration", ""); } public void testLinkPageIndexedAlternateIdEnumerationProperty() throws Exception { SimpleBeanForTesting sbft = new SimpleBeanForTesting(); StringTokenizer st = new StringTokenizer("Test Message"); sbft.setEnumeration(st); pageContext.setAttribute("lst", sbft, PageContext.REQUEST_SCOPE); runMyTest("testLinkPageIndexedAlternateIdEnumerationProperty", ""); } public void testLinkPageLinkName() throws Exception { runMyTest("testLinkPageLinkName", ""); } public void testLinkPageNameNoScope() throws Exception { HashMap map = new HashMap(); map.put("param1","value1"); map.put("param2","value2"); map.put("param3","value3"); map.put("param4","value4"); pageContext.setAttribute("paramMap", map, PageContext.REQUEST_SCOPE); runMyTest("testLinkPageNameNoScope", ""); } public void testLinkPageNamePropertyNoScope() throws Exception { HashMap map = new HashMap(); map.put("param1","value1"); map.put("param2","value2"); map.put("param3","value3"); map.put("param4","value4"); SimpleBeanForTesting sbft = new SimpleBeanForTesting(map); pageContext.setAttribute("paramPropertyMap", sbft, PageContext.REQUEST_SCOPE); runMyTest("testLinkPageNamePropertyNoScope", ""); } public void testLinkPageNameApplicationScope() throws Exception { HashMap map = new HashMap(); map.put("param1","value1"); map.put("param2","value2"); map.put("param3","value3"); map.put("param4","value4"); pageContext.setAttribute("paramMap", map, PageContext.APPLICATION_SCOPE); runMyTest("testLinkPageNameApplicationScope", ""); } public void testLinkPageNamePropertyApplicationScope() throws Exception { HashMap map = new HashMap(); map.put("param1","value1"); map.put("param2","value2"); map.put("param3","value3"); map.put("param4","value4"); SimpleBeanForTesting sbft = new SimpleBeanForTesting(map); pageContext.setAttribute("paramPropertyMap", sbft, PageContext.APPLICATION_SCOPE); runMyTest("testLinkPageNamePropertyApplicationScope", ""); } public void testLinkPageNameSessionScope() throws Exception { HashMap map = new HashMap(); map.put("param1","value1"); map.put("param2","value2"); map.put("param3","value3"); map.put("param4","value4"); pageContext.setAttribute("paramMap", map, PageContext.SESSION_SCOPE); runMyTest("testLinkPageNameSessionScope", ""); } public void testLinkPageNamePropertySessionScope() throws Exception { HashMap map = new HashMap(); map.put("param1","value1"); map.put("param2","value2"); map.put("param3","value3"); map.put("param4","value4"); SimpleBeanForTesting sbft = new SimpleBeanForTesting(map); pageContext.setAttribute("paramPropertyMap", sbft, PageContext.SESSION_SCOPE); runMyTest("testLinkPageNamePropertySessionScope", ""); } public void testLinkPageNameRequestScope() throws Exception { HashMap map = new HashMap(); map.put("param1","value1"); map.put("param2","value2"); map.put("param3","value3"); map.put("param4","value4"); pageContext.setAttribute("paramMap", map, PageContext.REQUEST_SCOPE); runMyTest("testLinkPageNameRequestScope", ""); } public void testLinkPageNamePropertyRequestScope() throws Exception { HashMap map = new HashMap(); map.put("param1","value1"); map.put("param2","value2"); map.put("param3","value3"); map.put("param4","value4"); SimpleBeanForTesting sbft = new SimpleBeanForTesting(map); pageContext.setAttribute("paramPropertyMap", sbft, PageContext.REQUEST_SCOPE); runMyTest("testLinkPageNamePropertyRequestScope", ""); } }
package io.rancher.type; import io.rancher.base.AbstractType; import java.util.List; import java.util.Map; public class ExternalService extends AbstractType { private String accountId; private String created; private Map<String, Object> data; private String description; private String externalId; private List<String> externalIpAddresses; private String fqdn; private InstanceHealthCheck healthCheck; private String healthState; private String hostname; private List<String> instanceIds; private String kind; private LaunchConfig launchConfig; private Map<String, Object> linkedServices; private Map<String, Object> metadata; private String name; private String removeTime; private String removed; private String stackId; private Boolean startOnCreate; private String state; private Boolean system; private String transitioning; private String transitioningMessage; private Integer transitioningProgress; private ServiceUpgrade upgrade; private String uuid; public String getAccountId() { return this.accountId; } public void setAccountId(String accountId) { this.accountId = accountId; } public String getCreated() { return this.created; } public void setCreated(String created) { this.created = created; } public Map<String, Object> getData() { return this.data; } public void setData(Map<String, Object> data) { this.data = data; } public String getDescription() { return this.description; } public void setDescription(String description) { this.description = description; } public String getExternalId() { return this.externalId; } public void setExternalId(String externalId) { this.externalId = externalId; } public List<String> getExternalIpAddresses() { return this.externalIpAddresses; } public void setExternalIpAddresses(List<String> externalIpAddresses) { this.externalIpAddresses = externalIpAddresses; } public String getFqdn() { return this.fqdn; } public void setFqdn(String fqdn) { this.fqdn = fqdn; } public InstanceHealthCheck getHealthCheck() { return this.healthCheck; } public void setHealthCheck(InstanceHealthCheck healthCheck) { this.healthCheck = healthCheck; } public String getHealthState() { return this.healthState; } public void setHealthState(String healthState) { this.healthState = healthState; } public String getHostname() { return this.hostname; } public void setHostname(String hostname) { this.hostname = hostname; } public List<String> getInstanceIds() { return this.instanceIds; } public void setInstanceIds(List<String> instanceIds) { this.instanceIds = instanceIds; } public String getKind() { return this.kind; } public void setKind(String kind) { this.kind = kind; } public LaunchConfig getLaunchConfig() { return this.launchConfig; } public void setLaunchConfig(LaunchConfig launchConfig) { this.launchConfig = launchConfig; } public Map<String, Object> getLinkedServices() { return this.linkedServices; } public void setLinkedServices(Map<String, Object> linkedServices) { this.linkedServices = linkedServices; } public Map<String, Object> getMetadata() { return this.metadata; } public void setMetadata(Map<String, Object> metadata) { this.metadata = metadata; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public String getRemoveTime() { return this.removeTime; } public void setRemoveTime(String removeTime) { this.removeTime = removeTime; } public String getRemoved() { return this.removed; } public void setRemoved(String removed) { this.removed = removed; } public String getStackId() { return this.stackId; } public void setStackId(String stackId) { this.stackId = stackId; } public Boolean getStartOnCreate() { return this.startOnCreate; } public void setStartOnCreate(Boolean startOnCreate) { this.startOnCreate = startOnCreate; } public String getState() { return this.state; } public void setState(String state) { this.state = state; } public Boolean getSystem() { return this.system; } public void setSystem(Boolean system) { this.system = system; } public String getTransitioning() { return this.transitioning; } public void setTransitioning(String transitioning) { this.transitioning = transitioning; } public String getTransitioningMessage() { return this.transitioningMessage; } public void setTransitioningMessage(String transitioningMessage) { this.transitioningMessage = transitioningMessage; } public Integer getTransitioningProgress() { return this.transitioningProgress; } public void setTransitioningProgress(Integer transitioningProgress) { this.transitioningProgress = transitioningProgress; } public ServiceUpgrade getUpgrade() { return this.upgrade; } public void setUpgrade(ServiceUpgrade upgrade) { this.upgrade = upgrade; } public String getUuid() { return this.uuid; } public void setUuid(String uuid) { this.uuid = uuid; } }
package graphedit.util; import graphedit.app.MainFrame; import graphedit.model.components.Package; import graphedit.model.diagram.GraphEditModel; import graphedit.model.elements.GraphEditPackage; import graphedit.model.properties.PropertyEnums.PackageProperties; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.List; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import kroki.uml_core_basic.UmlPackage; import com.thoughtworks.xstream.XStream; import com.thoughtworks.xstream.io.xml.DomDriver; /** * Provides couple of utility, convenience methods for data ( * <code>Project</code>, <code>GraphEditModel</code>) storage * * @author specijalac */ public class WorkspaceUtility { private static XStream xstream; private static BufferedWriter out; private static BufferedReader in; public static final String FILE_EXTENSION = ".dgm"; public static final String PROJECT_EXTENSION = ".kroki_graph"; private static JFileChooser chooser = new JFileChooser(); public static void save(GraphEditModel model) { /* xstream = new XStream(new DomDriver()); configureAliases(); omitObservable(); if (!model.getParentProject().isSerialized()) saveProject(model.getParentProject()); try { out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(model.getFile()), "UTF-8")); xstream.toXML(model, out); out.close(); } catch (Exception e) { e.printStackTrace(); }*/ } private static String chooseLocation(){ chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); int returnVal = chooser.showSaveDialog(MainFrame.getInstance()); if (returnVal == JFileChooser.APPROVE_OPTION) { String path = chooser.getSelectedFile().getPath(); return path; } return null; } public static boolean saveProject(GraphEditPackage project) { xstream = new XStream(new DomDriver()); configureAliases(); omitObservable(); File file = project.getFile(); if (file == null){ String path = chooseLocation(); if (path == null) return false; file = new File(path, (String)project.getProperty(PackageProperties.NAME) + PROJECT_EXTENSION); if (file.exists()){ if (JOptionPane.showConfirmDialog(null, "Project already exists. Overwrite?", "Confirm", JOptionPane.YES_NO_OPTION) != JOptionPane.YES_OPTION) return false; } project.setFile(file); } //parentProject.setSerialized(true); try{ out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8")); xstream.toXML(project, out); out.close(); } catch (Exception e) { e.printStackTrace(); JOptionPane.showMessageDialog(MainFrame.getInstance(), "Project " +(String)project.getProperty(PackageProperties.NAME) + " wasn't saved successfully!"); return false; } JOptionPane.showMessageDialog(MainFrame.getInstance(), "Project " + (String)project.getProperty(PackageProperties.NAME) + " saved successfully!"); return true; } public static GraphEditPackage load(File file) { try { in = new BufferedReader(new InputStreamReader(new FileInputStream(file))); xstream = new XStream(); configureAliases(); return (GraphEditPackage) xstream.fromXML(in); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; /* xstream = new XStream(); configureAliases(); GraphEditWorkspace workspace = GraphEditWorkspace.getInstance(); List<Project> projects = new ArrayList<Project>(); Properties<ProjectProperties> properties; Project project; File confFile; try { for (File f : workspace.getFile().listFiles()) { if ((confFile = hasConfFile(f)) instanceof File) { project = new Project(confFile.getName()); in = new BufferedReader(new InputStreamReader(new FileInputStream(confFile))); properties = (Properties<ProjectProperties>) xstream.fromXML(in); in.close(); project.setProperties(properties); project.setFile(confFile.getParentFile()); // tag it as serialized project.setSerialized(true); projects.add(project); } } workspace.setProjects(projects); } catch (Exception e) { e.printStackTrace(); }*/ } public static void load(UmlPackage project) { /* xstream = new XStream(); configureAliases(); List<GraphEditModel> elements = new ArrayList<GraphEditModel>(); List<GraphEditPackage> packages = new ArrayList<GraphEditPackage>(); GraphEditModel element; GraphEditPackage pack; try { for (File f : project.getFile().listFiles()) { if (f.isFile() && f.getName().toLowerCase().endsWith(FILE_EXTENSION)) { in = new BufferedReader(new InputStreamReader(new FileInputStream(f))); element = (GraphEditModel) xstream.fromXML(in); in.close(); element.setParentProject(project); elements.add(new GraphEditModel(element)); } else if (f.isDirectory()) { pack = new GraphEditPackage(f.getName()); pack.setParentProject(project); pack.setProperty(PackageProperties.NAME, f.getName()); pack.setFile(f); // do the same for every single child of its subpackage if (pack.getFile().listFiles().length > 0) parseFileStructure(pack, project); packages.add(pack); } } project.setDiagrams(elements); project.setPackages(packages); } catch (Exception e) { e.printStackTrace(); }*/ } /** * Beware this method permanently removes target file from file system. * @param target represents a file which is to be deleted. */ public static void removeFileFromFileSystem(File target) { target.delete(); } /** * Beware this method permanently removes target directory and its * contents from file system. * @param target represents a file which is to be deleted. */ public static void removeDirectoryFromFileSystem(File target) { if (target.isDirectory() && target.listFiles().length > 0) { for (File f : target.listFiles()) if (f.isDirectory()) removeDirectoryFromFileSystem(f); else removeFileFromFileSystem(f); } target.delete(); } @SuppressWarnings("unused") private static void parseFileStructure(GraphEditPackage masterPackage, UmlPackage parentProject) { /* GraphEditModel element; GraphEditPackage pack; System.out.println("Recursive call for: " + masterPackage.getFile().getName()); for (File f : masterPackage.getFile().listFiles()) { if (f.isFile() && f.getName().toLowerCase().endsWith(FILE_EXTENSION)) { try { in = new BufferedReader(new InputStreamReader(new FileInputStream(f))); element = (GraphEditModel) xstream.fromXML(in); in.close(); element.setParentProject(parentProject); masterPackage.addDiagram(new GraphEditModel(element)); } catch (Exception e) { e.printStackTrace(); } } else if (f.isDirectory()) { pack = new GraphEditPackage(f.getName()); pack.setParentProject(parentProject); pack.setProperty(PackageProperties.NAME, f.getName()); pack.setFile(f); masterPackage.addPackage(pack); // do the same for every single child of its subpackage if (pack.getFile().listFiles().length > 0) parseFileStructure(pack, parentProject); } }*/ } public static GraphEditPackage getTopPackage(GraphEditPackage pack){ while (pack.getParentPackage() != null) pack = pack.getParentPackage(); return pack; } public static List<GraphEditModel> allDiagramsInProject(GraphEditPackage project){ List<GraphEditModel> ret = new ArrayList<GraphEditModel>(); allDiagramsInPackage(project, ret); return ret; } private static void allDiagramsInPackage(GraphEditPackage pack, List<GraphEditModel> ret){ ret.add(pack.getDiagram()); for (Package p : pack.getDiagram().getContainedPackages()) allDiagramsInPackage((GraphEditPackage) p.getRepresentedElement(), ret); } /** * Method checks whether provided a file meets the rules regarding * project's hierarchy. * @param file represents a file which is to be checked. * @return whether provided <code>file</code> is a <code>Project</code> directory. * @author specijalac */ @SuppressWarnings("unused") private static File hasConfFile(File file) { if (file.isDirectory()) { for (File f: file.listFiles()) { if (f.getName().toLowerCase().endsWith(PROJECT_EXTENSION)) return f; } } return null; } /** * This method excludes Observable and its dependencies from being * serialized, along with the <code>GraphEditModel</code>. * @author specijalac */ private static void omitObservable() { if (xstream instanceof XStream) { xstream.omitField(java.util.Observable.class, "obs"); xstream.omitField(java.util.Observable.class, "changed"); } } /** * This method sets aliases for better appearance of generated xml * @author specijalac */ private static void configureAliases() { xstream.alias("package", graphedit.model.elements.GraphEditPackage.class); xstream.alias("model", graphedit.model.diagram.GraphEditModel.class); xstream.alias("class", graphedit.model.components.Class.class); xstream.alias("interface", graphedit.model.components.Interface.class); xstream.alias("properties", graphedit.model.properties.PropertyEnums.class); xstream.alias("umlPackage", kroki.profil.subsystem.BussinesSubsystem.class); xstream.alias("nestingPackage", kroki.profil.subsystem.BussinesSubsystem.class); } }
/** * <copyright> * </copyright> * * $Id$ */ package org.wso2.developerstudio.eclipse.ds.impl; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.impl.ENotificationImpl; import org.eclipse.emf.ecore.impl.EObjectImpl; import org.wso2.developerstudio.eclipse.ds.DoubleRangeValidator; import org.wso2.developerstudio.eclipse.ds.DsPackage; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Double Range Validator</b></em> * '. * <!-- end-user-doc --> * <p> * The following features are implemented: * <ul> * <li>{@link org.wso2.developerstudio.eclipse.ds.impl.DoubleRangeValidatorImpl#getMaximum <em>Maximum</em>}</li> * <li>{@link org.wso2.developerstudio.eclipse.ds.impl.DoubleRangeValidatorImpl#getMinimum <em>Minimum</em>}</li> * </ul> * </p> * * @generated */ public class DoubleRangeValidatorImpl extends EObjectImpl implements DoubleRangeValidator { /** * The default value of the '{@link #getMaximum() <em>Maximum</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getMaximum() * @generated * @ordered */ protected static final double MAXIMUM_EDEFAULT = 0.0; /** * The cached value of the '{@link #getMaximum() <em>Maximum</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getMaximum() * @generated * @ordered */ protected double maximum = MAXIMUM_EDEFAULT; /** * The default value of the '{@link #getMinimum() <em>Minimum</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getMinimum() * @generated * @ordered */ protected static final double MINIMUM_EDEFAULT = 0.0; /** * The cached value of the '{@link #getMinimum() <em>Minimum</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getMinimum() * @generated * @ordered */ protected double minimum = MINIMUM_EDEFAULT; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected DoubleRangeValidatorImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return DsPackage.Literals.DOUBLE_RANGE_VALIDATOR; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public double getMaximum() { return maximum; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setMaximum(double newMaximum) { double oldMaximum = maximum; maximum = newMaximum; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, DsPackage.DOUBLE_RANGE_VALIDATOR__MAXIMUM, oldMaximum, maximum)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public double getMinimum() { return minimum; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setMinimum(double newMinimum) { double oldMinimum = minimum; minimum = newMinimum; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, DsPackage.DOUBLE_RANGE_VALIDATOR__MINIMUM, oldMinimum, minimum)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case DsPackage.DOUBLE_RANGE_VALIDATOR__MAXIMUM: return getMaximum(); case DsPackage.DOUBLE_RANGE_VALIDATOR__MINIMUM: return getMinimum(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case DsPackage.DOUBLE_RANGE_VALIDATOR__MAXIMUM: setMaximum((Double)newValue); return; case DsPackage.DOUBLE_RANGE_VALIDATOR__MINIMUM: setMinimum((Double)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case DsPackage.DOUBLE_RANGE_VALIDATOR__MAXIMUM: setMaximum(MAXIMUM_EDEFAULT); return; case DsPackage.DOUBLE_RANGE_VALIDATOR__MINIMUM: setMinimum(MINIMUM_EDEFAULT); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case DsPackage.DOUBLE_RANGE_VALIDATOR__MAXIMUM: return maximum != MAXIMUM_EDEFAULT; case DsPackage.DOUBLE_RANGE_VALIDATOR__MINIMUM: return minimum != MINIMUM_EDEFAULT; } return super.eIsSet(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { if (eIsProxy()) return super.toString(); StringBuffer result = new StringBuffer(super.toString()); result.append(" (maximum: "); result.append(maximum); result.append(", minimum: "); result.append(minimum); result.append(')'); return result.toString(); } } // DoubleRangeValidatorImpl
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.cassandra.stress; import java.util.ArrayList; import java.util.List; import java.util.Queue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.LockSupport; import org.apache.cassandra.stress.operations.OpDistribution; import org.apache.cassandra.stress.operations.OpDistributionFactory; import org.apache.cassandra.stress.report.StressMetrics; import org.apache.cassandra.stress.settings.ConnectionAPI; import org.apache.cassandra.stress.settings.SettingsCommand; import org.apache.cassandra.stress.settings.StressSettings; import org.apache.cassandra.stress.util.JavaDriverClient; import org.apache.cassandra.stress.util.ResultLogger; import org.apache.cassandra.transport.SimpleClient; import org.jctools.queues.SpscArrayQueue; import org.jctools.queues.SpscUnboundedArrayQueue; import com.google.common.util.concurrent.Uninterruptibles; public class StressAction implements Runnable { private final StressSettings settings; private final ResultLogger output; public StressAction(StressSettings settings, ResultLogger out) { this.settings = settings; output = out; } public void run() { // creating keyspace and column families settings.maybeCreateKeyspaces(); output.println("Sleeping 2s..."); Uninterruptibles.sleepUninterruptibly(2, TimeUnit.SECONDS); if (!settings.command.noWarmup) warmup(settings.command.getFactory(settings)); if ((settings.command.truncate == SettingsCommand.TruncateWhen.ONCE) || ((settings.rate.threadCount != -1) && (settings.command.truncate == SettingsCommand.TruncateWhen.ALWAYS))) settings.command.truncateTables(settings); // Required for creating a graph from the output file if (settings.rate.threadCount == -1) output.println("Thread count was not specified"); // TODO : move this to a new queue wrapper that gates progress based on a poisson (or configurable) distribution UniformRateLimiter rateLimiter = null; if (settings.rate.opsPerSecond > 0) rateLimiter = new UniformRateLimiter(settings.rate.opsPerSecond); boolean success; if (settings.rate.minThreads > 0) success = runMulti(settings.rate.auto, rateLimiter); else success = null != run(settings.command.getFactory(settings), settings.rate.threadCount, settings.command.count, settings.command.duration, rateLimiter, settings.command.durationUnits, output, false); if (success) output.println("END"); else output.println("FAILURE"); settings.disconnect(); if (!success) throw new RuntimeException("Failed to execute stress action"); } // type provided separately to support recursive call for mixed command with each command type it is performing @SuppressWarnings("resource") // warmupOutput doesn't need closing private void warmup(OpDistributionFactory operations) { // do 25% of iterations as warmup but no more than 50k (by default hotspot compiles methods after 10k invocations) int iterations = (settings.command.count > 0 ? Math.min(50000, (int)(settings.command.count * 0.25)) : 50000) * settings.node.nodes.size(); int threads = 100; if (settings.rate.maxThreads > 0) threads = Math.min(threads, settings.rate.maxThreads); if (settings.rate.threadCount > 0) threads = Math.min(threads, settings.rate.threadCount); for (OpDistributionFactory single : operations.each()) { // we need to warm up all the nodes in the cluster ideally, but we may not be the only stress instance; // so warm up all the nodes we're speaking to only. output.println(String.format("Warming up %s with %d iterations...", single.desc(), iterations)); boolean success = null != run(single, threads, iterations, 0, null, null, ResultLogger.NOOP, true); if (!success) throw new RuntimeException("Failed to execute warmup"); } } // TODO : permit varying more than just thread count // TODO : vary thread count based on percentage improvement of previous increment, not by fixed amounts private boolean runMulti(boolean auto, UniformRateLimiter rateLimiter) { if (settings.command.targetUncertainty >= 0) output.println("WARNING: uncertainty mode (err<) results in uneven workload between thread runs, so should be used for high level analysis only"); int prevThreadCount = -1; int threadCount = settings.rate.minThreads; List<StressMetrics> results = new ArrayList<>(); List<String> runIds = new ArrayList<>(); do { output.println(""); output.println(String.format("Running with %d threadCount", threadCount)); if (settings.command.truncate == SettingsCommand.TruncateWhen.ALWAYS) settings.command.truncateTables(settings); StressMetrics result = run(settings.command.getFactory(settings), threadCount, settings.command.count, settings.command.duration, rateLimiter, settings.command.durationUnits, output, false); if (result == null) return false; results.add(result); if (prevThreadCount > 0) System.out.println(String.format("Improvement over %d threadCount: %.0f%%", prevThreadCount, 100 * averageImprovement(results, 1))); runIds.add(threadCount + " threadCount"); prevThreadCount = threadCount; if (threadCount < 16) threadCount *= 2; else threadCount *= 1.5; if (!results.isEmpty() && threadCount > settings.rate.maxThreads) break; if (settings.command.type.updates) { // pause an arbitrary period of time to let the commit log flush, etc. shouldn't make much difference // as we only increase load, never decrease it output.println("Sleeping for 15s"); try { Thread.sleep(15 * 1000); } catch (InterruptedException e) { return false; } } // run until we have not improved throughput significantly for previous three runs } while (!auto || (hasAverageImprovement(results, 3, 0) && hasAverageImprovement(results, 5, settings.command.targetUncertainty))); // summarise all results StressMetrics.summarise(runIds, results, output); return true; } private boolean hasAverageImprovement(List<StressMetrics> results, int count, double minImprovement) { return results.size() < count + 1 || averageImprovement(results, count) >= minImprovement; } private double averageImprovement(List<StressMetrics> results, int count) { double improvement = 0; for (int i = results.size() - count ; i < results.size() ; i++) { double prev = results.get(i - 1).opRate(); double cur = results.get(i).opRate(); improvement += (cur - prev) / prev; } return improvement / count; } private StressMetrics run(OpDistributionFactory operations, int threadCount, long opCount, long duration, UniformRateLimiter rateLimiter, TimeUnit durationUnits, ResultLogger output, boolean isWarmup) { output.println(String.format("Running %s with %d threads %s", operations.desc(), threadCount, durationUnits != null ? duration + " " + durationUnits.toString().toLowerCase() : opCount > 0 ? "for " + opCount + " iteration" : "until stderr of mean < " + settings.command.targetUncertainty)); final WorkManager workManager; if (opCount < 0) workManager = new WorkManager.ContinuousWorkManager(); else workManager = new WorkManager.FixedWorkManager(opCount); final StressMetrics metrics = new StressMetrics(output, settings.log.intervalMillis, settings); final CountDownLatch releaseConsumers = new CountDownLatch(1); final CountDownLatch done = new CountDownLatch(threadCount); final CountDownLatch start = new CountDownLatch(threadCount); final Consumer[] consumers = new Consumer[threadCount]; for (int i = 0; i < threadCount; i++) { consumers[i] = new Consumer(operations, isWarmup, done, start, releaseConsumers, workManager, metrics, rateLimiter); } // starting worker threadCount for (int i = 0; i < threadCount; i++) consumers[i].start(); // wait for the lot of them to get their pants on try { start.await(); } catch (InterruptedException e) { throw new RuntimeException("Unexpected interruption", e); } // start counting from NOW! if(rateLimiter != null) { rateLimiter.start(); } // release the hounds!!! releaseConsumers.countDown(); metrics.start(); if (durationUnits != null) { Uninterruptibles.sleepUninterruptibly(duration, durationUnits); workManager.stop(); } else if (opCount <= 0) { try { metrics.waitUntilConverges(settings.command.targetUncertainty, settings.command.minimumUncertaintyMeasurements, settings.command.maximumUncertaintyMeasurements); } catch (InterruptedException e) { } workManager.stop(); } try { done.await(); metrics.stop(); } catch (InterruptedException e) {} if (metrics.wasCancelled()) return null; metrics.summarise(); boolean success = true; for (Consumer consumer : consumers) success &= consumer.success; if (!success) return null; return metrics; } /** * Provides a 'next operation time' for rate limited operation streams. The rate limiter is thread safe and is to be * shared by all consumer threads. */ private static class UniformRateLimiter { long start = Long.MIN_VALUE; final long intervalNs; final AtomicLong opIndex = new AtomicLong(); UniformRateLimiter(int opsPerSec) { intervalNs = 1000000000 / opsPerSec; } void start() { start = System.nanoTime(); } /** * @param partitionCount * @return expect start time in ns for the operation */ long acquire(int partitionCount) { long currOpIndex = opIndex.getAndAdd(partitionCount); return start + currOpIndex * intervalNs; } } /** * Provides a blocking stream of operations per consumer. */ private static class StreamOfOperations { private final OpDistribution operations; private final UniformRateLimiter rateLimiter; private final WorkManager workManager; public StreamOfOperations(OpDistribution operations, UniformRateLimiter rateLimiter, WorkManager workManager) { this.operations = operations; this.rateLimiter = rateLimiter; this.workManager = workManager; } /** * This method will block until the next operation becomes available. * * @return next operation or null if no more ops are coming */ Operation nextOp() { Operation op = operations.next(); final int partitionCount = op.ready(workManager); if (partitionCount == 0) return null; if (rateLimiter != null) { long intendedTime = rateLimiter.acquire(partitionCount); op.intendedStartNs(intendedTime); long now; while ((now = System.nanoTime()) < intendedTime) { LockSupport.parkNanos(intendedTime - now); } } return op; } void abort() { workManager.stop(); } } public static class OpMeasurement { public String opType; public long intended,started,ended,rowCnt,partitionCnt; public boolean err; @Override public String toString() { return "OpMeasurement [opType=" + opType + ", intended=" + intended + ", started=" + started + ", ended=" + ended + ", rowCnt=" + rowCnt + ", partitionCnt=" + partitionCnt + ", err=" + err + "]"; } } public interface MeasurementSink { void record(String opType,long intended, long started, long ended, long rowCnt, long partitionCnt, boolean err); } public class Consumer extends Thread implements MeasurementSink { private final StreamOfOperations opStream; private final StressMetrics metrics; private volatile boolean success = true; private final CountDownLatch done; private final CountDownLatch start; private final CountDownLatch releaseConsumers; public final Queue<OpMeasurement> measurementsRecycling; public final Queue<OpMeasurement> measurementsReporting; public Consumer(OpDistributionFactory operations, boolean isWarmup, CountDownLatch done, CountDownLatch start, CountDownLatch releaseConsumers, WorkManager workManager, StressMetrics metrics, UniformRateLimiter rateLimiter) { OpDistribution opDistribution = operations.get(isWarmup, this); this.done = done; this.start = start; this.releaseConsumers = releaseConsumers; this.metrics = metrics; this.opStream = new StreamOfOperations(opDistribution, rateLimiter, workManager); this.measurementsRecycling = new SpscArrayQueue<OpMeasurement>(8*1024); this.measurementsReporting = new SpscUnboundedArrayQueue<OpMeasurement>(2048); metrics.add(this); } public void run() { try { SimpleClient sclient = null; JavaDriverClient jclient = null; final ConnectionAPI clientType = settings.mode.api; try { switch (clientType) { case JAVA_DRIVER_NATIVE: jclient = settings.getJavaDriverClient(); break; case SIMPLE_NATIVE: sclient = settings.getSimpleNativeClient(); break; default: throw new IllegalStateException(); } } finally { // synchronize the start of all the consumer threads start.countDown(); } releaseConsumers.await(); while (true) { // Assumption: All ops are thread local, operations are never shared across threads. Operation op = opStream.nextOp(); if (op == null) break; try { switch (clientType) { case JAVA_DRIVER_NATIVE: op.run(jclient); break; case SIMPLE_NATIVE: op.run(sclient); break; default: throw new IllegalStateException(); } } catch (Exception e) { if (output == null) System.err.println(e.getMessage()); else output.printException(e); success = false; opStream.abort(); metrics.cancel(); return; } } } catch (Exception e) { System.err.println(e.getMessage()); success = false; } finally { done.countDown(); } } @Override public void record(String opType, long intended, long started, long ended, long rowCnt, long partitionCnt, boolean err) { OpMeasurement opMeasurement = measurementsRecycling.poll(); if(opMeasurement == null) { opMeasurement = new OpMeasurement(); } opMeasurement.opType = opType; opMeasurement.intended = intended; opMeasurement.started = started; opMeasurement.ended = ended; opMeasurement.rowCnt = rowCnt; opMeasurement.partitionCnt = partitionCnt; opMeasurement.err = err; measurementsReporting.offer(opMeasurement); } } }
/* * Copyright (c) 2016, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package io.siddhi.core.managment; import io.siddhi.core.SiddhiAppRuntime; import io.siddhi.core.SiddhiManager; import io.siddhi.core.event.Event; import io.siddhi.core.stream.input.InputHandler; import io.siddhi.core.stream.output.StreamCallback; import io.siddhi.core.util.EventPrinter; import io.siddhi.core.util.SiddhiConstants; import io.siddhi.core.util.statistics.metrics.Level; import org.apache.log4j.Logger; import org.testng.AssertJUnit; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import java.io.ByteArrayOutputStream; import java.io.PrintStream; public class StatisticsTestCase { private static final Logger log = Logger.getLogger(StatisticsTestCase.class); private int count; private boolean eventArrived; private long firstValue; private long lastValue; @BeforeMethod public void init() { count = 0; eventArrived = false; firstValue = 0; lastValue = 0; } @Test public void statisticsTest1() throws InterruptedException { log.info("statistics test 1"); SiddhiManager siddhiManager = new SiddhiManager(); String siddhiApp = "" + "@app:statistics(reporter = 'console', interval = '2' )" + " " + "define stream cseEventStream (symbol string, price float, volume int);" + "define stream cseEventStream2 (symbol string, price float, volume int);" + "" + "@info(name = 'query1') " + "from cseEventStream[70 > price] " + "select * " + "insert into outputStream ;" + "" + "@info(name = 'query2') " + "from cseEventStream[volume > 90] " + "select * " + "insert into outputStream ;"; SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(siddhiApp); siddhiAppRuntime.addCallback("outputStream", new StreamCallback() { @Override public void receive(Event[] events) { EventPrinter.print(events); eventArrived = true; for (Event event : events) { count++; AssertJUnit.assertTrue("IBM".equals(event.getData(0)) || "WSO2".equals(event.getData(0))); } } }); InputHandler inputHandler = siddhiAppRuntime.getInputHandler("cseEventStream"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); PrintStream old = System.out; System.setOut(ps); siddhiAppRuntime.start(); siddhiAppRuntime.setStatisticsLevel(Level.DETAIL); inputHandler.send(new Object[]{"WSO2", 55.6f, 100}); inputHandler.send(new Object[]{"IBM", 75.6f, 100}); Thread.sleep(3010); siddhiAppRuntime.shutdown(); AssertJUnit.assertTrue(eventArrived); AssertJUnit.assertEquals(3, count); System.out.flush(); String output = baos.toString(); AssertJUnit.assertTrue(output.contains("Gauges")); AssertJUnit.assertTrue(output.contains("io.siddhi." + SiddhiConstants.METRIC_INFIX_SIDDHI_APPS)); AssertJUnit.assertTrue(output.contains("query1.memory")); AssertJUnit.assertTrue(output.contains("Meters")); AssertJUnit.assertTrue(output.contains(SiddhiConstants.METRIC_INFIX_SIDDHI + SiddhiConstants.METRIC_DELIMITER + SiddhiConstants.METRIC_INFIX_STREAMS + SiddhiConstants.METRIC_DELIMITER + "cseEventStream")); AssertJUnit.assertTrue(output.contains("Timers")); AssertJUnit.assertTrue(output.contains("query1.latency")); log.info(output); System.setOut(old); } /** * To test stats disabling */ @Test(dependsOnMethods = "statisticsTest1") public void statisticsTest2() throws InterruptedException { log.info("statistics test 2"); SiddhiManager siddhiManager = new SiddhiManager(); String siddhiApp = "" + "@app:statistics(reporter = 'console', interval = '2' )" + " " + "define stream cseEventStream (symbol string, price float, volume int);" + "define stream cseEventStream2 (symbol string, price float, volume int);" + "" + "@info(name = 'query1') " + "from cseEventStream[70 > price] " + "select * " + "insert into outputStream ;" + "" + "@info(name = 'query2') " + "from cseEventStream[volume > 90] " + "select * " + "insert into outputStream ;"; SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(siddhiApp); siddhiAppRuntime.setStatisticsLevel(Level.OFF); siddhiAppRuntime.addCallback("outputStream", new StreamCallback() { @Override public void receive(Event[] events) { EventPrinter.print(events); eventArrived = true; for (Event event : events) { count++; AssertJUnit.assertTrue("IBM".equals(event.getData(0)) || "WSO2".equals(event.getData(0))); } } }); InputHandler inputHandler = siddhiAppRuntime.getInputHandler("cseEventStream"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); PrintStream old = System.out; System.setOut(ps); siddhiAppRuntime.start(); siddhiAppRuntime.setStatisticsLevel(Level.OFF); inputHandler.send(new Object[]{"WSO2", 55.6f, 100}); inputHandler.send(new Object[]{"IBM", 75.6f, 100}); Thread.sleep(3010); AssertJUnit.assertTrue(eventArrived); AssertJUnit.assertEquals(3, count); //reset eventArrived = false; count = 0; Thread.sleep(1000); System.out.flush(); String output = baos.toString(); log.info(output); //assert AssertJUnit.assertFalse(output.contains("Gauges")); siddhiAppRuntime.shutdown(); System.setOut(old); } /** * To test stats dynamic disabling */ @Test(dependsOnMethods = "statisticsTest2") public void statisticsTest3() throws InterruptedException { log.info("statistics test 3"); SiddhiManager siddhiManager = new SiddhiManager(); String siddhiApp = "" + "@app:statistics(reporter = 'console', interval = '2' )" + " " + "define stream cseEventStream (symbol string, price float, volume int);" + "define stream cseEventStream2 (symbol string, price float, volume int);" + "" + "@info(name = 'query1') " + "from cseEventStream[70 > price] " + "select * " + "insert into outputStream ;" + "" + "@info(name = 'query2') " + "from cseEventStream[volume > 90] " + "select * " + "insert into outputStream ;"; SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(siddhiApp); siddhiAppRuntime.addCallback("outputStream", new StreamCallback() { @Override public void receive(Event[] events) { EventPrinter.print(events); eventArrived = true; for (Event event : events) { count++; AssertJUnit.assertTrue("IBM".equals(event.getData(0)) || "WSO2".equals(event.getData(0))); } } }); InputHandler inputHandler = siddhiAppRuntime.getInputHandler("cseEventStream"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); PrintStream old = System.out; System.setOut(ps); siddhiAppRuntime.start(); siddhiAppRuntime.setStatisticsLevel(Level.DETAIL); inputHandler.send(new Object[]{"WSO2", 55.6f, 100}); inputHandler.send(new Object[]{"IBM", 75.6f, 100}); Thread.sleep(3010); AssertJUnit.assertTrue(eventArrived); AssertJUnit.assertEquals(3, count); System.out.flush(); String output = baos.toString(); baos.reset(); log.info(output); AssertJUnit.assertTrue(output.contains("Gauges")); //reset eventArrived = false; count = 0; Thread.sleep(100); siddhiAppRuntime.setStatisticsLevel(Level.OFF); Thread.sleep(100); inputHandler.send(new Object[]{"IBM", 75.6f, 100}); Thread.sleep(3010); AssertJUnit.assertTrue(eventArrived); AssertJUnit.assertEquals(1, count); System.out.flush(); output = baos.toString(); baos.reset(); log.info(output); AssertJUnit.assertFalse(output.contains("Gauges")); siddhiAppRuntime.shutdown(); System.setOut(old); } /** * To test stats dynamic enabling */ @Test(dependsOnMethods = "statisticsTest3") public void statisticsTest4() throws InterruptedException { log.info("statistics test 4"); SiddhiManager siddhiManager = new SiddhiManager(); String siddhiApp = "" + "@app:statistics(reporter = 'console', interval = '2' )" + " " + "define stream cseEventStream (symbol string, price float, volume int);" + "define stream cseEventStream2 (symbol string, price float, volume int);" + "" + "@info(name = 'query1') " + "from cseEventStream[70 > price] " + "select * " + "insert into outputStream ;" + "" + "@info(name = 'query2') " + "from cseEventStream[volume > 90] " + "select * " + "insert into outputStream ;"; SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(siddhiApp); siddhiAppRuntime.setStatisticsLevel(Level.OFF); siddhiAppRuntime.addCallback("outputStream", new StreamCallback() { @Override public void receive(Event[] events) { EventPrinter.print(events); eventArrived = true; for (Event event : events) { count++; AssertJUnit.assertTrue("IBM".equals(event.getData(0)) || "WSO2".equals(event.getData(0))); } } }); InputHandler inputHandler = siddhiAppRuntime.getInputHandler("cseEventStream"); PrintStream old = System.out; ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); System.setOut(ps); siddhiAppRuntime.start(); siddhiAppRuntime.setStatisticsLevel(Level.OFF); inputHandler.send(new Object[]{"WSO2", 55.6f, 100}); inputHandler.send(new Object[]{"IBM", 75.6f, 100}); Thread.sleep(3010); AssertJUnit.assertTrue(eventArrived); AssertJUnit.assertEquals(3, count); System.out.flush(); String output = baos.toString(); baos.reset(); log.info(output); AssertJUnit.assertFalse(output.contains("Gauges")); //reset eventArrived = false; count = 0; siddhiAppRuntime.setStatisticsLevel(Level.DETAIL); Thread.sleep(100); inputHandler.send(new Object[]{"IBM", 75.6f, 100}); Thread.sleep(3030); AssertJUnit.assertTrue(eventArrived); AssertJUnit.assertEquals(1, count); System.out.flush(); output = baos.toString(); baos.reset(); log.info(output); AssertJUnit.assertTrue(output.contains("Gauges")); siddhiAppRuntime.shutdown(); System.setOut(old); } /** * To not enable stats if no Stats manager enabled */ @Test(dependsOnMethods = "statisticsTest4") public void statisticsTest5() throws InterruptedException { log.info("statistics test 5"); SiddhiManager siddhiManager = new SiddhiManager(); String siddhiApp = "" + "define stream cseEventStream (symbol string, price float, volume int);" + "define stream cseEventStream2 (symbol string, price float, volume int);" + "" + "@info(name = 'query1') " + "from cseEventStream[70 > price] " + "select * " + "insert into outputStream ;" + "" + "@info(name = 'query2') " + "from cseEventStream[volume > 90] " + "select * " + "insert into outputStream ;"; SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(siddhiApp); siddhiAppRuntime.setStatisticsLevel(Level.OFF); siddhiAppRuntime.addCallback("outputStream", new StreamCallback() { @Override public void receive(Event[] events) { EventPrinter.print(events); eventArrived = true; for (Event event : events) { count++; AssertJUnit.assertTrue("IBM".equals(event.getData(0)) || "WSO2".equals(event.getData(0))); } } }); InputHandler inputHandler = siddhiAppRuntime.getInputHandler("cseEventStream"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); PrintStream old = System.out; System.setOut(ps); siddhiAppRuntime.start(); siddhiAppRuntime.setStatisticsLevel(Level.DETAIL); inputHandler.send(new Object[]{"WSO2", 55.6f, 100}); inputHandler.send(new Object[]{"IBM", 75.6f, 100}); Thread.sleep(3010); siddhiAppRuntime.shutdown(); AssertJUnit.assertTrue(eventArrived); AssertJUnit.assertEquals(3, count); System.out.flush(); String output = baos.toString(); AssertJUnit.assertFalse(output.contains("Gauges")); log.info(output); System.setOut(old); } @Test(dependsOnMethods = "statisticsTest5") public void statisticsTest6() throws InterruptedException { log.info("statistics test 1"); SiddhiManager siddhiManager = new SiddhiManager(); String siddhiApp = "" + "@app:statistics(reporter = 'console', interval = '2', include='*query2.*,*cseEventStream2*' )" + " " + "define stream cseEventStream (symbol string, price float, volume int);" + "define stream cseEventStream2 (symbol string, price float, volume int);" + "" + "@info(name = 'query1') " + "from cseEventStream[70 > price] " + "select * " + "insert into outputStream ;" + "" + "@info(name = 'query2') " + "from cseEventStream[volume > 90] " + "select * " + "insert into outputStream ;"; SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(siddhiApp); siddhiAppRuntime.addCallback("outputStream", new StreamCallback() { @Override public void receive(Event[] events) { EventPrinter.print(events); eventArrived = true; for (Event event : events) { count++; AssertJUnit.assertTrue("IBM".equals(event.getData(0)) || "WSO2".equals(event.getData(0))); } } }); InputHandler inputHandler = siddhiAppRuntime.getInputHandler("cseEventStream"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); PrintStream old = System.out; System.setOut(ps); siddhiAppRuntime.start(); siddhiAppRuntime.setStatisticsLevel(Level.DETAIL); inputHandler.send(new Object[]{"WSO2", 55.6f, 100}); inputHandler.send(new Object[]{"IBM", 75.6f, 100}); Thread.sleep(3010); siddhiAppRuntime.shutdown(); AssertJUnit.assertTrue(eventArrived); AssertJUnit.assertEquals(3, count); System.out.flush(); String output = baos.toString(); AssertJUnit.assertTrue(output.contains("Gauges")); AssertJUnit.assertTrue(output.contains("io.siddhi." + SiddhiConstants.METRIC_INFIX_SIDDHI_APPS)); AssertJUnit.assertFalse(output.contains("query1.memory")); AssertJUnit.assertTrue(output.contains("cseEventStream2.throughput")); AssertJUnit.assertTrue(output.contains("Meters")); AssertJUnit.assertTrue(output.contains(SiddhiConstants.METRIC_INFIX_SIDDHI + SiddhiConstants.METRIC_DELIMITER + SiddhiConstants.METRIC_INFIX_STREAMS + SiddhiConstants.METRIC_DELIMITER + "cseEventStream")); AssertJUnit.assertTrue(output.contains("Timers")); AssertJUnit.assertFalse(output.contains("query1.latency")); AssertJUnit.assertTrue(output.contains("query2.memory")); log.info(output); System.setOut(old); } @Test//(dependsOnMethods = "statisticsTest6") public void statisticsTest7() throws InterruptedException { log.info("statistics test 7"); SiddhiManager siddhiManager = new SiddhiManager(); String siddhiApp = "" + "@app:statistics(reporter = 'console', interval = '2' )" + " " + "define stream cseEventStream (symbol string, price float, volume int);" + "define stream cseEventStream2 (symbol string, price float, volume int);" + "" + "@info(name = 'query1') " + "from cseEventStream[70 > price] " + "select * " + "insert into outputStream ;" + "" + "@info(name = 'query2') " + "from cseEventStream[volume > 90] " + "select * " + "insert into outputStream ;"; SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(siddhiApp); siddhiAppRuntime.addCallback("outputStream", new StreamCallback() { @Override public void receive(Event[] events) { EventPrinter.print(events); eventArrived = true; for (Event event : events) { count++; AssertJUnit.assertTrue("IBM".equals(event.getData(0)) || "WSO2".equals(event.getData(0))); } } }); InputHandler inputHandler = siddhiAppRuntime.getInputHandler("cseEventStream"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); PrintStream old = System.out; System.setOut(ps); siddhiAppRuntime.start(); siddhiAppRuntime.setStatisticsLevel(Level.BASIC); inputHandler.send(new Object[]{"WSO2", 55.6f, 100}); inputHandler.send(new Object[]{"IBM", 75.6f, 100}); Thread.sleep(3010); siddhiAppRuntime.shutdown(); AssertJUnit.assertTrue(eventArrived); AssertJUnit.assertEquals(3, count); System.out.flush(); String output = baos.toString(); AssertJUnit.assertFalse(output.contains("Gauges")); AssertJUnit.assertFalse(output.contains("query1.memory")); AssertJUnit.assertTrue(output.contains("io.siddhi." + SiddhiConstants.METRIC_INFIX_SIDDHI_APPS)); AssertJUnit.assertTrue(output.contains("Meters")); AssertJUnit.assertTrue(output.contains(SiddhiConstants.METRIC_INFIX_SIDDHI + SiddhiConstants.METRIC_DELIMITER + SiddhiConstants.METRIC_INFIX_STREAMS + SiddhiConstants.METRIC_DELIMITER + "cseEventStream")); AssertJUnit.assertTrue(output.contains("Timers")); AssertJUnit.assertTrue(output.contains("query1.latency")); log.info(output); System.setOut(old); } @Test//(dependsOnMethods = "statisticsTest6") public void statisticsTest8() throws InterruptedException { log.info("statistics test 8"); SiddhiManager siddhiManager = new SiddhiManager(); String siddhiApp = "" + "@app:statistics(reporter = 'console', interval = '2' )" + " " + "@async(buffer.size='2') " + "define stream cseEventStream (symbol string, price float, volume int);" + "define stream cseEventStream2 (symbol string, price float, volume int);" + "" + "@info(name = 'query1') " + "from cseEventStream[70 > price] " + "select * " + "insert into outputStream ;" + "" + "@info(name = 'query2') " + "from cseEventStream[volume > 90] " + "select * " + "insert into outputStream ;"; SiddhiAppRuntime siddhiAppRuntime = siddhiManager.createSiddhiAppRuntime(siddhiApp); siddhiAppRuntime.addCallback("outputStream", new StreamCallback() { @Override public void receive(Event[] events) { EventPrinter.print(events); eventArrived = true; for (Event event : events) { count++; AssertJUnit.assertTrue("IBM".equals(event.getData(0)) || "WSO2".equals(event.getData(0))); } } }); InputHandler inputHandler = siddhiAppRuntime.getInputHandler("cseEventStream"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); PrintStream ps = new PrintStream(baos); PrintStream old = System.out; System.setOut(ps); siddhiAppRuntime.start(); siddhiAppRuntime.setStatisticsLevel(Level.BASIC); inputHandler.send(new Object[]{"WSO2", 55.6f, 100}); inputHandler.send(new Object[]{"IBM", 75.6f, 100}); Thread.sleep(3010); siddhiAppRuntime.shutdown(); AssertJUnit.assertTrue(eventArrived); AssertJUnit.assertEquals(3, count); System.out.flush(); String output = baos.toString(); log.info(output); AssertJUnit.assertTrue(output.contains("Gauges")); AssertJUnit.assertTrue(output.contains("cseEventStream.size")); AssertJUnit.assertFalse(output.contains("query1.memory")); AssertJUnit.assertTrue(output.contains("io.siddhi." + SiddhiConstants.METRIC_INFIX_SIDDHI_APPS)); AssertJUnit.assertTrue(output.contains("Meters")); AssertJUnit.assertTrue(output.contains(SiddhiConstants.METRIC_INFIX_SIDDHI + SiddhiConstants.METRIC_DELIMITER + SiddhiConstants.METRIC_INFIX_STREAMS + SiddhiConstants.METRIC_DELIMITER + "cseEventStream")); AssertJUnit.assertTrue(output.contains("Timers")); AssertJUnit.assertTrue(output.contains("query1.latency")); System.setOut(old); } }
/* * Copyright 2013 Rackspace * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.rackspacecloud.blueflood.service; import com.google.common.collect.Lists; import com.netflix.astyanax.MutationBatch; import com.netflix.astyanax.connectionpool.exceptions.ConnectionException; import com.rackspacecloud.blueflood.io.*; import com.rackspacecloud.blueflood.io.astyanax.AstyanaxReader; import com.rackspacecloud.blueflood.io.astyanax.AstyanaxWriter; import com.rackspacecloud.blueflood.io.CassandraModel.MetricColumnFamily; import com.rackspacecloud.blueflood.outputs.formats.MetricData; import com.rackspacecloud.blueflood.rollup.Granularity; import com.rackspacecloud.blueflood.types.*; import com.rackspacecloud.blueflood.utils.TimeValue; import com.rackspacecloud.blueflood.utils.Util; import org.junit.Assert; import org.junit.Test; import org.mockito.internal.util.reflection.Whitebox; import java.io.IOException; import java.util.*; import java.util.concurrent.TimeUnit; /** * Some of these tests here were horribly contrived to mimic behavior in Writer. The problem with this approach is that * when logic in Writer changes, these tests can break unless the logic is changed here too. */ public class MetricsIntegrationTest extends IntegrationTestBase { // returns a collection all checks that were written at some point. // this was a lot cooler back when the slot changed with time. private Collection<Locator> writeLocatorsOnly(int hours) throws Exception { // duplicate the logic from Writer.writeFull() that inserts locator rows. final String tenantId = "ac" + randString(8); final List<Locator> locators = new ArrayList<Locator>(); for (int i = 0; i < hours; i++) { locators.add(Locator.createLocatorFromPathComponents(tenantId, "test:locator:inserts:" + i)); } AstyanaxTester at = new AstyanaxTester(); MutationBatch mb = at.createMutationBatch(); for (Locator locator : locators) { int shard = Util.computeShard(locator.toString()); mb.withRow(at.getLocatorCF(), (long)shard) .putColumn(locator, "", 100000); } mb.execute(); return locators; } private void writeFullData( Locator locator, long baseMillis, int hours, AstyanaxWriter writer) throws Exception { // insert something every minute for 48h for (int i = 0; i < 60 * hours; i++) { final long curMillis = baseMillis + i * 60000; List<Metric> metrics = new ArrayList<Metric>(); metrics.add(getRandomIntMetric(locator, curMillis)); writer.insertFull(metrics); } } @Test public void testLocatorsWritten() throws Exception { Collection<Locator> locators = writeLocatorsOnly(48); LocatorIO locatorIO = IOContainer.fromConfig().getLocatorIO(); Set<String> actualLocators = new HashSet<String>(); for (Locator locator : locators) { for (Locator databaseLocator : locatorIO.getLocators(Util.computeShard(locator.toString()))) { actualLocators.add(databaseLocator.toString()); } } Assert.assertEquals(48, actualLocators.size()); } @Test public void testRollupGenerationSimple() throws Exception { AstyanaxWriter writer = AstyanaxWriter.getInstance(); AstyanaxReader reader = AstyanaxReader.getInstance(); final long baseMillis = 1333635148000L; // some point during 5 April 2012. int hours = 48; final String acctId = "ac" + IntegrationTestBase.randString(8); final String metricName = "fooService,barServer," + randString(8); final long endMillis = baseMillis + (1000 * 60 * 60 * hours); final Locator locator = Locator.createLocatorFromPathComponents(acctId, metricName); writeFullData(locator, baseMillis, hours, writer); // FULL -> 5m ArrayList<SingleRollupWriteContext> writes = new ArrayList<SingleRollupWriteContext>(); for (Range range : Range.getRangesToRollup(Granularity.FULL, baseMillis, endMillis)) { // each range should produce one average Points<SimpleNumber> input = reader.getDataToRoll(SimpleNumber.class, locator, range, CassandraModel.CF_METRICS_FULL); BasicRollup basicRollup = BasicRollup.buildRollupFromRawSamples(input); writes.add(new SingleRollupWriteContext(basicRollup, locator, Granularity.FULL.coarser(), CassandraModel.getColumnFamily(BasicRollup.class, Granularity.FULL.coarser()), range.start)); } writer.insertRollups(writes); // 5m -> 20m writes.clear(); for (Range range : Range.getRangesToRollup(Granularity.MIN_5, baseMillis, endMillis)) { Points<BasicRollup> input = reader.getDataToRoll(BasicRollup.class, locator, range, CassandraModel.getColumnFamily(BasicRollup.class, Granularity.MIN_5)); BasicRollup basicRollup = BasicRollup.buildRollupFromRollups(input); writes.add(new SingleRollupWriteContext(basicRollup, locator, Granularity.MIN_5.coarser(), CassandraModel.getColumnFamily(BasicRollup.class, Granularity.MIN_5.coarser()), range.start)); } writer.insertRollups(writes); // 20m -> 60m writes.clear(); for (Range range : Range.getRangesToRollup(Granularity.MIN_20, baseMillis, endMillis)) { Points<BasicRollup> input = reader.getDataToRoll(BasicRollup.class, locator, range, CassandraModel.getColumnFamily(BasicRollup.class, Granularity.MIN_20)); BasicRollup basicRollup = BasicRollup.buildRollupFromRollups(input); writes.add(new SingleRollupWriteContext(basicRollup, locator, Granularity.MIN_20.coarser(), CassandraModel.getColumnFamily(BasicRollup.class, Granularity.MIN_20.coarser()), range.start)); } writer.insertRollups(writes); // 60m -> 240m writes.clear(); for (Range range : Range.getRangesToRollup(Granularity.MIN_60, baseMillis, endMillis)) { Points<BasicRollup> input = reader.getDataToRoll(BasicRollup.class, locator, range, CassandraModel.getColumnFamily(BasicRollup.class, Granularity.MIN_60)); BasicRollup basicRollup = BasicRollup.buildRollupFromRollups(input); writes.add(new SingleRollupWriteContext(basicRollup, locator, Granularity.MIN_60.coarser(), CassandraModel.getColumnFamily(BasicRollup.class, Granularity.MIN_60.coarser()), range.start)); } writer.insertRollups(writes); // 240m -> 1440m writes.clear(); for (Range range : Range.getRangesToRollup(Granularity.MIN_240, baseMillis, endMillis)) { Points<BasicRollup> input = reader.getDataToRoll(BasicRollup.class, locator, range, CassandraModel.getColumnFamily(BasicRollup.class, Granularity.MIN_240)); BasicRollup basicRollup = BasicRollup.buildRollupFromRollups(input); writes.add(new SingleRollupWriteContext(basicRollup, locator, Granularity.MIN_240.coarser(), CassandraModel.getColumnFamily(BasicRollup.class, Granularity.MIN_240.coarser()), range.start)); } writer.insertRollups(writes); // verify the number of points in 48h worth of rollups. Range range = new Range(Granularity.MIN_1440.snapMillis(baseMillis), Granularity.MIN_1440.snapMillis(endMillis + Granularity.MIN_1440.milliseconds())); Points<BasicRollup> input = reader.getDataToRoll(BasicRollup.class, locator, range, CassandraModel.getColumnFamily(BasicRollup.class, Granularity.MIN_1440)); BasicRollup basicRollup = BasicRollup.buildRollupFromRollups(input); Assert.assertEquals(60 * hours, basicRollup.getCount()); } @Test public void testSimpleInsertAndGet() throws Exception { AstyanaxWriter writer = AstyanaxWriter.getInstance(); AstyanaxReader reader = AstyanaxReader.getInstance(); final long baseMillis = 1333635148000L; // some point during 5 April 2012. long lastMillis = baseMillis + (300 * 1000); // 300 seconds. final String acctId = "ac" + IntegrationTestBase.randString(8); final String metricName = "fooService,barServer," + randString(8); final Locator locator = Locator.createLocatorFromPathComponents(acctId, metricName); Set<Long> expectedTimestamps = new HashSet<Long>(); // insert something every 30s for 5 mins. for (int i = 0; i < 10; i++) { final long curMillis = baseMillis + (i * 30000); // 30 seconds later. expectedTimestamps.add(curMillis); List<Metric> metrics = new ArrayList<Metric>(); metrics.add(getRandomIntMetric(locator, curMillis)); writer.insertFull(metrics); } Set<Long> actualTimestamps = new HashSet<Long>(); // get back the cols that were written from start to stop. Points<SimpleNumber> points = reader.getDataToRoll(SimpleNumber.class, locator, new Range(baseMillis, lastMillis), CassandraModel.getColumnFamily(BasicRollup.class, Granularity.FULL)); actualTimestamps = points.getPoints().keySet(); Assert.assertEquals(expectedTimestamps, actualTimestamps); } @Test //In this test, string metrics are configured to be always dropped. So they are not persisted at all. public void testStringMetricsIfSoConfiguredAreAlwaysDropped() throws Exception { Boolean orgAreStringDropped = (Boolean) Whitebox.getInternalState(AstyanaxWriter.getInstance(), "areStringMetricsDropped"); try { Whitebox.setInternalState(AstyanaxWriter.getInstance(), "areStringMetricsDropped", true); AstyanaxWriter writer = AstyanaxWriter.getInstance(); AstyanaxReader reader = AstyanaxReader.getInstance(); final long baseMillis = 1333635148000L; // some point during 5 April 2012. long lastMillis = baseMillis + (300 * 1000); // 300 seconds. final String acctId = "ac" + IntegrationTestBase.randString(8); final String metricName = "fooService,barServer," + randString(8); final Locator locator = Locator.createLocatorFromPathComponents(acctId, metricName); Set<Long> expectedTimestamps = new HashSet<Long>(); // insert something every 30s for 5 mins. for (int i = 0; i < 10; i++) { final long curMillis = baseMillis + (i * 30000); // 30 seconds later. expectedTimestamps.add(curMillis); List<Metric> metrics = new ArrayList<Metric>(); metrics.add(makeMetric(locator, curMillis, getRandomStringMetricValue())); writer.insertFull(metrics); } Set<Long> actualTimestamps = new HashSet<Long>(); // get back the cols that were written from start to stop. MetricData data = reader.getDatapointsForRange(locator, new Range(baseMillis, lastMillis), Granularity.FULL); actualTimestamps = data.getData().getPoints().keySet(); Assert.assertTrue(actualTimestamps.size() == 0); } finally { Whitebox.setInternalState(AstyanaxWriter.getInstance(), "areStringMetricsDropped", orgAreStringDropped.booleanValue()); } } @Test //In this test, string metrics are configured to be always dropped. So they are not persisted at all. public void testStringMetricsIfSoConfiguredAreNotDroppedForKeptTenantIds() throws Exception { Boolean orgAreStringDropped = (Boolean) Whitebox.getInternalState(AstyanaxWriter.getInstance(), "areStringMetricsDropped"); try { Whitebox.setInternalState(AstyanaxWriter.getInstance(), "areStringMetricsDropped", true); AstyanaxWriter writer = AstyanaxWriter.getInstance(); AstyanaxReader reader = AstyanaxReader.getInstance(); final long baseMillis = 1333635148000L; // some point during 5 April 2012. long lastMillis = baseMillis + (300 * 1000); // 300 seconds. final String acctId = "ac" + IntegrationTestBase.randString(8); final String metricName = "fooService,barServer," + randString(8); final Locator locator = Locator.createLocatorFromPathComponents(acctId, metricName); HashSet<String> keptTenants = new HashSet<String>(); keptTenants.add(locator.getTenantId()); Whitebox.setInternalState(AstyanaxWriter.getInstance(), "keptTenantIdsSet", keptTenants); Set<Long> expectedTimestamps = new HashSet<Long>(); // insert something every 30s for 5 mins. for (int i = 0; i < 10; i++) { final long curMillis = baseMillis + (i * 30000); // 30 seconds later. expectedTimestamps.add(curMillis); List<Metric> metrics = new ArrayList<Metric>(); metrics.add(makeMetric(locator, curMillis, getRandomStringMetricValue())); writer.insertFull(metrics); } Set<Long> actualTimestamps = new HashSet<Long>(); // get back the cols that were written from start to stop. MetricData data = reader.getDatapointsForRange(locator, new Range(baseMillis, lastMillis), Granularity.FULL); actualTimestamps = data.getData().getPoints().keySet(); Assert.assertEquals(expectedTimestamps, actualTimestamps); } finally { Whitebox.setInternalState(AstyanaxWriter.getInstance(), "areStringMetricsDropped", orgAreStringDropped.booleanValue()); } } @Test //In this test, string metrics are not configured to be dropped so they are persisted. public void testStringMetricsIfSoConfiguredArePersistedAsExpected() throws Exception { Boolean orgAreStringDropped = (Boolean) Whitebox.getInternalState(AstyanaxWriter.getInstance(), "areStringMetricsDropped"); try { Whitebox.setInternalState(AstyanaxWriter.getInstance(), "areStringMetricsDropped", false); AstyanaxWriter writer = AstyanaxWriter.getInstance(); AstyanaxReader reader = AstyanaxReader.getInstance(); final long baseMillis = 1333635148000L; // some point during 5 April 2012. long lastMillis = baseMillis + (300 * 1000); // 300 seconds. final String acctId = "ac" + IntegrationTestBase.randString(8); final String metricName = "fooService,barServer," + randString(8); final Locator locator = Locator.createLocatorFromPathComponents(acctId, metricName); Set<Long> expectedTimestamps = new HashSet<Long>(); // insert something every 30s for 5 mins. for (int i = 0; i < 10; i++) { final long curMillis = baseMillis + (i * 30000); // 30 seconds later. expectedTimestamps.add(curMillis); List<Metric> metrics = new ArrayList<Metric>(); metrics.add(makeMetric(locator, curMillis, getRandomStringMetricValue())); writer.insertFull(metrics); } Set<Long> actualTimestamps = new HashSet<Long>(); // get back the cols that were written from start to stop. MetricData data = reader.getDatapointsForRange(locator, new Range(baseMillis, lastMillis), Granularity.FULL); actualTimestamps = data.getData().getPoints().keySet(); Assert.assertEquals(expectedTimestamps, actualTimestamps); } finally { Whitebox.setInternalState(AstyanaxWriter.getInstance(), "areStringMetricsDropped", orgAreStringDropped.booleanValue()); } } @Test //In this test, we attempt to persist the same value of String Metric every single time. Only the first one is persisted. public void testStringMetricsWithSameValueAreNotPersisted() throws Exception { Boolean orgAreStringDropped = (Boolean) Whitebox.getInternalState(AstyanaxWriter.getInstance(), "areStringMetricsDropped"); try { Whitebox.setInternalState(AstyanaxWriter.getInstance(), "areStringMetricsDropped", false); AstyanaxWriter writer = AstyanaxWriter.getInstance(); AstyanaxReader reader = AstyanaxReader.getInstance(); final long baseMillis = 1333635148000L; // some point during 5 April 2012. long lastMillis = baseMillis + (300 * 1000); // 300 seconds. final String acctId = "ac" + IntegrationTestBase.randString(8); final String metricName = "fooService,barServer," + randString(8); final Locator locator = Locator.createLocatorFromPathComponents(acctId, metricName); String sameValue = getRandomStringMetricValue(); Set<Long> expectedTimestamps = new HashSet<Long>(); // insert something every 30s for 5 mins. //value remains the same for (int i = 0; i < 10; i++) { final long curMillis = baseMillis + (i * 30000); // 30 seconds later. expectedTimestamps.add(curMillis); List<Metric> metrics = new ArrayList<Metric>(); metrics.add(makeMetric(locator, curMillis, sameValue)); writer.insertFull(metrics); } Set<Long> actualTimestamps = new HashSet<Long>(); // get back the cols that were written from start to stop. MetricData data = reader.getDatapointsForRange(locator, new Range(baseMillis, lastMillis), Granularity.FULL); actualTimestamps = data.getData().getPoints().keySet(); Assert.assertTrue(actualTimestamps.size() == 1); for (long ts : actualTimestamps) { Assert.assertEquals(ts, baseMillis); break; } } finally { Whitebox.setInternalState(AstyanaxWriter.getInstance(), "areStringMetricsDropped", orgAreStringDropped.booleanValue()); } } @Test //In this case, we alternate between two values for a string metric. But since the string metric does not have the same value in two //consecutive writes, it's always persisted. public void testStringMetricsWithDifferentValuesArePersisted() throws Exception { AstyanaxWriter writer = AstyanaxWriter.getInstance(); AstyanaxReader reader = AstyanaxReader.getInstance(); final long baseMillis = 1333635148000L; // some point during 5 April 2012. long lastMillis = baseMillis + (300 * 1000); // 300 seconds. final String acctId = "ac" + IntegrationTestBase.randString(8); final String metricName = "fooService,barServer," + randString(8); final Locator locator = Locator.createLocatorFromPathComponents(acctId, metricName); String firstValue = getRandomStringMetricValue(); String secondValue = getRandomStringMetricValue(); Set<Long> expectedTimestamps = new HashSet<Long>(); // insert something every 30s for 5 mins. //string metric value is alternated. for (int i = 0; i < 10; i++) { final long curMillis = baseMillis + (i * 30000); // 30 seconds later. String value = null; if (i % 2 == 0) { value = firstValue; } else { value = secondValue; } expectedTimestamps.add(curMillis); List<Metric> metrics = new ArrayList<Metric>(); metrics.add(makeMetric(locator, curMillis, value)); writer.insertFull(metrics); } Set<Long> actualTimestamps = new HashSet<Long>(); // get back the cols that were written from start to stop. MetricData data = reader.getDatapointsForRange(locator, new Range(baseMillis, lastMillis),Granularity.FULL); actualTimestamps = data.getData().getPoints().keySet(); Assert.assertEquals(expectedTimestamps, actualTimestamps); } @Test //Numeric value is always persisted. public void testNumericMetricsAreAlwaysPersisted() throws Exception { AstyanaxWriter writer = AstyanaxWriter.getInstance(); AstyanaxReader reader = AstyanaxReader.getInstance(); final long baseMillis = 1333635148000L; // some point during 5 April 2012. long lastMillis = baseMillis + (300 * 1000); // 300 seconds. final String acctId = "ac" + IntegrationTestBase.randString(8); final String metricName = "fooService,barServer," + randString(8); final Locator locator = Locator.createLocatorFromPathComponents(acctId, metricName); int sameValue = getRandomIntMetricValue(); Set<Long> expectedTimestamps = new HashSet<Long>(); // insert something every 30s for 5 mins. //value of numeric metric remains the same, still it is always persisted for (int i = 0; i < 10; i++) { final long curMillis = baseMillis + (i * 30000); // 30 seconds later. expectedTimestamps.add(curMillis); List<Metric> metrics = new ArrayList<Metric>(); metrics.add(makeMetric(locator, curMillis,sameValue)); writer.insertFull(metrics); } Set<Long> actualTimestamps = new HashSet<Long>(); // get back the cols that were written from start to stop. Points<SimpleNumber> points = reader.getDataToRoll(SimpleNumber.class, locator, new Range(baseMillis, lastMillis), CassandraModel.getColumnFamily(BasicRollup.class, Granularity.FULL)); actualTimestamps = points.getPoints().keySet(); Assert.assertEquals(expectedTimestamps, actualTimestamps); } @Test //In this test, the same value is sent, and the metric is not persisted except for the first time. public void testBooleanMetricsWithSameValueAreNotPersisted() throws Exception { AstyanaxWriter writer = AstyanaxWriter.getInstance(); AstyanaxReader reader = AstyanaxReader.getInstance(); final long baseMillis = 1333635148000L; // some point during 5 April 2012. long lastMillis = baseMillis + (300 * 1000); // 300 seconds. final String acctId = "ac" + IntegrationTestBase.randString(8); final String metricName = "fooService,barServer," + randString(8); final Locator locator = Locator.createLocatorFromPathComponents(acctId, metricName); boolean sameValue = true; Set<Long> expectedTimestamps = new HashSet<Long>(); // insert something every 30s for 5 mins. for (int i = 0; i < 10; i++) { final long curMillis = baseMillis + (i * 30000); // 30 seconds later. expectedTimestamps.add(curMillis); List<Metric> metrics = new ArrayList<Metric>(); metrics.add(makeMetric(locator,curMillis,sameValue)); writer.insertFull(metrics); } Set<Long> actualTimestamps = new HashSet<Long>(); // get back the cols that were written from start to stop. MetricData data = reader.getDatapointsForRange(locator, new Range(baseMillis, lastMillis),Granularity.FULL); actualTimestamps = data.getData().getPoints().keySet(); Assert.assertTrue(actualTimestamps.size() == 1); for(long ts : actualTimestamps) { Assert.assertEquals(ts, baseMillis); break; } } @Test //In this test, we alternately persist true and false. All the boolean metrics are persisted. public void testBooleanMetricsWithDifferentValuesArePersisted() throws Exception { AstyanaxWriter writer = AstyanaxWriter.getInstance(); AstyanaxReader reader = AstyanaxReader.getInstance(); final long baseMillis = 1333635148000L; // some point during 5 April 2012. long lastMillis = baseMillis + (300 * 1000); // 300 seconds. final String acctId = "ac" + IntegrationTestBase.randString(8); final String metricName = "fooService,barServer," + randString(8); final Locator locator = Locator.createLocatorFromPathComponents(acctId, metricName); Set<Long> expectedTimestamps = new HashSet<Long>(); // insert something every 30s for 5 mins. for (int i = 0; i < 10; i++) { final long curMillis = baseMillis + (i * 30000); // 30 seconds later. boolean value; if (i % 2 == 0) { value = true; } else { value = false; } expectedTimestamps.add(curMillis); List<Metric> metrics = new ArrayList<Metric>(); metrics.add(makeMetric(locator, curMillis, value)); writer.insertFull(metrics); } Set<Long> actualTimestamps = new HashSet<Long>(); // get back the cols that were written from start to stop. MetricData data = reader.getDatapointsForRange(locator, new Range(baseMillis, lastMillis),Granularity.FULL); actualTimestamps = data.getData().getPoints().keySet(); Assert.assertEquals(expectedTimestamps, actualTimestamps); } @Test public void testConsecutiveWriteAndRead() throws ConnectionException, IOException { AstyanaxWriter writer = AstyanaxWriter.getInstance(); AstyanaxReader reader = AstyanaxReader.getInstance(); final long baseMillis = 1333635148000L; final Locator locator = Locator.createLocatorFromPathComponents("ac0001", "fooService,fooServer," + randString(8)); final List<Metric> metrics = new ArrayList<Metric>(); for (int i = 0; i < 100; i++) { final Metric metric = new Metric(locator, i, baseMillis + (i * 1000), new TimeValue(1, TimeUnit.DAYS), "unknown"); metrics.add(metric); writer.insertFull(metrics); metrics.clear(); } int count = 0; MetricColumnFamily CF_metrics_full = CassandraModel.getColumnFamily(BasicRollup.class, Granularity.FULL); Points<SimpleNumber> points = reader.getDataToRoll(SimpleNumber.class, locator, new Range(baseMillis, baseMillis + 500000), CF_metrics_full); for (Map.Entry<Long, Points.Point<SimpleNumber>> data : points.getPoints().entrySet()) { Points.Point<SimpleNumber> point = data.getValue(); Assert.assertEquals(count, point.getData().getValue()); count++; } } @Test public void testShardStateWriteRead() throws Exception { final Collection<Integer> shards = Lists.newArrayList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); ShardStateIO shardStateIO = IOContainer.fromConfig().getShardStateIO(); // Simulate active or running state for all the slots for all granularities. for (int shard : shards) { Map<Granularity, Map<Integer, UpdateStamp>> allUpdates = new HashMap<Granularity, Map<Integer, UpdateStamp>>(); for (Granularity granularity : Granularity.rollupGranularities()) { Map<Integer, UpdateStamp> updates = new HashMap<Integer, UpdateStamp>(); for (int slot = 0; slot < granularity.numSlots(); slot++) { updates.put(slot, new UpdateStamp(System.currentTimeMillis() - 10000, UpdateStamp.State.Active, true)); } allUpdates.put(granularity, updates); } shardStateIO.putShardState(shard, allUpdates); } // Now simulate rolled up state for all the slots for all granularities. for (int shard : shards) { Map<Granularity, Map<Integer, UpdateStamp>> allUpdates = new HashMap<Granularity, Map<Integer, UpdateStamp>>(); for (Granularity granularity : Granularity.rollupGranularities()) { Map<Integer, UpdateStamp> updates = new HashMap<Integer, UpdateStamp>(); for (int slot = 0; slot < granularity.numSlots(); slot++) { updates.put(slot, new UpdateStamp(System.currentTimeMillis(), UpdateStamp.State.Rolled, true)); } allUpdates.put(granularity, updates); } shardStateIO.putShardState(shard, allUpdates); } // Now we would have the longest row for each shard because we filled all the slots. // Now test whether getShardState returns all the slots ScheduleContext ctx = new ScheduleContext(System.currentTimeMillis(), shards); ShardStateManager shardStateManager = ctx.getShardStateManager(); for (Integer shard : shards) { Collection<SlotState> slotStates = shardStateIO.getShardState(shard); for (SlotState slotState : slotStates) { shardStateManager.updateSlotOnRead(shard, slotState); } for (Granularity granularity : Granularity.rollupGranularities()) { ShardStateManager.SlotStateManager slotStateManager = shardStateManager.getSlotStateManager(shard, granularity); Assert.assertEquals(granularity.numSlots(), slotStateManager.getSlotStamps().size()); } } } @Test public void testUpdateStampCoaelescing() throws Exception { final int shard = 24; final int slot = 16; ShardStateIO shardStateIO = IOContainer.fromConfig().getShardStateIO(); Map<Granularity, Map<Integer, UpdateStamp>> updates = new HashMap<Granularity, Map<Integer, UpdateStamp>>(); Map<Integer, UpdateStamp> slotUpdates = new HashMap<Integer, UpdateStamp>(); updates.put(Granularity.MIN_5, slotUpdates); long time = 1234; slotUpdates.put(slot, new UpdateStamp(time++, UpdateStamp.State.Active, true)); shardStateIO.putShardState(shard, updates); slotUpdates.put(slot, new UpdateStamp(time++, UpdateStamp.State.Rolled, true)); shardStateIO.putShardState(shard, updates); ScheduleContext ctx = new ScheduleContext(System.currentTimeMillis(), Lists.newArrayList(shard)); Collection<SlotState> slotStates = shardStateIO.getShardState(shard); for (SlotState slotState : slotStates) { ctx.getShardStateManager().updateSlotOnRead(shard, slotState); } ShardStateManager shardStateManager = ctx.getShardStateManager(); ShardStateManager.SlotStateManager slotStateManager = shardStateManager.getSlotStateManager(shard, Granularity.MIN_5); Assert.assertNotNull(slotStateManager.getSlotStamps()); Assert.assertEquals(UpdateStamp.State.Active, slotStateManager.getSlotStamps().get(slot).getState()); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq.artemis.tests.unit.core.asyncio; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.LinkedList; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicInteger; import org.apache.activemq.artemis.core.io.IOCallback; import org.apache.activemq.artemis.core.io.aio.AIOSequentialFile; import org.apache.activemq.artemis.core.io.aio.AIOSequentialFileFactory; import org.apache.activemq.artemis.nativo.jlibaio.LibaioContext; import org.apache.activemq.artemis.tests.util.ActiveMQTestBase; import org.apache.activemq.artemis.utils.ActiveMQThreadFactory; import org.jboss.logging.Logger; import org.junit.After; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; /** * you need to define -Djava.library.path=${project-root}/native/src/.libs when calling the JVM * If you are running this test in eclipse you should do: * I - Run->Open Run Dialog * II - Find the class on the list (you will find it if you already tried running this testcase before) * III - Add -Djava.library.path=<your project place>/native/src/.libs */ public class MultiThreadAsynchronousFileTest extends AIOTestBase { private static final Logger log = Logger.getLogger(MultiThreadAsynchronousFileTest.class); @BeforeClass public static void hasAIO() { org.junit.Assume.assumeTrue("Test case needs AIO to run", AIOSequentialFileFactory.isSupported()); } AtomicInteger position = new AtomicInteger(0); static final int SIZE = 1024; static final int NUMBER_OF_THREADS = 1; static final int NUMBER_OF_LINES = 1000; ExecutorService executor; ExecutorService pollerExecutor; private static void debug(final String msg) { log.info(msg); } @Override @Before public void setUp() throws Exception { super.setUp(); pollerExecutor = Executors.newCachedThreadPool(new ActiveMQThreadFactory("ActiveMQ-AIO-poller-pool" + System.identityHashCode(this), false, this.getClass().getClassLoader())); executor = Executors.newSingleThreadExecutor(ActiveMQThreadFactory.defaultThreadFactory()); } @Override @After public void tearDown() throws Exception { executor.shutdown(); pollerExecutor.shutdown(); super.tearDown(); } @Test public void testMultipleASynchronousWrites() throws Throwable { executeTest(false); } @Test public void testMultipleSynchronousWrites() throws Throwable { executeTest(true); } private void executeTest(final boolean sync) throws Throwable { MultiThreadAsynchronousFileTest.debug(sync ? "Sync test:" : "Async test"); AIOSequentialFileFactory factory = new AIOSequentialFileFactory(getTestDirfile(), 100); factory.start(); factory.disableBufferReuse(); AIOSequentialFile file = (AIOSequentialFile) factory.createSequentialFile(fileName); file.open(); try { MultiThreadAsynchronousFileTest.debug("Preallocating file"); file.fill(MultiThreadAsynchronousFileTest.NUMBER_OF_THREADS * MultiThreadAsynchronousFileTest.SIZE * MultiThreadAsynchronousFileTest.NUMBER_OF_LINES); MultiThreadAsynchronousFileTest.debug("Done Preallocating file"); CountDownLatch latchStart = new CountDownLatch(MultiThreadAsynchronousFileTest.NUMBER_OF_THREADS + 1); ArrayList<ThreadProducer> list = new ArrayList<>(MultiThreadAsynchronousFileTest.NUMBER_OF_THREADS); for (int i = 0; i < MultiThreadAsynchronousFileTest.NUMBER_OF_THREADS; i++) { ThreadProducer producer = new ThreadProducer("Thread " + i, latchStart, file, sync); list.add(producer); producer.start(); } latchStart.countDown(); ActiveMQTestBase.waitForLatch(latchStart); long startTime = System.currentTimeMillis(); for (ThreadProducer producer : list) { producer.join(); if (producer.failed != null) { throw producer.failed; } } long endTime = System.currentTimeMillis(); MultiThreadAsynchronousFileTest.debug((sync ? "Sync result:" : "Async result:") + " Records/Second = " + MultiThreadAsynchronousFileTest.NUMBER_OF_THREADS * MultiThreadAsynchronousFileTest.NUMBER_OF_LINES * 1000 / (endTime - startTime) + " total time = " + (endTime - startTime) + " total number of records = " + MultiThreadAsynchronousFileTest.NUMBER_OF_THREADS * MultiThreadAsynchronousFileTest.NUMBER_OF_LINES); } finally { file.close(); factory.stop(); } } class ThreadProducer extends Thread { Throwable failed = null; CountDownLatch latchStart; boolean sync; AIOSequentialFile libaio; ThreadProducer(final String name, final CountDownLatch latchStart, final AIOSequentialFile libaio, final boolean sync) { super(name); this.latchStart = latchStart; this.libaio = libaio; this.sync = sync; } @Override public void run() { super.run(); ByteBuffer buffer = null; buffer = LibaioContext.newAlignedBuffer(MultiThreadAsynchronousFileTest.SIZE, 512); try { // I'm always reusing the same buffer, as I don't want any noise from // malloc on the measurement // Encoding buffer MultiThreadAsynchronousFileTest.addString("Thread name=" + Thread.currentThread().getName() + ";" + "\n", buffer); for (int local = buffer.position(); local < buffer.capacity() - 1; local++) { buffer.put((byte) ' '); } buffer.put((byte) '\n'); latchStart.countDown(); waitForLatch(latchStart); CountDownLatch latchFinishThread = null; if (!sync) { latchFinishThread = new CountDownLatch(MultiThreadAsynchronousFileTest.NUMBER_OF_LINES); } LinkedList<CountDownCallback> list = new LinkedList<>(); for (int i = 0; i < MultiThreadAsynchronousFileTest.NUMBER_OF_LINES; i++) { if (sync) { latchFinishThread = new CountDownLatch(1); } CountDownCallback callback = new CountDownCallback(latchFinishThread, null, null, 0); if (!sync) { list.add(callback); } addData(libaio, buffer, callback); if (sync) { waitForLatch(latchFinishThread); assertEquals(0, callback.errorCalled); assertTrue(callback.doneCalled); } } if (!sync) { waitForLatch(latchFinishThread); } for (CountDownCallback callback : list) { assertTrue(callback.doneCalled); assertFalse(callback.errorCalled != 0); } for (CountDownCallback callback : list) { assertTrue(callback.doneCalled); assertFalse(callback.errorCalled != 0); } } catch (Throwable e) { e.printStackTrace(); failed = e; } finally { synchronized (MultiThreadAsynchronousFileTest.class) { LibaioContext.freeBuffer(buffer); } } } } private static void addString(final String str, final ByteBuffer buffer) { byte[] bytes = str.getBytes(); buffer.put(bytes); } private void addData(final AIOSequentialFile aio, final ByteBuffer buffer, final IOCallback callback) throws Exception { aio.writeDirect(buffer, true, callback); } }
/* * Copyright 2015 JBoss Inc * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.drools.compiler.factmodel.traits; import org.drools.compiler.CommonTestMethodBase; import org.drools.core.factmodel.traits.TraitFactory; import org.drools.core.factmodel.traits.VirtualPropertyMode; import org.junit.Test; import org.kie.internal.runtime.StatefulKnowledgeSession; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class TraitMapCoreTest extends CommonTestMethodBase { @Test(timeout=10000) public void testMapCoreManyTraits( ) { String source = "package org.drools.test;\n" + "\n" + "import java.util.*;\n" + "import org.drools.core.factmodel.traits.Traitable;\n" + "" + "global List list;\n " + "\n" + "declare HashMap @Traitable end \n" + "" + "\n" + "global List list; \n" + "\n" + "declare trait PersonMap\n" + "@propertyReactive \n" + " name : String \n" + " age : int \n" + " height : Double \n" + "end\n" + "\n" + "declare trait StudentMap\n" + "@propertyReactive\n" + " ID : String\n" + " GPA : Double = 3.0\n" + "end\n" + "\n" + "rule Don \n" + "no-loop \n" + "when \n" + " $m : Map( this[ \"age\"] == 18 )\n" + "then \n" + " Object obj1 = don( $m, PersonMap.class );\n" + " Object obj2 = don( obj1, StudentMap.class );\n" + " System.out.println( \"done: PersonMap\" );\n" + "\n" + "end\n" + "\n"; StatefulKnowledgeSession ks = loadKnowledgeBaseFromString( source ).newStatefulKnowledgeSession(); TraitFactory.setMode( VirtualPropertyMode.MAP, ks.getKieBase() ); List list = new ArrayList(); ks.setGlobal( "list", list ); Map<String,Object> map = new HashMap<String, Object>( ); map.put( "name", "john" ); map.put( "age", 18 ); ks.insert( map ); ks.fireAllRules(); for ( Object o : ks.getObjects() ) { System.err.println( o ); } assertEquals( 3.0, map.get( "GPA" ) ); } @Test(timeout=10000) public void donMapTest() { String source = "package org.drools.traits.test; \n" + "import java.util.*\n;" + "import org.drools.core.factmodel.traits.Traitable;\n" + "" + "global List list; \n" + "" + "declare HashMap @Traitable end \n" + "" + "declare trait PersonMap" + "@propertyReactive \n" + " name : String \n" + " age : int \n" + " height : Double \n" + "end\n" + "" + "" + "rule Don \n" + "when \n" + " $m : Map( this[ \"age\"] == 18 ) " + "then \n" + " don( $m, PersonMap.class );\n" + "end \n" + "" + "rule Log \n" + "when \n" + " $p : PersonMap( name == \"john\", age > 10 ) \n" + "then \n" + " System.out.println( $p ); \n" + " modify ( $p ) { \n" + " setHeight( 184.0 ); \n" + " }" + " System.out.println( $p ); " + "end \n"; StatefulKnowledgeSession ksession = loadKnowledgeBaseFromString( source ).newStatefulKnowledgeSession(); TraitFactory.setMode( VirtualPropertyMode.MAP, ksession.getKieBase() ); List list = new ArrayList(); ksession.setGlobal( "list", list ); Map map = new HashMap(); map.put( "name", "john" ); map.put( "age", 18 ); ksession.insert( map ); ksession.fireAllRules(); assertTrue( map.containsKey( "height" ) ); assertEquals( map.get( "height"), 184.0 ); } @Test(timeout=10000) public void testMapCore2( ) { String source = "package org.drools.core.factmodel.traits.test;\n" + "\n" + "import java.util.*;\n" + "import org.drools.core.factmodel.traits.Traitable;\n" + "" + "global List list;\n " + "" + "declare HashMap @Traitable end \n" + "\n" + "\n" + "global List list; \n" + "\n" + "declare trait PersonMap\n" + "@propertyReactive \n" + " name : String \n" + " age : int \n" + " height : Double \n" + "end\n" + "\n" + "declare trait StudentMap\n" + "@propertyReactive\n" + " ID : String\n" + " GPA : Double = 3.0\n" + "end\n" + "\n" + "rule Don \n" + "when \n" + " $m : Map( this[ \"age\"] == 18, this[ \"ID\" ] != \"100\" )\n" + "then \n" + " don( $m, PersonMap.class );\n" + " System.out.println( \"done: PersonMap\" );\n" + "\n" + "end\n" + "\n" + "rule Log \n" + "when \n" + " $p : PersonMap( name == \"john\", age > 10 )\n" + "then \n" + " modify ( $p ) { \n" + " setHeight( 184.0 ); \n" + " }\n" + " System.out.println(\"Log: \" + $p );\n" + "end\n" + "" + "" + "rule Don2\n" + "salience -1\n" + "when\n" + " $m : Map( this[ \"age\"] == 18, this[ \"ID\" ] != \"100\" ) " + "then\n" + " don( $m, StudentMap.class );\n" + " System.out.println( \"done2: StudentMap\" );\n" + "end\n" + "" + "" + "rule Log2\n" + "salience -2\n" + "no-loop\n" + "when\n" + " $p : StudentMap( $h : fields[ \"height\" ], GPA >= 3.0 ) " + "then\n" + " modify ( $p ) {\n" + " setGPA( 4.0 ),\n" + " setID( \"100\" );\n" + " }\n" + " System.out.println(\"Log2: \" + $p );\n" + "end\n" + "" + "" + "\n" + "rule Shed1\n" + "salience -5// it seams that the order of shed must be the same as applying don\n" + "when\n" + " $m : PersonMap()\n" + "then\n" + " shed( $m, PersonMap.class );\n" + " System.out.println( \"shed: PersonMap\" );\n" + "end\n" + "\n" + "rule Shed2\n" + "salience -9\n" + "when\n" + " $m : StudentMap()\n" + "then\n" + " shed( $m, StudentMap.class );\n" + " System.out.println( \"shed: StudentMap\" );\n" + "end\n" + "" + "rule Last \n" + "salience -99 \n" + "when \n" + " $m : Map( this not isA StudentMap.class )\n" + "then \n" + " System.out.println( \"Final\" );\n" + " $m.put( \"final\", true );" + "\n" + "end\n" + "\n" + "\n"; StatefulKnowledgeSession ks = loadKnowledgeBaseFromString( source ).newStatefulKnowledgeSession(); TraitFactory.setMode( VirtualPropertyMode.MAP, ks.getKieBase() ); List list = new ArrayList(); ks.setGlobal( "list", list ); Map<String,Object> map = new HashMap<String, Object>( ); map.put( "name", "john" ); map.put( "age", 18 ); ks.insert( map ); ks.fireAllRules(); for ( Object o : ks.getObjects() ) { System.err.println( o ); } assertEquals( "100", map.get( "ID" ) ); assertEquals( 184.0, map.get( "height" ) ); assertEquals( 4.0, map.get( "GPA" ) ); assertEquals( true, map.get( "final" ) ); } @Test(timeout=10000) public void testMapCoreAliasing( ) { String source = "package org.drools.core.factmodel.traits.test;\n" + "\n" + "import java.util.*;\n" + "import org.drools.core.factmodel.traits.*;\n" + "" + "global List list;\n " + "" + "declare HashMap @Traitable() end \n" + "\n" + "global List list; \n" + "\n" + "declare trait PersonMap\n" + "@propertyReactive \n" + " name : String \n" + " age : Integer @Alias( \"years\" ) \n" + " eta : Integer @Alias( \"years\" ) \n" + " height : Double @Alias( \"tall\" ) \n" + " sen : String @Alias(\"years\") \n " + "end\n" + "\n" + "rule Don \n" + "when \n" + " $m : Map()\n" + "then \n" + " don( $m, PersonMap.class );\n" + "\n" + "end\n" + "\n" + "rule Log \n" + "when \n" + " $p : PersonMap( name == \"john\", age > 10 && < 35 )\n" + "then \n" + " modify ( $p ) { \n" + " setHeight( 184.0 ), \n" + " setEta( 42 ); \n" + " }\n" + " System.out.println(\"Log: \" + $p );\n" + "end\n" + "" + "\n"; StatefulKnowledgeSession ks = loadKnowledgeBaseFromString( source ).newStatefulKnowledgeSession(); TraitFactory.setMode( VirtualPropertyMode.MAP, ks.getKieBase() ); List list = new ArrayList(); ks.setGlobal( "list", list ); Map<String,Object> map = new HashMap<String, Object>( ); map.put( "name", "john" ); map.put( "years", new Integer( 18 ) ); ks.insert( map ); ks.fireAllRules(); for ( Object o : ks.getObjects() ) { System.err.println( o ); } assertEquals( 42, map.get( "years" ) ); assertEquals( 184.0, map.get( "tall" ) ); } @Test(timeout=10000) public void testMapCoreAliasingLogicalTrueWithTypeClash( ) { String source = "package org.drools.core.factmodel.traits.test;\n" + "\n" + "import java.util.*;\n" + "import org.drools.core.factmodel.traits.*;\n" + "" + "global List list;\n " + "" + "declare HashMap @Traitable( logical = true ) end \n" + "\n" + "global List list; \n" + "\n" + "declare trait PersonMap\n" + "@propertyReactive \n" + " name : String \n" + " age : Integer @Alias( \"years\" ) \n" + " eta : Integer @Alias( \"years\" ) \n" + " height : Double @Alias( \"tall\" ) \n" + " sen : String @Alias(\"years\") \n " + "end\n" + "\n" + "rule Don \n" + "when \n" + " $m : Map()\n" + "then \n" + // will fail due to the alias "sen", typed String and incompatible with Int " PersonMap pm = don( $m, PersonMap.class ); \n" + " list.add ( pm ); \n" + "\n" + "end\n" + "\n" + "" + "\n"; StatefulKnowledgeSession ks = loadKnowledgeBaseFromString( source ).newStatefulKnowledgeSession(); TraitFactory.setMode( VirtualPropertyMode.MAP, ks.getKieBase() ); List list = new ArrayList(); ks.setGlobal( "list", list ); Map<String,Object> map = new HashMap<String, Object>( ); map.put( "name", "john" ); map.put( "years", new Integer( 18 ) ); ks.insert( map ); ks.fireAllRules(); assertTrue( list.size() == 1 && list.get( 0 ) == null ); } @Test public void testDrools216(){ String drl = "" + "\n" + "\n" + "package org.drools.core.factmodel.traits.test;\n" + "\n" + "import java.util.*;\n" + "import org.drools.core.factmodel.traits.Alias\n" + "\n" + "global java.util.List list;\n" + "\n" + "declare HashMap @Traitable(logical=true) end \n" + "\n" + "declare trait Citizen\n" + "@traitable\n" + " citizenship : String = \"Unknown\"\n" + "end\n" + "\n" + "declare trait Student extends Citizen\n" + "@propertyReactive\n" + " ID : String = \"412314\" @Alias(\"personID\")\n" + " GPA : Double = 3.99\n" + "end\n" + "\n" + "declare Person\n" + "@Traitable\n" + " personID : String\n" + " isStudent : boolean\n" + "end\n" + "\n" + "declare trait Worker\n" + "@propertyReactive\n" + " hasBenefits : Boolean = true\n" + "end\n" + "\n" + "\n" + "rule \"1\"\n" + "salience 1\n" + "no-loop\n" + "when\n" + "then\n" + " Person p = new Person(\"1020\",true);\n" + " Map map = new HashMap();\n" + " map.put(\"isEmpty\",true);\n" + " insert(p);\n" + " insert(map);\n" + " list.add(\"initialized\");\n" + "end\n" + "\n" + "rule \"2\"\n" + "salience 1\n" + "no-loop\n" + "when\n" + " $stu : Person(isStudent == true)\n" + " $map : Map(this[\"isEmpty\"] == true)\n" + "then\n" + " Student s = don( $stu , Student.class );\n" + " $map.put(\"worker\" , s);\n" + " $map.put(\"isEmpty\" , false);\n" + " update($map);\n" + " System.out.println(\"don: Person -> Student \");\n" + " list.add(\"student is donned\");\n" + "end\n" + "\n" + "rule \"3\"\n" + "salience 1\n" + "no-loop\n" + "when\n" + " $map : Map($stu : this[\"worker\"] isA Student.class)\n" + "then\n" + " Object obj = don( $map , Worker.class );\n" + " System.out.println(\"don: Map -> Worker : \"+obj);\n" + " list.add(\"worker is donned\");\n" + "end\n"; StatefulKnowledgeSession ksession = loadKnowledgeBaseFromString(drl).newStatefulKnowledgeSession(); TraitFactory.setMode(VirtualPropertyMode.MAP, ksession.getKieBase()); List list = new ArrayList(); ksession.setGlobal( "list", list ); ksession.fireAllRules(); assertTrue(list.contains("initialized")); assertTrue(list.contains("student is donned")); assertTrue(list.contains("worker is donned")); } @Test public void testDrools217(){ String drl = "" + "\n" + "package org.drools.core.factmodel.traits.test;\n" + "\n" + "import java.util.*;\n" + "import org.drools.core.factmodel.traits.Alias\n" + "\n" + "global java.util.List list;\n" + "" + "declare HashMap @Traitable(logical=true) end \n" + "\n" + "declare trait Citizen\n" + "@traitable\n" + " citizenship : String = \"Unknown\"\n" + "end\n" + "\n" + "declare trait Student extends Citizen\n" + "@propertyReactive\n" + " ID : String = \"412314\" @Alias(\"personID\")\n" + " GPA : Double = 3.99\n" + "end\n" + "\n" + "declare Person\n" + "@Traitable\n" + " personID : String\n" + " isStudent : boolean\n" + "end\n" + "\n" + "declare trait Worker\n" + "@propertyReactive\n" + " hasBenefits : Boolean = true\n" + "end\n" + "\n" + "\n" + "rule \"1\"\n" + "salience 1\n" + "no-loop\n" + "when\n" + "then\n" + " Person p = new Person(\"1020\",true);\n" + " Map map = new HashMap();\n" + " map.put(\"isEmpty\",true);\n" + " insert(p);\n" + " insert(map);\n" + " list.add(\"initialized\");\n" + "end\n" + "\n" + "rule \"2\"\n" + "salience 1\n" + "no-loop\n" + "when\n" + " $stu : Person(isStudent == true)\n" + " $map : Map(this[\"isEmpty\"] == true)\n" + "then\n" + " Student s = don( $stu , Student.class );\n" + " $map.put(\"worker\" , s);\n" + " $map.put(\"isEmpty\" , false);\n" + " update($map);\n" + " System.out.println(\"don: Person -> Student \");\n" + " list.add(\"student is donned\");\n" + "end\n" + "\n" + "rule \"3\"\n" + "salience 1\n" + "no-loop\n" + "when\n" + " $map : Map($stu : this[\"worker\"], $stu isA Student.class)\n" + "then\n" + " Object obj = don( $map , Worker.class );\n" + " System.out.println(\"don: Map -> Worker : \"+obj);\n" + " list.add(\"worker is donned\");\n" + "end\n"; StatefulKnowledgeSession ksession = loadKnowledgeBaseFromString(drl).newStatefulKnowledgeSession(); TraitFactory.setMode(VirtualPropertyMode.MAP, ksession.getKieBase()); List list = new ArrayList(); ksession.setGlobal("list", list); ksession.fireAllRules(); assertTrue(list.contains("initialized")); assertTrue(list.contains("student is donned")); assertTrue(list.contains("worker is donned")); } @Test public void testDrools218(){ String drl = "" + "\n" + "package org.drools.core.factmodel.traits.test;\n" + "\n" + "import java.util.*;\n" + "import org.drools.core.factmodel.traits.Alias\n" + "\n" + "global java.util.List list;\n" + "\n" + "declare trait Citizen\n" + "@traitable\n" + " citizenship : String = \"Unknown\"\n" + "end\n" + "\n" + "declare HashMap @Traitable(logical=true) end \n" + "" + "" + "declare trait Student extends Citizen\n" + "@propertyReactive\n" + " ID : String = \"412314\" @Alias(\"personID\")\n" + " GPA : Double = 3.99\n" + "end\n" + "\n" + "declare Person\n" + "@Traitable\n" + " personID : String\n" + " isStudent : boolean\n" + "end\n" + "\n" + "declare trait Worker\n" + "@propertyReactive\n" + " //customer : Citizen\n" + " hasBenefits : Boolean = true\n" + "end\n" + "\n" + "declare trait StudentWorker extends Worker\n" + "@propertyReactive\n" + " //currentStudent : Citizen @Alias(\"customer\")\n" + " tuitionWaiver : Boolean @Alias(\"hasBenefits\")\n" + "end\n" + "\n" + "rule \"1\"\n" + "salience 1\n" + "no-loop\n" + "when\n" + "then\n" + " Person p = new Person(\"1020\",true);\n" + " Map map = new HashMap();\n" + " map.put(\"isEmpty\",true);\n" + " insert(p);\n" + " insert(map);\n" + " list.add(\"initialized\");\n" + "end\n" + "\n" + "rule \"2\"\n" + "salience 1\n" + "no-loop\n" + "when\n" + " $stu : Person(isStudent == true)\n" + " $map : Map(this[\"isEmpty\"] == true)\n" + "then\n" + " Student s = don( $stu , Student.class );\n" + " $map.put(\"worker\" , s);\n" + " $map.put(\"isEmpty\" , false);\n" + " $map.put(\"hasBenefits\",null);\n" + " update($map);\n" + " System.out.println(\"don: Person -> Student \");\n" + " list.add(\"student is donned\");\n" + "end\n" + "\n" + "rule \"3\"\n" + "salience 1\n" + "no-loop\n" + "when\n" + " $map : Map($stu : this[\"worker\"])\n" + " Map($stu isA Student.class, this == $map)\n" + "then\n" + " Object obj = don( $map , Worker.class );\n" + " System.out.println(\"don: Map -> Worker : \"+obj);\n" + " list.add(\"worker is donned\");\n" + "end\n" + "\n" + "rule \"4\"\n" + "salience 1\n" + "no-loop\n" + "when\n" + " $stu : Student()\n" + "then\n" + " Object obj = don( $stu , StudentWorker.class );\n" + " System.out.println(\"don: Map -> StudentWorker : \"+obj);\n" + " list.add(\"studentworker is donned\");\n" + "end\n" + "\n" + "rule \"5\"\n" + "salience 1\n" + "no-loop\n" + "when\n" + " StudentWorker(tuitionWaiver == true)\n" + "then\n" + " System.out.println(\"tuitionWaiver == true\");\n" + " list.add(\"tuitionWaiver is true\");\n" + "end\n" + "\n"; StatefulKnowledgeSession ksession = loadKnowledgeBaseFromString(drl).newStatefulKnowledgeSession(); TraitFactory.setMode(VirtualPropertyMode.MAP, ksession.getKieBase()); List list = new ArrayList(); ksession.setGlobal( "list", list ); ksession.fireAllRules(); assertTrue(list.contains("initialized")); assertTrue(list.contains("student is donned")); assertTrue(list.contains("worker is donned")); assertTrue(list.contains("studentworker is donned")); assertTrue(list.contains("tuitionWaiver is true")); } @Test public void testDrools219(){ String drl = "" + "\n" + "\n" + "package org.drools.core.factmodel.traits.test;\n" + "\n" + "import java.util.*;\n" + "import org.drools.core.factmodel.traits.Alias\n" + "\n" + "global java.util.List list;\n" + "\n" + "\n" + "declare trait Citizen\n" + " citizenship : String = \"Unknown\"\n" + " socialSecurity : String = \"0\"\n" + "end\n" + "\n" + "declare trait Student extends Citizen\n" + "@propertyReactive\n" + " ID : String = \"412314\" @Alias(\"personID\") \n" + " GPA : Double = 3.99\n" + " SSN : String = \"888111155555\" @Alias(\"socialSecurity\")\n" + "end\n" + "\n" + "declare Person\n" + "@Traitable(logical=true)\n" + " personID : String\n" + " isStudent : boolean\n" + "end\n" + "\n" + "rule \"1\"\n" + "salience 1\n" + "no-loop\n" + "when\n" + "then\n" + " Person p = new Person( null, true );\n" + " insert(p);\n" + " list.add(\"initialized\");\n" + "end\n" + "\n" + "rule \"2\"\n" + "salience 1\n" + "no-loop\n" + "when\n" + " $stu : Person(isStudent == true)\n" + "then\n" + " Student s = don( $stu , Student.class );\n" + " System.out.println(\"don: Person -> Student \" + s);\n" + " list.add(\"student is donned\");\n" + "end\n" + "\n" + "rule \"3\"\n" + "salience 1\n" + "no-loop\n" + "when\n" + " $stu : Student(ID == \"412314\", SSN == \"888111155555\")\n" + "then\n" + " list.add(\"student has ID and SSN\");\n" + "end\n" + "\n" + "rule \"4\"\n" + "salience 1\n" + "no-loop\n" + "when\n" + " Student(fields[\"personID\"] == \"412314\", fields[\"socialSecurity\"] == \"888111155555\")\n" + "then\n" + " list.add(\"student has personID and socialSecurity\");\n" + "end\n" + "\n" + "rule \"5\"\n" + "salience 1\n" + "no-loop\n" + "when\n" + " $ctz : Citizen(socialSecurity == \"888111155555\")\n" + "then\n" + " list.add(\"citizen has socialSecurity\");\n" + "end\n" + "\n" + "rule \"6\"\n" + "salience 1\n" + "no-loop\n" + "when\n" + " $p : Person(personID == \"412314\")\n" + "then\n" + " list.add(\"person has personID\");\n" + "end\n"; StatefulKnowledgeSession ksession = loadKnowledgeBaseFromString(drl).newStatefulKnowledgeSession(); TraitFactory.setMode(VirtualPropertyMode.MAP, ksession.getKieBase()); List list = new ArrayList(); ksession.setGlobal( "list", list ); ksession.fireAllRules(); assertTrue(list.contains("initialized")); assertTrue(list.contains("student is donned")); assertTrue(list.contains("student has ID and SSN")); assertTrue(list.contains("student has personID and socialSecurity")); assertTrue(list.contains("citizen has socialSecurity")); assertTrue(list.contains("person has personID")); } @Test public void testMapTraitsMismatchTypes() { String drl = "" + "package org.drools.core.factmodel.traits;\n" + "\n" + "import org.drools.core.factmodel.traits.Traitable;\n" + "import org.drools.core.factmodel.traits.Trait;\n" + "import org.drools.core.factmodel.traits.Alias;\n" + "import java.util.*;\n" + "\n" + "global java.util.List list;\n" + "\n" + "declare org.drools.factmodel.MapCore\n" + "@Traitable( logical = true )\n" + "end\n" + "" + "declare HashMap @Traitable( logical = true ) end \n" + "\n" + "\n" + "declare trait ParentTrait\n" + "@propertyReactive\n" + " name : String\n" + " id : int\n" + "end\n" + "\n" + "declare trait ChildTrait\n" + "@propertyReactive\n" + " naam : String\n" + " id : float \n" + "end\n" + "\n" + "rule \"don1\"\n" + "no-loop\n" + "when\n" + " $map : Map()\n" + "then\n" + // fails since current value for id is float, incompatible with int " ParentTrait pt = don( $map , ParentTrait.class );\n" + // success " ChildTrait ct = don( $map , ChildTrait.class );\n" + "" + " System.out.println( $map ); \n" + " list.add( pt );\n" + " list.add( ct );\n" + "end"; StatefulKnowledgeSession ksession = loadKnowledgeBaseFromString(drl).newStatefulKnowledgeSession(); TraitFactory.setMode(VirtualPropertyMode.MAP, ksession.getKieBase()); List list = new ArrayList(); ksession.setGlobal("list",list); Map<String,Object> map = new HashMap<String, Object>(); map.put( "name","hulu" ); map.put( "id", 3.4f ); ksession.insert( map ); ksession.fireAllRules(); assertEquals( 2, list.size() ); assertNull( list.get( 0 ) ); assertNotNull( list.get( 1 ) ); } @Test public void testMapTraitNoType() { String drl = "" + "package openehr.test;//org.drools.core.factmodel.traits;\n" + "\n" + "import org.drools.core.factmodel.traits.Traitable;\n" + "import org.drools.core.factmodel.traits.Trait;\n" + "import org.drools.core.factmodel.traits.Alias;\n" + "import java.util.*;\n" + "\n" + "global java.util.List list;\n" + "\n" + "declare HashMap @Traitable end \n" + "\n" + "declare trait ChildTrait\n" + "@propertyReactive\n" + " naam : String = \"kudak\"\n" + " id : int = 1020\n" + "end\n" + "\n" + "rule \"don\"\n" + "no-loop\n" + "when\n" + " $map : Map()" + //map is empty "then\n" + " don( $map , ChildTrait.class );\n" + " list.add(\"correct1\");\n" + "end\n" + "\n" + "rule \"check\"\n" + "no-loop\n" + "when\n" + " $c : ChildTrait($n : naam == \"kudak\", id == 1020 )\n" + " $p : Map( this[\"naam\"] == $n )\n" + "then\n" + " System.out.println($p);\n" + " System.out.println($c);\n" + " list.add(\"correct2\");\n" + "end"; StatefulKnowledgeSession ksession = loadKnowledgeBaseFromString(drl).newStatefulKnowledgeSession(); TraitFactory.setMode(VirtualPropertyMode.MAP, ksession.getKieBase()); List list = new ArrayList(); ksession.setGlobal("list",list); Map<String,Object> map = new HashMap<String, Object>(); // map.put("name", "hulu"); ksession.insert(map); ksession.fireAllRules(); assertTrue(list.contains("correct1")); assertTrue(list.contains("correct2")); } @Test(timeout=10000) public void testMapTraitMismatchTypes() { String drl = "" + "package openehr.test;//org.drools.core.factmodel.traits;\n" + "\n" + "import org.drools.core.factmodel.traits.Traitable;\n" + "import org.drools.core.factmodel.traits.Trait;\n" + "import org.drools.core.factmodel.traits.Alias;\n" + "import java.util.*;\n" + "\n" + "global java.util.List list;\n" + "\n" + "" + "declare HashMap @Traitable( logical = true ) end \n" + "\n" + "\n" + "declare trait ChildTrait\n" + "@Trait( logical = true )" + "@propertyReactive\n" + " naam : String = \"kudak\"\n" + " id : int = 1020\n" + "end\n" + "\n" + "rule \"don\"\n" + "no-loop\n" + "when\n" + " $map : Map()" + "then\n" + // fails because current name is Int, while ChildTrait tries to enforce String " ChildTrait ct = don( $map , ChildTrait.class );\n" + " list.add( ct );\n" + "end\n" + "\n" + ""; StatefulKnowledgeSession ksession = loadKnowledgeBaseFromString(drl).newStatefulKnowledgeSession(); TraitFactory.setMode( VirtualPropertyMode.MAP, ksession.getKieBase()); List list = new ArrayList(); ksession.setGlobal("list",list); Map<String,Object> map = new HashMap<String, Object>(); map.put("naam", new Integer(12) ); ksession.insert(map); ksession.fireAllRules(); assertEquals( 1, list.size() ); assertEquals( null, list.get( 0 ) ); } @Test public void testMapTraitPossibilities1() { String drl = "" + "package openehr.test;//org.drools.core.factmodel.traits;\n" + "\n" + "import org.drools.core.factmodel.traits.Traitable;\n" + "import org.drools.core.factmodel.traits.Trait;\n" + "import org.drools.core.factmodel.traits.Alias;\n" + "import java.util.*;\n" + "\n" + "global java.util.List list;\n" + "\n" + "" + "declare HashMap @Traitable( logical = true ) end \n" + "\n" + "declare ESM @Traitable( logical = true )\n" + " val : String\n" + "end\n" + "\n" + "declare trait TName\n" + "//@Trait( logical = true )\n" + " length : Integer\n" + "end\n" + "\n" + "declare trait ChildTrait\n" + "//@Trait( logical = true )\n" + "@propertyReactive\n" + " name : ESM\n" + " id : int = 1002\n" + "end\n" + "\n" + "rule \"init\"\n" + "no-loop\n" + "when\n" + "then\n" + " Map map = new HashMap();\n" + " ESM esm = new ESM(\"ali\");\n" + " TName tname = don( esm , TName.class );\n" + " map.put(\"name\",tname);\n" + " insert(map);\n" + "end\n" + "\n" + "\n" + "rule \"don\"\n" + "no-loop\n" + "when\n" + " $map : Map()" + "then\n" + " ChildTrait ct = don( $map , ChildTrait.class );\n" + " list.add( ct );\n" + " System.out.println(ct);\n" + "end\n" + "\n" + ""; StatefulKnowledgeSession ksession = loadKnowledgeBaseFromString(drl).newStatefulKnowledgeSession(); TraitFactory.setMode(VirtualPropertyMode.MAP, ksession.getKieBase()); List list = new ArrayList(); ksession.setGlobal("list",list); ksession.fireAllRules(); assertEquals( 1, list.size() ); assertNotNull(list.get(0)); } @Test public void testMapTraitPossibilities2() { String drl = "" + "package openehr.test;//org.drools.core.factmodel.traits;\n" + "\n" + "import org.drools.core.factmodel.traits.Traitable;\n" + "import org.drools.core.factmodel.traits.Trait;\n" + "import org.drools.core.factmodel.traits.Alias;\n" + "import java.util.*;\n" + "\n" + "global java.util.List list;\n" + "\n" + "" + "declare HashMap @Traitable( logical = true ) end \n" + "\n" + "declare ESM @Traitable( logical = true )\n" + " val : String\n" + "end\n" + "\n" + "declare trait TName\n" + "//@Trait( logical = true )\n" + " length : Integer\n" + "end\n" + "\n" + "declare trait TEsm extends TName\n" + "//@Trait( logical = true )\n" + " isValid : boolean\n" + "end\n" + "\n" + "declare trait ChildTrait\n" + "//@Trait( logical = true )\n" + "@propertyReactive\n" + " name : ESM\n" + " id : int = 1002\n" + "end\n" + "\n" + "rule \"init\"\n" + "no-loop\n" + "when\n" + "then\n" + " Map map = new HashMap();\n" + " ESM esm = new ESM(\"ali\");\n" + " TName tname = don( esm , TName.class );\n" + " TEsm tesm = don( esm , TEsm.class );\n" + " map.put(\"name\",tesm);\n" + " insert(map);\n" + "end\n" + "\n" + "\n" + "rule \"don\"\n" + "no-loop\n" + "when\n" + " $map : Map()" + "then\n" + " ChildTrait ct = don( $map , ChildTrait.class );\n" + " list.add( ct );\n" + " System.out.println(ct);\n" + "end\n" + "\n" + ""; StatefulKnowledgeSession ksession = loadKnowledgeBaseFromString(drl).newStatefulKnowledgeSession(); TraitFactory.setMode(VirtualPropertyMode.MAP, ksession.getKieBase()); List list = new ArrayList(); ksession.setGlobal("list",list); ksession.fireAllRules(); assertEquals( 1, list.size() ); assertNotNull(list.get(0)); } @Test public void testMapTraitPossibilities3() { String drl = "" + "package openehr.test;//org.drools.core.factmodel.traits;\n" + "\n" + "import org.drools.core.factmodel.traits.Traitable;\n" + "import org.drools.core.factmodel.traits.Trait;\n" + "import org.drools.core.factmodel.traits.Alias;\n" + "import java.util.*;\n" + "\n" + "global java.util.List list;\n" + "\n" + "" + "declare HashMap @Traitable( logical = true ) end \n" + "\n" + "declare ESM @Traitable( logical = true )\n" + " val : String\n" + "end\n" + "\n" + "declare trait TName\n" + "//@Trait( logical = true )\n" + " length : Integer\n" + "end\n" + "\n" + "declare trait TEsm extends TName\n" + "//@Trait( logical = true )\n" + " isValid : boolean\n" + "end\n" + "\n" + "declare trait ChildTrait\n" + "//@Trait( logical = true )\n" + "@propertyReactive\n" + " name : TName\n" + //<<<<< " id : int = 1002\n" + "end\n" + "\n" + "rule \"init\"\n" + "no-loop\n" + "when\n" + "then\n" + " Map map = new HashMap();\n" + " ESM esm = new ESM(\"ali\");\n" + " TName tname = don( esm , TName.class );\n" + " TEsm tesm = don( esm , TEsm.class );\n" + " map.put(\"name\",tesm);\n" + " insert(map);\n" + "end\n" + "\n" + "\n" + "rule \"don\"\n" + "no-loop\n" + "when\n" + " $map : Map()" + "then\n" + " ChildTrait ct = don( $map , ChildTrait.class );\n" + " list.add( ct );\n" + " System.out.println(ct);\n" + "end\n" + "\n" + ""; StatefulKnowledgeSession ksession = loadKnowledgeBaseFromString(drl).newStatefulKnowledgeSession(); TraitFactory.setMode(VirtualPropertyMode.MAP, ksession.getKieBase()); List list = new ArrayList(); ksession.setGlobal("list",list); ksession.fireAllRules(); assertEquals( 1, list.size() ); assertNotNull(list.get(0)); } @Test public void testMapTraitPossibilities4() { String drl = "" + "package openehr.test;//org.drools.core.factmodel.traits;\n" + "\n" + "import org.drools.core.factmodel.traits.Traitable;\n" + "import org.drools.core.factmodel.traits.Trait;\n" + "import org.drools.core.factmodel.traits.Alias;\n" + "import java.util.*;\n" + "\n" + "global java.util.List list;\n" + "\n" + "" + "declare HashMap @Traitable( logical = true ) end \n" + "\n" + "declare ESM @Traitable( logical = true )\n" + " val : String\n" + "end\n" + "\n" + "declare NAAM @Traitable( logical = true )\n" + //<<<<< " val : String\n" + "end\n" + "\n" + "declare trait TName\n" + "@Trait( logical = true )\n" + //<<<<< " length : Integer\n" + "end\n" + "\n" + "declare trait TEsm //extends TName\n" + "//@Trait( logical = true )\n" + " isValid : boolean\n" + "end\n" + "\n" + "declare trait ChildTrait\n" + "//@Trait( logical = true )\n" + "@propertyReactive\n" + " name : TName\n" + " id : int = 1002\n" + "end\n" + "\n" + "rule \"init\"\n" + "no-loop\n" + "when\n" + "then\n" + " Map map = new HashMap();\n" + " ESM esm = new ESM(\"ali\");\n" + " TEsm tesm = don( esm , TEsm.class );\n" + " map.put(\"name\",tesm);\n" + " insert(map);\n" + "end\n" + "\n" + "\n" + "rule \"don\"\n" + "no-loop\n" + "when\n" + " $map : Map()" + "then\n" + " ChildTrait ct = don( $map , ChildTrait.class );\n" + " list.add( ct );\n" + " System.out.println(ct);\n" + "end\n" + "\n" + ""; StatefulKnowledgeSession ksession = loadKnowledgeBaseFromString(drl).newStatefulKnowledgeSession(); TraitFactory.setMode( VirtualPropertyMode.MAP, ksession.getKieBase()); List list = new ArrayList(); ksession.setGlobal("list",list); ksession.fireAllRules(); assertEquals( 1, list.size() ); assertNotNull(list.get(0)); } }
/* * Copyright 2021 Hazelcast Inc. * * Licensed under the Hazelcast Community License (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://hazelcast.com/hazelcast-community-license * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.hazelcast.jet.sql.impl.connector.keyvalue; import com.hazelcast.internal.serialization.Data; import com.hazelcast.nio.ObjectDataInput; import com.hazelcast.nio.ObjectDataOutput; import com.hazelcast.nio.serialization.DataSerializable; import com.hazelcast.query.impl.getters.Extractors; import com.hazelcast.sql.impl.expression.ConstantExpression; import com.hazelcast.sql.impl.expression.Expression; import com.hazelcast.sql.impl.expression.ExpressionEvalContext; import com.hazelcast.sql.impl.extract.QueryExtractor; import com.hazelcast.sql.impl.extract.QueryPath; import com.hazelcast.sql.impl.extract.QueryTarget; import com.hazelcast.sql.impl.extract.QueryTargetDescriptor; import com.hazelcast.sql.impl.row.Row; import com.hazelcast.sql.impl.type.QueryDataType; import java.io.IOException; import java.util.List; import static com.hazelcast.internal.util.Preconditions.checkTrue; import static com.hazelcast.jet.sql.impl.ExpressionUtil.evaluate; /** * A utility to convert a key-value entry to a row represented as * {@code Object[]}. As a convenience, it also contains a * {@link #predicate} - it is applied before projecting. * <p> * {@link KvProjector} does the reverse. */ public class KvRowProjector implements Row { private final QueryTarget keyTarget; private final QueryTarget valueTarget; private final QueryExtractor[] extractors; private final Expression<Boolean> predicate; private final List<Expression<?>> projections; private final ExpressionEvalContext evalContext; @SuppressWarnings("unchecked") KvRowProjector( QueryPath[] paths, QueryDataType[] types, QueryTarget keyTarget, QueryTarget valueTarget, Expression<Boolean> predicate, List<Expression<?>> projections, ExpressionEvalContext evalContext ) { checkTrue(paths.length == types.length, "paths.length != types.length"); this.keyTarget = keyTarget; this.valueTarget = valueTarget; this.extractors = createExtractors(paths, types, keyTarget, valueTarget); this.predicate = predicate != null ? predicate : (Expression<Boolean>) ConstantExpression.create(true, QueryDataType.BOOLEAN); this.projections = projections; this.evalContext = evalContext; } private static QueryExtractor[] createExtractors( QueryPath[] paths, QueryDataType[] types, QueryTarget keyTarget, QueryTarget valueTarget ) { QueryExtractor[] extractors = new QueryExtractor[paths.length]; for (int i = 0; i < paths.length; i++) { QueryPath path = paths[i]; QueryDataType type = types[i]; extractors[i] = path.isKey() ? keyTarget.createExtractor(path.getPath(), type) : valueTarget.createExtractor(path.getPath(), type); } return extractors; } public Object[] project(Object key, Object value) { return project(key, null, value, null); } public Object[] project(Data key, Data value) { return project(null, key, null, value); } private Object[] project(Object key, Data keyData, Object value, Data valueData) { keyTarget.setTarget(key, keyData); valueTarget.setTarget(value, valueData); if (!Boolean.TRUE.equals(evaluate(predicate, this, evalContext))) { return null; } Object[] row = new Object[projections.size()]; for (int i = 0; i < projections.size(); i++) { row[i] = evaluate(projections.get(i), this, evalContext); } return row; } @Override @SuppressWarnings("unchecked") public <T> T get(int index) { return (T) extractors[index].get(); } @Override public int getColumnCount() { return projections.size(); } public static Supplier supplier( QueryPath[] paths, QueryDataType[] types, QueryTargetDescriptor keyDescriptor, QueryTargetDescriptor valueDescriptor, Expression<Boolean> predicate, List<Expression<?>> projections ) { return new Supplier(paths, types, keyDescriptor, valueDescriptor, predicate, projections); } public static class Supplier implements DataSerializable { private QueryPath[] paths; private QueryDataType[] types; private QueryTargetDescriptor keyDescriptor; private QueryTargetDescriptor valueDescriptor; private Expression<Boolean> predicate; private List<Expression<?>> projections; @SuppressWarnings("unused") private Supplier() { } Supplier( QueryPath[] paths, QueryDataType[] types, QueryTargetDescriptor keyDescriptor, QueryTargetDescriptor valueDescriptor, Expression<Boolean> predicate, List<Expression<?>> projections ) { this.paths = paths; this.types = types; this.keyDescriptor = keyDescriptor; this.valueDescriptor = valueDescriptor; this.predicate = predicate; this.projections = projections; } public int columnCount() { return paths.length; } public QueryPath[] paths() { return paths; } public KvRowProjector get(ExpressionEvalContext evalContext, Extractors extractors) { return new KvRowProjector( paths, types, keyDescriptor.create(evalContext.getSerializationService(), extractors, true), valueDescriptor.create(evalContext.getSerializationService(), extractors, false), predicate, projections, evalContext ); } @Override public void writeData(ObjectDataOutput out) throws IOException { out.writeInt(paths.length); for (QueryPath path : paths) { out.writeObject(path); } out.writeInt(types.length); for (QueryDataType type : types) { out.writeObject(type); } out.writeObject(keyDescriptor); out.writeObject(valueDescriptor); out.writeObject(predicate); out.writeObject(projections); } @Override public void readData(ObjectDataInput in) throws IOException { paths = new QueryPath[in.readInt()]; for (int i = 0; i < paths.length; i++) { paths[i] = in.readObject(); } types = new QueryDataType[in.readInt()]; for (int i = 0; i < types.length; i++) { types[i] = in.readObject(); } keyDescriptor = in.readObject(); valueDescriptor = in.readObject(); predicate = in.readObject(); projections = in.readObject(); } } }
/* * Copyright 2013-2015 the original author or authors. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.okwallet.offline; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.InputStream; import javax.annotation.Nullable; import org.bitcoin.protocols.payments.Protos; import org.bitcoin.protocols.payments.Protos.Payment; import org.bitcoinj.protocols.payments.PaymentProtocol; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.squareup.okhttp.CacheControl; import com.squareup.okhttp.Call; import com.squareup.okhttp.MediaType; import com.squareup.okhttp.Request; import com.squareup.okhttp.RequestBody; import com.squareup.okhttp.Response; import com.okwallet.Constants; import com.okwallet.util.Bluetooth; import com.okwallet_test.R; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothSocket; import android.os.Handler; import android.os.Looper; import okio.BufferedSink; /** * @author Andreas Schildbach */ public abstract class DirectPaymentTask { private final Handler backgroundHandler; private final Handler callbackHandler; private final ResultCallback resultCallback; private static final Logger log = LoggerFactory.getLogger(DirectPaymentTask.class); public interface ResultCallback { void onResult(boolean ack); void onFail(int messageResId, Object... messageArgs); } public DirectPaymentTask(final Handler backgroundHandler, final ResultCallback resultCallback) { this.backgroundHandler = backgroundHandler; this.callbackHandler = new Handler(Looper.myLooper()); this.resultCallback = resultCallback; } public final static class HttpPaymentTask extends DirectPaymentTask { private final String url; @Nullable private final String userAgent; public HttpPaymentTask(final Handler backgroundHandler, final ResultCallback resultCallback, final String url, @Nullable final String userAgent) { super(backgroundHandler, resultCallback); this.url = url; this.userAgent = userAgent; } @Override public void send(final Payment payment) { super.backgroundHandler.post(new Runnable() { @Override public void run() { log.info("trying to send tx to {}", url); final Request.Builder request = new Request.Builder(); request.url(url); request.cacheControl(new CacheControl.Builder().noCache().build()); request.header("Accept", PaymentProtocol.MIMETYPE_PAYMENTACK); if (userAgent != null) request.header("User-Agent", userAgent); request.post(new RequestBody() { @Override public MediaType contentType() { return MediaType.parse(PaymentProtocol.MIMETYPE_PAYMENT); } @Override public long contentLength() throws IOException { return payment.getSerializedSize(); } @Override public void writeTo(final BufferedSink sink) throws IOException { payment.writeTo(sink.outputStream()); } }); final Call call = Constants.HTTP_CLIENT.newCall(request.build()); try { final Response response = call.execute(); if (response.isSuccessful()) { log.info("tx sent via http"); final InputStream is = response.body().byteStream(); final Protos.PaymentACK paymentAck = Protos.PaymentACK.parseFrom(is); is.close(); final boolean ack = !"nack".equals(PaymentProtocol.parsePaymentAck(paymentAck).getMemo()); log.info("received {} via http", ack ? "ack" : "nack"); onResult(ack); } else { final int responseCode = response.code(); final String responseMessage = response.message(); log.info("got http error {}: {}", responseCode, responseMessage); onFail(R.string.error_http, responseCode, responseMessage); } } catch (final IOException x) { log.info("problem sending", x); onFail(R.string.error_io, x.getMessage()); } } }); } } public final static class BluetoothPaymentTask extends DirectPaymentTask { private final BluetoothAdapter bluetoothAdapter; private final String bluetoothMac; public BluetoothPaymentTask(final Handler backgroundHandler, final ResultCallback resultCallback, final BluetoothAdapter bluetoothAdapter, final String bluetoothMac) { super(backgroundHandler, resultCallback); this.bluetoothAdapter = bluetoothAdapter; this.bluetoothMac = bluetoothMac; } @Override public void send(final Payment payment) { super.backgroundHandler.post(new Runnable() { @Override public void run() { log.info("trying to send tx via bluetooth {}", bluetoothMac); if (payment.getTransactionsCount() != 1) throw new IllegalArgumentException("wrong transactions count"); final BluetoothDevice device = bluetoothAdapter .getRemoteDevice(Bluetooth.decompressMac(bluetoothMac)); BluetoothSocket socket = null; DataOutputStream os = null; DataInputStream is = null; try { socket = device .createInsecureRfcommSocketToServiceRecord(Bluetooth.BIP70_PAYMENT_PROTOCOL_UUID); socket.connect(); log.info("connected to payment protocol {}", bluetoothMac); is = new DataInputStream(socket.getInputStream()); os = new DataOutputStream(socket.getOutputStream()); payment.writeDelimitedTo(os); os.flush(); log.info("tx sent via bluetooth"); final Protos.PaymentACK paymentAck = Protos.PaymentACK.parseDelimitedFrom(is); final boolean ack = "ack".equals(PaymentProtocol.parsePaymentAck(paymentAck).getMemo()); log.info("received {} via bluetooth", ack ? "ack" : "nack"); onResult(ack); } catch (final IOException x) { log.info("problem sending", x); onFail(R.string.error_io, x.getMessage()); } finally { if (os != null) { try { os.close(); } catch (final IOException x) { // swallow } } if (is != null) { try { is.close(); } catch (final IOException x) { // swallow } } if (socket != null) { try { socket.close(); } catch (final IOException x) { // swallow } } } } }); } } public abstract void send(Payment payment); protected void onResult(final boolean ack) { callbackHandler.post(new Runnable() { @Override public void run() { resultCallback.onResult(ack); } }); } protected void onFail(final int messageResId, final Object... messageArgs) { callbackHandler.post(new Runnable() { @Override public void run() { resultCallback.onFail(messageResId, messageArgs); } }); } }
/******************************************************************************* * Copyright (c) 2004 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Common Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/cpl-v10.html * * Contributors: * IBM Corporation - initial API and implementation * Bjorn Freeman-Benson - initial API and implementation *******************************************************************************/ package rhogenwizard.debugger.model; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IFolder; import org.eclipse.core.resources.IMarkerDelta; import org.eclipse.core.resources.IProject; import org.eclipse.core.resources.IResource; import org.eclipse.core.runtime.CoreException; import org.eclipse.debug.core.DebugEvent; import org.eclipse.debug.core.DebugException; import org.eclipse.debug.core.DebugPlugin; import org.eclipse.debug.core.IExpressionListener; import org.eclipse.debug.core.IExpressionManager; import org.eclipse.debug.core.ILaunch; import org.eclipse.debug.core.model.IBreakpoint; import org.eclipse.debug.core.model.IDebugTarget; import org.eclipse.debug.core.model.IExpression; import org.eclipse.debug.core.model.IMemoryBlock; import org.eclipse.debug.core.model.IProcess; import org.eclipse.debug.core.model.IStackFrame; import org.eclipse.debug.core.model.IThread; import org.eclipse.debug.core.model.IValue; import org.eclipse.dltk.internal.debug.core.model.ScriptLineBreakpoint; import rhogenwizard.ConsoleHelper; import rhogenwizard.PlatformType; import rhogenwizard.RhodesConfigurationRO; import rhogenwizard.RunType; import rhogenwizard.ShowOnlyHidePerspectiveJob; import rhogenwizard.constants.DebugConstants; import rhogenwizard.debugger.RhogenWatchExpression; import rhogenwizard.debugger.RhogenWatchExpressionResult; import rhogenwizard.debugger.backend.DebugServer; import rhogenwizard.debugger.backend.DebugServerException; import rhogenwizard.debugger.backend.DebugState; import rhogenwizard.debugger.backend.DebugVariableType; import rhogenwizard.debugger.backend.IDebugCallback; import rhogenwizard.debugger.model.selector.ResourceNameSelector; import rhogenwizard.project.ProjectFactory; import rhogenwizard.project.RhoconnectProject; import rhogenwizard.project.extension.BadProjectTagException; import rhogenwizard.sdk.task.StopRhodesAppTask; import rhogenwizard.sdk.task.StopSyncAppTask; /** * PDA Debug Target */ public class DebugTarget extends DebugElement implements IDebugTarget, IDebugCallback, IExpressionListener { private static String fwTag = "framework"; private IProject m_debugProject = null; // associated system process (VM) private IProcess m_processHandle = null; // containing launch object private ILaunch m_launchHandle = null; // program name private String m_programName = null; // suspend state private boolean m_isSuspended = true; // threads private DebugThread m_threadHandle = null; private IThread[] m_allThreads = null; private static DebugServer m_debugServer = null; private RunType m_runType; private PlatformType m_platformType; public DebugTarget(ILaunch launch, IProcess process, IProject debugProject, RunType runType, PlatformType platformType) { super(null); m_platformType = platformType; m_runType = runType; m_debugProject = debugProject; m_launchHandle = launch; m_debugTarget = this; m_processHandle = process; m_threadHandle = new DebugThread(this); m_allThreads = new IThread[] { m_threadHandle }; DebugServer.setDebugOutputStream(System.out); if (m_debugServer != null) { m_debugServer.shutdown(); } DebugPlugin.getDefault().getBreakpointManager().addBreakpointListener(this); DebugPlugin.getDefault().getExpressionManager().addExpressionListener(this); m_debugServer = new DebugServer(this); m_debugServer.start(); m_debugServer.debugSkipBreakpoints(false); } @Override protected void finalize() throws Throwable { exited(); super.finalize(); } public void setProcess(IProcess p) { m_processHandle = p; } public IProcess getProcess() { return m_processHandle; } public IThread[] getThreads() throws DebugException { return m_allThreads; } public boolean hasThreads() throws DebugException { return true; } public String getName() throws DebugException { if (m_programName == null) { m_programName = new RhodesConfigurationRO(getLaunch().getLaunchConfiguration()).project(); } return m_programName; } public boolean supportsBreakpoint(IBreakpoint breakpoint) { if (breakpoint.getModelIdentifier().equals(DebugConstants.debugModelId)) { return true; } return false; } public IDebugTarget getDebugTarget() { return this; } public ILaunch getLaunch() { return m_launchHandle; } public boolean canTerminate() { if (m_processHandle == null) return true; return m_processHandle.canTerminate(); } public boolean isTerminated() { if (m_processHandle == null) return true; return m_processHandle.isTerminated(); } public void terminate() throws DebugException { try { m_debugServer.debugTerminate(); if (ProjectFactory.getInstance().typeFromProject(m_debugProject).equals(RhoconnectProject.class)) { new StopSyncAppTask().run(); } else if (m_runType == RunType.eDevice || m_runType == RunType.eSimulator) { String workDir = m_debugProject.getLocation().makeAbsolute().toString(); new StopRhodesAppTask(workDir, m_platformType, m_runType).run(); } if (m_processHandle != null) { m_processHandle.terminate(); m_processHandle = null; } } catch (DebugServerException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } public boolean canResume() { return !isTerminated() && isSuspended(); } public boolean canSuspend() { return !isTerminated() && !isSuspended(); } private void waitDebugProcessing() { try { while (m_debugServer.debugIsProcessing()) { } Thread.currentThread(); Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } public boolean isSuspended() { return m_isSuspended; } public void resume() throws DebugException { waitDebugProcessing(); cleanState(); waitDebugProcessing(); resumed(DebugEvent.CLIENT_REQUEST); waitDebugProcessing(); m_debugServer.debugResume(); } /** * Notification the target has resumed for the given reason * * @param detail * reason for the resume */ private void resumed(int detail) { waitDebugProcessing(); m_isSuspended = false; m_threadHandle.fireResumeEvent(detail); } /** * Notification the target has suspended for the given reason * * @param detail * reason for the suspend */ private void suspended(int detail) { waitDebugProcessing(); m_isSuspended = true; m_threadHandle.fireSuspendEvent(detail); } public void suspend() throws DebugException { } //TODO - hot fix private boolean isFunctionDefinition(ScriptLineBreakpoint lineBp) { IFile file = (IFile) lineBp.getResource(); try { BufferedReader contentBuffer = new BufferedReader(new InputStreamReader(file.getContents())); String buf = ""; for (int i=0; i < lineBp.getLineNumber(); i++) { buf = contentBuffer.readLine(); } return buf.matches("^\\s*def\\s.*$"); } catch (CoreException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return false; } public void breakpointAdded(IBreakpoint breakpoint) { boolean globalBpEnable = DebugPlugin.getDefault().getBreakpointManager().isEnabled(); if (supportsBreakpoint(breakpoint)) { try { if (breakpoint.isEnabled() && globalBpEnable) { ScriptLineBreakpoint lineBr = (ScriptLineBreakpoint) breakpoint; if (!isFunctionDefinition(lineBr)) { int lineNum = lineBr.getLineNumber(); String srcFile = ResourceNameSelector.getInstance().convertBpName(ProjectFactory.getInstance().typeFromProject(m_debugProject), lineBr); m_debugServer.debugBreakpoint(srcFile, lineNum); } else { breakpoint.setEnabled(false); } } } catch (CoreException e) { } catch (BadProjectTagException e) { e.printStackTrace(); } } } public void breakpointRemoved(IBreakpoint breakpoint, IMarkerDelta delta) { if (supportsBreakpoint(breakpoint)) { try { ScriptLineBreakpoint lineBr = (ScriptLineBreakpoint) breakpoint; int lineNum = lineBr.getLineNumber(); String srcFile = ResourceNameSelector.getInstance().convertBpName(ProjectFactory.getInstance().typeFromProject(m_debugProject), lineBr); m_debugServer.debugRemoveBreakpoint(srcFile, lineNum); } catch (CoreException e) { } catch (BadProjectTagException e) { e.printStackTrace(); } } } public void breakpointChanged(IBreakpoint breakpoint, IMarkerDelta delta) { boolean globalBpEnable = DebugPlugin.getDefault().getBreakpointManager().isEnabled(); if (supportsBreakpoint(breakpoint)) { if (!globalBpEnable) { breakpointRemoved(breakpoint, null); return; } try { if (breakpoint.isEnabled()) { breakpointAdded(breakpoint); } else { breakpointRemoved(breakpoint, null); } } catch (CoreException e) { } } } public boolean canDisconnect() { return false; } public void disconnect() throws DebugException { } public void stepOver() { waitDebugProcessing(); m_threadHandle.setStepping(true); waitDebugProcessing(); resumed(DebugEvent.STEP_OVER); waitDebugProcessing(); m_debugServer.debugStepOver(); } public void stepReturn() { waitDebugProcessing(); m_threadHandle.setStepping(true); waitDebugProcessing(); resumed(DebugEvent.STEP_RETURN); waitDebugProcessing(); m_debugServer.debugStepReturn(); } public void stepInto() { waitDebugProcessing(); m_threadHandle.setStepping(true); waitDebugProcessing(); resumed(DebugEvent.STEP_INTO); waitDebugProcessing(); m_debugServer.debugStepInto(); } public boolean isDisconnected() { return false; } public boolean supportsStorageRetrieval() { return false; } public IMemoryBlock getMemoryBlock(long startAddress, long length) throws DebugException { return null; } /** * Install breakpoints that are already registered with the breakpoint * manager. */ private void installDeferredBreakpoints() { IBreakpoint[] breakpoints = DebugPlugin.getDefault().getBreakpointManager().getBreakpoints(DebugConstants.debugModelId); for (int i = 0; i < breakpoints.length; i++) { breakpointAdded(breakpoints[i]); } } private void installDeferredWatchs() { IExpression[] watchs = DebugPlugin.getDefault().getExpressionManager().getExpressions(); for (IExpression exp : watchs) { waitDebugProcessing(); m_debugServer.debugEvaluate(exp.getExpressionText()); } } /** * Returns the current stack frames in the target. * * @return the current stack frames in the target * @throws DebugException * if unable to perform the request */ protected IStackFrame[] getStackFrames() throws DebugException { waitDebugProcessing(); StackData stackData = new StackData(m_debugServer.debugGetFile(), m_debugServer.debugGetLine()); IStackFrame[] theFrames = new IStackFrame[1]; for (int i = 0; i < 3; ++i) { try { stackData.m_currVariables = m_debugServer.debugWatchList(); theFrames[0] = new DebugStackFrame(m_threadHandle, stackData, 0); break; } catch (DebugServerException e) { try { Thread.sleep(200); } catch (InterruptedException e1) { } } } return theFrames; } @Override public void connected() { try { cleanState(); fireCreationEvent(); installDeferredBreakpoints(); resume(); } catch (DebugException e) { } } boolean isFoundFramework() { IFolder fwFodler = m_debugProject.getFolder(fwTag); try { IResource[] childRes = fwFodler.members(); return fwFodler.exists() && childRes.length != 0; } catch (CoreException e) { e.printStackTrace(); } return false; } private void showDebugPerspective() { ShowOnlyHidePerspectiveJob job = new ShowOnlyHidePerspectiveJob("Show debug perspective", DebugConstants.debugPerspectiveId); job.schedule(); } @Override public void stopped(DebugState state, String file, int line, String className, String method) { waitDebugProcessing(); showDebugPerspective(); if (file.contains(fwTag)) { if (!isFoundFramework()) { try { resume(); } catch (DebugException e) { e.printStackTrace(); } return; } } cleanState(); installDeferredWatchs(); waitDebugProcessing(); if (state == DebugState.BREAKPOINT) { IBreakpoint[] breakpoints = DebugPlugin.getDefault().getBreakpointManager().getBreakpoints(DebugConstants.debugModelId); for (int i = 0; i < breakpoints.length; i++) { waitDebugProcessing(); IBreakpoint breakpoint = breakpoints[i]; if (breakpoint instanceof ScriptLineBreakpoint) { try { ScriptLineBreakpoint lineBreakpoint = (ScriptLineBreakpoint) breakpoint; String resPath = ResourceNameSelector.getInstance().convertBpName(ProjectFactory.getInstance().typeFromProject(m_debugProject), lineBreakpoint); if (lineBreakpoint.getLineNumber() == line && resPath.equals(file)) { m_threadHandle.setBreakpoints(new IBreakpoint[] { breakpoint }); break; } } catch (CoreException e) { } catch (BadProjectTagException e1) { } } } suspended(DebugEvent.BREAKPOINT); } else if (DebugState.paused(state)) { m_threadHandle.setStepping(true); suspended(DebugEvent.STEP_END); } } @Override public void unknown(String cmd) { } @Override public void exited() { m_isSuspended = false; DebugPlugin.getDefault().getBreakpointManager().removeBreakpointListener(this); DebugPlugin.getDefault().getExpressionManager().removeExpressionListener(this); fireTerminateEvent(); if (m_processHandle != null) { try { terminate(); } catch (DebugException e) { e.printStackTrace(); } } try { m_debugServer.shutdown(); } catch (DebugServerException e) { } } @Override public void resumed() { waitDebugProcessing(); cleanState(); m_isSuspended = false; waitDebugProcessing(); resumed(DebugEvent.CLIENT_REQUEST); } void cleanState() { m_threadHandle.setBreakpoints(null); m_threadHandle.setStepping(false); } @Override synchronized public void evaluation(boolean valid, String code, String value) { ConsoleHelper.getAppConsole().show(); ConsoleHelper.getAppConsole().getStream().println("start"); IExpressionManager expManager = DebugPlugin.getDefault().getExpressionManager(); IExpression[] modelExps = expManager.getExpressions(); for (IExpression currExp : modelExps) { if (currExp.getExpressionText().equals(code)) { if (currExp instanceof RhogenWatchExpression) { IValue watchVal = new DebugValue(this, value); RhogenWatchExpression watchExp = (RhogenWatchExpression) currExp; watchExp.setResult(new RhogenWatchExpressionResult(code, watchVal)); } } } } @Override public void watchBOL(DebugVariableType type) { // TODO Auto-generated method stub } @Override public void watchEOL(DebugVariableType type) { // TODO Auto-generated method stub } @Override public void expressionAdded(IExpression expression) { IExpressionManager m = DebugPlugin.getDefault().getExpressionManager(); waitDebugProcessing(); String expText = expression.getExpressionText(); if (!(expression instanceof RhogenWatchExpression)) { m.removeExpression(expression); m.addExpression(new RhogenWatchExpression(expText)); m_debugServer.debugEvaluate(expText); } } @Override public void expressionRemoved(IExpression expression) { // TODO Auto-generated method stub } @Override public void expressionChanged(IExpression expression) { // waitDebugProcessing(); // String expText = expression.getExpressionText(); // expression = new RhogenWatchExpression(expText); // m_debugServer.debugEvaluate(expText); } @Override public void watch(DebugVariableType type, String variable, String value) { // TODO Auto-generated method stub } }
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ide.actions; import com.intellij.CommonBundle; import com.intellij.diagnostic.ThreadDumper; import com.intellij.ide.IdeBundle; import com.intellij.ide.plugins.IdeaPluginDescriptor; import com.intellij.ide.plugins.PluginManagerCore; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.project.DumbAwareAction; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Pair; import com.intellij.openapi.util.text.StringUtil; import com.intellij.ui.components.JBScrollPane; import com.intellij.util.ReflectionUtil; import com.intellij.util.concurrency.AppExecutorUtil; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.text.CharArrayUtil; import it.unimi.dsi.fastutil.longs.Long2LongMap; import it.unimi.dsi.fastutil.longs.Long2LongOpenHashMap; import it.unimi.dsi.fastutil.objects.Object2LongMap; import it.unimi.dsi.fastutil.objects.Object2LongOpenHashMap; import one.util.streamex.StreamEx; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import javax.swing.*; import java.lang.management.*; import java.lang.reflect.Method; import java.util.*; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; final class ActivityMonitorAction extends DumbAwareAction { private static final @NonNls String[] MEANINGLESS_PREFIXES_1 = {"com.intellij.", "com.jetbrains.", "org.jetbrains.", "org.intellij."}; private static final @NonNls String[] MEANINGLESS_PREFIXES_2 = {"util.", "openapi.", "plugins.", "extapi."}; private static final @NonNls String[] INFRASTRUCTURE_PREFIXES = { "sun.", "com.sun.", "com.yourkit.", "com.fasterxml.jackson.", "net.sf.cglib.", "org.jetbrains.org.objectweb.asm.", "org.picocontainer.", "net.jpountz.lz4.", "net.n3.nanoxml.", "org.apache.", "one.util.streamex", "java.", "gnu.", "kotlin.", "groovy.", "org.codehaus.groovy.", "org.gradle.", "com.google.common.", "com.google.gson.", "com.intellij.openapi.application.impl.", "com.intellij.psi.impl.", "com.intellij.extapi.psi.", "com.intellij.psi.util.Cached", "com.intellij.openapi.extensions.", "com.intellij.openapi.util.", "com.intellij.facet.", "com.intellij.util.", "com.intellij.concurrency.", "com.intellij.semantic.", "com.intellij.serviceContainer.", "com.intellij.jam.", "com.intellij.psi.stubs.", "com.intellij.openapi.progress.impl.", "com.intellij.ide.IdeEventQueue", "com.intellij.openapi.fileTypes.", "com.intellij.openapi.vfs.newvfs.persistent.PersistentFS", "com.intellij.openapi.vfs.newvfs.persistent.FSRecords", "com.intellij.openapi.roots.impl", "javax." }; @Override public void actionPerformed(@NotNull AnActionEvent e) { JTextArea textArea = new JTextArea(12, 100); textArea.setText(CommonBundle.getLoadingTreeNodeText()); ThreadMXBean threadBean = ManagementFactory.getThreadMXBean(); List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans(); CompilationMXBean jitBean = ManagementFactory.getCompilationMXBean(); OperatingSystemMXBean osBean = ManagementFactory.getOperatingSystemMXBean(); Method getProcessCpuTime = Objects.requireNonNull(ReflectionUtil.getMethod(osBean.getClass().getInterfaces()[0], "getProcessCpuTime")); ScheduledFuture<?> future = AppExecutorUtil.getAppScheduledExecutorService().scheduleWithFixedDelay(new Runnable() { final Long2LongMap lastThreadTimes = new Long2LongOpenHashMap(); final Object2LongMap<String> subsystemToSamples = new Object2LongOpenHashMap<>(); long lastGcTime = totalGcTime(); long lastProcessTime = totalProcessTime(); long lastJitTime = jitBean.getTotalCompilationTime(); long lastUiUpdate = System.currentTimeMillis(); private final Map<String, String> classToSubsystem = new HashMap<>(); @NotNull private String calcSubSystemName(String className) { String pkg = StringUtil.getPackageName(className); if (pkg.isEmpty()) pkg = className; String prefix = getMeaninglessPrefix(pkg); if (!prefix.isEmpty()) { pkg = pkg.substring(prefix.length()) + " (in " + StringUtil.trimEnd(prefix, ".") + ")"; } IdeaPluginDescriptor plugin = PluginManagerCore.getPlugin(PluginManagerCore.getPluginByClassName(className)); return plugin != null ? "Plugin " + plugin.getName() + ": " + pkg : pkg; } private String getMeaninglessPrefix(String qname) { String result = findPrefix(qname, MEANINGLESS_PREFIXES_1); if (!result.isEmpty()) { result += findPrefix(qname.substring(result.length()), MEANINGLESS_PREFIXES_2); } return result; } private String findPrefix(String qname, String[] prefixes) { for (String prefix : prefixes) { if (qname.startsWith(prefix)) { return prefix; } } return ""; } private long totalGcTime() { return gcBeans.stream().mapToLong(GarbageCollectorMXBean::getCollectionTime).sum(); } private long totalProcessTime() { try { return (long)getProcessCpuTime.invoke(osBean); } catch (Exception ex) { return 0; } } @NotNull private String getSubsystemName(long threadId) { if (threadId == Thread.currentThread().getId()) { return "<Activity Monitor>"; } ThreadInfo info = threadBean.getThreadInfo(threadId, Integer.MAX_VALUE); if (info == null) return "<unidentified: thread finished>"; boolean runnable = info.getThreadState() == Thread.State.RUNNABLE; if (runnable) { for (StackTraceElement element : info.getStackTrace()) { String className = element.getClassName(); if (!isInfrastructureClass(className)) { return classToSubsystem.computeIfAbsent(className, this::calcSubSystemName); } } } return (runnable ? "<infrastructure: " : "<unidentified: ") + getCommonThreadName(info) + ">"; } private String getCommonThreadName(ThreadInfo info) { String name = info.getThreadName(); if (ThreadDumper.isEDT(name)) return "UI thread"; int numberStart = CharArrayUtil.shiftBackward(name, name.length() - 1, "0123456789/ ") + 1; if (numberStart > 0) return name.substring(0, numberStart); return name; } private boolean isInfrastructureClass(String className) { return ContainerUtil.exists(INFRASTRUCTURE_PREFIXES, className::startsWith); } @Override public void run() { for (long id : threadBean.getAllThreadIds()) { long cpuTime = threadBean.getThreadCpuTime(id); long prev = lastThreadTimes.put(id, cpuTime); if (prev != 0 && cpuTime > prev) { String subsystem = getSubsystemName(id); subsystemToSamples.put(subsystem, subsystemToSamples.getLong(subsystem) + cpuTime - prev); } } long now = System.currentTimeMillis(); long sinceLastUpdate = now - lastUiUpdate; if (sinceLastUpdate > 2_000) { lastUiUpdate = now; scheduleUiUpdate(sinceLastUpdate); } } private void scheduleUiUpdate(long sinceLastUpdate) { List<Pair<String, Long>> times = takeSnapshot(); String text = " %CPU Subsystem\n\n" + StreamEx.of(times) .filter(p -> p.second > 10) .sorted(Comparator.comparing((Pair<String, Long> p) -> p.second).reversed()) .limit(8) .map(p -> String.format("%5.1f %s", (double) p.second*100 / sinceLastUpdate, p.first)) .joining("\n"); ApplicationManager.getApplication().invokeLater(() -> { textArea.setText(text); textArea.setCaretPosition(0); }, ModalityState.any()); } @NotNull private List<Pair<String, Long>> takeSnapshot() { List<Pair<String, Long>> times = new ArrayList<>(); for (Object2LongMap.Entry<String> entry : subsystemToSamples.object2LongEntrySet()) { times.add(new Pair<>(entry.getKey(), TimeUnit.NANOSECONDS.toMillis(entry.getLongValue()))); } subsystemToSamples.clear(); long gcTime = totalGcTime(); if (gcTime != lastGcTime) { times.add(Pair.create("<Garbage collection>", gcTime - lastGcTime)); lastGcTime = gcTime; } long jitTime = jitBean.getTotalCompilationTime(); if (jitTime != lastJitTime) { times.add(Pair.create("<JIT compiler>", jitTime - lastJitTime)); lastJitTime = jitTime; } long processTime = totalProcessTime(); if (processTime != lastProcessTime) { times.add(Pair.create("<Process total CPU usage>", TimeUnit.NANOSECONDS.toMillis(processTime - lastProcessTime))); lastProcessTime = processTime; } return times; } }, 0, 20, TimeUnit.MILLISECONDS); DialogWrapper dialog = new DialogWrapper(false) { { init(); } @Override protected JComponent createCenterPanel() { JBScrollPane pane = new JBScrollPane(textArea); pane.setPreferredSize(textArea.getPreferredSize()); return pane; } @Override protected String getDimensionServiceKey() { return "Performance.Activity.Monitor"; } @Override protected Action @NotNull [] createActions() { return new Action[]{getOKAction()}; } }; dialog.setTitle(IdeBundle.message("dialog.title.activity.monitor")); dialog.setModal(false); Disposer.register(dialog.getDisposable(), () -> future.cancel(false)); dialog.show(); } }
package ch.uzh.ddis.katts.bolts.join; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.NavigableSet; import java.util.Set; import java.util.TreeMap; import org.springframework.expression.Expression; import org.springframework.expression.ExpressionParser; import org.springframework.expression.spel.standard.SpelExpressionParser; import org.springframework.expression.spel.support.StandardEvaluationContext; import ch.uzh.ddis.katts.query.processor.join.EvictionRuleConfiguration; import com.google.common.collect.HashMultimap; import com.google.common.collect.ImmutableList; /** * Eviction rules define conditions under which certain elements can be evicted from the caches of {@link JoinCondition} * and the eviction rule indices. They make use of optimized data structures in order to keep the set of variable * bindings in the current join cache relevant. * * @author Lorenz Fischer */ public class EvictionRuleManager { public enum DT { START { @Override public Long getTime(SimpleVariableBindings bindings) { return ((Date) bindings.get("startDate")).getTime(); } }, END { public Long getTime(SimpleVariableBindings bindings) { return ((Date) bindings.get("endDate")).getTime(); } }; public abstract Long getTime(SimpleVariableBindings bindings); } /** A set containing all ids of all incoming streams. */ private Set<String> streamIds; /** The join condition this bolt uses. */ private JoinCondition joinCondition; /** * Rules for the {@link #executeBeforeEvictionRules(SimpleVariableBindings, String)} method grouped by the * identifier of the stream on which they have to operate. See * {@link #executeEvitionRules(List, SimpleVariableBindings, String)} for more information. * * @see EvictionRuleManager#executeAfterEvictionRules(SimpleVariableBindings, String) */ private HashMultimap<String, EvictionRuleConfiguration> beforeEvictionRules; /** * The for the {@link #executeAfterEvictionRules(SimpleVariableBindings, String)} method will execute. See * {@link #executeEvitionRules(List, SimpleVariableBindings, String)} for more information. * * @see EvictionRuleManager#executeAfterEvictionRules(SimpleVariableBindings, String) */ private HashMultimap<String, EvictionRuleConfiguration> afterEvictionRules; /** * For each <b>stream</b> we keep a sorted {@link TreeMap} of all variable bindings for both the <b>start</b> and * the <b>end</b> time of the variable bindings that arrived over it. This data structure keeps all this information * as follows: * * <pre> * Map&lt;streamId, Map&lt;DT, TreeMap&lt;TimeValue, HashSet&lt;VariableBinding&gt;&gt;&gt;&gt; * </pre> * * <ul> * <li>The key of the outer most map is the identifier of the stream.</li> * <li>The key of the map inside the first map states if the contained treemap is sorted by either the start * (DT.START) or end (DT.END) time of the variable binding</li> * <li>The key of the TreeMap is a long value representing the standard java time of the variable binding.</li> * <li>The inner most HashSet then contains all variable bindings for the given date, date type, and stream.</li> * </ul> */ private HashMap<String, HashMap<DT, TreeMap<Long, HashSet<SimpleVariableBindings>>>> evictionCaches; /** * After creating the manager, new bindings can be added to its indexes using the * {@link #addBindingsToIndices(SimpleVariableBindings, String)} method. The methods * {@link #executeBeforeEvictionRules(SimpleVariableBindings, String)} and * {@link #executeAfterEvictionRules(SimpleVariableBindings, String)} methods will evict variable bindings from the * indexes of this manager and also from the index of the provided {@link #joinCondition}. * * @param beforeEvictionRules * a collection of configuration details for the eviction rules that have to be executed <i>before</i> * the actual join takes place. * @param afterEvictionRules * a collection of configuration details for the eviction rules that have to be executed <i>before</i> * the actual join takes place. * @param joinCondition * the configured join condition instance. This reference is necessary, so the rules in this manager can * remove the evicted variable bindings from the join cache accordingly. * @param streamIds * a set containing the identifiers of all streams this condition will process data of. * * @see #addBindingsToIndices(SimpleVariableBindings, String) * @see #executeBeforeEvictionRules(SimpleVariableBindings, String) * @see #executeAfterEvictionRules(SimpleVariableBindings, String) */ public EvictionRuleManager(List<EvictionRuleConfiguration> beforeEvictionRules, List<EvictionRuleConfiguration> afterEvictionRules, JoinCondition joinCondition, Set<String> streamIds) { this.joinCondition = joinCondition; this.streamIds = streamIds; /* * create a sorted treemap for both the start times and the end times of variable bindings per stream */ this.evictionCaches = new HashMap<String, HashMap<DT, TreeMap<Long, HashSet<SimpleVariableBindings>>>>(); for (String streamId : streamIds) { HashMap<DT, TreeMap<Long, HashSet<SimpleVariableBindings>>> dtMap = new HashMap<DT, TreeMap<Long, HashSet<SimpleVariableBindings>>>(); for (DT dt : DT.values()) { dtMap.put(dt, new TreeMap<Long, HashSet<SimpleVariableBindings>>()); } this.evictionCaches.put(streamId, dtMap); } // Create the multi maps for both the before and the after rules. this.beforeEvictionRules = createRuleMaps(beforeEvictionRules); this.afterEvictionRules = createRuleMaps(afterEvictionRules); } /** * This method creates the rule index maps for fast rule retrieval. The are later used by the * {@link #executeEvitionRules(List, SimpleVariableBindings, String)} method. * * @see EvictionRuleManager#executeEvitionRules(List, SimpleVariableBindings, String) * @return a map based on the */ private HashMultimap<String, EvictionRuleConfiguration> createRuleMaps(List<EvictionRuleConfiguration> rules) { HashMultimap<String, EvictionRuleConfiguration> result = HashMultimap.create(); for (EvictionRuleConfiguration rule : rules) { for (String streamId : evaluateIdExpression(rule.getOn())) { result.put(streamId, rule); } } return result; } /** * This method evaluates the configured expression of the 'from' and 'to' fields in the configuration of an eviction * rule. These fields can contain either a single star ("*") character or a comma separated list of stream * identifiers. The validity of the stream identifiers are tested against the contents of the member variable * {@link #streamIds}. * * @param expression * the configuration expression to be evaluated. * @return a list containing all identifiers configured by the supplied expression */ private List<String> evaluateIdExpression(String expression) { List<String> result = new ArrayList<String>(); if (expression == null || expression.length() == 0) { throw new IllegalArgumentException("Missing field in eviction rule configuration: " + expression); } if (expression.equals("*")) {// add the rule for all stream ids result.addAll(this.streamIds); } else { // add all configured stream ids Collections.addAll(result, expression.split(",")); } // make sure we have no configuration errors for (String configuredStreamId : result) { if (!this.streamIds.contains(configuredStreamId)) { throw new IllegalArgumentException("Unknown streamId in rule configuration: " + expression + " only the following stream identifiers have been configured: " + this.streamIds); } } return result; } /** * Calling this method will run all eviction rules that have been configured to be ran "before" the join. * * <b>Please Note:</b> This method will not add the bindings to this managers indices. You will have to do this * yourself using the {@link #addBindingsToIndices(SimpleVariableBindings, String)} method. * * @param newBindings * the new variable bindings object that has been received. * @param arrivedOnStreamId * the identifier of the stream the variable bindings have been received on. */ public void executeBeforeEvictionRules(SimpleVariableBindings newBindings, String arrivedOnStreamId) { executeEvitionRules(this.beforeEvictionRules, newBindings, arrivedOnStreamId); } /** * Calling this method will run all eviction rules that have been configured to be ran "after" the join. * * <b>Please Note:</b> This method will not add the bindings to this managers indices. You will have to do this * yourself using the {@link #addBindingsToIndices(SimpleVariableBindings, String)} method. * * @param newBindings * the new variable bindings object that has been received. * @param arrivedOnStreamId * the identifier of the stream the variable bindings have been received on. */ public void executeAfterEvictionRules(SimpleVariableBindings newBindings, String arrivedOnStreamId) { executeEvitionRules(this.afterEvictionRules, newBindings, arrivedOnStreamId); } /** * Executes the provided eviction rules for the new provided bindings that have arrived on the stream identified by * arrivedOnStreamId. * * The user can specify the stream on which the rule is "listening" on (using the "on" field). This field accepts a * comma separated list of stream identifiers or a single star ('*') character. Whenever a new variable binding * arrives, we check which rules need to be executed based on the identifier of the stream the variable binding * arrived on. The way the "from" field es evaluated works analogous. See {@link #createRuleMaps()} and * {@link #evaluateIdExpression(String)} for how the index maps we use here are being created. * * @param evictionRules * the rules to execute. * @param newBindings * the new variable bindings object that has been received. * @param arrivedOnStreamId * the identifier of the stream the variable bindings have been received on. * @see #createRuleMaps() */ private void executeEvitionRules(HashMultimap<String, EvictionRuleConfiguration> evictionRules, SimpleVariableBindings newBindings, String arrivedOnStreamId) { StandardEvaluationContext expressionContext = new StandardEvaluationContext(); ExpressionParser expressionParser = new SpelExpressionParser(); /* * Example expression: * #{ from.getLongByField('endDate') < on.getLongByField('startDate') } * * since we expect most of the eviction expression being based on 'endDate' and 'startDate' our objects support * these two fields in the java bean notation * * #{ from.endDate < on.startDate } */ expressionContext.setVariable("on", newBindings); // execute rules! for (EvictionRuleConfiguration rule : evictionRules.get(arrivedOnStreamId)) { Expression expression = expressionParser.parseExpression(rule.getCondition()); for (String fromStreamId : evaluateIdExpression(rule.getFrom())) { String condition = rule.getCondition(); TreeMap<Long, HashSet<SimpleVariableBindings>> sortedMap; // find the most efficient index to use if (condition.contains("from.endDate")) { sortedMap = this.evictionCaches.get(fromStreamId).get(DT.END); } else if (condition.contains("from.startDate")) { sortedMap = this.evictionCaches.get(fromStreamId).get(DT.START); } else { throw new IllegalArgumentException( "Missing date in if-condition. You must specify either 'from.startDate' " + "or 'from.endDate' in rule configuration: " + rule); } // TODO lorenz: support equals conditions! /* * Our treemap is sorted by the date of the "from" condition. We start looking for items to evict * starting from both ends of the treemap and stop as soon as the expression is false for the first * time. This way we make sure, that we only process as many items as we absolutely have to. */ for (NavigableSet<Long> set : ImmutableList.of(sortedMap.navigableKeySet(), sortedMap.descendingKeySet())) { Iterator<Long> iter = set.iterator(); List<SimpleVariableBindings> bindingsToRemove = new ArrayList<SimpleVariableBindings>(); while (iter.hasNext()) { Long current = iter.next(); Iterator<SimpleVariableBindings> setIterator; if (!sortedMap.containsKey(current)) { // we reached the end of this search run - abort the // loop! break; } setIterator = sortedMap.get(current).iterator(); while (setIterator.hasNext()) { SimpleVariableBindings bindings = setIterator.next(); expressionContext.setVariable("from", bindings); if (expression.getValue(expressionContext, Boolean.class)) { // hit! remember to remove it after the loop bindingsToRemove.add(bindings); } } } // now remove the f**kers from all indices and caches for (SimpleVariableBindings bindings : bindingsToRemove) { this.joinCondition.removeBindingsFromCache(bindings, fromStreamId); for (DT dt : DT.values()) { TreeMap<Long, HashSet<SimpleVariableBindings>> treeMap; Set<SimpleVariableBindings> bindingsSet; treeMap = this.evictionCaches.get(fromStreamId).get(dt); bindingsSet = treeMap.get(dt.getTime(bindings)); bindingsSet.remove(bindings); // remove empty sets from the index if (bindingsSet.size() == 0) { treeMap.remove(dt.getTime(bindings)); } } } } } } } /** * Adds the given variable bindings to the indices of this manager. * * @param newBindings * the new variable bindings object that has been received. * @param arrivedOnStreamId * the identifier of the stream the variable bindings have been received on. */ public void addBindingsToIndices(SimpleVariableBindings newBindings, String arrivedOnStreamId) { for (DT dt : DT.values()) { Long date = dt.getTime(newBindings); HashSet<SimpleVariableBindings> bindingsSet = this.evictionCaches.get(arrivedOnStreamId).get(dt).get(date); if (bindingsSet == null) { bindingsSet = new HashSet<SimpleVariableBindings>(); this.evictionCaches.get(arrivedOnStreamId).get(dt).put(date, bindingsSet); } bindingsSet.add(newBindings); } } }
/* * Copyright 2002-2012 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.jmx.support; import java.io.IOException; import java.net.MalformedURLException; import java.util.HashMap; import java.util.Map; import java.util.Properties; import javax.management.MBeanServerConnection; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; import org.springframework.aop.TargetSource; import org.springframework.aop.framework.ProxyFactory; import org.springframework.aop.target.AbstractLazyCreationTargetSource; import org.springframework.beans.factory.BeanClassLoaderAware; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.FactoryBean; import org.springframework.beans.factory.InitializingBean; import org.springframework.util.ClassUtils; import org.springframework.util.CollectionUtils; /** * {@link FactoryBean} that creates a JMX 1.2 {@code MBeanServerConnection} * to a remote {@code MBeanServer} exposed via a {@code JMXServerConnector}. * Exposes the {@code MBeanServer} for bean references. * * @author Rob Harrop * @author Juergen Hoeller * @since 1.2 * @see MBeanServerFactoryBean * @see ConnectorServerFactoryBean * @see org.springframework.jmx.access.MBeanClientInterceptor#setServer * @see org.springframework.jmx.access.NotificationListenerRegistrar#setServer */ public class MBeanServerConnectionFactoryBean implements FactoryBean<MBeanServerConnection>, BeanClassLoaderAware, InitializingBean, DisposableBean { private JMXServiceURL serviceUrl; private Map<String, Object> environment = new HashMap<String, Object>(); private boolean connectOnStartup = true; private ClassLoader beanClassLoader = ClassUtils.getDefaultClassLoader(); private JMXConnector connector; private MBeanServerConnection connection; private JMXConnectorLazyInitTargetSource connectorTargetSource; /** * Set the service URL of the remote {@code MBeanServer}. */ public void setServiceUrl(String url) throws MalformedURLException { this.serviceUrl = new JMXServiceURL(url); } /** * Set the environment properties used to construct the {@code JMXConnector} * as {@code java.util.Properties} (String key/value pairs). */ public void setEnvironment(Properties environment) { CollectionUtils.mergePropertiesIntoMap(environment, this.environment); } /** * Set the environment properties used to construct the {@code JMXConnector} * as a {@code Map} of String keys and arbitrary Object values. */ public void setEnvironmentMap(Map<String, ?> environment) { if (environment != null) { this.environment.putAll(environment); } } /** * Set whether to connect to the server on startup. Default is "true". * <p>Can be turned off to allow for late start of the JMX server. * In this case, the JMX connector will be fetched on first access. */ public void setConnectOnStartup(boolean connectOnStartup) { this.connectOnStartup = connectOnStartup; } @Override public void setBeanClassLoader(ClassLoader classLoader) { this.beanClassLoader = classLoader; } /** * Creates a {@code JMXConnector} for the given settings * and exposes the associated {@code MBeanServerConnection}. */ @Override public void afterPropertiesSet() throws IOException { if (this.serviceUrl == null) { throw new IllegalArgumentException("Property 'serviceUrl' is required"); } if (this.connectOnStartup) { connect(); } else { createLazyConnection(); } } /** * Connects to the remote {@code MBeanServer} using the configured service URL and * environment properties. */ private void connect() throws IOException { this.connector = JMXConnectorFactory.connect(this.serviceUrl, this.environment); this.connection = this.connector.getMBeanServerConnection(); } /** * Creates lazy proxies for the {@code JMXConnector} and {@code MBeanServerConnection} */ private void createLazyConnection() { this.connectorTargetSource = new JMXConnectorLazyInitTargetSource(); TargetSource connectionTargetSource = new MBeanServerConnectionLazyInitTargetSource(); this.connector = (JMXConnector) new ProxyFactory(JMXConnector.class, this.connectorTargetSource).getProxy(this.beanClassLoader); this.connection = (MBeanServerConnection) new ProxyFactory(MBeanServerConnection.class, connectionTargetSource).getProxy(this.beanClassLoader); } @Override public MBeanServerConnection getObject() { return this.connection; } @Override public Class<? extends MBeanServerConnection> getObjectType() { return (this.connection != null ? this.connection.getClass() : MBeanServerConnection.class); } @Override public boolean isSingleton() { return true; } /** * Closes the underlying {@code JMXConnector}. */ @Override public void destroy() throws IOException { if (this.connectorTargetSource == null || this.connectorTargetSource.isInitialized()) { this.connector.close(); } } /** * Lazily creates a {@code JMXConnector} using the configured service URL * and environment properties. * @see MBeanServerConnectionFactoryBean#setServiceUrl(String) * @see MBeanServerConnectionFactoryBean#setEnvironment(java.util.Properties) */ private class JMXConnectorLazyInitTargetSource extends AbstractLazyCreationTargetSource { @Override protected Object createObject() throws Exception { return JMXConnectorFactory.connect(serviceUrl, environment); } @Override public Class<?> getTargetClass() { return JMXConnector.class; } } /** * Lazily creates an {@code MBeanServerConnection}. */ private class MBeanServerConnectionLazyInitTargetSource extends AbstractLazyCreationTargetSource { @Override protected Object createObject() throws Exception { return connector.getMBeanServerConnection(); } @Override public Class<?> getTargetClass() { return MBeanServerConnection.class; } } }
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.testGuiFramework.fixtures; import com.intellij.codeInspection.ui.InspectionTree; import com.intellij.ide.DataManager; import com.intellij.ide.actions.CloseProjectAction; import com.intellij.ide.actions.ShowSettingsUtilImpl; import com.intellij.openapi.Disposable; import com.intellij.openapi.actionSystem.ActionManager; import com.intellij.openapi.actionSystem.ActionPlaces; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.externalSystem.model.ExternalSystemException; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleManager; import com.intellij.openapi.options.ShowSettingsUtil; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.DumbService; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.ContentEntry; import com.intellij.openapi.roots.ModifiableRootModel; import com.intellij.openapi.roots.ModuleRootManager; import com.intellij.openapi.roots.SourceFolder; import com.intellij.openapi.util.Disposer; import com.intellij.openapi.util.Ref; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.openapi.wm.impl.IdeFrameImpl; import com.intellij.openapi.wm.impl.ProjectFrameHelper; import com.intellij.openapi.wm.impl.welcomeScreen.FlatWelcomeFrame; import com.intellij.testGuiFramework.framework.GuiTestUtil; import com.intellij.testGuiFramework.framework.Timeouts; import com.intellij.testGuiFramework.framework.TimeoutsKt; import com.intellij.ui.EditorNotificationPanel; import com.intellij.xdebugger.impl.ui.tree.nodes.XDebuggerTreeNode; import org.fest.swing.core.GenericTypeMatcher; import org.fest.swing.core.Robot; import org.fest.swing.core.matcher.JButtonMatcher; import org.fest.swing.core.matcher.JLabelMatcher; import org.fest.swing.edt.GuiQuery; import org.fest.swing.edt.GuiTask; import org.fest.swing.exception.ComponentLookupException; import org.fest.swing.exception.WaitTimedOutError; import org.fest.swing.fixture.ContainerFixture; import org.fest.swing.fixture.FrameFixture; import org.fest.swing.timing.Condition; import org.fest.swing.timing.Timeout; import org.jetbrains.annotations.Contract; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.jps.model.module.JpsModuleSourceRootType; import javax.swing.*; import javax.swing.tree.TreeNode; import java.awt.*; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.io.File; import java.nio.file.Path; import java.util.List; import java.util.*; import java.util.concurrent.TimeUnit; import static com.intellij.openapi.util.io.FileUtil.getRelativePath; import static com.intellij.openapi.util.io.FileUtil.toSystemDependentName; import static com.intellij.openapi.util.text.StringUtil.isNotEmpty; import static com.intellij.openapi.vfs.VfsUtilCore.urlToPath; import static junit.framework.Assert.assertNotNull; import static junit.framework.Assert.fail; import static org.fest.assertions.Assertions.assertThat; import static org.fest.swing.edt.GuiActionRunner.execute; import static org.fest.swing.timing.Pause.pause; import static org.fest.util.Strings.quote; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; public class IdeFrameFixture extends ComponentFixture<IdeFrameFixture, IdeFrameImpl> implements ContainerFixture<IdeFrameImpl> { @NotNull private final File myProjectPath; private MainToolbarFixture myToolbar; private NavigationBarFixture myNavBar; private RunConfigurationListFixture myRCList; private GutterFixture myGutter; private FrameFixture myFrameFixture; @NotNull public static IdeFrameFixture find(@NotNull final Robot robot, @Nullable final Path projectPath, @Nullable final String projectName, @NotNull final Timeout timeout) { final GenericTypeMatcher<IdeFrameImpl> matcher = new GenericTypeMatcher<IdeFrameImpl>(IdeFrameImpl.class) { @Override protected boolean isMatching(@NotNull IdeFrameImpl frame) { ProjectFrameHelper helper = ProjectFrameHelper.getFrameHelper(frame); Project project = helper != null ? helper.getProject() : null; if (projectPath == null && project != null) return true; if (project != null && PathManager.getAbsolutePath(projectPath.toString()).equals(PathManager.getAbsolutePath(project.getBasePath()))) { return projectName == null || projectName.equals(project.getName()); } return false; } }; try { pause(new Condition("IdeFrame " + (projectPath != null ? quote(projectPath.toString()) : "") + " to show up") { @Override public boolean test() { return !robot.finder().findAll(matcher).isEmpty(); } }, timeout); IdeFrameImpl ideFrame = robot.finder().find(matcher); return new IdeFrameFixture(robot, ideFrame, new File(ProjectFrameHelper.getFrameHelper(ideFrame).getProject().getBasePath())); } catch (WaitTimedOutError timedOutError) { throw new ComponentLookupException("Unable to find IdeFrame in " + TimeoutsKt.toPrintable(timeout)); } } public static IdeFrameFixture find(@NotNull final Robot robot, @Nullable final Path projectPath, @Nullable final String projectName) { return find(robot, projectPath, projectName, Timeouts.INSTANCE.getDefaultTimeout()); } public IdeFrameFixture(@NotNull Robot robot, @NotNull IdeFrameImpl target, @NotNull File projectPath) { super(IdeFrameFixture.class, robot, target); myFrameFixture = new FrameFixture(robot, target); myProjectPath = projectPath; final Project project = getProject(); Disposable disposable = new NoOpDisposable(); Disposer.register(project, disposable); //myGradleProjectEventListener = new GradleProjectEventListener(); //GradleSyncState.subscribe(project, myGradleProjectEventListener); //PostProjectBuildTasksExecutor.subscribe(project, myGradleProjectEventListener); } public void maximize(){ myFrameFixture.maximize(); } @NotNull public File getProjectPath() { return myProjectPath; } @NotNull public List<String> getModuleNames() { List<String> names = new ArrayList<>(); for (Module module : getModuleManager().getModules()) { names.add(module.getName()); } return names; } @NotNull public IdeFrameFixture requireModuleCount(int expected) { Module[] modules = getModuleManager().getModules(); assertThat(modules).as("Module count in project " + quote(getProject().getName())).hasSize(expected); return this; } @NotNull public Collection<String> getSourceFolderRelativePaths(@NotNull String moduleName, @NotNull final JpsModuleSourceRootType<?> sourceType) { final Set<String> paths = new HashSet<>(); Module module = getModule(moduleName); final ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(module); execute(new GuiTask() { @Override protected void executeInEDT() throws Throwable { ModifiableRootModel rootModel = moduleRootManager.getModifiableModel(); try { for (ContentEntry contentEntry : rootModel.getContentEntries()) { for (SourceFolder folder : contentEntry.getSourceFolders()) { JpsModuleSourceRootType<?> rootType = folder.getRootType(); if (rootType.equals(sourceType)) { String path = urlToPath(folder.getUrl()); String relativePath = getRelativePath(myProjectPath, new File(toSystemDependentName(path))); paths.add(relativePath); } } } } finally { rootModel.dispose(); } } }); return paths; } @NotNull public Module getModule(@NotNull String name) { Module module = findModule(name); assertNotNull("Unable to find module with name " + quote(name), module); return module; } @Nullable public Module findModule(@NotNull String name) { for (Module module : getModuleManager().getModules()) { if (name.equals(module.getName())) { return module; } } return null; } @NotNull private ModuleManager getModuleManager() { return ModuleManager.getInstance(getProject()); } @NotNull public FileEditorFixture getEditor() { return new FileEditorFixture(robot(), this); } @NotNull public MainToolbarFixture getToolbar() { if (myToolbar == null) { myToolbar = MainToolbarFixture.Companion.createMainToolbarFixture(robot(), this); } return myToolbar; } @NotNull public NavigationBarFixture getNavigationBar() { if (myNavBar == null) { myNavBar = NavigationBarFixture.Companion.createNavigationBarFixture(robot(), this); } return myNavBar; } @NotNull public RunConfigurationListFixture getRunConfigurationList() { if (myRCList == null) { myRCList = new RunConfigurationListFixture(robot(), this); } return myRCList; } @NotNull public GutterFixture getGutter() { if (myGutter == null) { myGutter = new GutterFixture(this); } return myGutter; } //@NotNull //public GradleInvocationResult invokeProjectMake() { // return invokeProjectMake(null); //} //@NotNull //public GradleInvocationResult invokeProjectMake(@Nullable Runnable executeAfterInvokingMake) { // myGradleProjectEventListener.reset(); // // final AtomicReference<GradleInvocationResult> resultRef = new AtomicReference<GradleInvocationResult>(); // AndroidProjectBuildNotifications.subscribe(getProject(), new AndroidProjectBuildNotifications.AndroidProjectBuildListener() { // @Override // public void buildComplete(@NotNull AndroidProjectBuildNotifications.BuildContext context) { // if (context instanceof GradleBuildContext) { // resultRef.set(((GradleBuildContext)context).getBuildResult()); // } // } // }); // selectProjectMakeAction(); // // if (executeAfterInvokingMake != null) { // executeAfterInvokingMake.run(); // } // // waitForBuildToFinish(COMPILE_JAVA); // // GradleInvocationResult result = resultRef.get(); // assertNotNull(result); // // return result; //} @NotNull public IdeFrameFixture invokeProjectMakeAndSimulateFailure(@NotNull final String failure) { Runnable failTask = () -> { throw new ExternalSystemException(failure); }; //ApplicationManager.getApplication().putUserData(EXECUTE_BEFORE_PROJECT_BUILD_IN_GUI_TEST_KEY, failTask); selectProjectMakeAction(); return this; } /** * Finds the Run button in the IDE interface. * * @return ActionButtonFixture for the run button. */ @NotNull public ActionButtonFixture findRunApplicationButton() { return findActionButtonByActionId("Run"); } public void debugApp(@NotNull String appName) throws ClassNotFoundException { selectApp(appName); findActionButtonByActionId("Debug").click(); } public void runApp(@NotNull String appName) throws ClassNotFoundException { selectApp(appName); findActionButtonByActionId("Run").click(); } @NotNull public RunToolWindowFixture getRunToolWindow() { return new RunToolWindowFixture(this); } @NotNull public DebugToolWindowFixture getDebugToolWindow() { return new DebugToolWindowFixture(this); } protected void selectProjectMakeAction() { invokeMenuPath("Build", "Make Project"); } /** * Invokes an action by menu path * * @param path the series of menu names, e.g. {@code invokeActionByMenuPath("Build", "Make Project")} */ public void invokeMenuPath(String @NotNull ... path) { getMenuFixture().invokeMenuPath(path); } /** * Returns a JMenuItem for a corresponding path * * @param path the series of menu names, e.g. {@code invokeActionByMenuPath("Build", "Make Project")} */ public MenuFixture.MenuItemFixture getMenuPath(String @NotNull ... path) { return getMenuFixture().getMenuItemFixture(path); } /** * Invokes an action from main menu * * @param mainMenuActionId is the typical AnAction with ActionPlaces.MAIN_MENU */ public void invokeMainMenu(@NotNull String mainMenuActionId) { ActionManager actionManager = ActionManager.getInstance(); AnAction mainMenuAction = actionManager.getAction(mainMenuActionId); JMenuBar jMenuBar = this.target().getRootPane().getJMenuBar(); MouseEvent fakeMainMenuMouseEvent = new MouseEvent(jMenuBar, MouseEvent.MOUSE_CLICKED, System.currentTimeMillis(), 0, MouseInfo.getPointerInfo().getLocation().x, MouseInfo.getPointerInfo().getLocation().y, 1, false); DumbService.getInstance(getProject()) .smartInvokeLater(() -> actionManager.tryToExecute(mainMenuAction, fakeMainMenuMouseEvent, null, ActionPlaces.MAIN_MENU, true)); } /** * Invokes an action by menu path (where each segment is a regular expression). This is particularly * useful when the menu items can change dynamically, such as the labels of Undo actions, Run actions, * etc. * * @param path the series of menu name regular expressions, e.g. {@code invokeActionByMenuPath("Build", "Make( Project)?")} */ public void invokeMenuPathRegex(String @NotNull ... path) { getMenuFixture().invokeMenuPathRegex(path); } @NotNull private MenuFixture getMenuFixture() { //noinspection ResultOfMethodCallIgnored target(); return new MenuFixture(robot()); } //@NotNull //public IdeFrameFixture waitForBuildToFinish(@NotNull final BuildMode buildMode) { // final Project project = getProject(); // if (buildMode == SOURCE_GEN && !GradleProjectBuilder.getInstance(project).isSourceGenerationEnabled()) { // return this; // } // // pause(new Condition("Build (" + buildMode + ") for project " + quote(project.getName()) + " to finish'") { // @Override // public boolean test() { // if (buildMode == SOURCE_GEN) { // PostProjectBuildTasksExecutor tasksExecutor = PostProjectBuildTasksExecutor.getInstance(project); // if (tasksExecutor.getLastBuildTimestamp() > -1) { // // This will happen when creating a new project. Source generation happens before the IDE frame is found and build listeners // // are created. It is fairly safe to assume that source generation happened if we have a timestamp for a "last performed build". // return true; // } // } // return myGradleProjectEventListener.isBuildFinished(buildMode); // } // }, Timeouts.INSTANCE.getMinutes05); // // waitForBackgroundTasksToFinish(); // robot().waitForIdle(); // // return this; //} @NotNull public FileFixture findExistingFileByRelativePath(@NotNull String relativePath) { VirtualFile file = findFileByRelativePath(relativePath, true); return new FileFixture(getProject(), file); } @Nullable @Contract("_, true -> !null") public VirtualFile findFileByRelativePath(@NotNull String relativePath, boolean requireExists) { assertFalse("Should use '/' in test relative paths, not File.separator", relativePath.contains("\\")); Project project = getProject(); VirtualFile file = project.getBaseDir().findFileByRelativePath(relativePath); if (requireExists) { assertNotNull("Unable to find file with relative path " + quote(relativePath), file); } return file; } //@NotNull //public IdeFrameFixture requestProjectSyncAndExpectFailure() { // requestProjectSync(); // return waitForGradleProjectSyncToFail(); //} @NotNull public IdeFrameFixture requestProjectSyncAndSimulateFailure(@NotNull final String failure) { Runnable failTask = () -> { throw new ExternalSystemException(failure); }; //ApplicationManager.getApplication().putUserData(EXECUTE_BEFORE_PROJECT_SYNC_TASK_IN_GUI_TEST_KEY, failTask); // When simulating the error, we don't have to wait for sync to happen. Sync never happens because the error is thrown before it (sync) // is started. return requestProjectSync(); } @NotNull public IdeFrameFixture requestProjectSync() { //myGradleProjectEventListener.reset(); // We wait until all "Run Configurations" are populated in the toolbar combo-box. Until then the "Project Sync" button is not in its // final position, and FEST will click the wrong button. pause(new Condition("Waiting for 'Run Configurations' to be populated") { @Override public boolean test() { RunConfigurationComboBoxFixture runConfigurationComboBox = RunConfigurationComboBoxFixture.find(IdeFrameFixture.this); return isNotEmpty(runConfigurationComboBox.getText()); } }, Timeouts.INSTANCE.getMinutes02()); waitForBackgroundTasksToFinish(); findGradleSyncAction(); // TODO figure out why in IDEA 15 even though an action is enabled, visible and showing, clicking it (via UI testing infrastructure) // does not work consistently return this; } @NotNull private ActionButtonFixture findGradleSyncAction() { return findActionButtonByActionId("Android.SyncProject"); } //@NotNull //public IdeFrameFixture waitForGradleProjectSyncToFail() { // try { // waitForGradleProjectSyncToFinish(true); // fail("Expecting project sync to fail"); // } // catch (RuntimeException expected) { // // expected failure. // } // return waitForBackgroundTasksToFinish(); //} //@NotNull //public IdeFrameFixture waitForGradleProjectSyncToStart() { // Project project = getProject(); // final GradleSyncState syncState = GradleSyncState.getInstance(project); // if (!syncState.isSyncInProgress()) { // pause(new Condition("Syncing project " + quote(project.getName()) + " to finish") { // @Override // public boolean test() { // return myGradleProjectEventListener.isSyncStarted(); // } // }, Timeouts.INSTANCE.getMinutes02); // } // return this; //} //@NotNull //public IdeFrameFixture waitForGradleProjectSyncToFinish() { // waitForGradleProjectSyncToFinish(false); // return this; //} //private void waitForGradleProjectSyncToFinish(final boolean expectSyncFailure) { // final Project project = getProject(); // // // ensure GradleInvoker (in-process build) is always enabled. // AndroidGradleBuildConfiguration buildConfiguration = AndroidGradleBuildConfiguration.getInstance(project); // buildConfiguration.USE_EXPERIMENTAL_FASTER_BUILD = true; // // pause(new Condition("Syncing project " + quote(project.getName()) + " to finish") { // @Override // public boolean test() { // GradleSyncState syncState = GradleSyncState.getInstance(project); // boolean syncFinished = // (myGradleProjectEventListener.isSyncFinished() || syncState.isSyncNeeded() != ThreeState.YES) && !syncState.isSyncInProgress(); // if (expectSyncFailure) { // syncFinished = syncFinished && myGradleProjectEventListener.hasSyncError(); // } // return syncFinished; // } // }, Timeouts.INSTANCE.getMinutes05); // // findGradleSyncAction().waitEnabledAndShowing(); // // if (myGradleProjectEventListener.hasSyncError()) { // RuntimeException syncError = myGradleProjectEventListener.getSyncError(); // myGradleProjectEventListener.reset(); // throw syncError; // } // // if (!myGradleProjectEventListener.isSyncSkipped()) { // waitForBuildToFinish(SOURCE_GEN); // } // // waitForBackgroundTasksToFinish(); //} @NotNull public IdeFrameFixture waitForBackgroundTasksToFinish() { DumbService.getInstance(getProject()).waitForSmartMode(); return this; } @NotNull public IdeFrameFixture waitForStartingIndexing() { return waitForStartingIndexing(20); } @NotNull public IdeFrameFixture waitForStartingIndexing(int secondsToWait) { try { pause(new Condition("Indexing to start") { @Override public boolean test() { ProgressManager progressManager = ProgressManager.getInstance(); return progressManager.hasModalProgressIndicator() || progressManager.hasProgressIndicator() || progressManager.hasUnsafeProgressIndicator(); } } , Timeout.timeout(secondsToWait, TimeUnit.SECONDS)); } catch (WaitTimedOutError ignored) { } robot().waitForIdle(); return this; } @NotNull private ActionButtonFixture findActionButtonByActionId(String actionId) { return ActionButtonFixture.Companion.fixtureByActionId(target(), robot(), actionId); } @NotNull public MessagesToolWindowFixture getMessagesToolWindow() { return new MessagesToolWindowFixture(getProject(), robot()); } @NotNull public EditorNotificationPanelFixture requireEditorNotification(@NotNull final String message) { final Ref<EditorNotificationPanel> notificationPanelRef = new Ref<>(); pause(new Condition("Notification with message '" + message + "' shows up") { @Override public boolean test() { EditorNotificationPanel notificationPanel = findNotificationPanel(message); notificationPanelRef.set(notificationPanel); return notificationPanel != null; } }); EditorNotificationPanel notificationPanel = notificationPanelRef.get(); assertNotNull(notificationPanel); return new EditorNotificationPanelFixture(robot(), notificationPanel); } public void requireNoEditorNotification() { assertNull(findNotificationPanel(null)); } /** * Locates an editor notification with the given main message (unless the message is {@code null}, in which case we assert that there are * no visible editor notifications. Will fail if the given notification is not found. */ @Nullable private EditorNotificationPanel findNotificationPanel(@Nullable String message) { Collection<EditorNotificationPanel> panels = robot().finder().findAll(target(), new GenericTypeMatcher<EditorNotificationPanel>( EditorNotificationPanel.class, true) { @Override protected boolean isMatching(@NotNull EditorNotificationPanel panel) { return panel.isShowing(); } }); if (message == null) { if (!panels.isEmpty()) { List<String> labels = new ArrayList<>(); for (EditorNotificationPanel panel : panels) { labels.addAll(getEditorNotificationLabels(panel)); } fail("Found editor notifications when none were expected" + labels); } return null; } List<String> labels = new ArrayList<>(); for (EditorNotificationPanel panel : panels) { List<String> found = getEditorNotificationLabels(panel); labels.addAll(found); for (String label : found) { if (label.contains(message)) { return panel; } } } return null; } /** * Looks up the main label for a given editor notification panel */ private List<String> getEditorNotificationLabels(@NotNull EditorNotificationPanel panel) { final List<String> allText = new ArrayList<>(); final Collection<JLabel> labels = robot().finder().findAll(panel, JLabelMatcher.any().andShowing()); for (final JLabel label : labels) { String text = execute(new GuiQuery<String>() { @Override @Nullable protected String executeInEDT() throws Throwable { return label.getText(); } }); if (isNotEmpty(text)) { allText.add(text); } } return allText; } @NotNull public IdeSettingsDialogFixture openIdeSettings() { // Using invokeLater because we are going to show a *modal* dialog via API (instead of clicking a button, for example.) If we use // GuiActionRunner the test will hang until the modal dialog is closed. ApplicationManager.getApplication().invokeLater(() -> { Project project = getProject(); ShowSettingsUtil.getInstance().showSettingsDialog(project, ShowSettingsUtilImpl.getConfigurableGroups(project, true)); }); return IdeSettingsDialogFixture.find(robot()); } @NotNull public RunConfigurationsDialogFixture invokeRunConfigurationsDialog() { invokeMenuPath("Run", "Edit Configurations..."); return RunConfigurationsDialogFixture.find(robot()); } @NotNull public InspectionsFixture inspectCode() { invokeMenuPath("Analyze", "Inspect Code..."); //final Ref<FileChooserDialogImpl> wrapperRef = new Ref<FileChooserDialogImpl>(); JDialog dialog = robot().finder().find(new GenericTypeMatcher<JDialog>(JDialog.class) { @Override protected boolean isMatching(@NotNull JDialog dialog) { return "Specify Inspection Scope".equals(dialog.getTitle()); } }); JButton button = robot().finder().find(dialog, JButtonMatcher.withText("OK").andShowing()); robot().click(button); final InspectionTree tree = GuiTestUtil.INSTANCE.waitUntilFound(robot(), new GenericTypeMatcher<InspectionTree>(InspectionTree.class) { @Override protected boolean isMatching(@NotNull InspectionTree component) { return true; } }); return new InspectionsFixture(robot(), getProject(), tree); } @NotNull public ProjectViewFixture getProjectView() { return new ProjectViewFixture(getProject(), robot()); } @NotNull public Project getProject() { Project project = Objects.requireNonNull(ProjectFrameHelper.getFrameHelper(target())).getProject(); assertNotNull(project); return project; } public void closeProjectAndWaitWelcomeFrame() { closeProjectAndWaitWelcomeFrame(true); } public void closeProjectAndWaitWelcomeFrame(boolean waitWelcomeFrame) { closeProject(); if (!waitWelcomeFrame) return; pause(new Condition("Waiting for 'Welcome' page to show up") { @Override public boolean test() { for (Frame frame : Frame.getFrames()) { if (frame instanceof FlatWelcomeFrame && frame.isShowing()) { return true; } } return false; } }, Timeouts.INSTANCE.getMinutes01()); } public void closeProject() { CloseProjectAction closeAction = new CloseProjectAction(); AnActionEvent actionEvent = AnActionEvent.createFromAnAction(closeAction, null, "", DataManager.getInstance().getDataContext(target().getRootPane())); DumbService.getInstance(getProject()).smartInvokeLater(() -> closeAction.actionPerformed(actionEvent)); } @NotNull public MessagesFixture findMessageDialog(@NotNull String title) { return MessagesFixture.findByTitle(robot(), target(), title); } @NotNull public FindToolWindowFixture getFindToolWindow() { return new FindToolWindowFixture(this); } //@NotNull //public GradleBuildModelFixture parseBuildFileForModule(@NotNull String moduleName, boolean openInEditor) { // Module module = getModule(moduleName); // return parseBuildFile(module, openInEditor); //} // //@NotNull //public GradleBuildModelFixture parseBuildFile(@NotNull Module module, boolean openInEditor) { // VirtualFile buildFile = getGradleBuildFile(module); // assertNotNull(buildFile); // return parseBuildFile(buildFile, openInEditor); //} // //@NotNull //public GradleBuildModelFixture parseBuildFile(@NotNull final VirtualFile buildFile, boolean openInEditor) { // if (openInEditor) { // getEditor().open(buildFile, Tab.DEFAULT).getCurrentFile(); // } // final Ref<GradleBuildModel> buildModelRef = new Ref<GradleBuildModel>(); // new ReadAction() { // @Override // protected void run(@NotNull Result result) throws Throwable { // buildModelRef.set(GradleBuildModel.parseBuildFile(buildFile, getProject())); // } // }.execute(); // GradleBuildModel buildModel = buildModelRef.get(); // assertNotNull(buildModel); // return new GradleBuildModelFixture(buildModel); //} private static class NoOpDisposable implements Disposable { @Override public void dispose() { } } public void selectApp(@NotNull String appName) { final ActionButtonFixture runButton = findRunApplicationButton(); Container actionToolbarContainer = execute(new GuiQuery<Container>() { @Override protected Container executeInEDT() throws Throwable { return runButton.target().getParent(); } }); assertNotNull(actionToolbarContainer); ComboBoxActionFixture comboBoxActionFixture = ComboBoxActionFixture.Companion.findComboBox(robot(), actionToolbarContainer); comboBoxActionFixture.selectItem(appName); robot().pressAndReleaseKey(KeyEvent.VK_ENTER); robot().waitForIdle(); } ///////////////////////////////////////////////////////////////// //// Methods to help control debugging under a test. /////// ///////////////////////////////////////////////////////////////// public void resumeProgram() { GuiTestUtil.INSTANCE.invokeMenuPathOnRobotIdle(this, "Run", "Resume Program"); } public void stepOver() { GuiTestUtil.INSTANCE.invokeMenuPathOnRobotIdle(this, "Run", "Step Over"); } public void stepInto() { GuiTestUtil.INSTANCE.invokeMenuPathOnRobotIdle(this, "Run", "Step Into"); } public void stepOut() { GuiTestUtil.INSTANCE.invokeMenuPathOnRobotIdle(this, "Run", "Step Out"); } /** * Toggles breakpoints at the line numbers in {@code lines} of the source file with basename {@code fileBaseName}. This will work only * if the fileBasename is unique in the project that's open on Android Studio. */ public void toggleBreakPoints(String fileBasename, int[] lines) { // We open the file twice to bring the editor into focus. Idea 1.15 has this bug where opening a file doesn't automatically bring its // editor window into focus. GuiTestUtil.INSTANCE.openFile(this, fileBasename); GuiTestUtil.INSTANCE.openFile(this, fileBasename); for (int line : lines) { GuiTestUtil.INSTANCE.navigateToLine(this, line); GuiTestUtil.INSTANCE.invokeMenuPathOnRobotIdle(this, "Run", "Toggle Line Breakpoint"); } } // Recursively prints out the debugger tree rooted at {@code node} into {@code builder} with an indent of // "{@code level} * {@code numIndentSpaces}" whitespaces. Each node is printed on a separate line. The indent level for every child node // is 1 more than their parent. private static void printNode(XDebuggerTreeNode node, StringBuilder builder, int level, int numIndentSpaces) { if (builder.length() > 0) { builder.append(System.getProperty("line.separator")); } for (int i = 0; i < level * numIndentSpaces; ++i) { builder.append(' '); } builder.append(node.getText().toString()); Enumeration<XDebuggerTreeNode> children = node.children(); while (children.hasMoreElements()) { printNode(children.nextElement(), builder, level + 1, numIndentSpaces); } } /** * Prints out the debugger tree rooted at {@code root}. */ @NotNull public static String printDebuggerTree(XDebuggerTreeNode root) { StringBuilder builder = new StringBuilder(); printNode(root, builder, 0, 2); return builder.toString(); } private static String @NotNull [] debuggerTreeRootToChildrenTexts(XDebuggerTreeNode treeRoot) { List<? extends TreeNode> children = treeRoot.getChildren(); String[] childrenTexts = new String[children.size()]; int i = 0; for (TreeNode child : children) { childrenTexts[i] = ((XDebuggerTreeNode)child).getText().toString(); ++i; } return childrenTexts; } /** * Returns the subset of {@code expectedPatterns} which do not match any of the children (just the first level children, not recursive) of * {@code treeRoot} . */ @NotNull public static List<String> getUnmatchedTerminalVariableValues(String[] expectedPatterns, XDebuggerTreeNode treeRoot) { String[] childrenTexts = debuggerTreeRootToChildrenTexts(treeRoot); List<String> unmatchedPatterns = new ArrayList<>(); for (String expectedPattern : expectedPatterns) { boolean matched = false; for (String childText : childrenTexts) { if (childText.matches(expectedPattern)) { matched = true; break; } } if (!matched) { unmatchedPatterns.add(expectedPattern); } } return unmatchedPatterns; } /** * Returns the appropriate pattern to look for a variable named {@code name} with the type {@code type} and value {@code value} appearing * in the Variables window in Android Studio. */ @NotNull public static String variableToSearchPattern(String name, String type, String value) { return String.format("%s = \\{%s\\} %s", name, type, value); } public boolean verifyVariablesAtBreakpoint(String[] expectedVariablePatterns, String debugConfigName, long tryUntilMillis) { DebugToolWindowFixture debugToolWindowFixture = new DebugToolWindowFixture(this); final ExecutionToolWindowFixture.ContentFixture contentFixture = debugToolWindowFixture.findContent(debugConfigName); contentFixture.clickDebuggerTreeRoot(); // Wait for the debugger tree to appear. pause(new Condition("Looking for debugger tree.") { @Override public boolean test() { return contentFixture.getDebuggerTreeRoot() != null; } }, Timeout.timeout(tryUntilMillis)); // Get the debugger tree and print it. XDebuggerTreeNode debuggerTreeRoot = contentFixture.getDebuggerTreeRoot(); if (debuggerTreeRoot == null) { return false; } List<String> unmatchedPatterns = getUnmatchedTerminalVariableValues(expectedVariablePatterns, debuggerTreeRoot); return unmatchedPatterns.isEmpty(); } }
package org.freecode.irc.votebot; import org.freecode.irc.CtcpRequest; import org.freecode.irc.CtcpResponse; import org.freecode.irc.IrcConnection; import org.freecode.irc.Privmsg; import org.freecode.irc.event.CtcpRequestListener; import org.freecode.irc.event.JoinListener; import org.freecode.irc.event.NumericListener; import org.freecode.irc.event.PrivateMessageListener; import org.freecode.irc.votebot.api.AdminModule; import org.freecode.irc.votebot.api.FVBModule; import org.freecode.irc.votebot.dao.PollDAO; import org.freecode.irc.votebot.dao.VoteDAO; import org.freecode.irc.votebot.entity.Poll; import org.freecode.irc.votebot.entity.Vote; import org.freecode.irc.votebot.modules.admin.LoadModules; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.sql.SQLException; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.*; import java.util.concurrent.*; /** * User: Shivam * Date: 17/06/13 * Time: 00:05 */ public class FreeVoteBot implements PrivateMessageListener, JoinListener { public static final String CHANNEL_SOURCE = "#freecode"; private String[] channels; private String nick, realName, serverHost, user; private int port; private ScriptModuleLoader sml; private IrcConnection connection; private String version; private ExpiryQueue<String> expiryQueue = new ExpiryQueue<>(1500L); private LinkedList<FVBModule> moduleList = new LinkedList<>(); private PollDAO pollDAO; private VoteDAO voteDAO; public ScheduledExecutorService pollExecutor; public HashMap<Integer, Future> pollFutures; private KVStore kvStore; public void init() { connectToIRCServer(); NoticeFilter.setFilterQueue(connection, 5000L); addNickInUseListener(); registerUser(); addCTCPRequestListener(); try { Thread.sleep(10000L); } catch (InterruptedException e) { e.printStackTrace(); } identifyToNickServ(); joinChannels(); kvStore.load(); sml = new ScriptModuleLoader(this); AdminModule mod = new LoadModules(); mod.setFvb(this); moduleList.add(mod); pollExecutor = Executors.newScheduledThreadPool(5); pollFutures = new HashMap<>(); try { for (Poll poll : pollDAO.getOpenPolls()) { long expiry = poll.getExpiry(); int id = poll.getId(); PollExpiryAnnouncer announcer = new PollExpiryAnnouncer(expiry, id, this); ScheduledFuture future = pollExecutor.scheduleAtFixedRate(announcer, 60000L, 500L, TimeUnit.MILLISECONDS); announcer.setFuture(future); pollFutures.put(id, future); } } catch (SQLException e) { e.printStackTrace(); } } private void registerUser() { try { connection.register(nick, user, realName); } catch (IOException e) { e.printStackTrace(); } connection.addListener(this); } private void addNickInUseListener() { NumericListener nickInUse = new NumericListener(connection) { public int getNumeric() { return IrcConnection.ERR_NICKNAMEINUSE; } public void execute(String rawLine) { FreeVoteBot.this.nick = FreeVoteBot.this.nick + "_"; try { connection.sendRaw("NICK " + FreeVoteBot.this.nick); } catch (IOException e) { e.printStackTrace(); } } }; connection.addListener(nickInUse); } private void addCTCPRequestListener() { connection.addListener(new CtcpRequestListener() { public void onCtcpRequest(CtcpRequest request) { if (request.getCommand().equals("VERSION")) { request.getIrcConnection().send(new CtcpResponse(request.getIrcConnection(), request.getNick(), "VERSION", "FreeVoteBot " + version + " by " + CHANNEL_SOURCE + " on irc.rizon.net")); } else if (request.getCommand().equals("PING")) { request.getIrcConnection().send(new CtcpResponse(request.getIrcConnection(), request.getNick(), "PING", request.getArguments())); } } }); } private void connectToIRCServer() { try { connection = new IrcConnection(serverHost, port); } catch (IOException e) { e.printStackTrace(); } } private void identifyToNickServ() { File pass = new File("password.txt"); if (pass.exists()) { try { BufferedReader read = new BufferedReader(new FileReader(pass)); String s = read.readLine(); if (s != null) { connection.send(new Privmsg("NickServ", "identify " + s, connection)); } read.close(); } catch (IOException e) { e.printStackTrace(); } } } private void joinChannels() { for (String channel : channels) { connection.joinChannel(channel); } } public void onPrivmsg(final Privmsg privmsg) { if (privmsg.getNick().equalsIgnoreCase(nick)) { return; } String sender = privmsg.getNick().toLowerCase(); if (expiryQueue.contains(sender) || !expiryQueue.insert(sender)) { return; } for (FVBModule module : moduleList) { try { if (module.isEnabled() && module.canRun(privmsg)) { module.process(privmsg); return; } } catch (Exception e) { privmsg.send(e.getMessage()); } } } public void setNick(String nick) { this.nick = nick; } public void setRealName(String realName) { this.realName = realName; } public void setServerHost(String serverHost) { this.serverHost = serverHost; } public void setUser(String user) { this.user = user; } public void setPort(String port) { this.port = Integer.parseInt(port); } public void setChannels(String channels) { this.channels = channels.split(","); } public void setKvStore(KVStore kvStore) { this.kvStore = kvStore; } public void setModules(final FVBModule[] modules) { moduleList.clear(); moduleList.addAll(Arrays.asList(modules)); for (FVBModule module : moduleList) { if (module instanceof AdminModule) { ((AdminModule) module).setFvb(this); } } } public void setVersion(String version) { this.version = version; } public boolean addModule(final FVBModule module) { return moduleList.add(module); } public void addModules(final Collection<? extends FVBModule> module) { moduleList.addAll(module); for (FVBModule mod : moduleList) { if (mod instanceof AdminModule) { ((AdminModule) mod).setFvb(this); } } } public boolean removeModule(final FVBModule module) { return moduleList.remove(module); } public void removeModules(final Collection<? extends FVBModule> module) { moduleList.removeAll(module); } public ScriptModuleLoader getScriptModuleLoader() { return sml; } public void sendMsg(String s) { for (String channel : channels) { connection.sendMessage(channel, s); } } public void setPollDAO(PollDAO pollDAO) { this.pollDAO = pollDAO; } public PollDAO getPollDAO() { return pollDAO; } public void setVoteDAO(VoteDAO voteDAO) { this.voteDAO = voteDAO; } public VoteDAO getVoteDAO() { return voteDAO; } private DateFormat getDateFormatter() { DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z", Locale.UK); dateFormat.setTimeZone(TimeZone.getTimeZone("Europe/London")); return dateFormat; } static class PollVotes implements Comparable<PollVotes> { int votes; String question; PollVotes(int votes, String question) { this.votes = votes; this.question = question; } public int compareTo(PollVotes o) { return o.votes - votes; } } @Override public void onJoin(String channel, String nick, String mask) { System.out.println(nick + " joins " + channel); try { Poll[] openPolls = pollDAO.getOpenPolls(); Poll[] pollsNotVotedIn = voteDAO.getPollsNotVotedIn(openPolls, nick); PollVotes[] pollVotes = new PollVotes[pollsNotVotedIn.length]; for (int i = 0; i < pollsNotVotedIn.length; i++) { Poll poll = pollsNotVotedIn[i]; String question = poll.getQuestion(); int id = poll.getId(); long expiry = poll.getExpiry(); Date date = new Date(expiry); Vote[] votes = voteDAO.getVotesOnPoll(id); String msg = String.format("Open poll #%d: \"%s\", ends: %s, votes: %d", id, question, getDateFormatter().format(date), votes.length); pollVotes[i] = new PollVotes(votes.length, msg); } if (pollVotes.length == 0) { connection.sendNotice(nick, "No new polls to vote in!"); } else { Arrays.sort(pollVotes); connection.sendNotice(nick, "Trending polls list:"); if (pollVotes.length >= 3) { connection.sendNotice(nick, pollVotes[0].question); connection.sendNotice(nick, pollVotes[1].question); connection.sendNotice(nick, pollVotes[2].question); } else { for (PollVotes p : pollVotes) { connection.sendNotice(nick, p.question); } } } } catch (SQLException e) { e.printStackTrace(); } } }
package com.grapecity.debugrank.ui.solve; import android.app.Activity; import android.content.Intent; import android.content.res.Resources; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.support.annotation.DrawableRes; import android.support.annotation.NonNull; import android.support.annotation.StringRes; import android.support.design.widget.TabLayout; import android.support.v4.content.ContextCompat; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.ImageView; import android.widget.Toast; import com.afollestad.materialdialogs.DialogAction; import com.afollestad.materialdialogs.MaterialDialog; import com.github.amlcurran.showcaseview.ShowcaseView; import com.github.amlcurran.showcaseview.targets.ActionViewTarget; import com.github.amlcurran.showcaseview.targets.ViewTarget; import com.grapecity.debugrank.javalib.entities.AggregatedBugsPoints; import com.grapecity.debugrank.javalib.entities.CodeLine; import com.grapecity.debugrank.javalib.entities.CompletedPuzzle; import com.grapecity.debugrank.javalib.entities.TestCaseResult; import com.grapecity.debugrank.javalib.ui.solve.ISolvePresenter; import com.grapecity.debugrank.javalib.ui.solve.ISolveView; import java.util.List; import javax.inject.Inject; import butterknife.Bind; import com.grapecity.debugrank.MyApp; import com.grapecity.debugrank.R; import com.grapecity.debugrank.services.image.IImageLoadingService; import com.grapecity.debugrank.ui.misc.NonSwipeableViewPager; import com.grapecity.debugrank.ui.base.BaseActivity; import com.grapecity.debugrank.ui.languages.LanguagesActivity; import com.grapecity.debugrank.ui.misc.like.LikeButtonView; import com.grapecity.debugrank.ui.misc.timer.ITimerCompletedListener; import com.grapecity.debugrank.ui.solve.code.SolveCodeFragment; import com.grapecity.debugrank.ui.solve.result.SolveResultFragment; public class SolveActivity extends BaseActivity implements ISolveView, ITimerCompletedListener { final Activity activity = this; @Bind(R.id.tabViewPageParent) View tabViewPageParent; @Bind(R.id.tabs) TabLayout tabLayout; @Bind(R.id.viewpager) NonSwipeableViewPager viewPager; @Inject ISolvePresenter solvePresenter; @Inject IImageLoadingService imageLoadingService; SolveViewPagerAdapter adapter; boolean codeLoaded = false; ShowcaseView compileShowcaseView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); ((MyApp) getApplication()).getSolveComponent().inject(this); setImageDrawable(getFab(), R.drawable.ic_file_upload_white_24dp); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { uploadCode(); } }); hideActionBar(); aggregatedBugPointsLoaded(new AggregatedBugsPoints(puzzle.bugs, puzzle.points)); timerTextView.setTimeInSeconds(puzzle.time); timerTextView.setOnCompletedListener(this); attachView(); setupViewPager(); //hide fab till code loaded hideFab(); Button button = new Button(this); button.setVisibility(View.GONE); } @Override protected void dataLoadedSuccessfully() { super.dataLoadedSuccessfully(); showFab(); } @Override protected void onDestroy() { super.onDestroy(); if (timerTextView != null) { timerTextView.stopTimer(); } } @Override protected void onPause() { super.onPause(); if (timerTextView != null) { timerTextView.stopTimer(); } } @Override protected void onResume() { super.onResume(); //if resuming the activity and the code was previously loaded if (codeLoaded) { if (timerTextView != null) { timerTextView.startTimer(); } } } @Override protected void attachView() { solvePresenter.attachView(this); } private void setupViewPager() { Resources resources = getResources(); SolveCodeFragment solveCodeFragment = new SolveCodeFragment(); SolveResultFragment solveResultFragment = new SolveResultFragment(); adapter = new SolveViewPagerAdapter(getSupportFragmentManager()); adapter.addFragment(solveCodeFragment, resources.getString(R.string.code)); adapter.addFragment(solveResultFragment, resources.getString(R.string.result)); viewPager.setAdapter(adapter); tabLayout.setupWithViewPager(viewPager); solvePresenter.attachView(solveCodeFragment); solvePresenter.attachView(solveResultFragment); } @Override protected int getContentAreaLayoutId() { return R.layout.content_solve; } @Override public void solveCodeLoaded() { codeLoaded = true; timerTextView.startTimer(); super.dataLoadedSuccessfully(); //don't allow code to be refresh anymore swipeRefreshLayout.setEnabled(false); showFab(); } @Override public void unableToLoadSolveCode() { super.dataLoadedFailure(); } @Override public void unableToUploadAndCompileCode() { Toast.makeText(this, R.string.internet_error, Toast.LENGTH_LONG).show(); enableFabForUpload(); updateResultTabTitle(getResources().getString(R.string.internet_no)); } @Override public void codeCompiling() { //set FAB to uploading setImageDrawable(getFab(), R.drawable.ic_sync_white_24dp); getFab().setEnabled(false); //set tab title to uploading updateResultTabTitle(getResources().getString(R.string.uploading)); } @Override public void codeCompiled(List<TestCaseResult> result, boolean passed, int numberPassedTestCases) { showcaseStep2(); //compile error if (result != null && !passed && numberPassedTestCases == 0 && result.size() > 0 && result.get(0).isCompileError()) { updateResultTabTitle(getResources().getString(R.string.compile_error)); } //valid code else { updateResultTabTitle(String.format(getResources().getString(R.string.passed_test_cases), numberPassedTestCases, puzzle.answers.length)); } if (passed || timerTextView.isCompleted()) { if (!passed && timerTextView.isCompleted()) { showDialog(false); } timerTextView.stopTimer(); hideFab(); } else { enableFabForUpload(); } } private void enableFabForUpload() { setImageDrawable(getFab(), R.drawable.ic_file_upload_white_24dp); getFab().setEnabled(true); } @Override public void puzzleSolved(CompletedPuzzle result) { showDialog(true); } private void showDialog(boolean passed) { MaterialDialog.Builder builder = new MaterialDialog.Builder(this); LikeButtonView likeView = null; if (passed) { likeView = new LikeButtonView(this); builder .title(String.format(getResources().getString(R.string.points).replaceAll("\n", " "), puzzle.points)) .customView(likeView, false); } else { builder .title(getResources().getString(R.string.out_of_time)) .customView(R.layout.view_time_out, false); } builder .cancelable(false) .positiveText(R.string.ok) .onPositive(new MaterialDialog.SingleButtonCallback() { @Override public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) { Intent intent = getIntent(LanguagesActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK); activity.startActivity(intent); } }) .show(); if (passed) { //automatically trigger the like animation likeView.performClick(); likeView.setEnabled(false); } } private void uploadCode() { showcaseStep1Clicked(); //called whenever FAB is clicked to perform an upload, or the time runs out so we need to automatically upload solvePresenter.uploadCode(); } private void updateResultTabTitle(String newTitle) { tabLayout.getTabAt(1).setText(newTitle); } @Override public void timeRanOut() { //called when time runs out uploadCode(); } @Override public void beginEditing(CodeLine codeLine) { //hide fab when editing code hideFab(); } @Override public void finishEditing(CodeLine codeLine) { //show fab when done editing code showFab(); } private void setImageDrawable(ImageView imageView, @DrawableRes int resourceId) { imageLoadingService.setDrawable(imageView, resourceId); } @Override public void onRefresh() { if (!codeLoaded) { solvePresenter.loadCode(); } } @Override public void showTutorial() { //presenter will tell view that tutorial must be shown showShowcase(new ViewTarget(R.id.fab, this), R.string.showcase_step1_title, R.string.showcase_step1_desc); } //when fab is clicked this is called private void showcaseStep1Clicked() { hideShowcase(); } //when code is compile this is called private void showcaseStep2() { if(compileShowcaseView != null) { final View compileTab = ((ViewGroup) tabLayout.getChildAt(0)).getChildAt(1); compileTab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { compileTab.setOnClickListener(null); showcaseStep2Clicked(); } }); showShowcase(new ViewTarget(compileTab), R.string.showcase_step2_title, R.string.showcase_step2_desc); } } private void showcaseStep2Clicked() { hideShowcase(); new Handler(Looper.getMainLooper()).postDelayed(new Runnable() { @Override public void run() { showcaseStep3(); } }, 2500); } private void showcaseStep3() { final View codeTab = ((ViewGroup) tabLayout.getChildAt(0)).getChildAt(0); codeTab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { codeTab.setOnClickListener(null); hideShowcase(); compileShowcaseView = null; } }); showShowcase(new ViewTarget(codeTab), R.string.showcase_step3_title, R.string.showcase_step3_desc); } private void showShowcase(ViewTarget viewTarget, @StringRes int titleResId, @StringRes int descriptionResId) { Button button = new Button(this); button.setVisibility(View.GONE); compileShowcaseView = new ShowcaseView.Builder(this) .withNewStyleShowcase() .setStyle(R.style.CustomShowcaseTheme2) .setTarget(viewTarget) .setContentTitle(titleResId) .setContentText(descriptionResId) .replaceEndButton(button) .build(); } private void hideShowcase() { if (compileShowcaseView != null && compileShowcaseView.isShowing()) { compileShowcaseView.hide(); } } }
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. package org.chromium.chrome.browser.webapps; import android.content.Intent; import android.graphics.Bitmap; import android.net.Uri; import android.util.Log; import org.chromium.chrome.browser.ShortcutHelper; import org.chromium.chrome.browser.ShortcutSource; import org.chromium.chrome.browser.util.IntentUtils; import org.chromium.content_public.common.ScreenOrientationValues; /** * Stores info about a web app. */ public class WebappInfo { private boolean mIsInitialized; private String mId; private String mEncodedIcon; private Bitmap mDecodedIcon; private Uri mUri; private String mName; private String mShortName; private int mOrientation; private int mSource; private long mThemeColor; private long mBackgroundColor; public static WebappInfo createEmpty() { return new WebappInfo(); } private static String titleFromIntent(Intent intent) { // The reference to title has been kept for reasons of backward compatibility. For intents // and shortcuts which were created before we utilized the concept of name and shortName, // we set the name and shortName to be the title. String title = IntentUtils.safeGetStringExtra(intent, ShortcutHelper.EXTRA_TITLE); return title == null ? "" : title; } public static String nameFromIntent(Intent intent) { String name = IntentUtils.safeGetStringExtra(intent, ShortcutHelper.EXTRA_NAME); return name == null ? titleFromIntent(intent) : name; } public static String shortNameFromIntent(Intent intent) { String shortName = IntentUtils.safeGetStringExtra(intent, ShortcutHelper.EXTRA_SHORT_NAME); return shortName == null ? titleFromIntent(intent) : shortName; } /** * Construct a WebappInfo. * @param intent Intent containing info about the app. */ public static WebappInfo create(Intent intent) { String id = IntentUtils.safeGetStringExtra(intent, ShortcutHelper.EXTRA_ID); String icon = IntentUtils.safeGetStringExtra(intent, ShortcutHelper.EXTRA_ICON); String url = IntentUtils.safeGetStringExtra(intent, ShortcutHelper.EXTRA_URL); int orientation = IntentUtils.safeGetIntExtra(intent, ShortcutHelper.EXTRA_ORIENTATION, ScreenOrientationValues.DEFAULT); int source = IntentUtils.safeGetIntExtra(intent, ShortcutHelper.EXTRA_SOURCE, ShortcutSource.UNKNOWN); long themeColor = IntentUtils.safeGetLongExtra(intent, ShortcutHelper.EXTRA_THEME_COLOR, ShortcutHelper.MANIFEST_COLOR_INVALID_OR_MISSING); long backgroundColor = IntentUtils.safeGetLongExtra(intent, ShortcutHelper.EXTRA_BACKGROUND_COLOR, ShortcutHelper.MANIFEST_COLOR_INVALID_OR_MISSING); String name = nameFromIntent(intent); String shortName = shortNameFromIntent(intent); return create(id, url, icon, name, shortName, orientation, source, themeColor, backgroundColor); } /** * Construct a WebappInfo. * @param id ID for the webapp. * @param url URL for the webapp. * @param icon Icon to show for the webapp. * @param name Name of the webapp. * @param shortName The short name of the webapp. * @param orientation Orientation of the webapp. * @param source Source where the webapp was added from. * @param themeColor The theme color of the webapp. */ public static WebappInfo create(String id, String url, String icon, String name, String shortName, int orientation, int source, long themeColor, long backgroundColor) { if (id == null || url == null) { Log.e("WebappInfo", "Data passed in was incomplete: " + id + ", " + url); return null; } Uri uri = Uri.parse(url); return new WebappInfo(id, uri, icon, name, shortName, orientation, source, themeColor, backgroundColor); } private WebappInfo(String id, Uri uri, String encodedIcon, String name, String shortName, int orientation, int source, long themeColor, long backgroundColor) { mEncodedIcon = encodedIcon; mId = id; mName = name; mShortName = shortName; mUri = uri; mOrientation = orientation; mSource = source; mThemeColor = themeColor; mBackgroundColor = backgroundColor; mIsInitialized = mUri != null; } private WebappInfo() { } /** * Copies all the fields from the given WebappInfo into this instance. * @param newInfo Information about the new webapp. */ void copy(WebappInfo newInfo) { mIsInitialized = newInfo.mIsInitialized; mEncodedIcon = newInfo.mEncodedIcon; mDecodedIcon = newInfo.mDecodedIcon; mId = newInfo.mId; mUri = newInfo.mUri; mName = newInfo.mName; mShortName = newInfo.mShortName; mOrientation = newInfo.mOrientation; mSource = newInfo.mSource; mThemeColor = newInfo.mThemeColor; mBackgroundColor = newInfo.mBackgroundColor; } public boolean isInitialized() { return mIsInitialized; } public String id() { return mId; } public Uri uri() { return mUri; } public String name() { return mName; } public String shortName() { return mShortName; } public int orientation() { return mOrientation; } public int source() { return mSource; } /** * Theme color is actually a 32 bit unsigned integer which encodes a color * in ARGB format. mThemeColor is a long because we also need to encode the * error state of ShortcutHelper.MANIFEST_COLOR_INVALID_OR_MISSING. */ public long themeColor() { return mThemeColor; } /** * Background color is actually a 32 bit unsigned integer which encodes a color * in ARGB format. mBackgroundColor is a long because we also need to encode the * error state of ShortcutHelper.MANIFEST_COLOR_INVALID_OR_MISSING. */ public long backgroundColor() { return mBackgroundColor; } /** * Returns the background color specified by {@link #backgroundColor()} if the value is * not ShortcutHelper.MANIFEST_COLOR_INVALID_OR_MISSING. Returns the specified fallback color * otherwise. */ public int backgroundColor(int fallback) { if (mBackgroundColor == ShortcutHelper.MANIFEST_COLOR_INVALID_OR_MISSING) { return fallback; } return (int) mBackgroundColor; } // This is needed for clients that want to send the icon trough an intent. public String encodedIcon() { return mEncodedIcon; } /** * Returns the icon in Bitmap form. Caches the result for future retrievals. */ public Bitmap icon() { if (mDecodedIcon != null) return mDecodedIcon; mDecodedIcon = ShortcutHelper.decodeBitmapFromString(mEncodedIcon); return mDecodedIcon; } /** * Sets extras on an Intent that will launch a WebappActivity. * @param intent Intent that will be used to launch a WebappActivity. */ public void setWebappIntentExtras(Intent intent) { intent.putExtra(ShortcutHelper.EXTRA_ID, id()); intent.putExtra(ShortcutHelper.EXTRA_URL, uri().toString()); intent.putExtra(ShortcutHelper.EXTRA_ICON, encodedIcon()); intent.putExtra(ShortcutHelper.EXTRA_NAME, name()); intent.putExtra(ShortcutHelper.EXTRA_SHORT_NAME, shortName()); intent.putExtra(ShortcutHelper.EXTRA_ORIENTATION, orientation()); intent.putExtra(ShortcutHelper.EXTRA_SOURCE, source()); intent.putExtra(ShortcutHelper.EXTRA_THEME_COLOR, themeColor()); intent.putExtra(ShortcutHelper.EXTRA_BACKGROUND_COLOR, backgroundColor()); } }
package com.alibaba.csp.sentinel.datasource.zookeeper; import com.alibaba.csp.sentinel.concurrent.NamedThreadFactory; import com.alibaba.csp.sentinel.datasource.AbstractDataSource; import com.alibaba.csp.sentinel.datasource.Converter; import com.alibaba.csp.sentinel.log.RecordLog; import com.alibaba.csp.sentinel.util.StringUtil; import org.apache.curator.framework.AuthInfo; import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.recipes.cache.ChildData; import org.apache.curator.framework.recipes.cache.NodeCache; import org.apache.curator.framework.recipes.cache.NodeCacheListener; import org.apache.curator.retry.ExponentialBackoffRetry; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; /** * A read-only {@code DataSource} with ZooKeeper backend. * * @author guonanjun */ public class ZookeeperDataSource<T> extends AbstractDataSource<String, T> { private static final int RETRY_TIMES = 3; private static final int SLEEP_TIME = 1000; private static volatile Map<String, CuratorFramework> zkClientMap = new HashMap<>(); private static final Object lock = new Object(); private final ExecutorService pool = new ThreadPoolExecutor(1, 1, 0, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(1), new NamedThreadFactory("sentinel-zookeeper-ds-update", true), new ThreadPoolExecutor.DiscardOldestPolicy()); private NodeCacheListener listener; private final String path; private CuratorFramework zkClient = null; private NodeCache nodeCache = null; public ZookeeperDataSource(final String serverAddr, final String path, Converter<String, T> parser) { super(parser); if (StringUtil.isBlank(serverAddr) || StringUtil.isBlank(path)) { throw new IllegalArgumentException(String.format("Bad argument: serverAddr=[%s], path=[%s]", serverAddr, path)); } this.path = path; init(serverAddr, null); } /** * This constructor is Nacos-style. */ public ZookeeperDataSource(final String serverAddr, final String groupId, final String dataId, Converter<String, T> parser) { super(parser); if (StringUtil.isBlank(serverAddr) || StringUtil.isBlank(groupId) || StringUtil.isBlank(dataId)) { throw new IllegalArgumentException(String.format("Bad argument: serverAddr=[%s], groupId=[%s], dataId=[%s]", serverAddr, groupId, dataId)); } this.path = getPath(groupId, dataId); init(serverAddr, null); } /** * This constructor adds authentication information. */ public ZookeeperDataSource(final String serverAddr, final List<AuthInfo> authInfos, final String groupId, final String dataId, Converter<String, T> parser) { super(parser); if (StringUtil.isBlank(serverAddr) || StringUtil.isBlank(groupId) || StringUtil.isBlank(dataId)) { throw new IllegalArgumentException(String.format("Bad argument: serverAddr=[%s], authInfos=[%s], groupId=[%s], dataId=[%s]", serverAddr, authInfos, groupId, dataId)); } this.path = getPath(groupId, dataId); init(serverAddr, authInfos); } private void init(final String serverAddr, final List<AuthInfo> authInfos) { initZookeeperListener(serverAddr, authInfos); loadInitialConfig(); } private void loadInitialConfig() { try { T newValue = loadConfig(); if (newValue == null) { RecordLog.warn("[ZookeeperDataSource] WARN: initial config is null, you may have to check your data source"); } getProperty().updateValue(newValue); } catch (Exception ex) { RecordLog.warn("[ZookeeperDataSource] Error when loading initial config", ex); } } private void initZookeeperListener(final String serverAddr, final List<AuthInfo> authInfos) { try { this.listener = new NodeCacheListener() { @Override public void nodeChanged() { try { T newValue = loadConfig(); RecordLog.info("[ZookeeperDataSource] New property value received for ({}, {}): {}", serverAddr, path, newValue); // Update the new value to the property. getProperty().updateValue(newValue); } catch (Exception ex) { RecordLog.warn("[ZookeeperDataSource] loadConfig exception", ex); } } }; String zkKey = getZkKey(serverAddr, authInfos); if (zkClientMap.containsKey(zkKey)) { this.zkClient = zkClientMap.get(zkKey); } else { synchronized (lock) { if (!zkClientMap.containsKey(zkKey)) { CuratorFramework zc = null; if (authInfos == null || authInfos.size() == 0) { zc = CuratorFrameworkFactory.newClient(serverAddr, new ExponentialBackoffRetry(SLEEP_TIME, RETRY_TIMES)); } else { zc = CuratorFrameworkFactory.builder(). connectString(serverAddr). retryPolicy(new ExponentialBackoffRetry(SLEEP_TIME, RETRY_TIMES)). authorization(authInfos). build(); } this.zkClient = zc; this.zkClient.start(); Map<String, CuratorFramework> newZkClientMap = new HashMap<>(zkClientMap.size()); newZkClientMap.putAll(zkClientMap); newZkClientMap.put(zkKey, zc); zkClientMap = newZkClientMap; } else { this.zkClient = zkClientMap.get(zkKey); } } } this.nodeCache = new NodeCache(this.zkClient, this.path); this.nodeCache.getListenable().addListener(this.listener, this.pool); this.nodeCache.start(); } catch (Exception e) { RecordLog.warn("[ZookeeperDataSource] Error occurred when initializing Zookeeper data source", e); e.printStackTrace(); } } @Override public String readSource() throws Exception { if (this.zkClient == null) { throw new IllegalStateException("Zookeeper has not been initialized or error occurred"); } String configInfo = null; ChildData childData = nodeCache.getCurrentData(); if (null != childData && childData.getData() != null) { configInfo = new String(childData.getData()); } return configInfo; } @Override public void close() throws Exception { if (this.nodeCache != null) { this.nodeCache.getListenable().removeListener(listener); this.nodeCache.close(); } if (this.zkClient != null) { this.zkClient.close(); } pool.shutdown(); } private String getPath(String groupId, String dataId) { return String.format("/%s/%s", groupId, dataId); } private String getZkKey(final String serverAddr, final List<AuthInfo> authInfos) { if (authInfos == null || authInfos.size() == 0) { return serverAddr; } StringBuilder builder = new StringBuilder(64); builder.append(serverAddr).append(getAuthInfosKey(authInfos)); return builder.toString(); } private String getAuthInfosKey(List<AuthInfo> authInfos) { StringBuilder builder = new StringBuilder(32); for (AuthInfo authInfo : authInfos) { if (authInfo == null) { builder.append("{}"); } else { builder.append("{" + "sc=" + authInfo.getScheme() + ",au=" + Arrays.toString(authInfo.getAuth()) + "}"); } } return builder.toString(); } protected CuratorFramework getZkClient() { return this.zkClient; } }
package gr.bytecode.apps.android.phonebook.ui.adapters; import gr.bytecode.apps.android.phonebook.R; import gr.bytecode.apps.android.phonebook.entities.Entry; import java.util.List; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.ImageView; import android.widget.TextView; /** * The data adapter of a single entry list, responsible for both filling in the * entry list view items as well as listening on click/tap events. * * @author Dimitris Balaouras * @copyright 2013 ByteCode.gr * */ public class EntryListAdapter extends ArrayAdapter<Entry> implements EntryListClickHandler { /** * An activity context */ private Context mcontext; /** * the id of the layout resource that we will be using to illustrate the * phone */ private int layoutResourceId; /** * A list of phones */ private List<Entry> entries = null; /** * An instance of a layout inflater */ private LayoutInflater inflater; /** * Main constructor * * @param context * @param layoutResourceId * @param entries * @param defaultIconResourceId */ public EntryListAdapter(Context context, int layoutResourceId, List<Entry> entries) { super(context, layoutResourceId, entries); this.mcontext = context; this.layoutResourceId = layoutResourceId; this.entries = entries; // load an inflater inflater = (LayoutInflater) mcontext.getSystemService(Context.LAYOUT_INFLATER_SERVICE); } // @Override /* * (non-Javadoc) * * @see android.widget.ArrayAdapter#getView(int, android.view.View, * android.view.ViewGroup) */ public View getView(int pos, View convertView, ViewGroup parent) { if (convertView == null) { // inflate the layout resource into the views convertView = inflater.inflate(layoutResourceId, parent, false); } // get the @Entry Entry entry = entries.get(pos); // locate the text and image views TextView labelView = (TextView) convertView.findViewById(R.id.label); // locate the text and image views View iconSeperator = (View) convertView.findViewById(R.id.sep_icon); // set the text and image resources labelView.setText(entry.getName()); // locate the text and image views labelView = (TextView) convertView.findViewById(R.id.number); // get the phone number String phoneNumber = entry.getPhoneNumber(); // set the text and image resources labelView.setText(phoneNumber); // find the listview String website = entry.getWebsite(); final int position = pos; ImageView netIcon = (ImageView) convertView.findViewById(R.id.net_icon); if (website != null && !"".equals(website)) { // set a click listener netIcon.setOnClickListener(new OnClickListener() { /* * (non-Javadoc) * * @see * android.view.View.OnClickListener#onClick(android.view.View) */ @Override public void onClick(View v) { onWebsiteClicked(position); } }); // show the browser icon netIcon.setVisibility(View.VISIBLE); // show the seperator iconSeperator.setVisibility(View.VISIBLE); } else { // hide the browser icon netIcon.setVisibility(View.GONE); // hide the seperator iconSeperator.setVisibility(View.GONE); } if (phoneNumber != null && !"".equals(phoneNumber)) { // create the phone icon ImageView phoneIcon = (ImageView) convertView.findViewById(R.id.phone_icon); // set a click listener phoneIcon.setOnClickListener(new OnClickListener() { /* * (non-Javadoc) * * @see * android.view.View.OnClickListener#onClick(android.view.View) */ @Override public void onClick(View v) { // activate the phone click callback onPhoneClicked(position); } }); // show the phone icon phoneIcon.setVisibility(View.VISIBLE); } // return the view return convertView; } /* * (non-Javadoc) * * @see * gr.evima.apps.android.ui.adapters.IPhoneClickHandler#phoneClicked(gr. * evima.domain.entities.Phone) */ @Override public void onPhoneClicked(Entry entry) { Intent intent = new Intent(Intent.ACTION_DIAL); intent.setData(Uri.parse(String.format("tel:%s", entry.getPhoneNumber()))); mcontext.startActivity(intent); } /* * (non-Javadoc) * * @see gr.bytecode.apps.android.phonebook.ui.adapters.EntryListClickHandler * #onPhoneClicked(int) */ @Override public void onPhoneClicked(int position) { // locate the entry Entry entry = entries.get(position); // check if we got a valid entry object, and call it if (entry != null) { onPhoneClicked(entry); } } /* * (non-Javadoc) * * @see * gr.evima.apps.android.ui.adapters.EntryListClickHandler#phoneListItemClicked * (int) */ @Override public void onEntryListItemClicked(int position) { // use the the phone clicked action as the default for // list item taps onPhoneClicked(position); } /* * (non-Javadoc) * * @see * gr.bytecode.apps.android.phonebook.ui.adapters.EntryListClickHandler# * onWebsiteClicked(gr.bytecode.apps.android.phonebook.entities.Entry) */ @Override public void onWebsiteClicked(Entry entry) { // get the url of this @Entry String url = entry.getWebsite(); // only start the browser with a valid url if (url != null && !"".equals(url)) { Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url)); mcontext.startActivity(browserIntent); } } /* * (non-Javadoc) * * @see * gr.bytecode.apps.android.phonebook.ui.adapters.EntryListClickHandler# * onWebsiteClicked(int) */ @Override public void onWebsiteClicked(int position) { // locate the @Entry Entry enry = entries.get(position); // check if we got a valid @Entry object if (enry != null) { onWebsiteClicked(enry); } } /** * @param entries */ public void notifyDataChanged(List<Entry> entries) { this.entries = entries; notifyDataSetChanged(); } }
/********************************************************************************** * $URL$ * $Id$ *********************************************************************************** * * Copyright (c) 2004, 2005, 2006, 2007, 2008, 2009 The Sakai Foundation * * Licensed under the Educational Community License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.opensource.org/licenses/ECL-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * **********************************************************************************/ package org.sakaiproject.tool.assessment.ui.listener.delivery; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.ResourceBundle; import javax.faces.context.FacesContext; import javax.faces.event.AbortProcessingException; import javax.faces.event.ActionEvent; import javax.faces.event.ActionListener; import javax.servlet.http.HttpServletRequest; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.sakaiproject.component.cover.ComponentManager; import org.sakaiproject.event.api.Event; import org.sakaiproject.event.api.LearningResourceStoreService; import org.sakaiproject.event.cover.EventTrackingService; import org.sakaiproject.event.cover.NotificationService; import org.sakaiproject.tool.assessment.api.SamigoApiFactory; import org.sakaiproject.tool.assessment.data.dao.assessment.EventLogData; import org.sakaiproject.tool.assessment.data.dao.grading.AssessmentGradingData; import org.sakaiproject.tool.assessment.facade.AgentFacade; import org.sakaiproject.tool.assessment.facade.EventLogFacade; import org.sakaiproject.tool.assessment.facade.PublishedAssessmentFacade; import org.sakaiproject.tool.assessment.services.GradingService; import org.sakaiproject.tool.assessment.services.assessment.EventLogService; import org.sakaiproject.tool.assessment.services.assessment.PublishedAssessmentService; import org.sakaiproject.tool.assessment.shared.api.assessment.SecureDeliveryServiceAPI; import org.sakaiproject.tool.assessment.shared.api.assessment.SecureDeliveryServiceAPI.Phase; import org.sakaiproject.tool.assessment.shared.api.assessment.SecureDeliveryServiceAPI.PhaseStatus; import org.sakaiproject.tool.assessment.ui.bean.delivery.DeliveryBean; import org.sakaiproject.tool.assessment.ui.listener.util.ContextUtil; import org.sakaiproject.tool.assessment.ui.web.session.SessionUtil; public class LinearAccessDeliveryActionListener extends DeliveryActionListener implements ActionListener { private static Log log = LogFactory.getLog(LinearAccessDeliveryActionListener.class); private static ResourceBundle eventLogMessages = ResourceBundle.getBundle("org.sakaiproject.tool.assessment.bundle.EventLogMessages"); /** * ACTION. * @param ae * @throws AbortProcessingException */ public void processAction(ActionEvent ae) throws AbortProcessingException { log.debug("LinearAccessDeliveryActionListener.processAction() "); // get managed bean DeliveryBean delivery = (DeliveryBean) ContextUtil.lookupBean("delivery"); // set publishedId, note that id can be changed by isPreviewingMode() String id = getPublishedAssessmentId(delivery); String agent = getAgentString(); // Clear elapsed time, set not timed out clearElapsedTime(delivery); // get assessment from deliveryBean if id matches. otherwise, this is the 1st time // that DeliveryActionListener is called, so pull it from DB PublishedAssessmentFacade publishedAssessment = getPublishedAssessment(delivery, id); // set show student score setShowStudentScore(delivery, publishedAssessment); setShowStudentQuestionScore(delivery, publishedAssessment); setDeliverySettings(delivery, publishedAssessment); if (ae != null && ae.getComponent().getId().startsWith("beginAssessment")) { // #1. check password if (!delivery.getSettings().getUsername().equals("")) { if ("passwordAccessError".equals(delivery.validatePassword())) { return; } } // #2. check IP if (delivery.getSettings().getIpAddresses() != null && !delivery.getSettings().getIpAddresses().isEmpty()) { if ("ipAccessError".equals(delivery.validateIP())) { return; } } // #3. secure delivery START phase SecureDeliveryServiceAPI secureDelivery = SamigoApiFactory.getInstance().getSecureDeliveryServiceAPI(); if ( secureDelivery.isSecureDeliveryAvaliable() ) { String moduleId = publishedAssessment.getAssessmentMetaDataByLabel( SecureDeliveryServiceAPI.MODULE_KEY ); if ( moduleId != null && ! SecureDeliveryServiceAPI.NONE_ID.equals( moduleId ) ) { HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest(); PhaseStatus status = secureDelivery.validatePhase(moduleId, Phase.ASSESSMENT_START, publishedAssessment, request ); if ( PhaseStatus.FAILURE == status ) { return; } } } } // itemGradingHash will end up with // (Long publishedItemId, ArrayList itemGradingDatas) and // (String "sequence"+itemId, Integer sequence) and // (String "items", Long itemscount) GradingService service = new GradingService(); PublishedAssessmentService pubService = new PublishedAssessmentService(); AssessmentGradingData ag = null; // this returns a HashMap with (publishedItemId, itemGrading) HashMap itemGradingHash = service.getLastItemGradingData(id, agent); boolean isFirstTimeBegin = false; if (itemGradingHash!=null && itemGradingHash.size()>0){ log.debug("itemGradingHash!=null && itemGradingHash.size()>0"); ag = setAssessmentGradingFromItemData(delivery, itemGradingHash, true); setAttemptDateIfNull(ag); } else{ ag = service.getLastSavedAssessmentGradingByAgentId(id, agent); if (ag == null) { ag = createAssessmentGrading(publishedAssessment); isFirstTimeBegin = true; } else { setAttemptDateIfNull(ag); } } delivery.setAssessmentGrading(ag); log.debug("itemgrading size = " + ag.getItemGradingSet().size()); delivery.setAssessmentGradingId(delivery.getAssessmentGrading().getAssessmentGradingId()); //ag can't be null beyond this point and must have persisted to DB // version 2.1.1 requirement setFeedbackMode(delivery); if (ae != null && ae.getComponent().getId().startsWith("beginAssessment")) { setTimer(delivery, publishedAssessment, true, isFirstTimeBegin); setStatus(delivery, pubService, Long.valueOf(id)); // If it comes from Begin Assessment button clicks, reset isNoQuestion to false // because we want to always display the first page // Otherwise, if isNoQuestion set to true in the last delivery and // if the first part has no question, it will not be rendered // See getPageContentsByQuestion() for more details // Of course it is better to do this inside getPageContentsByQuestion() // However, ae is not passed in getPageContentsByQuestion() // and there are multiple places to modify if I want to get ae inside getPageContentsByQuestion() delivery.setNoQuestions(false); // ONC event log EventLogService eventService = new EventLogService(); EventLogFacade eventLogFacade = new EventLogFacade(); String agentEid = AgentFacade.getEid(); //set event log data EventLogData eventLogData = new EventLogData(); eventLogData.setAssessmentId(Long.valueOf(id)); eventLogData.setProcessId(delivery.getAssessmentGradingId()); eventLogData.setStartDate(new Date()); eventLogData.setTitle(publishedAssessment.getTitle()); eventLogData.setUserEid(agentEid); String site_id= AgentFacade.getCurrentSiteId(); if(site_id == null) { //take assessment via url PublishedAssessmentService publishedAssessmentService = new PublishedAssessmentService(); site_id = publishedAssessmentService.getPublishedAssessmentOwner(Long.valueOf(delivery.getAssessmentId())); } eventLogData.setSiteId(site_id); eventLogData.setErrorMsg(eventLogMessages.getString("no_submission")); eventLogData.setEndDate(null); eventLogData.setEclipseTime(null); eventLogFacade.setData(eventLogData); eventService.saveOrUpdateEventLog(eventLogFacade); int action = delivery.getActionMode(); if (action == DeliveryBean.TAKE_ASSESSMENT) { StringBuffer eventRef = new StringBuffer("publishedAssessmentId"); eventRef.append(delivery.getAssessmentId()); eventRef.append(", agentId="); eventRef.append(getAgentString()); if (delivery.isTimeRunning()) { eventRef.append(", elapsed="); eventRef.append(delivery.getTimeElapse()); eventRef.append(", remaining="); int timeRemaining = Integer.parseInt(delivery.getTimeLimit()) - Integer.parseInt(delivery.getTimeElapse()); eventRef.append(timeRemaining); } Event event = EventTrackingService.newEvent("sam.assessment.take", eventRef.toString(), true); EventTrackingService.post(event); registerIrss(delivery, event, false); } else if (action == DeliveryBean.TAKE_ASSESSMENT_VIA_URL) { StringBuffer eventRef = new StringBuffer("publishedAssessmentId"); eventRef.append(delivery.getAssessmentId()); eventRef.append(", agentId="); eventRef.append(getAgentString()); if (delivery.isTimeRunning()) { eventRef.append(", elapsed="); eventRef.append(delivery.getTimeElapse()); eventRef.append(", remaining="); int timeRemaining = Integer.parseInt(delivery.getTimeLimit()) - Integer.parseInt(delivery.getTimeElapse()); eventRef.append(timeRemaining); } PublishedAssessmentService publishedAssessmentService = new PublishedAssessmentService(); String siteId = publishedAssessmentService.getPublishedAssessmentOwner(Long.valueOf(delivery.getAssessmentId())); Event event = EventTrackingService.newEvent("sam.assessment.take", eventRef.toString(), siteId, true, NotificationService.NOTI_REQUIRED); EventTrackingService.post(event); registerIrss(delivery, event, true); } } else { setTimer(delivery, publishedAssessment, false, false); } // extend session time out SessionUtil.setSessionTimeout(FacesContext.getCurrentInstance(), delivery, true); log.debug("Set begin time " + delivery.getBeginTime()); log.debug("Set elapsed time " + delivery.getTimeElapse()); // overload itemGradingHash with the sequence in case renumbering is turned off. overloadItemData(delivery, itemGradingHash, publishedAssessment); // get the position of last question which has ben answered/viewed by the student log.debug("before partIndex = " + delivery.getPartIndex()); log.debug("before questionIndex = " + delivery.getQuestionIndex()); setPosition(delivery, publishedAssessment, ae); log.debug("after partIndex = " + delivery.getPartIndex()); log.debug("after questionIndex = " + delivery.getQuestionIndex()); HashMap publishedAnswerHash = pubService.preparePublishedAnswerHash(publishedAssessment); // get current page contents delivery.setPageContents(getPageContents(publishedAssessment, delivery, itemGradingHash, publishedAnswerHash)); } private void setPosition(DeliveryBean delivery, PublishedAssessmentFacade publishedAssessment, ActionEvent ae) { GradingService gradingService = new GradingService(); if (ae != null && ae.getComponent().getId().startsWith("beginAssessment")) { if (delivery.getNumberRetake() == -1 || delivery.getActualNumberRetake() == -1) { delivery.setNumberRetake(gradingService.getNumberRetake(publishedAssessment.getPublishedAssessmentId(), AgentFacade.getAgentString())); log.debug("numberRetake = " + delivery.getNumberRetake()); delivery.setActualNumberRetake(gradingService.getActualNumberRetake(publishedAssessment.getPublishedAssessmentId(), AgentFacade.getAgentString())); log.debug("actualNumberRetake =" + delivery.getActualNumberRetake()); } if (delivery.getActualNumberRetake() == delivery.getNumberRetake() - 1) { delivery.setPartIndex(0); delivery.setQuestionIndex(0); return; } } AssessmentGradingData assessmentGradingData = delivery.getAssessmentGrading(); log.debug("assessmentGradingData.getAssessmentGradingId() = " + assessmentGradingData.getAssessmentGradingId()); if (assessmentGradingData.getLastVisitedPart() != null && assessmentGradingData.getLastVisitedQuestion() != null) { delivery.setPartIndex(assessmentGradingData.getLastVisitedPart().intValue()); delivery.setQuestionIndex(assessmentGradingData.getLastVisitedQuestion().intValue()); } else { // For backward compatible ArrayList alist = gradingService.getLastItemGradingDataPosition(assessmentGradingData.getAssessmentGradingId(), assessmentGradingData.getAgentId()); int partIndex = ((Integer)alist.get(0)).intValue(); if (partIndex == 0) { delivery.setPartIndex(0); } else { delivery.setPartIndex(partIndex - 1); } delivery.setQuestionIndex(((Integer)alist.get(1)).intValue()); } } public void saveLastVisitedPosition(DeliveryBean delivery, int partNumber, int questionNumber) { GradingService gradingService = new GradingService(); AssessmentGradingData assessmentGradingData = delivery.getAssessmentGrading(); assessmentGradingData.setStatus(2); assessmentGradingData.setLastVisitedPart(partNumber); assessmentGradingData.setLastVisitedQuestion(questionNumber); gradingService.saveOrUpdateAssessmentGradingOnly(assessmentGradingData); } }
/* Copyright 2012 Selenium committers Copyright 2012 Software Freedom Conservancy Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package org.openqa.selenium.server.htmlrunner; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.Writer; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Vector; import java.util.logging.Level; import java.util.logging.Logger; import org.openqa.jetty.http.HttpContext; import org.openqa.jetty.http.HttpException; import org.openqa.jetty.http.HttpHandler; import org.openqa.jetty.http.HttpRequest; import org.openqa.jetty.http.HttpResponse; import org.openqa.jetty.util.StringUtil; /** * Handles results of HTMLRunner (aka TestRunner, FITRunner) in automatic mode. * * @author Dan Fabulich * @author Darren Cotterill * @author Ajit George * @author Olivier ETIENNE */ @SuppressWarnings("serial") public class SeleniumHTMLRunnerResultsHandler implements HttpHandler { static Logger log = Logger.getLogger(SeleniumHTMLRunnerResultsHandler.class.getName()); HttpContext context; List<HTMLResultsListener> listeners; boolean started = false; // private String serverExternalIp = ""; public SeleniumHTMLRunnerResultsHandler() { listeners = new Vector<HTMLResultsListener>(); // serverExternalIp = getServerIpAddress(); } // private String getServerIpAddress() { // String result = "127.0.0.1"; // try { // Enumeration<NetworkInterface> nets = // NetworkInterface.getNetworkInterfaces(); // for (NetworkInterface netint : Collections.list(nets)) { // if (netint.getDisplayName().indexOf("eth0") != -1) { // // Enumeration<InetAddress> inetAddresses = netint.getInetAddresses(); // for (InetAddress inetAddress : Collections.list(inetAddresses)) { // if (inetAddress instanceof Inet4Address) { // result = inetAddress.getHostAddress(); // log.info("Local server address = *" + result + "*"); // break; // } // } // // break; // } // } // } catch (Exception e) { // e.printStackTrace(); // } // return result; // } public void addListener(HTMLResultsListener listener) { listeners.add(listener); } public void handle(String pathInContext, String pathParams, HttpRequest request, HttpResponse res) throws HttpException, IOException { if (!"/postResults".equals(pathInContext)) return; request.setHandled(true); String postedLog = request.getParameter("log"); String logToConsole = request.getParameter("logToConsole"); String storeCrashReports = request.getParameter("storeCrashReports"); if (logToConsole != null && !"".equals(logToConsole)) { // log.info("Received log request"); String[] lines = postedLog.split("\n"); for (String line : lines) { // line = line.replaceAll("__SERVERIP__", serverExternalIp); if ((line != null) && (line.trim().length() > 0)) { Level level = Level.INFO; if (line.indexOf("info: ") != -1) { line = line.replaceAll("info: ", ""); level = Level.INFO; } else if (line.indexOf("warn: ") != -1) { line = line.replaceAll("warn: ", ""); level = Level.WARNING; } else if (line.indexOf("error: ") != -1) { level = Level.SEVERE; } log.log(level, line); } } // Log to console OutputStream out = res.getOutputStream(); Writer writer = new OutputStreamWriter(out, StringUtil.__ISO_8859_1); writer.write("OK"); } else if (storeCrashReports != null && !"".equals(storeCrashReports)) { log.info("Received store request"); String testSuiteName = request.getParameter("crashReportsTestSuite"); String testCaseName = request.getParameter("crashReportsTestCase"); String timeStamp = request.getParameter("crashReportsTimeStamp"); for (Iterator<HTMLResultsListener> i = listeners.iterator(); i.hasNext();) { HTMLResultsListener listener = i.next(); listener.processStoreReport(testSuiteName, testCaseName, timeStamp); } } else { log.info("Received posted results"); String seleniumVersion = request.getParameter("selenium.version"); String seleniumRevision = request.getParameter("selenium.revision"); String totalTime = request.getParameter("totalTime"); String numTestTotal = request.getParameter("numTestTotal"); String numTestPasses = request.getParameter("numTestPasses"); String numTestFailures = request.getParameter("numTestFailures"); String numCommandPasses = request.getParameter("numCommandPasses"); String numCommandFailures = request.getParameter("numCommandFailures"); String numCommandErrors = request.getParameter("numCommandErrors"); String suite = request.getParameter("suite"); String result = request.getParameter("result"); if (result == null) { res.getOutputStream().write("No result was specified!".getBytes()); } int numTotalTests = Integer.parseInt(numTestTotal); List<String> testTables = createTestTables(request, numTotalTests); // Replace local server address // if (result != null) { // result = result.replaceAll("__SERVERIP__", serverExternalIp); // } // postedLog = postedLog.replaceAll("__SERVERIP__", // serverExternalIp); // suite = suite.replaceAll("__SERVERIP__", serverExternalIp); HTMLTestResults results = new HTMLTestResults(seleniumVersion, seleniumRevision, result, totalTime, numTestTotal, numTestPasses, numTestFailures, numCommandPasses, numCommandFailures, numCommandErrors, suite, testTables, postedLog); for (Iterator<HTMLResultsListener> i = listeners.iterator(); i.hasNext();) { HTMLResultsListener listener = i.next(); listener.processResults(results); i.remove(); } processResults(results, res); } } /** Print the test results out to the HTML response */ private void processResults(HTMLTestResults results, HttpResponse res) throws IOException { res.setContentType("text/html"); OutputStream out = res.getOutputStream(); Writer writer = new OutputStreamWriter(out, StringUtil.__ISO_8859_1); results.write(writer); writer.flush(); } private List<String> createTestTables(HttpRequest request, int numTotalTests) { List<String> testTables = new LinkedList<String>(); for (int i = 1; i <= numTotalTests; i++) { String testTable = request.getParameter("testTable." + i); // testTable = testTable.replaceAll("__SERVERIP__", // serverExternalIp); // System.out.println("table " + i); // System.out.println(testTable); testTables.add(testTable); } return testTables; } public String getName() { return SeleniumHTMLRunnerResultsHandler.class.getName(); } public HttpContext getHttpContext() { return context; } public void initialize(HttpContext c) { this.context = c; } public void start() throws Exception { started = true; } public void stop() throws InterruptedException { started = false; } public boolean isStarted() { return started; } }
/* * Copyright (c) 2012 Hai Bison * * See the file LICENSE at the root directory of this project for copying * permission. */ package com.haibison.android.anhuu; import android.annotation.TargetApi; import android.content.Context; import android.content.SharedPreferences; import android.os.Build; import android.preference.PreferenceActivity; import android.preference.PreferenceFragment; import android.preference.PreferenceManager; import com.haibison.android.anhuu.FileChooserActivity.ViewType; import com.haibison.android.anhuu.providers.basefile.BaseFileContract.BaseFile; import com.haibison.android.anhuu.utils.Sys; /** * Convenient class for working with shared preferences. * * @author Hai Bison * @since v4.3 beta */ public class Settings { /** * Generates global preference filename of this library. * * @return the global preference filename. */ public static final String genPreferenceFilename() { return String.format("%s_%s", Sys.LIB_CODE_NAME, Sys.UID); }// genPreferenceFilename() /** * Generates global database filename. * * @param name * the database filename. * @return the global database filename. */ public static final String genDatabaseFilename(String name) { return String.format("%s_%s_%s", Sys.LIB_CODE_NAME, Sys.UID, name); }// genDatabaseFilename() /** * Gets new {@link SharedPreferences} * * @param context * the context. * @return {@link SharedPreferences} */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public static SharedPreferences p(Context context) { /* * Always use application context. */ return context.getApplicationContext().getSharedPreferences( genPreferenceFilename(), Context.MODE_MULTI_PROCESS); }// p() /** * Setup {@code pm} to use global unique filename and global access mode. * You must use this method if you let the user change preferences via UI * (such as {@link PreferenceActivity}, {@link PreferenceFragment}...). * * @param pm * {@link PreferenceManager}. * @since v4.9 beta */ @TargetApi(Build.VERSION_CODES.HONEYCOMB) public static void setupPreferenceManager(PreferenceManager pm) { pm.setSharedPreferencesMode(Context.MODE_MULTI_PROCESS); pm.setSharedPreferencesName(genPreferenceFilename()); }// setupPreferenceManager() /** * Display settings. * * @author Hai Bison * @since v4.3 beta */ public static class Display extends Settings { /** * Delay time for waiting for other threads inside a thread... This is * in milliseconds. */ public static final int DELAY_TIME_WAITING_THREADS = 10; /** * Delay time for waiting for very short animation, in milliseconds. */ public static final int DELAY_TIME_FOR_VERY_SHORT_ANIMATION = 199; /** * Delay time for waiting for short animation, in milliseconds. */ public static final int DELAY_TIME_FOR_SHORT_ANIMATION = 499; /** * Delay time for waiting for simple animation, in milliseconds. */ public static final int DELAY_TIME_FOR_SIMPLE_ANIMATION = 999; /** * Gets view type. * * @param c * {@link Context} * @return {@link ViewType} */ public static ViewType getViewType(Context c) { return ViewType.LIST.ordinal() == p(c) .getInt(c .getString(R.string.anhuu_f5be488d_pkey_display_view_type), c.getResources() .getInteger( R.integer.anhuu_f5be488d_pkey_display_view_type_def)) ? ViewType.LIST : ViewType.GRID; }// getViewType() /** * Sets view type. * * @param c * {@link Context} * @param v * {@link ViewType}, if {@code null}, default value will be * used. */ public static void setViewType(Context c, ViewType v) { String key = c .getString(R.string.anhuu_f5be488d_pkey_display_view_type); if (v == null) p(c).edit() .putInt(key, c.getResources() .getInteger( R.integer.anhuu_f5be488d_pkey_display_view_type_def)) .commit(); else p(c).edit().putInt(key, v.ordinal()).commit(); }// setViewType() /** * Gets sort type. * * @param c * {@link Context} * @return one of {@link BaseFile#SORT_BY_MODIFICATION_TIME}, * {@link BaseFile#SORT_BY_NAME}, {@link BaseFile#SORT_BY_SIZE}. */ public static int getSortType(Context c) { return p(c) .getInt(c .getString(R.string.anhuu_f5be488d_pkey_display_sort_type), c.getResources() .getInteger( R.integer.anhuu_f5be488d_pkey_display_sort_type_def)); }// getSortType() /** * Sets {@link SortType} * * @param c * {@link Context} * @param v * one of {@link BaseFile#SORT_BY_MODIFICATION_TIME}, * {@link BaseFile#SORT_BY_NAME}, * {@link BaseFile#SORT_BY_SIZE}., if {@code null}, default * value will be used. */ public static void setSortType(Context c, Integer v) { String key = c .getString(R.string.anhuu_f5be488d_pkey_display_sort_type); if (v == null) p(c).edit() .putInt(key, c.getResources() .getInteger( R.integer.anhuu_f5be488d_pkey_display_sort_type_def)) .commit(); else p(c).edit().putInt(key, v).commit(); }// setSortType() /** * Gets sort ascending. * * @param c * {@link Context} * @return {@code true} if sort is ascending, {@code false} otherwise. */ public static boolean isSortAscending(Context c) { return p(c) .getBoolean( c.getString(R.string.anhuu_f5be488d_pkey_display_sort_ascending), c.getResources() .getBoolean( R.bool.anhuu_f5be488d_pkey_display_sort_ascending_def)); }// isSortAscending() /** * Sets sort ascending. * * @param c * {@link Context} * @param v * {@link Boolean}, if {@code null}, default value will be * used. */ public static void setSortAscending(Context c, Boolean v) { if (v == null) v = c.getResources().getBoolean( R.bool.anhuu_f5be488d_pkey_display_sort_ascending_def); p(c).edit() .putBoolean( c.getString(R.string.anhuu_f5be488d_pkey_display_sort_ascending), v).commit(); }// setSortAscending() /** * Checks setting of showing time for old days in this year. Default is * {@code false}. * * @param c * {@link Context}. * @return {@code true} or {@code false}. * @since v4.7 beta */ public static boolean isShowTimeForOldDaysThisYear(Context c) { return p(c) .getBoolean( c.getString(R.string.anhuu_f5be488d_pkey_display_show_time_for_old_days_this_year), c.getResources() .getBoolean( R.bool.anhuu_f5be488d_pkey_display_show_time_for_old_days_this_year_def)); }// isShowTimeForOldDaysThisYear() /** * Enables or disables showing time of old days in this year. * * @param c * {@link Context}. * @param v * your preferred flag. If {@code null}, default will be used * ( {@code false}). * @since v4.7 beta */ public static void setShowTimeForOldDaysThisYear(Context c, Boolean v) { if (v == null) v = c.getResources() .getBoolean( R.bool.anhuu_f5be488d_pkey_display_show_time_for_old_days_this_year_def); p(c).edit() .putBoolean( c.getString(R.string.anhuu_f5be488d_pkey_display_show_time_for_old_days_this_year), v).commit(); }// setShowTimeForOldDaysThisYear() /** * Checks setting of showing time for old days in last year and older. * Default is {@code false}. * * @param c * {@link Context}. * @return {@code true} or {@code false}. * @since v4.7 beta */ public static boolean isShowTimeForOldDays(Context c) { return p(c) .getBoolean( c.getString(R.string.anhuu_f5be488d_pkey_display_show_time_for_old_days), c.getResources() .getBoolean( R.bool.anhuu_f5be488d_pkey_display_show_time_for_old_days_def)); }// isShowTimeForOldDays() /** * Enables or disables showing time of old days in last year and older. * * @param c * {@link Context}. * @param v * your preferred flag. If {@code null}, default will be used * ( {@code false}). * @since v4.7 beta */ public static void setShowTimeForOldDays(Context c, Boolean v) { if (v == null) v = c.getResources() .getBoolean( R.bool.anhuu_f5be488d_pkey_display_show_time_for_old_days_def); p(c).edit() .putBoolean( c.getString(R.string.anhuu_f5be488d_pkey_display_show_time_for_old_days), v).commit(); }// setShowTimeForOldDays() /** * Checks if remembering last location is enabled or not. * * @param c * {@link Context}. * @return {@code true} if remembering last location is enabled. * @since v4.7 beta */ public static boolean isRememberLastLocation(Context c) { return p(c) .getBoolean( c.getString(R.string.anhuu_f5be488d_pkey_display_remember_last_location), c.getResources() .getBoolean( R.bool.anhuu_f5be488d_pkey_display_remember_last_location_def)); }// isRememberLastLocation() /** * Enables or disables remembering last location. * * @param c * {@link Context}. * @param v * your preferred flag. If {@code null}, default will be used * ( {@code true}). * @since v4.7 beta */ public static void setRememberLastLocation(Context c, Boolean v) { if (v == null) v = c.getResources() .getBoolean( R.bool.anhuu_f5be488d_pkey_display_remember_last_location_def); p(c).edit() .putBoolean( c.getString(R.string.anhuu_f5be488d_pkey_display_remember_last_location), v).commit(); }// setRememberLastLocation() /** * Gets last location. * * @param c * {@link Context}. * @return the last location, or {@code null} if not available. * @since v4.7 beta */ public static String getLastLocation(Context c) { return p(c) .getString( c.getString(R.string.anhuu_f5be488d_pkey_display_last_location), null); }// getLastLocation() /** * Sets last location. * * @param c * {@link Context}. * @param v * the last location. */ public static void setLastLocation(Context c, String v) { p(c).edit() .putString( c.getString(R.string.anhuu_f5be488d_pkey_display_last_location), v).commit(); }// setLastLocation() }// Display }
// -------------------------------------------------------------------------- // $Id: Applic.java,v 1.3 1997/11/03 10:25:05 schreine Exp $ // execution framework for application // // (c) 1997, Wolfgang Schreiner <Wolfgang.Schreiner@risc.uni-linz.ac.at> // http://www.risc.uni-linz.ac.at/software/daj // -------------------------------------------------------------------------- package daj.awt; import java.applet.Applet; import java.awt.Button; import java.awt.Font; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.Point; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import daj.Application; import daj.Assertion; import daj.Channel; import daj.Network; import daj.Node; import daj.Program; import daj.Scheduler; import daj.Selector; import daj.SelectorDefault; @SuppressWarnings("serial") public abstract class Applic extends Applet implements ActionListener { // the network being executed private Network network; // visualization on or off? private boolean visualized; // visualization information private String title; private int width; private int height; // executing as applet? private boolean isAppl; /* * paths to browser */ // public String browserCommand = "/usr/local/bin/netscape"; public String browserCommand = ""; // global variables that may be customized by programmer public int nodeRadius = 19; public Font nodeNormalFont = new Font("Helvetica", Font.BOLD, 12); public Font nodeSmallFont = new Font("Helvetica", Font.PLAIN, 10); public int channelWidth = 3; public int channelRadius = 6; public Selector defaultSelector = new SelectorDefault(); // button for starting applet private Button button; // -------------------------------------------------------------------------- // run application without visualization // -------------------------------------------------------------------------- public Applic() { visualized = false; network = new Network((Application) this); } // -------------------------------------------------------------------------- // run application with visualization titled 't' and screen of size 'x/y' // -------------------------------------------------------------------------- public Applic(String t, int x, int y) { visualized = true; title = t; width = x; height = y; } public Network getNetwork() { return network; } // -------------------------------------------------------------------------- // // the following methods are used internally to control the application // // -------------------------------------------------------------------------- // -------------------------------------------------------------------------- // executed when run in standalone mode; execute network in current thread // -------------------------------------------------------------------------- public void run() { isAppl = false; network = new Network((Application) this, title, width, height, 100, 100, false, 0, 0); construct(); if (visualized) start(); network.run(); } // -------------------------------------------------------------------------- // executed when run in applet mode; create button to start application // -------------------------------------------------------------------------- public void init() { // create button; use parameters to determine its label button = new Button(title); String bname = getParameter("buttonLabel"); if (bname != null) { button.setLabel(bname); } // use parameters to determine button font Font font = getFont(); String name = font.getName(); String fname = getParameter("fontName"); if (fname != null) { name = fname; } int style = font.getStyle(); String fstyle = getParameter("fontStyle"); if (fstyle != null) { if (fstyle.equalsIgnoreCase("bold")) style = Font.BOLD; else if (fstyle.equalsIgnoreCase("italic")) style = Font.ITALIC; else if (fstyle.equalsIgnoreCase("plain")) style = Font.PLAIN; else Assertion.fail("invalid font style"); } int size = font.getSize(); String fsize = getParameter("fontSize"); if (fsize != null) { try { size = Integer.parseInt(fsize); } catch (NumberFormatException e) { Assertion.fail("invalid font size"); } } font = new Font(name, style, size); button.setFont(font); // layout button to cover all the applet space GridBagLayout gridbag = new GridBagLayout(); setLayout(gridbag); GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.BOTH; c.weightx = 1.0; c.weighty = 1.0; gridbag.setConstraints(button, c); add(button); // register event handler for button button.addActionListener(this); } // -------------------------------------------------------------------------- // called when button is pressed // -------------------------------------------------------------------------- public void actionPerformed(ActionEvent e) { if (e.getSource() == button) { startApplet(); button.setEnabled(false); } } // -------------------------------------------------------------------------- // start execution in applet mode; execute network in new thread // -------------------------------------------------------------------------- private void startApplet() { Assertion.test(visualized, "visualization off in applet mode"); isAppl = true; Point loc = getLocationOnScreen(); network = new Network((Application) this, title, width, height, loc.x + 100, loc.y + 100, false, 0, 0); construct(); network.start(); start(); } // -------------------------------------------------------------------------- // applet continues, show window but let user manually continue execution // -------------------------------------------------------------------------- public void start() { if (network != null) network.getVisualizer().setVisible(true); } // -------------------------------------------------------------------------- // applet is stopped; interrupt network execution and hide window // -------------------------------------------------------------------------- public void stop() { if (network != null) { Visualizer visualizer = network.getVisualizer(); visualizer.stop(); visualizer.setVisible(false); } } // -------------------------------------------------------------------------- // restart application // -------------------------------------------------------------------------- public void restart() { Assertion.test(visualized, "no visualization"); Visualizer visualizer = network.getVisualizer(); int px = visualizer.getXPos(); int py = visualizer.getYPos(); int w = visualizer.getWidth(); int h = visualizer.getHeight(); resetStatistics(); network.devisualize(); network = new Network((Application) this, title, width, height, px, py, true, w, h); construct(); start(); network.start(); } /** * additional functionality. resets counters in "Main" when "Restart" button pushed */ public abstract void resetStatistics(); // -------------------------------------------------------------------------- // terminate visualized application // -------------------------------------------------------------------------- public void terminate() { network.devisualize(); network = null; System.gc(); if (button != null) button.setEnabled(true); } // -------------------------------------------------------------------------- // informative text shown as applet info // -------------------------------------------------------------------------- public String getAppletInfo() { return getText(); } // -------------------------------------------------------------------------- // return true iff in applet mode // -------------------------------------------------------------------------- public boolean isApplet() { return isAppl; } // -------------------------------------------------------------------------- // informative text shown as applet info // -------------------------------------------------------------------------- public String[][] getParameterInfo() { String info[][] = { { "buttonLabel", "String", "text on button" }, { "fontName", "String", "name of button font" }, { "fontStyle", "plain, bold, italic", "style of button font" }, { "fontSize", "Integer >= 1", "size of button font" } }; return info; } // -------------------------------------------------------------------------- // // the following functions may/must be overridden by the user // // -------------------------------------------------------------------------- // -------------------------------------------------------------------------- // informative text // -------------------------------------------------------------------------- public String getText() { return "(no information)"; } // -------------------------------------------------------------------------- // network construction provided by user // -------------------------------------------------------------------------- public abstract void construct(); // -------------------------------------------------------------------------- // // the following functions may be used for network construction // // -------------------------------------------------------------------------- // -------------------------------------------------------------------------- // create new node in network // -------------------------------------------------------------------------- public Node node(Program prog, String text, int xPos, int yPos) { Assertion.test(network != null, "network not initialized"); return new Node(network, prog, text, xPos, yPos); } // -------------------------------------------------------------------------- // create new node in network (without visualization information) // -------------------------------------------------------------------------- public Node node(Program prog) { Assertion.test(network != null, "network not initialized"); return new Node(network, prog); } // -------------------------------------------------------------------------- // link two nodes by channel // -------------------------------------------------------------------------- public void link(Node sender, Node receiver) { Assertion.test(network != null, "network not initialized"); Channel.link(sender, receiver); } // -------------------------------------------------------------------------- // link two nodes by channel with selector `s` // -------------------------------------------------------------------------- public void link(Node sender, Node receiver, Selector s) { Assertion.test(network != null, "network not initialized"); Channel.link(sender, receiver, s); } // -------------------------------------------------------------------------- // // the following methods may be used to customize the application // // -------------------------------------------------------------------------- // -------------------------------------------------------------------------- // set scheduler for network // -------------------------------------------------------------------------- public void setScheduler(Scheduler sched) { network.setScheduler(sched); } // -------------------------------------------------------------------------- // set message selector for network // -------------------------------------------------------------------------- public void setSelector(Selector sel) { defaultSelector = sel; } // -------------------------------------------------------------------------- // set node radius // -------------------------------------------------------------------------- public void setNodeRadius(int r) { nodeRadius = r; } // -------------------------------------------------------------------------- // sets fonts for display of node label and time subscript // -------------------------------------------------------------------------- public void setNodeFonts(Font normal, Font small) { nodeNormalFont = normal; nodeSmallFont = small; } // -------------------------------------------------------------------------- // set channel width // -------------------------------------------------------------------------- public void setChannelWidth(int w) { channelWidth = w; channelRadius = 2 * w; } // -------------------------------------------------------------------------- // set browser to invoke in non-applet mode for help pages // -------------------------------------------------------------------------- public void setBrowser(String command) { browserCommand = command; } }
/* * Copyright 2015 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.kie.server.integrationtests.controller; import static org.hamcrest.core.Is.*; import static org.junit.Assert.*; import static org.junit.Assume.*; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.experimental.categories.Category; import org.kie.server.api.model.KieContainerResource; import org.kie.server.api.model.KieContainerResourceList; import org.kie.server.api.model.KieContainerStatus; import org.kie.server.api.model.KieServerInfo; import org.kie.server.api.model.ReleaseId; import org.kie.server.api.model.ServiceResponse; import org.kie.server.controller.api.model.KieServerInstance; import org.kie.server.controller.api.model.KieServerInstanceInfo; import org.kie.server.controller.api.model.KieServerInstanceList; import org.kie.server.controller.api.model.KieServerStatus; import org.kie.server.integrationtests.controller.client.exception.UnexpectedResponseCodeException; import org.kie.server.integrationtests.category.Smoke; import org.kie.server.integrationtests.shared.KieServerAssert; import org.kie.server.integrationtests.shared.KieServerDeployer; import org.kie.server.integrationtests.shared.KieServerSynchronization; public class KieControllerIntegrationTest extends KieControllerBaseTest { private static ReleaseId releaseId = new ReleaseId("org.kie.server.testing", "stateless-session-kjar", "1.0.0-SNAPSHOT"); private static final String CONTAINER_ID = "kie-concurrent"; private KieServerInfo kieServerInfo; @BeforeClass public static void initialize() throws Exception { KieServerDeployer.buildAndDeployCommonMavenParent(); KieServerDeployer.buildAndDeployMavenProject(ClassLoader.class.getResource("/kjars-sources/stateless-session-kjar").getFile()); } @Before public void getKieServerInfo() { // Getting info from currently started kie server. ServiceResponse<KieServerInfo> reply = client.getServerInfo(); assumeThat(reply.getType(), is(ServiceResponse.ResponseType.SUCCESS)); kieServerInfo = reply.getResult(); } @Test @Category(Smoke.class) public void testCreateKieServerInstance() { // Create kie server instance in controller. KieServerInstance serverInstance = controllerClient.createKieServerInstance(kieServerInfo); checkServerInstance(serverInstance); assertEquals(kieServerInfo.getVersion(), serverInstance.getVersion()); assertNotNull("Kie server instance isn't managed!", serverInstance.getManagedInstances()); assertEquals(1, serverInstance.getManagedInstances().size()); KieServerInstanceInfo managedInstance = serverInstance.getManagedInstances().iterator().next(); checkServerInstanceInfo(managedInstance); } @Test public void testCreateDuplicitKieServerInstance() { // Create kie server instance in controller. KieServerInstance serverInstance = controllerClient.createKieServerInstance(kieServerInfo); assertNotNull(serverInstance); try { // Try to create same kie server instance. controllerClient.createKieServerInstance(kieServerInfo); fail("Should throw exception about kie server instance already created."); } catch (UnexpectedResponseCodeException e) { assertEquals(400, e.getResponseCode()); } } @Test public void testDeleteKieServerInstance() { // Create kie server instance in controller. controllerClient.createKieServerInstance(kieServerInfo); // Check that instance is created. KieServerInstanceList instanceList = controllerClient.listKieServerInstances(); assertNotNull(instanceList); assertNotNull(instanceList.getKieServerInstances()); assertEquals(1, instanceList.getKieServerInstances().length); // Delete created kie server instance. controllerClient.deleteKieServerInstance(kieServerInfo.getServerId()); // There are no kie server instances in controller now. instanceList = controllerClient.listKieServerInstances(); assertNotNull(instanceList); KieServerAssert.assertNullOrEmpty("Active kie server instance found!", instanceList.getKieServerInstances()); } @Test public void testDeleteNotExistingKieServerInstance() { try { // Try to delete not existing kie server instance. controllerClient.deleteKieServerInstance(kieServerInfo.getServerId()); fail("Should throw exception about kie server instance not existing."); } catch (UnexpectedResponseCodeException e) { assertEquals(400, e.getResponseCode()); } } @Test @Category(Smoke.class) public void testGetKieServerInstance() { // Create kie server instance in controller. controllerClient.createKieServerInstance(kieServerInfo); // Get kie server instance. KieServerInstance serverInstance = controllerClient.getKieServerInstance(kieServerInfo.getServerId()); checkServerInstance(serverInstance); assertNotNull("Kie server instance isn't managed!", serverInstance.getManagedInstances()); assertEquals(1, serverInstance.getManagedInstances().size()); KieServerInstanceInfo managedInstance = serverInstance.getManagedInstances().iterator().next(); checkServerInstanceInfo(managedInstance); } @Test public void testGetNotExistingKieServerInstance() { try { // Try to get not existing kie server instance. controllerClient.getKieServerInstance(kieServerInfo.getServerId()); fail("Should throw exception about kie server instance not existing."); } catch (UnexpectedResponseCodeException e) { assertEquals(400, e.getResponseCode()); } } @Test public void testListKieServerInstances() { // Create kie server instance in controller. controllerClient.createKieServerInstance(kieServerInfo); // List kie server instances. KieServerInstanceList instanceList = controllerClient.listKieServerInstances(); assertNotNull(instanceList); assertNotNull(instanceList.getKieServerInstances()); assertEquals(1, instanceList.getKieServerInstances().length); KieServerInstance serverInstance = instanceList.getKieServerInstances()[0]; checkServerInstance(serverInstance); assertNotNull("Kie server instance isn't managed!", serverInstance.getManagedInstances()); assertEquals(1, serverInstance.getManagedInstances().size()); KieServerInstanceInfo managedInstance = serverInstance.getManagedInstances().iterator().next(); checkServerInstanceInfo(managedInstance); } @Test public void testEmptyListKieServerInstances() throws Exception { KieServerInstanceList instanceList = controllerClient.listKieServerInstances(); assertNotNull(instanceList); assertEquals("Active kie server instance found!", 0, instanceList.getKieServerInstances().length); } @Test public void testContainerHandling() { // Create kie server instance connection in controller. controllerClient.createKieServerInstance(kieServerInfo); // Deploy container for kie server instance. KieContainerResource containerToDeploy = new KieContainerResource(CONTAINER_ID, releaseId); KieContainerResource deployedContainer = controllerClient.createContainer(kieServerInfo.getServerId(), CONTAINER_ID, containerToDeploy); assertNotNull(deployedContainer); assertEquals(CONTAINER_ID, deployedContainer.getContainerId()); assertEquals(containerToDeploy.getReleaseId(), deployedContainer.getReleaseId()); // Check that container is deployed. KieContainerResource containerResponseEntity = controllerClient.getContainerInfo(kieServerInfo.getServerId(), CONTAINER_ID); checkContainer(containerResponseEntity, KieContainerStatus.STOPPED); // Container is in stopped state, so there are no containers deployed in kie server. ServiceResponse<KieContainerResourceList> containersList = client.listContainers(); assertEquals(ServiceResponse.ResponseType.SUCCESS, containersList.getType()); KieServerAssert.assertNullOrEmpty("Active containers found!", containersList.getResult().getContainers()); // Undeploy container for kie server instance. controllerClient.disposeContainer(kieServerInfo.getServerId(), CONTAINER_ID); // Check that container is disposed. try { controllerClient.getContainerInfo(kieServerInfo.getServerId(), CONTAINER_ID); fail("Should throw exception about container info not found."); } catch (UnexpectedResponseCodeException e) { assertEquals(400, e.getResponseCode()); } } @Test public void testCreateContainerOnNotExistingKieServerInstance() { // Try to create container using kie controller without created kie server instance. KieContainerResource containerToDeploy = new KieContainerResource(CONTAINER_ID, releaseId); try { controllerClient.createContainer(kieServerInfo.getServerId(), CONTAINER_ID, containerToDeploy); fail("Should throw exception about kie server instance not found."); } catch (UnexpectedResponseCodeException e) { assertEquals(400, e.getResponseCode()); } } @Test public void testCreateDuplicitContainer() { // Create kie server instance connection in controller. controllerClient.createKieServerInstance(kieServerInfo); // Create container using kie controller. KieContainerResource containerToDeploy = new KieContainerResource(CONTAINER_ID, releaseId); KieContainerResource deployedContainer = controllerClient.createContainer(kieServerInfo.getServerId(), CONTAINER_ID, containerToDeploy); assertNotNull(deployedContainer); assertEquals(CONTAINER_ID, deployedContainer.getContainerId()); assertEquals(containerToDeploy.getReleaseId(), deployedContainer.getReleaseId()); try { // Try to create same container. controllerClient.createContainer(kieServerInfo.getServerId(), CONTAINER_ID, containerToDeploy); fail("Should throw exception about container being created already."); } catch (UnexpectedResponseCodeException e) { assertEquals(400, e.getResponseCode()); } } @Test public void testDeleteNotExistingContainer() { // Try to dispose not existing container using kie controller without created kie server instance. try { controllerClient.disposeContainer(kieServerInfo.getServerId(), CONTAINER_ID); fail("Should throw exception about kie server instance not exists."); } catch (UnexpectedResponseCodeException e) { assertEquals(400, e.getResponseCode()); } controllerClient.createKieServerInstance(kieServerInfo); // Try to dispose not existing container using kie controller with created kie server instance. try { controllerClient.disposeContainer(kieServerInfo.getServerId(), CONTAINER_ID); fail("Should throw exception about container not exists."); } catch (UnexpectedResponseCodeException e) { assertEquals(400, e.getResponseCode()); } } @Test public void testGetContainer() { // Create kie server instance connection in controller. controllerClient.createKieServerInstance(kieServerInfo); // Deploy container for kie server instance. KieContainerResource containerToDeploy = new KieContainerResource(CONTAINER_ID, releaseId); controllerClient.createContainer(kieServerInfo.getServerId(), CONTAINER_ID, containerToDeploy); // Get container using kie controller. KieContainerResource containerResponseEntity = controllerClient.getContainerInfo(kieServerInfo.getServerId(), CONTAINER_ID); checkContainer(containerResponseEntity, KieContainerStatus.STOPPED); } @Test public void testStartAndStopContainer() throws Exception { // Create kie server instance connection in controller. controllerClient.createKieServerInstance(kieServerInfo); // Deploy container for kie server instance. KieContainerResource containerToDeploy = new KieContainerResource(CONTAINER_ID, releaseId); controllerClient.createContainer(kieServerInfo.getServerId(), CONTAINER_ID, containerToDeploy); // Get container using kie controller. KieContainerResource containerResponseEntity = controllerClient.getContainerInfo(kieServerInfo.getServerId(), CONTAINER_ID); checkContainer(containerResponseEntity, KieContainerStatus.STOPPED); // Check that container is not deployed in kie server (as container is in STOPPED state). ServiceResponse<KieContainerResource> containerInfo = client.getContainerInfo(CONTAINER_ID); assertEquals(ServiceResponse.ResponseType.FAILURE, containerInfo.getType()); KieServerAssert.assertResultContainsString(containerInfo.getMsg(), "Container " + CONTAINER_ID + " is not instantiated."); controllerClient.startContainer(kieServerInfo.getServerId(), CONTAINER_ID); containerResponseEntity = controllerClient.getContainerInfo(kieServerInfo.getServerId(), CONTAINER_ID); checkContainer(containerResponseEntity, KieContainerStatus.STARTED); // Check that container is deployed in kie server. KieServerSynchronization.waitForKieServerSynchronization(client, 1); containerInfo = client.getContainerInfo(CONTAINER_ID); assertEquals(ServiceResponse.ResponseType.SUCCESS, containerInfo.getType()); assertEquals(CONTAINER_ID, containerInfo.getResult().getContainerId()); assertEquals(KieContainerStatus.STARTED, containerInfo.getResult().getStatus()); assertEquals(releaseId, containerInfo.getResult().getReleaseId()); controllerClient.stopContainer(kieServerInfo.getServerId(), CONTAINER_ID); containerResponseEntity = controllerClient.getContainerInfo(kieServerInfo.getServerId(), CONTAINER_ID); checkContainer(containerResponseEntity, KieContainerStatus.STOPPED); // Check that container is not deployed in kie server (as container is in STOPPED state). KieServerSynchronization.waitForKieServerSynchronization(client, 0); containerInfo = client.getContainerInfo(CONTAINER_ID); assertEquals(ServiceResponse.ResponseType.FAILURE, containerInfo.getType()); KieServerAssert.assertResultContainsString(containerInfo.getMsg(), "Container " + CONTAINER_ID + " is not instantiated."); } @Test public void testStartNotExistingContainer() throws Exception { // Try to start not existing container using kie controller without created kie server instance. try { controllerClient.startContainer(kieServerInfo.getServerId(), CONTAINER_ID); fail("Should throw exception about container not found."); } catch (UnexpectedResponseCodeException e) { assertEquals(400, e.getResponseCode()); } controllerClient.createKieServerInstance(kieServerInfo); // Try to start not existing container using kie controller with created kie server instance. try { controllerClient.startContainer(kieServerInfo.getServerId(), CONTAINER_ID); fail("Should throw exception about container not found."); } catch (UnexpectedResponseCodeException e) { assertEquals(400, e.getResponseCode()); } } @Test public void testStopNotExistingContainer() throws Exception { // Try to stop not existing container using kie controller without created kie server instance. try { controllerClient.stopContainer(kieServerInfo.getServerId(), CONTAINER_ID); fail("Should throw exception about container not found."); } catch (UnexpectedResponseCodeException e) { assertEquals(400, e.getResponseCode()); } controllerClient.createKieServerInstance(kieServerInfo); // Try to stop not existing container using kie controller with created kie server instance. try { controllerClient.stopContainer(kieServerInfo.getServerId(), CONTAINER_ID); fail("Should throw exception about container not found."); } catch (UnexpectedResponseCodeException e) { assertEquals(400, e.getResponseCode()); } } @Test public void testGetNotExistingContainer() { // Try to get not existing container using kie controller without created kie server instance. try { controllerClient.getContainerInfo(kieServerInfo.getServerId(), CONTAINER_ID); fail("Should throw exception about container info not found."); } catch (UnexpectedResponseCodeException e) { assertEquals(400, e.getResponseCode()); } controllerClient.createKieServerInstance(kieServerInfo); // Try to get not existing container using kie controller with created kie server instance. try { controllerClient.getContainerInfo(kieServerInfo.getServerId(), CONTAINER_ID); fail("Should throw exception about container info not found."); } catch (UnexpectedResponseCodeException e) { assertEquals(400, e.getResponseCode()); } } protected void checkContainer(KieContainerResource container, KieContainerStatus status) { assertNotNull(container); assertEquals(CONTAINER_ID, container.getContainerId()); assertEquals(releaseId, container.getReleaseId()); assertEquals(status, container.getStatus()); } protected void checkServerInstance(KieServerInstance serverInstance) { assertNotNull(serverInstance); assertEquals(kieServerInfo.getServerId(), serverInstance.getIdentifier()); assertEquals(kieServerInfo.getName(), serverInstance.getName()); assertEquals(KieServerStatus.UP, serverInstance.getStatus()); } protected void checkServerInstanceInfo(KieServerInstanceInfo serverInstanceInfo) { assertNotNull(serverInstanceInfo); assertArrayEquals(kieServerInfo.getCapabilities().toArray(), serverInstanceInfo.getCapabilities().toArray()); assertEquals(kieServerInfo.getLocation(), serverInstanceInfo.getLocation()); assertEquals(KieServerStatus.UP, serverInstanceInfo.getStatus()); } }
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.execution.configuration; import com.google.common.collect.ImmutableMap; import com.intellij.execution.ExecutionBundle; import com.intellij.execution.configurations.GeneralCommandLine; import com.intellij.execution.util.EnvVariablesTable; import com.intellij.execution.util.EnvironmentVariable; import com.intellij.icons.AllIcons; import com.intellij.ide.IdeBundle; import com.intellij.idea.ActionsBundle; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.ui.DialogWrapper; import com.intellij.openapi.ui.TextFieldWithBrowseButton; import com.intellij.openapi.ui.ValidationInfo; import com.intellij.openapi.util.Comparing; import com.intellij.openapi.util.text.StringUtil; import com.intellij.ui.AnActionButton; import com.intellij.ui.AnActionButtonRunnable; import com.intellij.ui.UserActivityProviderComponent; import com.intellij.ui.table.JBTable; import com.intellij.ui.table.TableView; import com.intellij.util.EnvironmentUtil; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.ui.JBUI; import com.intellij.util.ui.ListTableModel; import net.miginfocom.swing.MigLayout; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import javax.swing.event.ChangeEvent; import javax.swing.event.ChangeListener; import javax.swing.table.DefaultTableCellRenderer; import javax.swing.table.TableCellRenderer; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.List; import java.util.*; public class EnvironmentVariablesTextFieldWithBrowseButton extends TextFieldWithBrowseButton implements UserActivityProviderComponent { private EnvironmentVariablesData myData = EnvironmentVariablesData.DEFAULT; private final Map<String, String> myParentDefaults = new LinkedHashMap<>(); private final List<ChangeListener> myListeners = ContainerUtil.createLockFreeCopyOnWriteList(); public EnvironmentVariablesTextFieldWithBrowseButton() { super(); addActionListener(new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { setEnvs(EnvVariablesTable.parseEnvsFromText(getText())); new MyEnvironmentVariablesDialog().show(); } }); } /** * @return unmodifiable Map instance */ @NotNull public Map<String, String> getEnvs() { return myData.getEnvs(); } /** * @param envs Map instance containing user-defined environment variables * (iteration order should be reliable user-specified, like {@link LinkedHashMap} or {@link ImmutableMap}) */ public void setEnvs(@NotNull Map<String, String> envs) { setData(EnvironmentVariablesData.create(envs, myData.isPassParentEnvs())); } @NotNull public EnvironmentVariablesData getData() { return myData; } public void setData(@NotNull EnvironmentVariablesData data) { EnvironmentVariablesData oldData = myData; myData = data; setText(stringifyEnvs(data.getEnvs())); if (!oldData.equals(data)) { fireStateChanged(); } } @NotNull private static String stringifyEnvs(@NotNull Map<String, String> envs) { if (envs.isEmpty()) { return ""; } StringBuilder buf = new StringBuilder(); for (Map.Entry<String, String> entry : envs.entrySet()) { if (buf.length() > 0) { buf.append(";"); } buf.append(StringUtil.escapeChar(entry.getKey(), ';')) .append("=") .append(StringUtil.escapeChar(entry.getValue(), ';')); } return buf.toString(); } public boolean isPassParentEnvs() { return myData.isPassParentEnvs(); } public void setPassParentEnvs(boolean passParentEnvs) { setData(EnvironmentVariablesData.create(myData.getEnvs(), passParentEnvs)); } @Override public void addChangeListener(@NotNull ChangeListener changeListener) { myListeners.add(changeListener); } @Override public void removeChangeListener(@NotNull ChangeListener changeListener) { myListeners.remove(changeListener); } private void fireStateChanged() { for (ChangeListener listener : myListeners) { listener.stateChanged(new ChangeEvent(this)); } } private static List<EnvironmentVariable> convertToVariables(Map<String, String> map, final boolean readOnly) { return ContainerUtil.map(map.entrySet(), entry -> new EnvironmentVariable(entry.getKey(), entry.getValue(), readOnly) { @Override public boolean getNameIsWriteable() { return !readOnly; } }); } private class MyEnvironmentVariablesDialog extends DialogWrapper { private final EnvVariablesTable myUserTable; private final EnvVariablesTable mySystemTable; private final JCheckBox myIncludeSystemVarsCb; private final JPanel myWholePanel; protected MyEnvironmentVariablesDialog() { super(EnvironmentVariablesTextFieldWithBrowseButton.this, true); Map<String, String> userMap = new LinkedHashMap<>(myData.getEnvs()); Map<String, String> parentMap = new TreeMap<>(new GeneralCommandLine().getParentEnvironment()); myParentDefaults.putAll(parentMap); for (Iterator<Map.Entry<String, String>> iterator = userMap.entrySet().iterator(); iterator.hasNext(); ) { Map.Entry<String, String> entry = iterator.next(); if (parentMap.containsKey(entry.getKey())) { //User overrides system variable, we have to show it in 'parent' table as bold parentMap.put(entry.getKey(), entry.getValue()); iterator.remove(); } } List<EnvironmentVariable> userList = convertToVariables(userMap, false); List<EnvironmentVariable> systemList = convertToVariables(parentMap, true); myUserTable = new MyEnvVariablesTable(userList, true); mySystemTable = new MyEnvVariablesTable(systemList, false); myIncludeSystemVarsCb = new JCheckBox(ExecutionBundle.message("env.vars.system.title")); myIncludeSystemVarsCb.setSelected(isPassParentEnvs()); myIncludeSystemVarsCb.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { updateSysTableState(); } }); JLabel label = new JLabel(ExecutionBundle.message("env.vars.user.title")); label.setLabelFor(myUserTable.getTableView().getComponent()); myWholePanel = new JPanel(new MigLayout("fill, ins 0, gap 0, hidemode 3")); myWholePanel.add(label, "hmax pref, wrap"); myWholePanel.add(myUserTable.getComponent(), "push, grow, wrap, gaptop 5"); myWholePanel.add(myIncludeSystemVarsCb, "hmax pref, wrap, gaptop 5"); myWholePanel.add(mySystemTable.getComponent(), "push, grow, wrap, gaptop 5"); updateSysTableState(); setTitle(ExecutionBundle.message("environment.variables.dialog.title")); init(); } @Nullable @Override protected String getDimensionServiceKey() { return "EnvironmentVariablesDialog"; } private void updateSysTableState() { mySystemTable.getTableView().setEnabled(myIncludeSystemVarsCb.isSelected()); } @Nullable @Override protected JComponent createCenterPanel() { return myWholePanel; } @Nullable @Override protected ValidationInfo doValidate() { for (EnvironmentVariable variable : myUserTable.getEnvironmentVariables()) { String name = variable.getName(), value = variable.getValue(); if (StringUtil.isEmpty(name) && StringUtil.isEmpty(value)) continue; if (!EnvironmentUtil.isValidName(name)) return new ValidationInfo(IdeBundle.message("run.configuration.invalid.env.name", name)); if (!EnvironmentUtil.isValidValue(value)) return new ValidationInfo(IdeBundle.message("run.configuration.invalid.env.value", name, value)); } return super.doValidate(); } @Override protected void doOKAction() { myUserTable.stopEditing(); final Map<String, String> envs = new LinkedHashMap<>(); for (EnvironmentVariable variable : myUserTable.getEnvironmentVariables()) { if (StringUtil.isEmpty(variable.getName()) && StringUtil.isEmpty(variable.getValue())) continue; envs.put(variable.getName(), variable.getValue()); } for (EnvironmentVariable variable : mySystemTable.getEnvironmentVariables()) { if (isModifiedSysEnv(variable)) { envs.put(variable.getName(), variable.getValue()); } } setEnvs(envs); setPassParentEnvs(myIncludeSystemVarsCb.isSelected()); super.doOKAction(); } } private class MyEnvVariablesTable extends EnvVariablesTable { private final boolean myUserList; private MyEnvVariablesTable(List<EnvironmentVariable> list, boolean userList) { myUserList = userList; TableView<EnvironmentVariable> tableView = getTableView(); tableView.setPreferredScrollableViewportSize( new Dimension(tableView.getPreferredScrollableViewportSize().width, tableView.getRowHeight() * JBTable.PREFERRED_SCROLLABLE_VIEWPORT_HEIGHT_IN_ROWS)); setValues(list); setPasteActionEnabled(myUserList); } @Nullable @Override protected AnActionButtonRunnable createAddAction() { return myUserList ? super.createAddAction() : null; } @Nullable @Override protected AnActionButtonRunnable createRemoveAction() { return myUserList ? super.createRemoveAction() : null; } @NotNull @Override protected AnActionButton[] createExtraActions() { return myUserList ? super.createExtraActions() : new AnActionButton[]{ new AnActionButton(ActionsBundle.message("action.ChangesView.Revert.text"), AllIcons.Actions.Rollback) { @Override public void actionPerformed(@NotNull AnActionEvent e) { stopEditing(); List<EnvironmentVariable> variables = getSelection(); for (EnvironmentVariable environmentVariable : variables) { if (isModifiedSysEnv(environmentVariable)) { environmentVariable.setValue(myParentDefaults.get(environmentVariable.getName())); setModified(); } } getTableView().revalidate(); getTableView().repaint(); } @Override public boolean isEnabled() { List<EnvironmentVariable> selection = getSelection(); for (EnvironmentVariable variable : selection) { if (isModifiedSysEnv(variable)) return true; } return false; } }}; } @Override protected ListTableModel createListModel() { return new ListTableModel(new MyNameColumnInfo(), new MyValueColumnInfo()); } protected class MyNameColumnInfo extends EnvVariablesTable.NameColumnInfo { private final DefaultTableCellRenderer myModifiedRenderer = new DefaultTableCellRenderer() { @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { Component component = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); component.setEnabled(table.isEnabled() && (hasFocus || isSelected)); return component; } }; @Override public TableCellRenderer getCustomizedRenderer(EnvironmentVariable o, TableCellRenderer renderer) { return o.getNameIsWriteable() ? renderer : myModifiedRenderer; } } protected class MyValueColumnInfo extends EnvVariablesTable.ValueColumnInfo { private final DefaultTableCellRenderer myModifiedRenderer = new DefaultTableCellRenderer() { @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { Component component = super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); component.setFont(component.getFont().deriveFont(Font.BOLD)); if (!hasFocus && !isSelected) { component.setForeground(JBUI.CurrentTheme.Link.linkColor()); } return component; } }; @Override public boolean isCellEditable(EnvironmentVariable environmentVariable) { return true; } @Override public TableCellRenderer getCustomizedRenderer(EnvironmentVariable o, TableCellRenderer renderer) { return isModifiedSysEnv(o) ? myModifiedRenderer : renderer; } } } private boolean isModifiedSysEnv(@NotNull EnvironmentVariable v) { return !v.getNameIsWriteable() && !Comparing.equal(v.getValue(), myParentDefaults.get(v.getName())); } }
//======================================================================== //Copyright 2007-2009 David Yu dyuproject@gmail.com //------------------------------------------------------------------------ //Licensed under the Apache License, Version 2.0 (the "License"); //you may not use this file except in compliance with the License. //You may obtain a copy of the License at //http://www.apache.org/licenses/LICENSE-2.0 //Unless required by applicable law or agreed to in writing, software //distributed under the License is distributed on an "AS IS" BASIS, //WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. //See the License for the specific language governing permissions and //limitations under the License. //======================================================================== // Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // http://code.google.com/p/protobuf/ // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package com.dyuproject.protostuff.me; import java.io.DataOutput; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; /** * Immutable array of bytes. * * @author crazybob@google.com Bob Lee * @author kenton@google.com Kenton Varda * @author David Yu */ public final class ByteString { //START EXTRA // internal package access to avoid double memory allocation static ByteString wrap(byte[] bytes) { return new ByteString(bytes); } // internal package access to avoid double memory allocation byte[] getBytes() { return bytes; } /** Writes the bytes to the {@link OutputStream}. */ public static void writeTo(OutputStream out, ByteString bs) throws IOException { out.write(bs.bytes); } /** Writes the bytes to the {@link DataOutput}. */ public static void writeTo(DataOutput out, ByteString bs) throws IOException { out.write(bs.bytes); } /** Writes the bytes to the {@link Output}. */ public static void writeTo(Output output, ByteString bs, int fieldNumber, boolean repeated) throws IOException { output.writeByteArray(fieldNumber, bs.bytes, repeated); } public String toString() { return toStringUtf8(); } //END EXTRA private final byte[] bytes; private ByteString(final byte[] bytes) { this.bytes = bytes; } /** * Gets the byte at the given index. * * @throws ArrayIndexOutOfBoundsException {@code index} is < 0 or >= size */ public byte byteAt(final int index) { return bytes[index]; } /** * Gets the number of bytes. */ public int size() { return bytes.length; } /** * Returns {@code true} if the size is {@code 0}, {@code false} otherwise. */ public boolean isEmpty() { return bytes.length == 0; } // ================================================================= // byte[] -> ByteString /** * Empty String. */ public static final String EMPTY_STRING = ""; /** * Empty byte array. */ public static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; /** * Empty ByteString. */ public static final ByteString EMPTY = new ByteString(EMPTY_BYTE_ARRAY); /** * Copies the given bytes into a {@code ByteString}. */ public static ByteString copyFrom(final byte[] bytes, final int offset, final int size) { final byte[] copy = new byte[size]; System.arraycopy(bytes, offset, copy, 0, size); return new ByteString(copy); } /** * Copies the given bytes into a {@code ByteString}. */ public static ByteString copyFrom(final byte[] bytes) { return copyFrom(bytes, 0, bytes.length); } /** * Encodes {@code text} into a sequence of bytes using the named charset * and returns the result as a {@code ByteString}. */ public static ByteString copyFrom(final String text, final String charsetName) { try { return new ByteString(text.getBytes(charsetName)); } catch (UnsupportedEncodingException e) { throw new RuntimeException(charsetName + " not supported?"); } } /** * Encodes {@code text} into a sequence of UTF-8 bytes and returns the * result as a {@code ByteString}. */ public static ByteString copyFromUtf8(final String text) { return new ByteString(StringSerializer.STRING.ser(text)); /*@try { return new ByteString(text.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new RuntimeException("UTF-8 not supported?", e); }*/ } // ================================================================= // ByteString -> byte[] /** * Copies bytes into a buffer at the given offset. * * @param target buffer to copy into * @param offset in the target buffer */ public void copyTo(final byte[] target, final int offset) { System.arraycopy(bytes, 0, target, offset, bytes.length); } /** * Copies bytes into a buffer. * * @param target buffer to copy into * @param sourceOffset offset within these bytes * @param targetOffset offset within the target buffer * @param size number of bytes to copy */ public void copyTo(final byte[] target, final int sourceOffset, final int targetOffset, final int size) { System.arraycopy(bytes, sourceOffset, target, targetOffset, size); } /** * Copies bytes to a {@code byte[]}. */ public byte[] toByteArray() { final int size = bytes.length; final byte[] copy = new byte[size]; System.arraycopy(bytes, 0, copy, 0, size); return copy; } /*@ * Constructs a new read-only {@code java.nio.ByteBuffer} with the * same backing byte array. */ /*@public ByteBuffer asReadOnlyByteBuffer() { final ByteBuffer byteBuffer = ByteBuffer.wrap(bytes); return byteBuffer.asReadOnlyBuffer(); }*/ /*@ * Constructs a new {@code String} by decoding the bytes using the * specified charset. */ /*@public String toString(final String charsetName) throws UnsupportedEncodingException { return new String(bytes, charsetName); }*/ /** * Constructs a new {@code String} by decoding the bytes as UTF-8. */ public String toStringUtf8() { return StringSerializer.STRING.deser(bytes); /*@try { return new String(bytes, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new RuntimeException("UTF-8 not supported?", e); }*/ } // ================================================================= // equals() and hashCode() //@Override public boolean equals(final Object o) { if (o == this) { return true; } if (!(o instanceof ByteString)) { return false; } final ByteString other = (ByteString) o; final int size = bytes.length; if (size != other.bytes.length) { return false; } final byte[] thisBytes = bytes; final byte[] otherBytes = other.bytes; for (int i = 0; i < size; i++) { if (thisBytes[i] != otherBytes[i]) { return false; } } return true; } private volatile int hash = 0; //@Override public int hashCode() { int h = hash; if (h == 0) { final byte[] thisBytes = bytes; final int size = bytes.length; h = size; for (int i = 0; i < size; i++) { h = h * 31 + thisBytes[i]; } if (h == 0) { h = 1; } hash = h; } return h; } // ================================================================= // Input stream /*@ * Creates an {@code InputStream} which can be used to read the bytes. */ /*@public InputStream newInput() { return new ByteArrayInputStream(bytes); }*/ /*@ * Creates a {@link CodedInputStream} which can be used to read the bytes. * Using this is more efficient than creating a {@link CodedInputStream} * wrapping the result of {@link #newInput()}. */ /*@public CodedInputStream newCodedInput() { // We trust CodedInputStream not to modify the bytes, or to give anyone // else access to them. return CodedInputStream.newInstance(bytes); }*/ // ================================================================= // Output stream /*@ * Creates a new {@link Output} with the given initial capacity. */ /*@public static Output newOutput(final int initialCapacity) { return new Output(new ByteArrayOutputStream(initialCapacity)); }*/ /*@ * Creates a new {@link Output}. */ /*@public static Output newOutput() { return newOutput(32); }*/ /*@ * Outputs to a {@code ByteString} instance. Call {@link #toByteString()} to * create the {@code ByteString} instance. */ /*@public static final class Output extends FilterOutputStream { private final ByteArrayOutputStream bout; /** * Constructs a new output with the given initial capacity. *@ private Output(final ByteArrayOutputStream bout) { super(bout); this.bout = bout; } /** * Creates a {@code ByteString} instance from this {@code Output}. *@ public ByteString toByteString() { final byte[] byteArray = bout.toByteArray(); return new ByteString(byteArray); } } /** * Constructs a new ByteString builder, which allows you to efficiently * construct a {@code ByteString} by writing to a {@link CodedOutputStream}. * Using this is much more efficient than calling {@code newOutput()} and * wrapping that in a {@code CodedOutputStream}. * * <p>This is package-private because it's a somewhat confusing interface. * Users can call {@link Message#toByteString()} instead of calling this * directly. * * @param size The target byte size of the {@code ByteString}. You must * write exactly this many bytes before building the result. *@ static CodedBuilder newCodedBuilder(final int size) { return new CodedBuilder(size); } /** See {@link ByteString#newCodedBuilder(int)}. *@ static final class CodedBuilder { private final CodedOutputStream output; private final byte[] buffer; private CodedBuilder(final int size) { buffer = new byte[size]; output = CodedOutputStream.newInstance(buffer); } public ByteString build() { output.checkNoSpaceLeft(); // We can be confident that the CodedOutputStream will not modify the // underlying bytes anymore because it already wrote all of them. So, // no need to make a copy. return new ByteString(buffer); } public CodedOutputStream getCodedOutput() { return output; } }*/ // moved from Internal.java /** * Helper called by generated code to construct default values for string * fields. * <p> * The protocol compiler does not actually contain a UTF-8 decoder -- it * just pushes UTF-8-encoded text around without touching it. The one place * where this presents a problem is when generating Java string literals. * Unicode characters in the string literal would normally need to be encoded * using a Unicode escape sequence, which would require decoding them. * To get around this, protoc instead embeds the UTF-8 bytes into the * generated code and leaves it to the runtime library to decode them. * <p> * It gets worse, though. If protoc just generated a byte array, like: * new byte[] {0x12, 0x34, 0x56, 0x78} * Java actually generates *code* which allocates an array and then fills * in each value. This is much less efficient than just embedding the bytes * directly into the bytecode. To get around this, we need another * work-around. String literals are embedded directly, so protoc actually * generates a string literal corresponding to the bytes. The easiest way * to do this is to use the ISO-8859-1 character set, which corresponds to * the first 256 characters of the Unicode range. Protoc can then use * good old CEscape to generate the string. * <p> * So we have a string literal which represents a set of bytes which * represents another string. This function -- stringDefaultValue -- * converts from the generated string to the string we actually want. The * generated code calls this automatically. */ public static String stringDefaultValue(String bytes) { try { return new String(bytes.getBytes("ISO-8859-1"), "UTF-8"); } catch (UnsupportedEncodingException e) { // This should never happen since all JVMs are required to implement // both of the above character sets. throw new IllegalStateException( "Java VM does not support a standard character set."); } } /** * Helper called by generated code to construct default values for bytes * fields. * <p> * This is a lot like {@link #stringDefaultValue}, but for bytes fields. * In this case we only need the second of the two hacks -- allowing us to * embed raw bytes as a string literal with ISO-8859-1 encoding. */ public static ByteString bytesDefaultValue(String bytes) { try { return ByteString.wrap(bytes.getBytes("ISO-8859-1")); } catch (UnsupportedEncodingException e) { // This should never happen since all JVMs are required to implement // ISO-8859-1. throw new IllegalStateException( "Java VM does not support a standard character set."); } } }
package com.reactnativenavigation.controllers; import android.annotation.TargetApi; import android.content.Intent; import android.content.res.Configuration; import android.os.Build; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v7.app.AppCompatActivity; import android.view.KeyEvent; import android.view.Window; import com.facebook.react.bridge.Callback; import com.facebook.react.modules.core.DefaultHardwareBackBtnHandler; import com.facebook.react.modules.core.PermissionAwareActivity; import com.facebook.react.modules.core.PermissionListener; import com.reactnativenavigation.NavigationApplication; import com.reactnativenavigation.events.Event; import com.reactnativenavigation.events.EventBus; import com.reactnativenavigation.events.JsDevReloadEvent; import com.reactnativenavigation.events.ModalDismissedEvent; import com.reactnativenavigation.events.Subscriber; import com.reactnativenavigation.layouts.BottomTabsLayout; import com.reactnativenavigation.layouts.Layout; import com.reactnativenavigation.layouts.LayoutFactory; import com.reactnativenavigation.params.ActivityParams; import com.reactnativenavigation.params.AppStyle; import com.reactnativenavigation.params.ContextualMenuParams; import com.reactnativenavigation.params.FabParams; import com.reactnativenavigation.params.LightBoxParams; import com.reactnativenavigation.params.ScreenParams; import com.reactnativenavigation.params.SlidingOverlayParams; import com.reactnativenavigation.params.SnackbarParams; import com.reactnativenavigation.params.TitleBarButtonParams; import com.reactnativenavigation.params.TitleBarLeftButtonParams; import com.reactnativenavigation.react.ReactGateway; import com.reactnativenavigation.screens.Screen; import com.reactnativenavigation.utils.OrientationHelper; import com.reactnativenavigation.views.SideMenu.Side; import java.util.List; public class NavigationActivity extends AppCompatActivity implements DefaultHardwareBackBtnHandler, Subscriber, PermissionAwareActivity { /** * Although we start multiple activities, we make sure to pass Intent.CLEAR_TASK | Intent.NEW_TASK * So that we actually have only 1 instance of the activity running at one time. * We hold the currentActivity (resume->pause) so we know when we need to destroy the javascript context * (when currentActivity is null, ie pause and destroy was called without resume). * This is somewhat weird, and in the future we better use a single activity with changing contentView similar to ReactNative impl. * Along with that, we should handle commands from the bridge using onNewIntent */ static NavigationActivity currentActivity; private ActivityParams activityParams; private ModalController modalController; private Layout layout; @Nullable private PermissionListener mPermissionListener; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (!NavigationApplication.instance.isReactContextInitialized()) { NavigationApplication.instance.startReactContextOnceInBackgroundAndExecuteJS(); return; } activityParams = NavigationCommandsHandler.parseActivityParams(getIntent()); disableActivityShowAnimationIfNeeded(); setOrientation(); createModalController(); createLayout(); NavigationApplication.instance.getActivityCallbacks().onActivityCreated(this, savedInstanceState); } private void setOrientation() { OrientationHelper.setOrientation(this, AppStyle.appStyle.orientation); } private void disableActivityShowAnimationIfNeeded() { if (!activityParams.animateShow) { overridePendingTransition(0, 0); } } private void createModalController() { modalController = new ModalController(this); } private void createLayout() { layout = LayoutFactory.create(this, activityParams); if (hasBackgroundColor()) { layout.asView().setBackgroundColor(AppStyle.appStyle.screenBackgroundColor.getColor()); } setContentView(layout.asView()); } private boolean hasBackgroundColor() { return AppStyle.appStyle.screenBackgroundColor != null && AppStyle.appStyle.screenBackgroundColor.hasColor(); } @Override protected void onStart() { super.onStart(); NavigationApplication.instance.getActivityCallbacks().onActivityStarted(this); } @Override protected void onResume() { super.onResume(); if (isFinishing() || !NavigationApplication.instance.isReactContextInitialized()) { return; } currentActivity = this; IntentDataHandler.onResume(getIntent()); getReactGateway().onResumeActivity(this, this); NavigationApplication.instance.getActivityCallbacks().onActivityResumed(this); EventBus.instance.register(this); IntentDataHandler.onPostResume(getIntent()); } @Override protected void onNewIntent(Intent intent) { super.onNewIntent(intent); getReactGateway().onNewIntent(intent); NavigationApplication.instance.getActivityCallbacks().onNewIntent(intent); } @Override protected void onPause() { super.onPause(); currentActivity = null; IntentDataHandler.onPause(getIntent()); getReactGateway().onPauseActivity(); NavigationApplication.instance.getActivityCallbacks().onActivityPaused(this); EventBus.instance.unregister(this); } @Override protected void onStop() { super.onStop(); NavigationApplication.instance.getActivityCallbacks().onActivityStopped(this); } @Override protected void onDestroy() { destroyLayouts(); destroyJsIfNeeded(); NavigationApplication.instance.getActivityCallbacks().onActivityDestroyed(this); super.onDestroy(); } private void destroyLayouts() { if (modalController != null) { modalController.destroy(); } if (layout != null) { layout.destroy(); layout = null; } } private void destroyJsIfNeeded() { if (currentActivity == null || currentActivity.isFinishing()) { getReactGateway().onDestroyApp(); } } @Override public void invokeDefaultOnBackPressed() { super.onBackPressed(); } @Override public void onBackPressed() { if (layout != null && !layout.onBackPressed()) { getReactGateway().onBackPressed(); } } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { getReactGateway().onActivityResult(requestCode, resultCode, data); NavigationApplication.instance.getActivityCallbacks().onActivityResult(requestCode, resultCode, data); } @Override public boolean onKeyUp(int keyCode, KeyEvent event) { return getReactGateway().onKeyUp(getCurrentFocus(), keyCode) || super.onKeyUp(keyCode, event); } private ReactGateway getReactGateway() { return NavigationApplication.instance.getReactGateway(); } @Override public void onConfigurationChanged(Configuration newConfig) { OrientationHelper.onConfigurationChanged(newConfig); NavigationApplication.instance.getActivityCallbacks().onConfigurationChanged(newConfig); super.onConfigurationChanged(newConfig); } void push(ScreenParams params) { if (modalController.containsNavigator(params.getNavigatorId())) { modalController.push(params); } else { layout.push(params); } } void pop(ScreenParams params) { if (modalController.containsNavigator(params.getNavigatorId())) { modalController.pop(params); } else { layout.pop(params); } } void popToRoot(ScreenParams params) { if (modalController.containsNavigator(params.getNavigatorId())) { modalController.popToRoot(params); } else { layout.popToRoot(params); } } void newStack(ScreenParams params) { if (modalController.containsNavigator(params.getNavigatorId())) { modalController.newStack(params); } else { layout.newStack(params); } } void showModal(ScreenParams screenParams) { Screen previousScreen = layout.getCurrentScreen(); NavigationApplication.instance.getEventEmitter().sendScreenChangedEvent("willDisappear", previousScreen.getNavigatorEventId()); NavigationApplication.instance.getEventEmitter().sendScreenChangedEvent("didDisappear", previousScreen.getNavigatorEventId()); modalController.showModal(screenParams); } void dismissTopModal() { modalController.dismissTopModal(); Screen previousScreen = layout.getCurrentScreen(); NavigationApplication.instance.getEventEmitter().sendScreenChangedEvent("willAppear", previousScreen.getNavigatorEventId()); NavigationApplication.instance.getEventEmitter().sendScreenChangedEvent("didAppear", previousScreen.getNavigatorEventId()); } void dismissAllModals() { modalController.dismissAllModals(); Screen previousScreen = layout.getCurrentScreen(); NavigationApplication.instance.getEventEmitter().sendScreenChangedEvent("willAppear", previousScreen.getNavigatorEventId()); NavigationApplication.instance.getEventEmitter().sendScreenChangedEvent("didAppear", previousScreen.getNavigatorEventId()); } public void showLightBox(LightBoxParams params) { layout.showLightBox(params); } public void dismissLightBox() { layout.dismissLightBox(); } //TODO all these setters should be combined to something like setStyle void setTopBarVisible(String screenInstanceId, boolean hidden, boolean animated) { layout.setTopBarVisible(screenInstanceId, hidden, animated); modalController.setTopBarVisible(screenInstanceId, hidden, animated); } void setBottomTabsVisible(boolean hidden, boolean animated) { if (layout instanceof BottomTabsLayout) { ((BottomTabsLayout) layout).setBottomTabsVisible(hidden, animated); } } void setTitleBarTitle(String screenInstanceId, String title) { layout.setTitleBarTitle(screenInstanceId, title); modalController.setTitleBarTitle(screenInstanceId, title); } public void setTitleBarSubtitle(String screenInstanceId, String subtitle) { layout.setTitleBarSubtitle(screenInstanceId, subtitle); modalController.setTitleBarSubtitle(screenInstanceId, subtitle); } void setTitleBarButtons(String screenInstanceId, String navigatorEventId, List<TitleBarButtonParams> titleBarButtons) { layout.setTitleBarRightButtons(screenInstanceId, navigatorEventId, titleBarButtons); modalController.setTitleBarRightButtons(screenInstanceId, navigatorEventId, titleBarButtons); } void setTitleBarLeftButton(String screenInstanceId, String navigatorEventId, TitleBarLeftButtonParams titleBarLeftButton) { layout.setTitleBarLeftButton(screenInstanceId, navigatorEventId, titleBarLeftButton); modalController.setTitleBarLeftButton(screenInstanceId, navigatorEventId, titleBarLeftButton); } void setScreenFab(String screenInstanceId, String navigatorEventId, FabParams fab) { layout.setFab(screenInstanceId, navigatorEventId, fab); modalController.setFab(screenInstanceId, navigatorEventId, fab); } public void setScreenStyle(String screenInstanceId, Bundle styleParams) { layout.updateScreenStyle(screenInstanceId, styleParams); modalController.updateScreenStyle(screenInstanceId, styleParams); } public void toggleSideMenuVisible(boolean animated, Side side) { layout.toggleSideMenuVisible(animated, side); } public void setSideMenuVisible(boolean animated, boolean visible, Side side) { layout.setSideMenuVisible(animated, visible, side); } public void selectTopTabByTabIndex(String screenInstanceId, int index) { layout.selectTopTabByTabIndex(screenInstanceId, index); modalController.selectTopTabByTabIndex(screenInstanceId, index); } public void selectTopTabByScreen(String screenInstanceId) { layout.selectTopTabByScreen(screenInstanceId); modalController.selectTopTabByScreen(screenInstanceId); } public void selectBottomTabByTabIndex(Integer index) { if (layout instanceof BottomTabsLayout) { ((BottomTabsLayout) layout).selectBottomTabByTabIndex(index); } } public void selectBottomTabByNavigatorId(String navigatorId) { if (layout instanceof BottomTabsLayout) { ((BottomTabsLayout) layout).selectBottomTabByNavigatorId(navigatorId); } } public void setBottomTabBadgeByIndex(Integer index, String badge) { if (layout instanceof BottomTabsLayout) { ((BottomTabsLayout) layout).setBottomTabBadgeByIndex(index, badge); } } public void setBottomTabBadgeByNavigatorId(String navigatorId, String badge) { if (layout instanceof BottomTabsLayout) { ((BottomTabsLayout) layout).setBottomTabBadgeByNavigatorId(navigatorId, badge); } } public void setBottomTabButtonByIndex(Integer index, ScreenParams params) { if (layout instanceof BottomTabsLayout) { ((BottomTabsLayout) layout).setBottomTabButtonByIndex(index, params); } } public void setBottomTabButtonByNavigatorId(String navigatorId, ScreenParams params) { if (layout instanceof BottomTabsLayout) { ((BottomTabsLayout) layout).setBottomTabButtonByNavigatorId(navigatorId, params); } } public void showSlidingOverlay(SlidingOverlayParams params) { if (modalController.isShowing()) { modalController.showSlidingOverlay(params); } else { layout.showSlidingOverlay(params); } } public void hideSlidingOverlay() { if (modalController.isShowing()) { modalController.hideSlidingOverlay(); } else { layout.hideSlidingOverlay(); } } public void showSnackbar(SnackbarParams params) { layout.showSnackbar(params); } public void dismissSnackbar() { layout.dismissSnackbar(); } public void showContextualMenu(String screenInstanceId, ContextualMenuParams params, Callback onButtonClicked) { if (modalController.isShowing()) { modalController.showContextualMenu(screenInstanceId, params, onButtonClicked); } else { layout.showContextualMenu(screenInstanceId, params, onButtonClicked); } } public void dismissContextualMenu(String screenInstanceId) { if (modalController.isShowing()) { modalController.dismissContextualMenu(screenInstanceId); } else { layout.dismissContextualMenu(screenInstanceId); } } @Override public void onEvent(Event event) { if (event.getType().equals(ModalDismissedEvent.TYPE)) { handleModalDismissedEvent(); } else if (event.getType().equals(JsDevReloadEvent.TYPE)) { postHandleJsDevReloadEvent(); } } private void handleModalDismissedEvent() { if (!modalController.isShowing()) { layout.onModalDismissed(); OrientationHelper.setOrientation(this, AppStyle.appStyle.orientation); } } public Window getScreenWindow() { return modalController.isShowing() ? modalController.getWindow() : getWindow(); } private void postHandleJsDevReloadEvent() { NavigationApplication.instance.runOnMainThread(new Runnable() { @Override public void run() { layout.destroy(); modalController.destroy(); } }); } @TargetApi(Build.VERSION_CODES.M) public void requestPermissions(String[] permissions, int requestCode, PermissionListener listener) { mPermissionListener = listener; requestPermissions(permissions, requestCode); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { NavigationApplication.instance.getActivityCallbacks().onRequestPermissionsResult(requestCode, permissions, grantResults); if (mPermissionListener != null && mPermissionListener.onRequestPermissionsResult(requestCode, permissions, grantResults)) { mPermissionListener = null; } } }
// Copyright 2017 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package build.buildfarm.common; import build.bazel.remote.execution.v2.Action; import build.bazel.remote.execution.v2.Digest; import build.bazel.remote.execution.v2.DigestFunction; import build.bazel.remote.execution.v2.Directory; import build.bazel.remote.execution.v2.Tree; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Sets; import com.google.common.hash.Funnels; import com.google.common.hash.HashCode; import com.google.common.hash.Hasher; import com.google.common.hash.Hashing; import com.google.common.hash.HashingOutputStream; import com.google.common.io.ByteSource; import com.google.protobuf.ByteString; import com.google.protobuf.Descriptors.EnumValueDescriptor; import com.google.protobuf.Message; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collection; import java.util.Map; import java.util.Set; /** Utility methods to work with {@link Digest}. */ public class DigestUtil { /** Type of hash function to use for digesting blobs. */ // The underlying HashFunctions are immutable and thread safe. @SuppressWarnings("ImmutableEnumChecker") public enum HashFunction { @SuppressWarnings("deprecation") MD5(Hashing.md5()), @SuppressWarnings("deprecation") SHA1(Hashing.sha1()), SHA256(Hashing.sha256()); private final com.google.common.hash.HashFunction hash; final HashCode empty; HashFunction(com.google.common.hash.HashFunction hash) { this.hash = hash; empty = this.hash.newHasher().hash(); } public DigestFunction.Value getDigestFunction() { if (this == SHA256) { return DigestFunction.Value.SHA256; } if (this == SHA1) { return DigestFunction.Value.SHA1; } if (this == MD5) { return DigestFunction.Value.MD5; } return DigestFunction.Value.UNKNOWN; } public static HashFunction forHash(String hexDigest) { if (SHA256.isValidHexDigest(hexDigest)) { return SHA256; } if (SHA1.isValidHexDigest(hexDigest)) { return SHA1; } if (MD5.isValidHexDigest(hexDigest)) { return MD5; } throw new IllegalArgumentException("hash type unrecognized: " + hexDigest); } public static HashFunction get(DigestFunction.Value digestFunction) { switch (digestFunction) { default: case UNRECOGNIZED: case UNKNOWN: throw new IllegalArgumentException(digestFunction.toString()); case SHA256: return SHA256; case SHA1: return SHA1; case MD5: return MD5; } } public com.google.common.hash.HashFunction getHash() { return hash; } public boolean isValidHexDigest(String hexDigest) { return hexDigest != null && hexDigest.length() * 8 / 2 == hash.bits(); } public HashCode empty() { return empty; } } /** * A special type of Digest that is used only as a remote action cache key. This is a separate * type in order to prevent accidentally using other Digests as action keys. */ public static final class ActionKey { private final Digest digest; public Digest getDigest() { return digest; } private ActionKey(Digest digest) { this.digest = digest; } @Override public boolean equals(Object o) { if (o instanceof ActionKey) { ActionKey actionKey = (ActionKey) o; return digest.equals(actionKey.getDigest()); } return false; } @Override public int hashCode() { return digest.hashCode(); } } private final HashFunction hashFn; private final Digest empty; public static DigestUtil forHash(String hashName) { EnumValueDescriptor hashEnumDescriptor = DigestFunction.Value.getDescriptor().findValueByName(hashName); if (hashEnumDescriptor == null) { throw new IllegalArgumentException("hash type unrecognized: " + hashName); } DigestFunction.Value digestFunction = DigestFunction.Value.valueOf(hashEnumDescriptor); HashFunction hashFunction = HashFunction.get(digestFunction); return new DigestUtil(hashFunction); } public DigestUtil(HashFunction hashFn) { this.hashFn = hashFn; empty = buildDigest(hashFn.empty().toString(), 0); } public DigestFunction.Value getDigestFunction() { return hashFn.getDigestFunction(); } public Digest compute(Path file) throws IOException { return buildDigest(computeHash(file), Files.size(file)); } private String computeHash(Path file) throws IOException { return new ByteSource() { @Override public InputStream openStream() throws IOException { return Files.newInputStream(file); } }.hash(hashFn.getHash()).toString(); } public HashCode computeHash(ByteString blob) { Hasher hasher = hashFn.getHash().newHasher(); try { blob.writeTo(Funnels.asOutputStream(hasher)); } catch (IOException e) { /* impossible, due to Funnels.asOutputStream behavior */ } return hasher.hash(); } public Digest compute(ByteString blob) { return buildDigest(computeHash(blob).toString(), blob.size()); } public Digest build(String hexHash, long size) { if (!hashFn.isValidHexDigest(hexHash)) { throw new NumberFormatException( String.format("[%s] is not a valid %s hash.", hexHash, hashFn.name())); } return buildDigest(hexHash, size); } public Digest build(byte[] hash, long size) { return build(HashCode.fromBytes(hash).toString(), size); } /** * Computes a digest of the given proto message. Currently, we simply rely on message output as * bytes, but this implementation relies on the stability of the proto encoding, in particular * between different platforms and languages. TODO(olaola): upgrade to a better implementation! */ public Digest compute(Message message) { return compute(message.toByteString()); } public ActionKey computeActionKey(Action action) { return new ActionKey(compute(action)); } /** * Assumes that the given Digest is a valid digest of an Action, and creates an ActionKey wrapper. */ public static ActionKey asActionKey(Digest digest) { return new ActionKey(digest); } public Digest empty() { return empty; } public static Digest buildDigest(String hexHash, long size) { return Digest.newBuilder().setHash(hexHash).setSizeBytes(size).build(); } public HashingOutputStream newHashingOutputStream(OutputStream out) { return new HashingOutputStream(hashFn.getHash(), out); } public static String toString(Digest digest) { return String.format("%s/%d", digest.getHash(), digest.getSizeBytes()); } public static Digest parseDigest(String digest) { String[] components = digest.split("/"); return Digest.newBuilder() .setHash(components[0]) .setSizeBytes(Long.parseLong(components[1])) .build(); } public static DigestUtil forDigest(Digest digest) { return new DigestUtil(HashFunction.forHash(digest.getHash())); } public static Map<Digest, Directory> proxyDirectoriesIndex( Map<String, Directory> directoriesIndex) { return new Map<Digest, Directory>() { @Override public void clear() { throw new UnsupportedOperationException(); } @Override public boolean containsKey(Object key) { if (key instanceof Digest) { return directoriesIndex.containsKey(DigestUtil.toString((Digest) key)); } return false; } @Override public boolean containsValue(Object value) { return directoriesIndex.containsValue(value); } @SuppressWarnings("NullableProblems") @Override public Set<Map.Entry<Digest, Directory>> entrySet() { throw new UnsupportedOperationException(); } @Override public boolean equals(Object o) { throw new UnsupportedOperationException(); } @Override public Directory get(Object key) { if (key instanceof Digest) { Digest digest = (Digest) key; return directoriesIndex.get(digest.getHash()); } return null; } @Override public int hashCode() { return directoriesIndex.hashCode(); } @Override public boolean isEmpty() { return directoriesIndex.isEmpty(); } @SuppressWarnings("NullableProblems") @Override public Set<Digest> keySet() { throw new UnsupportedOperationException(); } @Override public Directory put(Digest key, Directory value) { throw new UnsupportedOperationException(); } @SuppressWarnings("NullableProblems") @Override public void putAll(Map<? extends Digest, ? extends Directory> m) { throw new UnsupportedOperationException(); } @Override public Directory remove(Object key) { throw new UnsupportedOperationException(); } @Override public int size() { return directoriesIndex.size(); } @SuppressWarnings("NullableProblems") @Override public Collection<Directory> values() { return directoriesIndex.values(); } }; } public Map<Digest, Directory> createDirectoriesIndex(Tree tree) { Set<Digest> directoryDigests = Sets.newHashSet(); ImmutableMap.Builder<Digest, Directory> directoriesIndex = ImmutableMap.builder(); directoriesIndex.put(compute(tree.getRoot()), tree.getRoot()); for (Directory directory : tree.getChildrenList()) { Digest directoryDigest = compute(directory); if (!directoryDigests.add(directoryDigest)) { continue; } directoriesIndex.put(directoryDigest, directory); } return directoriesIndex.build(); } }
/* Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.camunda.bpm.engine.rest.dto.repository; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.ws.rs.core.MultivaluedMap; import org.camunda.bpm.engine.ProcessEngine; import org.camunda.bpm.engine.repository.ProcessDefinitionQuery; import org.camunda.bpm.engine.rest.dto.AbstractQueryDto; import org.camunda.bpm.engine.rest.dto.CamundaQueryParam; import org.camunda.bpm.engine.rest.dto.converter.BooleanConverter; import org.camunda.bpm.engine.rest.dto.converter.IntegerConverter; import org.camunda.bpm.engine.rest.dto.converter.StringListConverter; import com.fasterxml.jackson.databind.ObjectMapper; public class ProcessDefinitionQueryDto extends AbstractQueryDto<ProcessDefinitionQuery> { private static final String SORT_BY_CATEGORY_VALUE = "category"; private static final String SORT_BY_KEY_VALUE = "key"; private static final String SORT_BY_ID_VALUE = "id"; private static final String SORT_BY_NAME_VALUE = "name"; private static final String SORT_BY_VERSION_VALUE = "version"; private static final String SORT_BY_DEPLOYMENT_ID_VALUE = "deploymentId"; private static final List<String> VALID_SORT_BY_VALUES; static { VALID_SORT_BY_VALUES = new ArrayList<String>(); VALID_SORT_BY_VALUES.add(SORT_BY_CATEGORY_VALUE); VALID_SORT_BY_VALUES.add(SORT_BY_KEY_VALUE); VALID_SORT_BY_VALUES.add(SORT_BY_ID_VALUE); VALID_SORT_BY_VALUES.add(SORT_BY_NAME_VALUE); VALID_SORT_BY_VALUES.add(SORT_BY_VERSION_VALUE); VALID_SORT_BY_VALUES.add(SORT_BY_DEPLOYMENT_ID_VALUE); } private String processDefinitionId; private List<String> processDefinitionIdIn; private String category; private String categoryLike; private String name; private String nameLike; private String deploymentId; private String key; private String keyLike; private Integer version; private Boolean latestVersion; private String resourceName; private String resourceNameLike; private String startableBy; private Boolean active; private Boolean suspended; private String incidentId; private String incidentType; private String incidentMessage; private String incidentMessageLike; public ProcessDefinitionQueryDto() { } public ProcessDefinitionQueryDto(ObjectMapper objectMapper, MultivaluedMap<String, String> queryParameters) { super(objectMapper, queryParameters); } @CamundaQueryParam("processDefinitionId") public void setProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; } @CamundaQueryParam(value = "processDefinitionIdIn", converter = StringListConverter.class) public void setProcessDefinitionIdIn(List<String> processDefinitionIdIn) { this.processDefinitionIdIn = processDefinitionIdIn; } @CamundaQueryParam("category") public void setCategory(String category) { this.category = category; } @CamundaQueryParam("categoryLike") public void setCategoryLike(String categoryLike) { this.categoryLike = categoryLike; } @CamundaQueryParam("name") public void setName(String name) { this.name = name; } @CamundaQueryParam("nameLike") public void setNameLike(String nameLike) { this.nameLike = nameLike; } @CamundaQueryParam("deploymentId") public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } @CamundaQueryParam("key") public void setKey(String key) { this.key = key; } @CamundaQueryParam("keyLike") public void setKeyLike(String keyLike) { this.keyLike = keyLike; } /** * @deprecated use {@link #setVersion(Integer)} */ @Deprecated @CamundaQueryParam(value = "ver", converter = IntegerConverter.class) public void setVer(Integer ver) { setVersion(ver); } @CamundaQueryParam(value = "version", converter = IntegerConverter.class) public void setVersion(Integer version) { this.version = version; } /** * @deprecated use {@link #setLatestVersion(Boolean)} */ @Deprecated @CamundaQueryParam(value = "latest", converter = BooleanConverter.class) public void setLatest(Boolean latest) { setLatestVersion(latest); } @CamundaQueryParam(value = "latestVersion", converter = BooleanConverter.class) public void setLatestVersion(Boolean latestVersion) { this.latestVersion = latestVersion; } @CamundaQueryParam("resourceName") public void setResourceName(String resourceName) { this.resourceName = resourceName; } @CamundaQueryParam("resourceNameLike") public void setResourceNameLike(String resourceNameLike) { this.resourceNameLike = resourceNameLike; } @CamundaQueryParam("startableBy") public void setStartableBy(String startableBy) { this.startableBy = startableBy; } @CamundaQueryParam(value = "active", converter = BooleanConverter.class) public void setActive(Boolean active) { this.active = active; } @CamundaQueryParam(value = "suspended", converter = BooleanConverter.class) public void setSuspended(Boolean suspended) { this.suspended = suspended; } @CamundaQueryParam(value = "incidentId") public void setIncidentId(String incidentId) { this.incidentId = incidentId; } @CamundaQueryParam(value = "incidentType") public void setIncidentType(String incidentType) { this.incidentType = incidentType; } @CamundaQueryParam(value = "incidentMessage") public void setIncidentMessage(String incidentMessage) { this.incidentMessage = incidentMessage; } @CamundaQueryParam(value = "incidentMessageLike") public void setIncidentMessageLike(String incidentMessageLike) { this.incidentMessageLike = incidentMessageLike; } @Override protected boolean isValidSortByValue(String value) { return VALID_SORT_BY_VALUES.contains(value); } @Override protected ProcessDefinitionQuery createNewQuery(ProcessEngine engine) { return engine.getRepositoryService().createProcessDefinitionQuery(); } @Override protected void applyFilters(ProcessDefinitionQuery query) { if (processDefinitionId != null) { query.processDefinitionId(processDefinitionId); } if (processDefinitionIdIn != null && !processDefinitionIdIn.isEmpty()) { query.processDefinitionIdIn(processDefinitionIdIn.toArray(new String[processDefinitionIdIn.size()])); } if (category != null) { query.processDefinitionCategory(category); } if (categoryLike != null) { query.processDefinitionCategoryLike(categoryLike); } if (name != null) { query.processDefinitionName(name); } if (nameLike != null) { query.processDefinitionNameLike(nameLike); } if (deploymentId != null) { query.deploymentId(deploymentId); } if (key != null) { query.processDefinitionKey(key); } if (keyLike != null) { query.processDefinitionKeyLike(keyLike); } if (version != null) { query.processDefinitionVersion(version); } if (latestVersion != null && latestVersion == true) { query.latestVersion(); } if (resourceName != null) { query.processDefinitionResourceName(resourceName); } if (resourceNameLike != null) { query.processDefinitionResourceNameLike(resourceNameLike); } if (startableBy != null) { query.startableByUser(startableBy); } if (active != null && active == true) { query.active(); } if (suspended != null && suspended == true) { query.suspended(); } if (incidentId != null) { query.incidentId(incidentId); } if (incidentType != null) { query.incidentType(incidentType); } if (incidentMessage != null) { query.incidentMessage(incidentMessage); } if (incidentMessageLike != null) { query.incidentMessageLike(incidentMessageLike); } } @Override protected void applySortBy(ProcessDefinitionQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) { if (sortBy.equals(SORT_BY_CATEGORY_VALUE)) { query.orderByProcessDefinitionCategory(); } else if (sortBy.equals(SORT_BY_KEY_VALUE)) { query.orderByProcessDefinitionKey(); } else if (sortBy.equals(SORT_BY_ID_VALUE)) { query.orderByProcessDefinitionId(); } else if (sortBy.equals(SORT_BY_VERSION_VALUE)) { query.orderByProcessDefinitionVersion(); } else if (sortBy.equals(SORT_BY_NAME_VALUE)) { query.orderByProcessDefinitionName(); } else if (sortBy.equals(SORT_BY_DEPLOYMENT_ID_VALUE)) { query.orderByDeploymentId(); } } }
/* * Copyright (c) 2010-2015 Pivotal Software, Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you * may not use this file except in compliance with the License. You * may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied. See the License for the specific language governing * permissions and limitations under the License. See accompanying * LICENSE file. */ package com.gemstone.gemfire.internal.cache; import com.gemstone.gemfire.cache.EntryEvent; import com.gemstone.gemfire.cache.EntryNotFoundException; import com.gemstone.gemfire.distributed.internal.DM; import com.gemstone.gemfire.internal.cache.store.SerializedDiskBuffer; import com.gemstone.gemfire.internal.cache.versions.VersionTag; import com.gemstone.gemfire.internal.offheap.annotations.Retained; import com.gemstone.gemfire.internal.shared.Version; /** * Abstract implementation class of RegionEntry interface. * This is adds Disk support behaviour * * @since 3.5.1 * * @author Darrel Schneider * */ @SuppressWarnings("serial") public abstract class AbstractOplogDiskRegionEntry extends AbstractDiskRegionEntry { protected AbstractOplogDiskRegionEntry(RegionEntryContext context, Object value) { super(context, value); } ///////////////////////////////////////////////////////////// /////////////////////////// fields ////////////////////////// ///////////////////////////////////////////////////////////// // Do not add any instance fields to this class. // Instead add them to the DISK section of LeafRegionEntry.cpp ///////////////////////////////////////////////////////////////////// ////////////////////////// instance methods ///////////////////////// ///////////////////////////////////////////////////////////////////// protected abstract void setDiskId(RegionEntry oldRe); @Override protected final void initContextForDiskBuffer(RegionEntryContext context, Object value) { if (value instanceof SerializedDiskBuffer) { ((SerializedDiskBuffer)value).setDiskEntry(this, context); } } public final void setDiskIdForRegion(RegionEntryContext context, RegionEntry oldRe) { setDiskId(oldRe); if (!isOffHeap()) { initContextForDiskBuffer(context, getValueField()); } } @Override public final void removePhase1(LocalRegion r, boolean isClear) throws RegionClearedException { synchronized (this) { Helper.removeFromDisk(this, r, isClear); _removePhase1(r); } } @Override public void removePhase2(LocalRegion r) { Object syncObj = getDiskId(); if (syncObj == null) { syncObj = this; } synchronized (syncObj) { super.removePhase2(r); } } @Override public final boolean fillInValue(LocalRegion r, InitialImageOperation.Entry entry, DM mgr, Version targetVersion) { return Helper.fillInValue(this, entry, r, mgr, r, targetVersion); } @Override public final boolean isOverflowedToDisk(LocalRegion r, DistributedRegion.DiskPosition dp, boolean alwaysFetchPosition) { return Helper.isOverflowedToDisk(this, r.getDiskRegion(), dp, alwaysFetchPosition); } @Retained @Override public final Object getValue(RegionEntryContext context) { return Helper.faultInValue(this, (LocalRegion) context); // OFFHEAP returned to callers } @Override public final Object getValueInVMOrDiskWithoutFaultIn(LocalRegion owner) { return Helper.getValueOffHeapOrDiskWithoutFaultIn(this, owner, true); } @Retained @Override public Object getValueOffHeapOrDiskWithoutFaultIn(LocalRegion owner) { return Helper.getValueOffHeapOrDiskWithoutFaultIn(this, owner, false); } @Retained @Override public Object getValueOffHeapOrDiskWithoutFaultIn(LocalRegion owner, DiskRegion dr) { return Helper.getValueOffHeapOrDiskWithoutFaultIn(this, owner, dr, false); } @Override public final Object getValueOnDisk(LocalRegion r) throws EntryNotFoundException { return Helper.getValueOnDisk(this, r.getDiskRegion()); } @Override public final Object getSerializedValueOnDisk(LocalRegion r) throws EntryNotFoundException { return Helper.getSerializedValueOnDisk(this, r.getDiskRegion()); } @Override public final Object getValueOnDiskOrBuffer(LocalRegion r) throws EntryNotFoundException { // @todo darrel if value is Token.REMOVED || Token.DESTROYED throw // EntryNotFoundException return Helper.getValueOnDiskOrBuffer(this, r.getDiskRegion(), r); } public DiskEntry getPrev() { return getDiskId().getPrev(); } public DiskEntry getNext() { return getDiskId().getNext(); } public void setPrev(DiskEntry v) { getDiskId().setPrev(v); } public void setNext(DiskEntry v) { getDiskId().setNext(v); } /* * If detected a conflict event, persist region needs to persist both the * golden copy and conflict tag */ @Override public void persistConflictingTag(LocalRegion region, VersionTag tag) { // only persist region needs to persist conflict tag Helper.updateVersionOnly(this, region, tag); setRecentlyUsed(); } /** * Process a version tag. This overrides AbtractRegionEntry so * we can check to see if the old value was recovered from disk. * If so, we don't check for conflicts. */ @Override public void processVersionTag(EntryEvent cacheEvent) { DiskId did = getDiskId(); boolean checkConflicts = true; if(did != null) { LocalRegion lr = (LocalRegion)cacheEvent.getRegion(); if (lr != null && lr.getDiskRegion().isReadyForRecovery()) { synchronized(did) { checkConflicts = !EntryBits.isRecoveredFromDisk(did.getUserBits()); } } } processVersionTag(cacheEvent, checkConflicts); } /** * Returns true if the DiskEntry value is equal to {@link Token#DESTROYED}, {@link Token#REMOVED_PHASE1}, or {@link Token#REMOVED_PHASE2}. */ @Override public boolean isRemovedFromDisk() { return Token.isRemovedFromDisk(getValueAsToken()); } }
package org.bioconductor.rserviceJms.services.caMachineLearning; import java.io.BufferedInputStream; import junit.framework.JUnit4TestAdapter; import org.junit.BeforeClass; import org.junit.Test; import org.junit.Ignore; import static org.junit.Assert.*; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.rmi.RemoteException; import org.omegahat.R.Java.RException; import org.omegahat.R.Java.ROmegahatInterpreter; import org.bioconductor.packages.caCommonClasses.*; import org.bioconductor.packages.caMachineLearning.*; public class caMachineLearningTest { private static caMachineLearning binding; /** * Used for backward compatibility (IDEs, Ant and JUnit 3.x text runner) */ public static junit.framework.Test suite() { return new JUnit4TestAdapter(caMachineLearningTest.class); } /** * Sets up the test fixture; Called before all the tests; Called only once. */ @BeforeClass public static void oneTimeSetUp() throws Exception { binding=new caMachineLearning(); } /** * We put this test here to let caMachineLearningTest work right out of box. */ @Test public void testcaMachineLearningService() { assertNotNull(binding); } /** * Tests caMachineLearning.caMachineLearning */ //@Ignore("please initialize function parameters") @Test public void TestcaMachineLearning() throws RemoteException { } /** * Tests supervised using a KNearestNeighborsMachineLearningParameters. */ //@Ignore("please initialize function parameters") @Test public void KNearestNeighborsTest() throws RemoteException { // Initialize the oneChannelExpressionData. OneChannelExpressionData oneChannelExpressionData = this.getOneChannelExpressionData(); // Read the KNearestNeighborsMachineLearningParameters object with which to test. InputStream inputStream = null; ObjectInput objectInput = null; KNearestNeighborsMachineLearningParameters parameters = null; try { inputStream = this.getClass().getResourceAsStream("../../worker/Data/KNearestNeighborsMachineLearningParameters.rda_java.Data"); objectInput = new ObjectInputStream (new BufferedInputStream( inputStream )); parameters = (KNearestNeighborsMachineLearningParameters)objectInput.readObject(); } catch (Exception ex) { ex.printStackTrace(); } finally { try { if (objectInput != null) objectInput.close(); } catch (IOException ioex) { ioex.printStackTrace(); } } // Execute the test. SupervisedMachineLearningResult knnResult = binding.supervised( oneChannelExpressionData, parameters ); } /** * Tests supervised using a SupportVectorMachineMachineLearningParameters. */ //@Ignore("please initialize function parameters") @Test public void SupportVectorMachineTest() throws RemoteException { // Initialize the oneChannelExpressionData. OneChannelExpressionData oneChannelExpressionData = this.getOneChannelExpressionData(); // Read the SupportVectorMachineMachineLearningParameters object with which to test. InputStream inputStream = null; ObjectInput objectInput = null; SupportVectorMachineMachineLearningParameters parameters = null; try { inputStream = this.getClass().getResourceAsStream("../../worker/Data/SupportVectorMachineMachineLearningParameters.rda_java.Data"); objectInput = new ObjectInputStream (new BufferedInputStream( inputStream )); parameters = (SupportVectorMachineMachineLearningParameters)objectInput.readObject(); } catch (Exception ex) { ex.printStackTrace(); } finally { try { if (objectInput != null) objectInput.close(); } catch (IOException ioex) { ioex.printStackTrace(); } } // Execute the test. SupervisedMachineLearningResult svmResult = binding.supervised( oneChannelExpressionData, parameters ); } /** * Tests supervised using a LinearDiscriminantAnalysisMachineLearningParameters. */ //@Ignore("please initialize function parameters") @Test public void LinearDiscriminantAnalysisTest() throws RemoteException { // Initialize the oneChannelExpressionData. OneChannelExpressionData oneChannelExpressionData = this.getOneChannelExpressionData(); // Read the LinearDiscriminantAnalysisMachineLearningParameters object with which to test. InputStream inputStream = null; ObjectInput objectInput = null; LinearDiscriminantAnalysisMachineLearningParameters parameters = null; try { inputStream = this.getClass().getResourceAsStream("../../worker/Data/LinearDiscriminantAnalysisMachineLearningParameters.rda_java.Data"); objectInput = new ObjectInputStream (new BufferedInputStream( inputStream )); parameters = (LinearDiscriminantAnalysisMachineLearningParameters)objectInput.readObject(); } catch (Exception ex) { ex.printStackTrace(); } finally { try { if (objectInput != null) objectInput.close(); } catch (IOException ioex) { ioex.printStackTrace(); } } // Execute the test. SupervisedMachineLearningResult ldaResult = binding.supervised( oneChannelExpressionData, parameters ); } /** * Tests supervised using a DiagonalLinearDiscriminantAnalysisMachineLearningParameters. */ //@Ignore("please initialize function parameters") @Test public void DiagonalLinearDiscriminantAnalysisTest() throws RemoteException { // Initialize the oneChannelExpressionData. OneChannelExpressionData oneChannelExpressionData = this.getOneChannelExpressionData(); // Read the DiagonalLinearDiscriminantAnalysisMachineLearningParameters object with which to test. InputStream inputStream = null; ObjectInput objectInput = null; DiagonalLinearDiscriminantAnalysisMachineLearningParameters parameters = null; try { inputStream = this.getClass().getResourceAsStream("../../worker/Data/DiagonalLinearDiscriminantAnalysisMachineLearningParameters.rda_java.Data"); objectInput = new ObjectInputStream (new BufferedInputStream( inputStream )); parameters = (DiagonalLinearDiscriminantAnalysisMachineLearningParameters)objectInput.readObject(); } catch (Exception ex) { ex.printStackTrace(); } finally { try { if (objectInput != null) objectInput.close(); } catch (IOException ioex) { ioex.printStackTrace(); } } // Execute the test. SupervisedMachineLearningResult dldaResult = binding.supervised( oneChannelExpressionData, parameters ); } /** * Tests supervised using a QuadraticDiscriminantAnalysisMachineLearningParameters. */ //@Ignore("please initialize function parameters") //@Test //public void QuadraticDiscriminantAnalysisTest() throws RemoteException { // Initialize the oneChannelExpressionData. // OneChannelExpressionData oneChannelExpressionData = // this.getOneChannelExpressionData(); // Read the QuadraticDiscriminantAnalysisMachineLearningParameters object with which to test. // InputStream inputStream = null; // ObjectInput objectInput = null; // QuadraticDiscriminantAnalysisMachineLearningParameters parameters = null; // try { // inputStream = this.getClass().getResourceAsStream("../../worker/Data/QuadraticDiscriminantAnalysisMachineLearningParameters.rda_java.Data"); // objectInput = new ObjectInputStream (new BufferedInputStream( inputStream )); // parameters = (QuadraticDiscriminantAnalysisMachineLearningParameters)objectInput.readObject(); // } catch (Exception ex) { // ex.printStackTrace(); // } finally { // try { // if (objectInput != null) objectInput.close(); // } catch (IOException ioex) { // ioex.printStackTrace(); // } // } // Execute the test. // SupervisedMachineLearningResult qdaResult = binding.supervised( oneChannelExpressionData, // parameters ); //} /** * Tests supervised using a NaiveBayesMachineLearningParameters. */ //@Ignore("please initialize function parameters") @Test public void NaiveBayesTest() throws RemoteException { // Initialize the oneChannelExpressionData. OneChannelExpressionData oneChannelExpressionData = this.getOneChannelExpressionData(); // Read the NaiveBayesMachineLearningParameters object with which to test. InputStream inputStream = null; ObjectInput objectInput = null; NaiveBayesMachineLearningParameters parameters = null; try { inputStream = this.getClass().getResourceAsStream("../../worker/Data/NaiveBayesMachineLearningParameters.rda_java.Data"); objectInput = new ObjectInputStream (new BufferedInputStream( inputStream )); parameters = (NaiveBayesMachineLearningParameters)objectInput.readObject(); } catch (Exception ex) { ex.printStackTrace(); } finally { try { if (objectInput != null) objectInput.close(); } catch (IOException ioex) { ioex.printStackTrace(); } } // Execute the test. SupervisedMachineLearningResult naiveBayesResult = binding.supervised( oneChannelExpressionData, parameters ); } /** * Tests the unsupervised function using a HierarchicalClusteringMachineLearningParameters. */ //@Ignore("please initialize function parameters") @Test public void HierarchicalClusteringTest() throws RemoteException { // Initialize the oneChannelExpressionData. OneChannelExpressionData oneChannelExpressionData = this.getOneChannelExpressionData(); // Read the HierarchicalClusteringMachineLearningParameters object with which to test. InputStream inputStream = null; ObjectInput objectInput = null; HierarchicalClusteringMachineLearningParameters parameters = null; try { inputStream = this.getClass().getResourceAsStream("../../worker/Data/HierarchicalClusteringMachineLearningParameters.rda_java.Data"); objectInput = new ObjectInputStream (new BufferedInputStream( inputStream )); parameters = (HierarchicalClusteringMachineLearningParameters)objectInput.readObject(); } catch (Exception ex) { ex.printStackTrace(); } finally { try { if (objectInput != null) objectInput.close(); } catch (IOException ioex) { ioex.printStackTrace(); } } // Execute the test. UnsupervisedMachineLearningResult unsupervisedLearningResult = binding.unsupervised( oneChannelExpressionData, parameters ); } /** * Tests the unsupervised function using a KMeansMachineLearningParameters. */ //@Ignore("please initialize function parameters") @Test public void KMeansTest() throws RemoteException { // Initialize the oneChannelExpressionData. OneChannelExpressionData oneChannelExpressionData = this.getOneChannelExpressionData(); // Read the KMeansMachineLearningParameters object with which to test. InputStream inputStream = null; ObjectInput objectInput = null; KMeansMachineLearningParameters parameters = null; try { inputStream = this.getClass().getResourceAsStream("../../worker/Data/KMeansMachineLearningParameters.rda_java.Data"); objectInput = new ObjectInputStream (new BufferedInputStream( inputStream )); parameters = (KMeansMachineLearningParameters)objectInput.readObject(); } catch (Exception ex) { ex.printStackTrace(); } finally { try { if (objectInput != null) objectInput.close(); } catch (IOException ioex) { ioex.printStackTrace(); } } // Execute the test. UnsupervisedMachineLearningResult unsupervisedLearningResult = binding.unsupervised( oneChannelExpressionData, parameters ); } /** * Returns the OneChannelExpressionData to be used for testing. */ private OneChannelExpressionData getOneChannelExpressionData() { InputStream inputStream = null; ObjectInput objectInput = null; OneChannelExpressionData oneChannelExpressionData = null; try { inputStream = this.getClass().getResourceAsStream("../../worker/Data/OneChannelExpressionData.rda_java.Data"); objectInput = new ObjectInputStream (new BufferedInputStream( inputStream )); oneChannelExpressionData = (OneChannelExpressionData)objectInput.readObject(); } catch (Exception ex) { ex.printStackTrace(); } finally { try { if (objectInput != null) objectInput.close(); } catch (IOException ioex) { ioex.printStackTrace(); } } return oneChannelExpressionData; } }
/* * All rights reserved. (C) Copyright 2009, Trinity College Dublin */ package com.mind_era.knime.common.view.impl; import java.awt.event.MouseListener; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.annotation.CheckReturnValue; import javax.annotation.Nonnull; import javax.swing.DefaultListModel; import javax.swing.JList; import javax.swing.ListModel; import javax.swing.ListSelectionModel; import javax.swing.event.ChangeListener; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; import org.knime.core.node.defaultnodesettings.SettingsModel; import com.mind_era.knime.common.util.select.Selectable; import com.mind_era.knime.common.util.swing.SelectionType; import com.mind_era.knime.common.util.swing.VariableControl; import com.mind_era.knime.common.view.ControlsHandler; import com.mind_era.knime.common.view.ListSelection; /** * A {@link VariableControl} with control type: * {@link VariableControl.ControlTypes#List}. * * @author <a href="mailto:bakosg@tcd.ie">Gabor Bakos</a> * @param <Model> * Type of the model for values. * @param <Sel> * The type of the container of {@code Model}s. */ @Nonnull @CheckReturnValue public class ListControl<Model, Sel extends Selectable<Model>> extends AbstractVariableControl<Model, Sel> { /** * Constructs a {@link ListControl}. * * @param model * The {@link SettingsModelListSelection} for the * {@link VariableControl}. * @param selectionType * The {@link SelectionType selection type}. * @param controlsHandler * The {@link ControlsHandler} for the possible transformations. * @param changeListener * The {@link ChangeListener} associated to the {@code model}. * @param domainModel * The model for possible parameters and selections. */ public ListControl(final SettingsModelListSelection model, final SelectionType selectionType, final ControlsHandler<SettingsModel, Model, Sel> controlsHandler, final ChangeListener changeListener, final Sel domainModel) { super(model, selectionType, controlsHandler, changeListener, domainModel); list.setName(model.getConfigName()); updateComponent(); switch (selectionType) { case Unmodifiable: // Do nothing. break; case Single: list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); break; case MultipleAtLeastOne: list .setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); break; case MultipleOrNone: list .setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); break; default: throw new UnsupportedOperationException( "Not supported selection type: " + selectionType); } list.addListSelectionListener(new ListSelectionListener() { @Override public void valueChanged(final ListSelectionEvent e) { final List<String> selectedValues = list.getSelectedValuesList(); final Set<String> selection = new HashSet<String>(); for (final String str : selectedValues) { selection.add(str); } switch (selectionType) { case Unmodifiable: // Do nothing, cannot change. break; case Single: if (selection.size() == 1) { model.setSelection(selection); } break; case MultipleAtLeastOne: if (selection.size() >= 1) { model.setSelection(selection); } break; case MultipleOrNone: model.setSelection(selection); break; default: throw new UnsupportedOperationException( "Not supported selection type: " + selectionType); } updateComponent(); } }); getPanel().add(list); } private final JList<String> list = new JList<>(new DefaultListModel<String>()); /* * (non-Javadoc) * * @see * org.knime.core.node.defaultnodesettings.DialogComponent#setEnabledComponents * (boolean) */ @Override protected void setEnabledComponents(final boolean enabled) { list.setEnabled(enabled); } /* * (non-Javadoc) * * @see * com.mind_era.knime.common.view.impl.AbstractVariableControl#updateComponent() */ @Override protected void updateComponent() { @SuppressWarnings("unchecked") final ListSelection<String> model = (ListSelection<String>) getModel(); final List<String> possibleValues = model.getPossibleValues(); final Set<String> selection = model.getSelection(); final List<String> elements = getElements(list.getModel()); final DefaultListModel<String> listModel = (DefaultListModel<String>) list.getModel(); if (!elements.equals(possibleValues)) { listModel.removeAllElements(); for (final String value : possibleValues) { listModel.addElement(value); } } final int[] indices = new int[selection.size()]; int index = 0; int i = 0; for (final String value : possibleValues) { if (selection.contains(value)) { indices[index++] = i; } ++i; } assert index == selection.size(); if (!Arrays.equals(indices, list.getSelectedIndices())) { list.setSelectedIndices(indices); } } /** * @param model * A {@link ListModel}. * @return The elements in the {@link ListModel}. */ private static List<String> getElements(final ListModel<String> model) { final List<String> ret = new ArrayList<String>(model.getSize()); for (int i = 0; i < model.getSize(); ++i) { ret.add((String) model.getElementAt(i)); } return ret; } /* * (non-Javadoc) * * @see com.mind_era.knime.common.view.impl.AbstractVariableControl#getType() */ @Override public ControlTypes getType() { return ControlTypes.List; } /* * (non-Javadoc) * * @see java.lang.Object#hashCode() */ @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + (list == null ? 0 : list.hashCode()); return result; } /* * (non-Javadoc) * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (getClass() != obj.getClass()) { return false; } final ListControl<?, ?> other = (ListControl<?, ?>) obj; if (list == null) { if (other.list != null) { return false; } } else if (list != other.list) { return false; } return true; } @Override protected void notifyChange(final MouseListener listener, final Change change) { switch (change) { case add: list.addMouseListener(listener); break; case remove: list.removeMouseListener(listener); break; default: throw new IllegalArgumentException("Not supported change type: " + change); } super.notifyChange(listener, change); } }
/* Copyright 2012 Jacek Kopecky (jacek@jacek.cz) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package uk.ac.open.kmi.parking; import java.io.IOException; import java.util.Iterator; import java.util.List; import uk.ac.open.kmi.parking.service.CarparkAvailabilityUpdateListener; import uk.ac.open.kmi.parking.service.CarparkDetailsUpdateListener; import uk.ac.open.kmi.parking.service.NearbyCarparkUpdateListener; import uk.ac.open.kmi.parking.service.ParkingsService; import uk.ac.open.kmi.parking.service.SortedCurrentItemsUpdateListener; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.SharedPreferences.Editor; import android.content.res.Configuration; import android.graphics.Rect; import android.graphics.drawable.AnimationDrawable; import android.graphics.drawable.Drawable; import android.location.Address; import android.location.Criteria; import android.location.Geocoder; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.net.Uri; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.DisplayMetrics; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.WindowManager; import android.view.animation.Animation; import android.view.animation.TranslateAnimation; import android.webkit.WebView; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import android.widget.ZoomControls; import com.google.android.maps.GeoPoint; import com.google.android.maps.MapActivity; import com.google.android.maps.MapController; import com.google.android.maps.MapView; import com.google.android.maps.MapView.LayoutParams; import com.google.android.maps.Overlay; /** * main * @author Jacek Kopecky * */ public class MainActivity extends MapActivity implements LocationListener, SortedCurrentItemsUpdateListener, NearbyCarparkUpdateListener, LoadingStatus.Listener, CarparkAvailabilityUpdateListener, CarparkDetailsUpdateListener { @SuppressWarnings("unused") private static final String TAG = "main activity"; private MapView mapView; private MyLocationOverlay myLoc; private MapController mapController; private DrawableItemsOverlay parkingsOverlay; private BubbleOverlay bubbleOverlay; private LocationManager locationManager; private AnimationDrawable loadingAnimation; private ParkingsService parkingsService = null; private TextView statusTextView; private View statusContainer; private View addparkContainer; private ListView pinnedDrawer; private View pinnedDrawerContainer; private PinnedDrawerListAdapter pinnedDrawerAdapter; boolean showingPinned = false; boolean showPinnedWhenAnyFound = true; private Location currentLocation = null; private boolean animateToNextLocationFix = false; private Uri desiredCarpark = null; boolean tooFarOut = false; boolean addingMode = false; private static final int DIALOG_TERMS = 0; private static final int DIALOG_SUBMITTING_CARPARK = 1; private static final int DIALOG_LOADING_CARPARK = 2; private static final int DIALOG_SEARCH = 3; private static final int INITIAL_ZOOM = 18; private Dialog termsDialog = null; private ProgressDialog addparkDialog = null; private ProgressDialog loadingDialog = null; private Dialog searchDialog = null; private boolean showingLoadingDialog = false; private EditText searchDialogAddress = null; private List<Address> searchResults = null; private static final String PREFERENCE_SEEN_TERMS = "preference.main.seen-terms-and-conditions"; // todo when t&c or privacy policy change, the app should be updated and prompt the user to accept the t&c&pp again, so it should keep track of the last-run version - it's ok to add this with the first version that needs it /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Log.i(TAG, "on create"); ParkingDetailsActivity.staticInit(this); this.parkingsService = ParkingsService.get(this); this.parkingsService.setShowUnconfirmedCarparks(checkSettingsPref(Preferences.PREFERENCE_SHOW_UNCONFIRMED_PROPERTIES, true)); Intent intent = this.getIntent(); this.desiredCarpark = intent.getData(); intent.setData(null); if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { if (checkSettingsPref(Preferences.PREFERENCE_FULLSCREEN, true)) { getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); } } setContentView(R.layout.main); if (checkSettingsPref(Preferences.PREFERENCE_NOSLEEP, false)) { getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); // Log.d(TAG, "setting nosleep"); } this.loadingAnimation = (AnimationDrawable) ((ImageView)findViewById(R.id.loading_animation)).getDrawable(); this.addparkContainer = findViewById(R.id.addpark_container); findViewById(R.id.addpark_cancel).setOnClickListener(new OnClickListener() { public void onClick(View v) { MainActivity.this.onBackPressed(); } }); findViewById(R.id.addpark_done).setOnClickListener(new OnClickListener() { public void onClick(View v) { MainActivity.this.onButtonPressAddpark(); } }); this.statusTextView = (TextView) findViewById(R.id.status_text); this.statusContainer = findViewById(R.id.status_container); this.pinnedDrawer = (ListView) findViewById(R.id.pinned_drawer); this.pinnedDrawerContainer = findViewById(R.id.pinned_drawer_container); this.pinnedDrawerAdapter = new PinnedDrawerListAdapter(this); this.pinnedDrawer.setAdapter(this.pinnedDrawerAdapter); if (savedInstanceState != null) { this.showingPinned = savedInstanceState.getBoolean(SAVED_SHOWING_PINNED_DRAWER, this.showingPinned); this.showPinnedWhenAnyFound = false; } this.mapView = (MapView) findViewById(R.id.mapview); this.mapController = this.mapView.getController(); this.mapController.setZoom(savedInstanceState == null ? INITIAL_ZOOM : savedInstanceState.getInt(SAVED_MAP_ZOOM, INITIAL_ZOOM)); this.mapView.setBuiltInZoomControls(false); final ZoomControls zoomControls = new ZoomControls(MainActivity.this); zoomControls.setOnZoomInClickListener(new OnClickListener() { public void onClick(View v) { MainActivity.this.mapController.zoomIn(); } }); zoomControls.setOnZoomOutClickListener(new OnClickListener() { public void onClick(View v) { MainActivity.this.mapController.zoomOut(); } }); this.mapView.post(new Runnable() { public void run() { LayoutParams lp = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, MainActivity.this.mapView.getWidth()-5, MainActivity.this.mapView.getHeight(), LayoutParams.BOTTOM|LayoutParams.RIGHT); zoomControls.setLayoutParams(lp); MainActivity.this.mapView.addView(zoomControls); } }); this.animateToNextLocationFix = this.desiredCarpark == null; List<Overlay> overlays = this.mapView.getOverlays(); // this should be added after the parkings and other stuff but before the bubble View viewMyLocationPoint = new View(this); viewMyLocationPoint.setBackgroundResource(R.drawable.mylocation); this.myLoc = new MyLocationOverlay(this.mapView, viewMyLocationPoint); overlays.add(this.myLoc); // set parking drawables Drawable drawableFull = this.getResources().getDrawable(R.drawable.parking_full); int width = drawableFull.getIntrinsicWidth(); int height = drawableFull.getIntrinsicHeight(); // Rect drawableFullBounds = new Rect(-width/2, -height/2, width-width/2, height-height/2); Rect drawableFullBounds = new Rect(-width/2, -height, width-width/2, 0); Drawable drawableAvailable = this.getResources().getDrawable(R.drawable.parking_available); width = drawableAvailable.getIntrinsicWidth(); height = drawableAvailable.getIntrinsicHeight(); // Rect drawableAvailableBounds = new Rect(-width/2, -height/2, width-width/2, height-height/2); Rect drawableAvailableBounds = new Rect(-width/2, -height, width-width/2, 0); Drawable drawableUnknown = this.getResources().getDrawable(R.drawable.parking_busy); width = drawableUnknown.getIntrinsicWidth(); height = drawableUnknown.getIntrinsicHeight(); // Rect drawableUnknownBounds = new Rect(-width/2, -height/2, width-width/2, height-height/2); Rect drawableUnknownBounds = new Rect(-width/2, -height, width-width/2, 0); View viewHighlightA = new View(this); viewHighlightA.setBackgroundResource(R.drawable.parking_available_highlight); View viewHighlightF = new View(this); viewHighlightF.setBackgroundResource(R.drawable.parking_full_highlight); View viewHighlightU = new View(this); viewHighlightU.setBackgroundResource(R.drawable.parking_busy_highlight); Parking.setDrawables(drawableFull, drawableFullBounds, drawableAvailable, drawableAvailableBounds, drawableUnknown, drawableUnknownBounds, viewHighlightA, viewHighlightF, viewHighlightU); DisplayMetrics dm = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(dm); this.bubbleOverlay = new BubbleOverlay( this, this.parkingsService, this.mapView, dm.density); this.parkingsOverlay = new DrawableItemsOverlay( this, checkSettingsPref(Preferences.PREFERENCE_SHADOW, true), this.bubbleOverlay, this.parkingsService, viewHighlightU, drawableUnknownBounds, dm.xdpi, dm.ydpi, this); overlays.add(this.parkingsOverlay); // this.parkings = this.parkingsOverlay.items; if (dm.widthPixels / 3 > getResources().getDimension(R.dimen.pinned_drawer_width_max)) { android.view.ViewGroup.LayoutParams lp = this.pinnedDrawerContainer.getLayoutParams(); lp.height = dm.heightPixels * 4 / 5; this.pinnedDrawerContainer.setLayoutParams(lp); } else if (dm.heightPixels / 3 > getResources().getDimension(R.dimen.pinned_drawer_height)) { android.view.ViewGroup.LayoutParams lp = this.pinnedDrawerContainer.getLayoutParams(); lp.height = dm.heightPixels / 3; this.pinnedDrawerContainer.setLayoutParams(lp); } // Acquire a reference to the system Location Manager this.locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE); } private void showTermsAndConditions() { boolean seenTerms = getPreferences(MODE_PRIVATE).getBoolean(PREFERENCE_SEEN_TERMS, false); if (!seenTerms) { showDialog(DIALOG_TERMS); } } @Override protected Dialog onCreateDialog(int id) { // Log.i(TAG, "onCreateDialog"); switch (id) { case DIALOG_TERMS: return prepareTermsDialog(); case DIALOG_SUBMITTING_CARPARK: return prepareAddparkProgressDialog(); case DIALOG_LOADING_CARPARK: return prepareLoadingProgressDialog(); case DIALOG_SEARCH: return prepareSearchDialog(); default: return super.onCreateDialog(id); } } private Dialog prepareAddparkProgressDialog() { if (this.addparkDialog != null) { return this.addparkDialog; } this.addparkDialog = new ProgressDialog(this); this.addparkDialog.setMessage(getResources().getString(R.string.add_carpark_submitting)); return this.addparkDialog; } private Dialog prepareLoadingProgressDialog() { if (this.loadingDialog != null) { return this.loadingDialog; } this.loadingDialog = new ProgressDialog(this); this.loadingDialog.setMessage(getResources().getString(R.string.loading_desired_carpark)); return this.loadingDialog; } @Override protected void onPrepareDialog(int id, Dialog dialog, Bundle args) { if (id == DIALOG_LOADING_CARPARK) { this.showingLoadingDialog = true; } } private Dialog prepareTermsDialog() { if (this.termsDialog != null) { return this.termsDialog; } Dialog dialog = new Dialog(this); this.termsDialog = dialog; dialog.setContentView(R.layout.terms_dalog); dialog.setTitle(R.string.tc_dialog_name); WebView wv = (WebView)dialog.findViewById(R.id.terms_webview); wv.loadUrl("file:///android_asset/terms.html"); Button b = (Button) dialog.findViewById(R.id.terms_button_accept); b.setOnClickListener(new OnClickListener() { public void onClick(View v) { MainActivity.this.onButtonPressAcceptTerms(); } }); b = (Button) dialog.findViewById(R.id.terms_button_decline); b.setOnClickListener(new OnClickListener() { public void onClick(View v) { MainActivity.this.onButtonPressDeclineTerms(); } }); WindowManager.LayoutParams lp = new WindowManager.LayoutParams(); lp.copyFrom(dialog.getWindow().getAttributes()); lp.width = WindowManager.LayoutParams.FILL_PARENT; lp.height = WindowManager.LayoutParams.FILL_PARENT; dialog.getWindow().setAttributes(lp); dialog.setCancelable(false); dialog.setCanceledOnTouchOutside(false); return dialog; } @Override protected void onRestart() { super.onRestart(); if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { if (checkSettingsPref(Preferences.PREFERENCE_FULLSCREEN, true)) { getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); } else { getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); } } if (checkSettingsPref(Preferences.PREFERENCE_NOSLEEP, false)) { getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } else { getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); } this.parkingsOverlay.setShadow(checkSettingsPref(Preferences.PREFERENCE_SHADOW, true)); this.parkingsService.setShowUnconfirmedCarparks(checkSettingsPref(Preferences.PREFERENCE_SHOW_UNCONFIRMED_PROPERTIES, true)); } private static final Criteria locationCriteria = new Criteria(); // default should be good enough? @Override protected void onStart() { // Log.i(TAG, "onStart"); super.onStart(); showTermsAndConditions(); ParkingDetailsActivity.preparePresentationOntologyInNewThread(this); } @Override public void onNewIntent(Intent intent) { this.desiredCarpark = intent.getData(); intent.setData(null); } @Override protected void onRestoreInstanceState(Bundle state) { this.animateToNextLocationFix = state.getBoolean(SAVED_ANIMATE_TO_NEXT_LOCATION, true); String bubble = state.getString(SAVED_BUBBLE_ITEM); if (bubble != null) { this.bubbleOverlay.setItem(Parking.getParking(Uri.parse(bubble))); } this.addingMode = state.getBoolean(SAVED_ADDING_MODE, false); } @Override public void onResume() { Log.i(TAG, "onResume"); super.onResume(); LoadingStatus.registerListener(this); this.parkingsService.registerSortedCurrentItemsUpdateListener(this); this.parkingsService.registerNearbyCurrentItemsUpdateListener(this); this.parkingsService.registerCarparkAvailabilityUpdateListener(this); this.parkingsService.registerCarparkDetailsUpdateListener(this); this.parkingsService.geocoder = new Geocoder(this); this.parkingsService.startService(); if (this.desiredCarpark != null) { showDialog(DIALOG_LOADING_CARPARK); this.parkingsService.loadExtraCarpark(this.desiredCarpark, new CarparkDetailsUpdateListener() { public void onCarparkInformationUpdated(final Parking parking) { MainActivity.this.runOnUiThread(new Runnable() { public void run() { if (MainActivity.this.showingLoadingDialog) { dismissDialog(DIALOG_LOADING_CARPARK); MainActivity.this.showingLoadingDialog = false; } if (parking == null) { Toast.makeText(MainActivity.this, R.string.error_parking_not_found, Toast.LENGTH_LONG).show(); return; } MainActivity.this.centerOnCarpark(parking, true); } }); } }); this.desiredCarpark = null; } if (this.currentLocation == null) { String bestProvider = this.locationManager.getBestProvider(locationCriteria, true); if (bestProvider != null) { this.currentLocation = this.locationManager.getLastKnownLocation(bestProvider); if (this.animateToNextLocationFix && this.currentLocation != null) { animateToCurrentLocation(true); this.animateToNextLocationFix = false; } this.myLoc.onLocationChanged(this.currentLocation); this.bubbleOverlay.bringToFront(); this.parkingsService.onLocationChanged(this.currentLocation); // Register the listener with the Location Manager to receive location updates this.locationManager.requestLocationUpdates(1000l, 10f, locationCriteria, this, null); } } this.pinnedDrawerAdapter.update(); updateUIState(); this.bubbleOverlay.updateDetails(null); } void centerOnCarpark(final Parking parking, boolean immediate) { if (immediate) { this.mapController.setCenter(parking.point); this.bubbleOverlay.setItem(parking); } else { if (!parking.equals(this.bubbleOverlay.getItem())) { this.bubbleOverlay.removeItem(); } this.mapController.animateTo(parking.point, new Runnable() { public void run() { MainActivity.this.bubbleOverlay.setItem(parking); } }); } // updateUIState(); } private boolean checkSettingsPref(String pref, boolean def) { return PreferenceManager.getDefaultSharedPreferences(this).getBoolean(pref, def); } @Override public void onPause() { Log.i(TAG, "onPause"); if (this.showingLoadingDialog) { dismissDialog(DIALOG_LOADING_CARPARK); this.showingLoadingDialog = false; } LoadingStatus.unregisterListener(this); this.locationManager.removeUpdates(this); this.parkingsService.geocoder = null; this.parkingsService.unregisterCarparkDetailsUpdateListener(this); this.parkingsService.unregisterCarparkAvailabilityUpdateListener(this); this.parkingsService.unregisterSortedCurrentItemsUpdateListener(this); this.parkingsService.unregisterNearbyCurrentItemsUpdateListener(this); this.parkingsService.stopService(this); super.onPause(); } @Override public void onStop() { this.parkingsOverlay.onStop(); super.onStop(); } @Override public void onBackPressed() { if (this.bubbleOverlay.removeItem()) { // updateUIState(); } else if (this.addingMode) { this.addingMode = false; updateUIState(); } else { super.onBackPressed(); } } void setTooFarOut(boolean far) { if (this.tooFarOut != far) { this.tooFarOut = far; this.updateUIState(); } } /** * helper method that calls the details view * @param context the current activity * @param item the parking whose details should be viewed */ public static void showDetailsForCarpark(Context context, DrawableOverlayItem item) { Intent intent = new Intent(context, ParkingDetailsActivity.class); intent.setData(item.id); context.startActivity(intent); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main_options, menu); return true; } @Override public boolean onPrepareOptionsMenu(Menu menu) { menu.findItem(R.id.menu_traffic).setChecked(this.mapView.isTraffic()); menu.findItem(R.id.menu_satellite).setChecked(this.mapView.isSatellite()); menu.findItem(R.id.menu_add_car_park).setVisible(!this.tooFarOut && !this.addingMode); menu.findItem(R.id.menu_pinned).setTitle(this.showingPinned ? R.string.menu_pinned_hide : R.string.menu_pinned_show); menu.findItem(R.id.menu_pinned).setVisible(!this.tooFarOut && !this.addingMode); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_traffic: boolean state = item.isChecked(); item.setChecked(!state); this.mapView.setTraffic(!state); return true; case R.id.menu_satellite: state = item.isChecked(); item.setChecked(!state); this.mapView.setSatellite(!state); return true; case R.id.menu_my_location: animateToCurrentLocation(false); return true; case R.id.menu_settings: Intent settingsActivity = new Intent(getBaseContext(), Preferences.class); startActivity(settingsActivity); return true; case R.id.menu_add_car_park: startAddingCarpark(); return true; case R.id.menu_search: // todo maybe search should be a separate activity, with immediate list of results // go to activity where at the top is search text box with the last search query // on button press, show list of results // on pressing a result, go on to main activity again, show map there, maybe with an annotated pin with location?, with car parks // back button then should take you back to search results startAddressSearch(); return true; case R.id.menu_pinned: this.showingPinned = !this.showingPinned; updateUIState(); return true; default: return super.onOptionsItemSelected(item); } } private void startAddingCarpark() { // what should be done if we're already in the mode? probably NOP if (this.addingMode) { return; // already in the mode } if (!checkSettingsPref(Preferences.PREFERENCE_SHOW_UNCONFIRMED_PROPERTIES, true)) { Toast.makeText(this, R.string.toast_pref_unconfirmedprops, Toast.LENGTH_LONG).show(); PreferenceManager.getDefaultSharedPreferences(this).edit().putBoolean(Preferences.PREFERENCE_SHOW_UNCONFIRMED_PROPERTIES, true).apply(); this.parkingsService.setShowUnconfirmedCarparks(true); } // drop bubble this.bubbleOverlay.removeItem(); this.addingMode = true; updateUIState(); } private void onButtonPressAddpark() { showDialog(DIALOG_SUBMITTING_CARPARK); // todo setOnDismissListener: catch the dismiss and make the listener below do NOP // or alternatively make it do NOP if the user has in the meantime done something that would make the action wrong - similar for initial desired carpark // there can be a global "last significant action timestamp" (or counter, doesn't matter) // significant actions: starting addpark again; selecting some other car park; maybe even creating a bubble; explicitly following nearest // the listener will remember its state when it was created // then on activation it can do NOP if the timestamp has changed this.addingMode = false; this.parkingsService.submitNewCarpark(this.mapView.getMapCenter(), new CarparkDetailsUpdateListener() { public void onCarparkInformationUpdated(final Parking parking) { MainActivity.this.runOnUiThread(new Runnable() { public void run() { MainActivity.this.dismissDialog(DIALOG_SUBMITTING_CARPARK); if (parking == null) { Toast.makeText(MainActivity.this, R.string.error_submitting_data, Toast.LENGTH_LONG).show(); return; } // Log.i(TAG, "car park added and loaded"); // upon submission, open the details view so user can immediately fill in properties // also automatically have the new car park as watched MainActivity.this.centerOnCarpark(parking, false); showDetailsForCarpark(MainActivity.this, parking); } }); } }); updateUIState(); } private void animateToCurrentLocation(boolean zoomOutIfNecessary) { if (this.currentLocation != null) { this.mapController.animateTo(new GeoPoint((int)(this.currentLocation.getLatitude()*1e6), (int)(this.currentLocation.getLongitude()*1e6))); final float accuracy = this.currentLocation.getAccuracy(); if (zoomOutIfNecessary & accuracy > 200f & this.mapView.getZoomLevel() == INITIAL_ZOOM) { this.mapView.post(new Runnable() { public void run() { MainActivity.this.mapController.zoomOut(); if (accuracy > 500f) { MainActivity.this.mapController.zoomOut(); } } }); } this.myLoc.setCurrentLocationOnScreen(true); } else { Toast.makeText(this, R.string.toast_no_location, Toast.LENGTH_SHORT).show(); } } // todo the context menu could also be on some stuff in the bubble or on the active carpark's icon (should it be highlighted?) or on pinned entries @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { if (v instanceof PinnedDrawerListAdapter.PinnedCarparkView) { getMenuInflater().inflate(R.menu.currpark_context, menu); this.contextMenuCarpark = ((PinnedDrawerListAdapter.PinnedCarparkView)v).getCarpark(); menu.setHeaderIcon(this.contextMenuCarpark.getEffectiveAvailability() == Parking.Availability.AVAILABLE ? R.drawable.parking_available : R.drawable.parking_full); // todo parking drawables here must be kept in sync with the ones used in onCreate; maybe Drawable.mutate() might help here? menu.setHeaderTitle(this.contextMenuCarpark.getTitle()); } } private Parking contextMenuCarpark = null; @Override public boolean onContextItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_currpark_zoom: centerOnCarpark(this.contextMenuCarpark, false); return true; case R.id.menu_currpark_mark_available: reportAvailability(this.contextMenuCarpark, true); return true; case R.id.menu_currpark_mark_full: reportAvailability(this.contextMenuCarpark, false); return true; case R.id.menu_currpark_show_details: showDetailsForCarpark(this, this.contextMenuCarpark); return true; case R.id.menu_currpark_unpin: pinCarpark(this.contextMenuCarpark, false); return true; default: return super.onContextItemSelected(item); } } void pinCarpark(Parking p, boolean pin) { this.parkingsService.pinCarpark(p, pin, this); boolean drawerHasItems = this.pinnedDrawerAdapter.update(); if (drawerHasItems != this.showingPinned) { this.showingPinned = drawerHasItems; updateUIState(); } this.bubbleOverlay.updatePinnedStatus(p); } void reportAvailability(Parking park, boolean avail) { this.parkingsService.submitAvailability(park, avail); updateUIState(); } public void onLocationChanged(Location location) { // todo filter out fixes that are worse than this one // todo only change current near carpark if the accuracy of the fix is good enough (e.g. within the limit distance to the near carpark) this.currentLocation = location; if (this.animateToNextLocationFix && this.currentLocation != null) { animateToCurrentLocation(false); this.animateToNextLocationFix = false; } this.parkingsService.onLocationChanged(location); this.myLoc.onLocationChanged(location); this.bubbleOverlay.bringToFront(); // Log.d(TAG, "onLocationChanged called"); // todo also make sure that after some time without updates, current location is no longer valid (this may be done by MyLocationOverlay itself) // then currentLocation must be set to null } /** * this method takes care of the state of the UI so it corresponds to the current mode as per ParkingsService */ private void updateUIState() { // Log.d(TAG, "updating UI state"); if (this.tooFarOut) { showStatusText(R.string.currpark_too_far_out); return; } if (!this.addingMode && !this.parkingsService.loadedSomeCarparks()) { showStatusText(R.string.currpark_initial); return; } hideStatusText(); this.bubbleOverlay.updateAvailability(); this.parkingsOverlay.forceRedraw(); this.mapView.invalidate(); if (this.addingMode) { hidePinnedDrawer(); showAddparkViews(); } else { hideAddparkViews(); if (this.showPinnedWhenAnyFound && !this.parkingsService.listKnownPinnedCarparks().isEmpty()) { this.showingPinned = true; this.showPinnedWhenAnyFound = false; } if (this.showingPinned) { showPinnedDrawer(); this.showPinnedWhenAnyFound = false; } else { hidePinnedDrawer(); } } // todo pinned car parks should have an icon for centering, reporting, voice info // todo details view may need an icon for pinning } private void showAddparkViews() { this.addparkContainer.setVisibility(View.VISIBLE); } private void hideAddparkViews() { this.addparkContainer.setVisibility(View.GONE); } private void showStatusText(int resource) { hideAddparkViews(); hidePinnedDrawer(); this.statusTextView.setText(resource); this.statusContainer.setVisibility(View.VISIBLE); } private void hideStatusText() { this.statusContainer.setVisibility(View.GONE); } private void hidePinnedDrawer() { if (this.pinnedDrawer.getVisibility() == View.VISIBLE) { Animation anim = new TranslateAnimation(0, 0, 0, -this.pinnedDrawerContainer.getHeight()); anim.setDuration(getResources().getInteger(R.integer.pinned_drawer_animation_duration)); anim.setAnimationListener(new Animation.AnimationListener() { public void onAnimationStart(Animation animation) { /* nothing */ } public void onAnimationRepeat(Animation animation) { /* nothing */ } public void onAnimationEnd(Animation animation) { MainActivity.this.pinnedDrawer.setVisibility(View.GONE); } }); this.pinnedDrawer.startAnimation(anim); } else { // make sure this.pinnedDrawer.setVisibility(View.GONE); } this.parkingsService.setPinnedUpdating(false); } private void showPinnedDrawer() { if (this.pinnedDrawer.getVisibility() != View.VISIBLE) { Animation anim = new TranslateAnimation(0, 0, -this.pinnedDrawerContainer.getHeight(), 0); anim.setDuration(getResources().getInteger(R.integer.pinned_drawer_animation_duration)); this.pinnedDrawer.startAnimation(anim); this.pinnedDrawer.setVisibility(View.VISIBLE); } this.parkingsService.setPinnedUpdating(true); } public void onProviderDisabled(String provider) { /* do nothing */ } // todo check if any provider is remaining? public void onProviderEnabled(String provider) { /* do nothing */ } // todo ask for location updates again? public void onStatusChanged(String provider, int status, Bundle extras) { /* do nothing */ } private final Runnable updateUIStateTask = new Runnable(){ public void run() { updateUIState(); MainActivity.this.pinnedDrawerAdapter.update(); } }; public void onSortedCurrentItemsUpdated() { runOnUiThread(this.updateUIStateTask); } public void onNearbyCarparkUpdated() { runOnUiThread(this.updateUIStateTask); // todo this only affects the pinned area with nearest carpark(s) so maybe not updateUIState? } public void onCarparkAvailabilityUpdated(final Parking parking) { runOnUiThread(new Runnable() { public void run() { MainActivity.this.bubbleOverlay.updateAvailability(parking); MainActivity.this.pinnedDrawerAdapter.updateIfContains(parking); MainActivity.this.parkingsOverlay.forceRedraw(); MainActivity.this.mapView.invalidate(); } }); } @Override protected boolean isRouteDisplayed() { return false; } public void onStartedLoading() { this.loadingAnimation.start(); } public void onStoppedLoading() { this.loadingAnimation.stop(); this.loadingAnimation.selectDrawable(0); } /** * called when terms&conditions are accepted */ private void onButtonPressAcceptTerms() { // Log.d(TAG, "pressed accept"); if (this.currentLocation != null) { this.mapController.setCenter(new GeoPoint((int)(this.currentLocation.getLatitude()*1000000), (int)(this.currentLocation.getLongitude()*1000000))); } dismissDialog(DIALOG_TERMS); Editor e = getPreferences(MODE_PRIVATE).edit(); e.putBoolean(PREFERENCE_SEEN_TERMS, true); e.commit(); } /** * called when terms&conditions are declined */ private void onButtonPressDeclineTerms() { Editor e = getPreferences(MODE_PRIVATE).edit(); e.putBoolean(PREFERENCE_SEEN_TERMS, false); e.commit(); finish(); } public void onCarparkInformationUpdated(final Parking parking) { runOnUiThread(new Runnable() { public void run() { MainActivity.this.bubbleOverlay.updateDetails(parking); MainActivity.this.pinnedDrawerAdapter.updateIfContains(parking); } }); } /** * this gets called when pressing the app icon * @param v ignored */ public void openOptionsMenu(@SuppressWarnings("unused") View v) { openOptionsMenu(); } private void startAddressSearch() { showDialog(DIALOG_SEARCH); // this.searchDialogAddress.requestFocusFromTouch(); } private void performSearch() { // Log.d(TAG, "searching for " + this.searchDialogAddress.getText().toString()); this.searchResults = null; try { if (this.parkingsService.geocoder != null) { this.searchResults = this.parkingsService.geocoder.getFromLocationName(this.searchDialogAddress.getText().toString(), 10); } } catch (IOException e) { // Log.d(TAG, "geocoding problem ", e); } if (this.searchResults == null || this.searchResults.size() == 0) { new AlertDialog.Builder(this). setTitle(R.string.search_results_title). setMessage(R.string.search_not_found). setCancelable(true). // setPositiveButton(R.string.search_dialog_ok, null). setNegativeButton(R.string.search_dialog_cancel, null). show(); } else { // drop possible places without location Iterator<Address> it = this.searchResults.iterator(); while (it.hasNext()) { Address a = it.next(); if (!a.hasLatitude() || !a.hasLongitude()) { it.remove(); } } CharSequence[] addrs = new CharSequence[this.searchResults.size()]; int i = 0; for (Address address : this.searchResults) { addrs[i] = formatAddress(address); i++; } AlertDialog.Builder resultsDialog = new AlertDialog.Builder(this); resultsDialog.setTitle(R.string.search_results_title); resultsDialog.setItems(addrs, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { Address selected = MainActivity.this.searchResults.get(which); // Log.d(TAG, "selected address " + which + " which is " + selected); MainActivity.this.mapController.animateTo(new GeoPoint((int)(selected.getLatitude()*1e6), (int)(selected.getLongitude()*1.e6))); } }); resultsDialog.setCancelable(true); if (addrs.length == 1) { resultsDialog.setPositiveButton(R.string.search_dialog_ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { Address selected = MainActivity.this.searchResults.get(0); MainActivity.this.mapController.animateTo(new GeoPoint((int)(selected.getLatitude()*1e6), (int)(selected.getLongitude()*1.e6))); } }); } resultsDialog.setNegativeButton(R.string.search_dialog_cancel, null); resultsDialog.show(); } } static String formatAddress(Address a) { // todo this may need more StringBuilder sb = new StringBuilder(); for (int i=0; i<=a.getMaxAddressLineIndex(); i++) { sb.append(a.getAddressLine(i)); if (i < a.getMaxAddressLineIndex()) { sb.append(", "); } } return sb.toString(); } private Dialog prepareSearchDialog() { if (this.searchDialog != null) { return this.searchDialog; } this.searchDialogAddress = new EditText(this); this.searchDialog = new AlertDialog.Builder(this). setCancelable(true). setTitle(R.string.search_dialog_title). setView(this.searchDialogAddress). setPositiveButton(R.string.search_dialog_search, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { MainActivity.this.performSearch(); } }). setNegativeButton(R.string.search_dialog_cancel, null). create(); this.searchDialogAddress.setOnFocusChangeListener(new View.OnFocusChangeListener() { public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { MainActivity.this.searchDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); } } }); return this.searchDialog; } void openNavigationTo(DrawableOverlayItem p) { String saddr = ""; // start point address if (this.currentLocation != null) { saddr = "saddr=" + this.currentLocation.getLatitude() + "," + this.currentLocation.getLongitude() + "&"; } String daddr = "daddr=" + (p.point.getLatitudeE6()/1e6) + "," + (p.point.getLongitudeE6()/1e6); // destination point address Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("http://maps.google.com/maps?" + saddr + daddr)); startActivity(intent); } private static final String SAVED_ANIMATE_TO_NEXT_LOCATION = "uk.ac.open.kmi.parking.animate-to-next-location"; private static final String SAVED_ADDING_MODE = "uk.ac.open.kmi.parking.adding-mode"; private static final String SAVED_BUBBLE_ITEM = "uk.ac.open.kmi.parking.bubble-item"; private static final String SAVED_MAP_ZOOM = "uk.ac.open.kmi.parking.zoom-level"; private static final String SAVED_SHOWING_PINNED_DRAWER = "uk.ac.open.kmi.parking.show-pinned-drawer"; @Override protected void onSaveInstanceState(Bundle state) { state.putBoolean(SAVED_ANIMATE_TO_NEXT_LOCATION, this.animateToNextLocationFix); Parking bubble = this.bubbleOverlay.getItem(); state.putString(SAVED_BUBBLE_ITEM, bubble == null ? null : bubble.id.toString()); state.putBoolean(SAVED_ADDING_MODE, this.addingMode); state.putInt(SAVED_MAP_ZOOM, this.mapView.getZoomLevel()); state.putBoolean(SAVED_SHOWING_PINNED_DRAWER, this.showingPinned); } }
/* * [New BSD License] * Copyright (c) 2011-2012, Brackit Project Team <info@brackit.org> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the Brackit Project Team nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.brackit.server.node.bracket; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Set; import org.brackit.server.BrackitDB; import org.brackit.server.ServerException; import org.brackit.server.metadata.pathSynopsis.PSNode; import org.brackit.server.store.index.bracket.BracketIndex; import org.brackit.server.store.index.bracket.StreamIterator; import org.brackit.server.store.index.bracket.filter.BracketFilter; import org.brackit.server.store.index.bracket.filter.MultiFilter; import org.brackit.server.store.index.bracket.filter.PSNodeFilter; import org.brackit.server.store.index.bracket.filter.MultiFilter.Type; import org.brackit.server.tx.IsolationLevel; import org.brackit.server.tx.Tx; import org.brackit.xquery.QueryContext; import org.brackit.xquery.QueryException; import org.brackit.xquery.XQuery; import org.brackit.xquery.atomic.QNm; import org.brackit.xquery.node.parser.DocumentParser; import org.brackit.xquery.util.path.Path; import org.brackit.xquery.xdm.DocumentException; import org.brackit.xquery.xdm.Kind; /** * * @author Martin Hiller * */ public class OutputPrefetchTest { // main method requires an xmark document stored in the DB // set "install" to true in order to load the xmark document referenced by "xmarkPath" into the DB private static final boolean install = false; private static final String xmarkPath = "./xmark1.xml"; private static final int WARMUP_COUNT = 3; private static final int TEST_COUNT = 5; // prints the query output into a file (only once for each method, just to evaluate the "correctness") private static final boolean PRINT_TO_FILE = false; private static final String PRINT_TO_FILE_PATH = "./output"; private static String query = "let $auction := .\r\n" + "for $t in $auction/site/people/person\r\n" + "where $t/@id != \"person0\"\r\n" + "return\r\n" + " <personne>\r\n" + " <statistiques>\r\n" + " <sexe>{$t/profile/gender/text()}</sexe>\r\n" + " <age>{$t/profile/age/text()}</age>\r\n" + " <education>{$t/profile/education/text()}</education>\r\n" + " </statistiques>\r\n" + " </personne>"; // BEGIN: specify query for the optimized execution private static String mainPath = "/site/people/person"; private static Predicate pred = new Predicate("id") { @Override public boolean eval(String value) { return value.compareTo("person0") != 0; } }; private static String[] outputPaths = new String[] { "/profile/gender", "/profile/age", "/profile/education" }; private static String returnFormat; static { StringBuilder sb = new StringBuilder(); sb.append("<personne>\n"); sb.append("\t<statistiques>\n"); sb.append("\t\t<sexe>%s</sexe>\n"); sb.append("\t\t<age>%s</age>\n"); sb.append("\t\t<education>%s</education>\n"); sb.append("\t</statistiques>\n"); sb.append("</personne>\n"); returnFormat = sb.toString(); } // END: specify query private static abstract class Predicate { public final String attribute; public Predicate(String attribute) { this.attribute = attribute; } public abstract boolean eval(String value); } private static interface ResultAggregator { public double aggregate(long[] results); } private static final ResultAggregator AVG = new ResultAggregator() { @Override public double aggregate(long[] results) { long sum = 0; long count = 0; for (long result : results) { sum += result; count++; } return sum / (double) count; } }; private static final ResultAggregator MIN = new ResultAggregator() { @Override public double aggregate(long[] results) { long min = Long.MAX_VALUE; for (long result : results) { min = Math.min(min, result); } return min; } }; private static Tx tx; private static BracketCollection coll; private static BracketIndex index; private static BracketNode doc; private static QueryContext ctx; private static XQuery xQuery; private static PrintWriter out; private static ByteArrayOutputStream byteOut; private static PrintWriter fileOut; /** * @param args * @throws ServerException * @throws QueryException * @throws FileNotFoundException */ public static void main(String[] args) throws ServerException, QueryException, FileNotFoundException { if (install) { System.out.println("Load xmark document into the DB..."); BrackitDB brackitDB = new BrackitDB(true); tx = brackitDB.getTaMgr().begin(IsolationLevel.NONE, null, false); brackitDB.getMetadataMgr().create(tx, "/xmark.xml", new DocumentParser(new File(xmarkPath))); tx.commit(); brackitDB.shutdown(); System.out.println("Completed! Start program again with \"install\" set to false."); return; } // start server BrackitDB brackitDB = new BrackitDB(false); // get TX tx = brackitDB.getTaMgr().begin(IsolationLevel.NONE, null, true); // get collection / document coll = (BracketCollection) brackitDB.getMetadataMgr().lookup(tx, "/xmark.xml"); doc = coll.getDocument(); // get index index = coll.store.index; // prepare Query + Context ctx = new QueryContext(); ctx.setContextItem(doc); xQuery = new XQuery(query); // prepare output writer byteOut = new ByteArrayOutputStream(); out = new PrintWriter(byteOut); if (PRINT_TO_FILE) { fileOut = new PrintWriter(PRINT_TO_FILE_PATH); } // execute query the usual way double result1 = performTest("Usual Execution", AVG, true, new Runnable() { @Override public void run() { try { executeQuery(); } catch (QueryException e) { System.err.print(e); } } }); System.out.println(); // execute query with MultiChildStreams, Data prefetch etc. double result2 = performTest("Optimized Execution", AVG, true, new Runnable() { @Override public void run() { try { executeQueryWithPrefetch2(); } catch (QueryException e) { System.err.print(e); } } }); out.close(); if (PRINT_TO_FILE) { fileOut.close(); } // commit TX tx.commit(); // shutdown DB brackitDB.shutdown(); } private static double performTest(String name, ResultAggregator aggr, boolean status, Runnable testMethod) { if (status) { System.out.println(String.format("Perform '%s':", name)); } if (PRINT_TO_FILE) { fileOut.println(String.format("\n\nQuery output for method '%s':\n", name)); PrintWriter tmp = out; out = fileOut; testMethod.run(); out = tmp; } for (int i = 0; i < WARMUP_COUNT; i++) { // warm up phase if (status) { if (i == 0) { System.out.print("\tWarmup 1..."); } else { System.out.print(String.format(" %s...", i + 1)); } } testMethod.run(); byteOut.reset(); } long[] results = new long[TEST_COUNT]; for (int i = 0; i < TEST_COUNT; i++) { // perform tests if (status) { if (i == 0) { System.out.print("\n\tTestrun 1..."); } else { System.out.print(String.format(" %s...", i + 1)); } } long start = System.currentTimeMillis(); testMethod.run(); long end = System.currentTimeMillis(); results[i] = end - start; byteOut.reset(); } double total = aggr.aggregate(results); if (status) { System.out.println(String.format("\n\tResults: %s", Arrays.toString(results))); System.out.println(String.format("\tTotal: %s", total)); } return total; } private static void executeQueryWithPrefetch() throws DocumentException { // lookup PCRs for following MultiChildStream access Path<QNm> path = Path.parse(mainPath); int[] pcrs = coll.pathSynopsis.matchChildPath(path); BracketFilter[] mainPathFilters = new BracketFilter[pcrs.length]; PSNode psNode = null; for (int i = 0; i < pcrs.length; i++) { PSNode current = coll.pathSynopsis.get(pcrs[i]); mainPathFilters[i] = new PSNodeFilter(coll.pathSynopsis, current, false); if (i == pcrs.length - 1) { psNode = current; } } // lookup PCR for evaluating predicate PSNode attributePSNode = coll.pathSynopsis.getChildIfExists( psNode.getPCR(), new QNm(pred.attribute), Kind.ATTRIBUTE.ID, null); if (attributePSNode == null) { throw new RuntimeException(); } // lookup PCRs for the output paths BracketFilter[][] outputPathFilters = new BracketFilter[outputPaths.length][]; for (int i = 0; i < outputPaths.length; i++) { Path<QNm> outputPath = Path.parse(outputPaths[i]); pcrs = coll.pathSynopsis.matchChildPath(path.copy().append( outputPath)); pcrs = Arrays.copyOfRange(pcrs, path.getLength(), pcrs.length); outputPathFilters[i] = new BracketFilter[pcrs.length + 1]; for (int j = 0; j < pcrs.length; j++) { outputPathFilters[i][j] = new PSNodeFilter(coll.pathSynopsis, pcrs[j], false); } // to obtain the text node, use the last PSNodeFilter twice outputPathFilters[i][pcrs.length] = outputPathFilters[i][pcrs.length - 1]; } // open MultiChildStream StreamIterator iter = index.openMultiChildStream(doc.locator, doc.getDeweyID(), doc.hintPageInfo, mainPathFilters); while (iter.moveNext()) { // for each node: check where clause // check attribute predicate StreamIterator attributeStream = index.forkAttributeStream(iter, new PSNodeFilter(coll.pathSynopsis, attributePSNode, true)); BracketNode attribute = attributeStream.next(); attributeStream.close(); boolean conditionFulfilled = pred.eval(attribute.getValue() .stringValue()); if (conditionFulfilled) { // load data // load BracketNode itself BracketNode qualified = iter.loadCurrent(); // DEBUG: print complete subtree of qualified node // StreamIterator s = index.forkSubtreeStream(iter, null, true, // false); // while (s.moveNext()) { // System.out.println(s.loadCurrent()); // } // s.close(); // use a 2D string array: // 1st dimension: different output paths // 2nd dimension: String value for each qualified text node qualified.outputPrefetch = new String[outputPathFilters.length][]; // prefetch data for output List<String> collect = new ArrayList<String>(); for (int i = 0; i < outputPathFilters.length; i++) { // open one MultiChildStream per output path (optimization // potential: extract common paths, or even use a // "brute force" subtree stream) StreamIterator outputIter = index.forkMultiChildStream( iter, outputPathFilters[i]); while (outputIter.moveNext()) { BracketNode textNode = outputIter.loadCurrent(); collect.add(textNode.getValue().stringValue()); } outputIter.close(); qualified.outputPrefetch[i] = collect .toArray(new String[collect.size()]); collect.clear(); } // System.out.println(qualified); // for (int i = 0; i < outputPaths.length; i++) { // System.out.println(String.format("Prefetch for path %s: %s", // outputPaths[i], // Arrays.toString(qualified.outputPrefetch[i]))); // } // return statement String[] output = new String[outputPaths.length]; for (int i = 0; i < output.length; i++) { output[i] = (qualified.outputPrefetch[i].length == 0) ? "" : ((qualified.outputPrefetch[i].length == 1) ? qualified.outputPrefetch[i][0] : Arrays.toString(qualified.outputPrefetch[i])); } out.println(String.format(returnFormat, (Object[]) output)); } } iter.close(); } private static void executeQueryWithPrefetch2() throws DocumentException { // lookup PCRs for following MultiChildStream access Path<QNm> path = Path.parse(mainPath); int[] pcrs = coll.pathSynopsis.matchChildPath(path); BracketFilter[] mainPathFilters = new BracketFilter[pcrs.length]; PSNode psNode = null; for (int i = 0; i < pcrs.length; i++) { PSNode current = coll.pathSynopsis.get(pcrs[i]); mainPathFilters[i] = new PSNodeFilter(coll.pathSynopsis, current, false); if (i == pcrs.length - 1) { psNode = current; } } // lookup PCR for evaluating predicate PSNode attributePSNode = coll.pathSynopsis.getChildIfExists( psNode.getPCR(), new QNm(pred.attribute), Kind.ATTRIBUTE.ID, null); if (attributePSNode == null) { throw new RuntimeException(); } // lookup PCRs for the output paths BracketFilter[] outputPathFilters = new BracketFilter[outputPaths.length]; for (int i = 0; i < outputPaths.length; i++) { Path<QNm> outputPath = Path.parse(outputPaths[i]); Set<Integer> pcrSet = coll.pathSynopsis.match(path.copy().append( outputPath)); if (pcrSet.size() != 1) { throw new RuntimeException(); } int pcr = -1; for (int current : pcrSet) { pcr = current; } outputPathFilters[i] = new PSNodeFilter(coll.pathSynopsis, pcr, true); } // create MultiFilter for future subtree scans MultiFilter multiFilter = new MultiFilter(Type.DISJUNCTION, outputPathFilters); // open MultiChildStream StreamIterator iter = index.openMultiChildStream(doc.locator, doc.getDeweyID(), doc.hintPageInfo, mainPathFilters); while (iter.moveNext()) { // for each node: check where clause // check attribute predicate StreamIterator attributeStream = index.forkAttributeStream(iter, new PSNodeFilter(coll.pathSynopsis, attributePSNode, true)); BracketNode attribute = attributeStream.next(); attributeStream.close(); boolean conditionFulfilled = pred.eval(attribute.getValue() .stringValue()); if (conditionFulfilled) { // load data // load BracketNode itself BracketNode qualified = iter.loadCurrent(); // DEBUG: print complete subtree of qualified node // StreamIterator s = index.forkSubtreeStream(iter, null, true, // false); // while (s.moveNext()) { // System.out.println(s.loadCurrent()); // } // s.close(); // use a 2D string array: // 1st dimension: different output paths // 2nd dimension: String value for each qualified text node qualified.outputPrefetch = new String[outputPathFilters.length][]; List<String>[] collect = new List[outputPathFilters.length]; for (int i = 0; i < collect.length; i++) { collect[i] = new ArrayList<String>(); } // subtree scan for qualified node: collect all needed output StreamIterator outputIter = index.forkSubtreeStream(iter, multiFilter, false, true); while (outputIter.moveNext()) { // load text BracketNode textNode = outputIter.loadCurrent(); // check which BracketFilter accepted this node boolean[] lastResults = multiFilter.getLastResults(); int i = 0; while (!lastResults[i]) { i++; } collect[i].add(textNode.getValue().stringValue()); } outputIter.close(); for (int i = 0; i < collect.length; i++) { qualified.outputPrefetch[i] = collect[i].toArray(new String[collect[i].size()]); } // System.out.println(qualified); // for (int i = 0; i < outputPaths.length; i++) { // System.out.println(String.format("Prefetch for path %s: %s", // outputPaths[i], // Arrays.toString(qualified.outputPrefetch[i]))); // } // return statement String[] output = new String[outputPaths.length]; for (int i = 0; i < output.length; i++) { output[i] = (qualified.outputPrefetch[i].length == 0) ? "" : ((qualified.outputPrefetch[i].length == 1) ? qualified.outputPrefetch[i][0] : Arrays.toString(qualified.outputPrefetch[i])); } out.println(String.format(returnFormat, (Object[]) output)); } } iter.close(); } private static void executeQuery() throws QueryException { xQuery.serialize(ctx, out); } }
package com.nguyenquyhy.discordbridge.utils; import com.google.common.base.Preconditions; import com.google.common.collect.Lists; import com.nguyenquyhy.discordbridge.DiscordBridge; import com.nguyenquyhy.discordbridge.models.ChannelMinecraftConfigCore; import com.nguyenquyhy.discordbridge.models.ChannelMinecraftEmojiConfig; import com.nguyenquyhy.discordbridge.models.ChannelMinecraftMentionConfig; import de.btobastian.javacord.entities.Channel; import de.btobastian.javacord.entities.Server; import de.btobastian.javacord.entities.User; import de.btobastian.javacord.entities.message.Message; import de.btobastian.javacord.entities.permissions.Role; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.spongepowered.api.entity.living.player.Player; import org.spongepowered.api.text.Text; import org.spongepowered.api.text.action.HoverAction; import org.spongepowered.api.text.action.TextActions; import org.spongepowered.api.text.format.TextColor; import org.spongepowered.api.text.format.TextColors; import org.spongepowered.api.text.format.TextStyle; import org.spongepowered.api.text.format.TextStyles; import org.spongepowered.api.text.serializer.TextSerializers; import java.awt.*; import java.net.MalformedURLException; import java.net.URL; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Created by Hy on 8/29/2016. */ public class TextUtil { private static final Pattern urlPattern = Pattern.compile("(?<first>(^|\\s))(?<colour>(&[0-9a-flmnork])+)?(?<url>(http(s)?://)?([A-Za-z0-9]+\\.)+[A-Za-z0-9]{2,}\\S*)", Pattern.CASE_INSENSITIVE); private static final Pattern mentionPattern = Pattern.compile("([@#]\\S*)"); public static final StyleTuple EMPTY = new StyleTuple(TextColors.NONE, TextStyles.NONE); public static String formatDiscordMessage(String message) { for (Emoji emoji : Emoji.values()) { message = message.replace(emoji.unicode, emoji.minecraftFormat); } return message; } public static String formatMinecraftMessage(String message) { for (Emoji emoji : Emoji.values()) { message = message.replace(emoji.minecraftFormat, emoji.discordFormat); } return message; } /** * @param message the Minecraft message to be checked for valid mentions * @param server the server to search through Users and Roles * @param player the player who's permissions to check * @param isBot used to ignore permission checks for authenticated users * @return the message with mentions properly formatted for Discord, if allowed */ public static String formatMinecraftMention(String message, Server server, Player player, boolean isBot) { Matcher m = mentionPattern.matcher(message); Logger logger = DiscordBridge.getInstance().getLogger(); while (m.find()) { String mention = m.group(); if (mention.contains("@")) { String mentionName = mention.replace("@", ""); if ((mentionName.equalsIgnoreCase("here") && isBot && !player.hasPermission("discordbridge.mention.here")) || (mentionName.equalsIgnoreCase("everyone") && isBot && !player.hasPermission("discordbridge.mention.everyone"))) { message = message.replace(mention, mentionName); continue; } if (!isBot || player.hasPermission("discordbridge.mention.name." + mentionName.toLowerCase())) { Optional<User> user = DiscordUtil.getUserByName(mentionName, server); logger.debug(String.format("Found user %s: %s", mentionName, user.isPresent())); if (user.isPresent()) { message = message.replace(mention, "<@" + user.get().getId() + ">"); continue; } } if (!isBot || player.hasPermission("discordbridge.mention.role." + mentionName.toLowerCase())) { Optional<Role> role = DiscordUtil.getRoleByName(mentionName, server); logger.debug(String.format("Found role %s: %s", mentionName, role.isPresent())); if (role.isPresent() && role.get().isMentionable()) { message = message.replace(mention, "<@&" + role.get().getId() + ">"); } } } else if (mention.contains("#")) { String mentionName = mention.replace("#", ""); if (!isBot || player.hasPermission("discordbridge.mention.channel." + mentionName.toLowerCase())) { Optional<Channel> channel = DiscordUtil.getChannelByName(mentionName, server); logger.debug(String.format("Found channel %s: %s", mentionName, channel.isPresent())); if (channel.isPresent()) { message = message.replace(mention, "<#" + channel.get().getId() + ">"); } } } } return message; } private static Map<String, Map<String, Boolean>> needReplacementMap = new HashMap<>(); public static String escapeForDiscord(String text, String template, String token) { if (!needReplacementMap.containsKey(token)) { needReplacementMap.put(token, new HashMap<>()); } Map<String, Boolean> needReplacement = needReplacementMap.get(token); if (!needReplacement.containsKey(template)) { boolean need = !Pattern.matches(".*`.*" + token + ".*`.*", template) && Pattern.matches(".*_.*" + token + ".*_.*", template); needReplacement.put(template, need); } if (needReplacement.get(template)) text = text.replace("_", "\\_"); return text; } /** * @param config * @param message * @return */ public static Text formatForMinecraft(ChannelMinecraftConfigCore config, Message message) { Server server = message.getChannelReceiver().getServer(); User author = message.getAuthor(); // Replace %u with author's username String s = ConfigUtil.get(config.chatTemplate, "&7<%a> &f%s").replace("%u", author.getName()); // Replace %n with author's nickname or username String nickname = (author.getNickname(server) != null) ? author.getNickname(server) : author.getName(); s = s.replace("%a", nickname); // Get author's highest role Optional<Role> highestRole = getHighestRole(author, server); String roleName = "Discord"; //(config.roles.containsKey("everyone")) ? config.roles.get("everyone").name : "Member"; Color roleColor = Color.WHITE; if (highestRole.isPresent()) { roleName = highestRole.get().getName(); roleColor = highestRole.get().getColor(); } // Replace %r with Message author's highest role String colorString = ColorUtil.getColorCode(roleColor); s = (StringUtils.isNotBlank(colorString)) ? s.replace("%r", colorString + roleName + "&r") : s.replace("%r", roleName); // Replace %g with Message author's game String game = author.getGame(); if (game != null) s = s.replace("%g", game); // Add the actual message s = String.format(s, message.getContent()); // Replace Discord-specific stuffs s = TextUtil.formatDiscordMessage(s); // Format URL List<Text> texts = formatUrl(s); // Replace user mentions with readable names texts = formatUserMentions(texts, config.mention, message.getMentions(), server); // Replace role mentions texts = formatRoleMentions(texts, config.mention, message.getMentionedRoles()); // Format @here/@everyone mentions texts = formatEveryoneMentions(texts, config.mention, message.isMentioningEveryone()); // Format #channel mentions texts = formatChannelMentions(texts, config.mention); // Format custom :emjoi: texts = formatCustomEmoji(texts, config.emoji); return Text.join(texts); } /** * @param texts The message that may contain User mentions * @param config The mention config to be used for formatting * @param mentions The list of users mentioned * @param server The server to be used for nickname support * @return The final message with User mentions formatted */ private static List<Text> formatUserMentions(List<Text> texts, ChannelMinecraftMentionConfig config, List<User> mentions, Server server) { if (mentions.isEmpty()) return texts; // Prepare the text builders Map<User, Text.Builder> formattedMentioning = new HashMap<>(); for (User mention : mentions) { Optional<Role> role = getHighestRole(mention, server); String nick = (mention.getNickname(server) != null) ? mention.getNickname(server) : mention.getName(); String mentionString = ConfigUtil.get(config.userTemplate, "@%a") .replace("%s", nick).replace("%a", nick) .replace("%u", mention.getName()); Text.Builder formatted = Text.builder().append(TextSerializers.FORMATTING_CODE.deserialize(mentionString)) .onHover(TextActions.showText(Text.of("Mentioning user " + nick + "."))); if (role.isPresent()) { formatted = formatted.color(ColorUtil.getColor(role.get().getColor())); } formattedMentioning.put(mention, formatted); } // Replace the mention for (User mention : mentions) { String mentionString = "<@" + mention.getId() + ">"; texts = replaceMention(texts, mentionString, formattedMentioning.get(mention)); mentionString = "<@!" + mention.getId() + ">"; texts = replaceMention(texts, mentionString, formattedMentioning.get(mention)); } return texts; } /** * @param texts The message that may contain Role mentions * @param config The mention config to be used for formatting * @param mentions The list of roles mentioned * @return The final message with Role mentions formatted */ private static List<Text> formatRoleMentions(List<Text> texts, ChannelMinecraftMentionConfig config, List<Role> mentions) { if (mentions.isEmpty()) return texts; // Prepare the text builders Map<Role, Text.Builder> formattedMentioning = new HashMap<>(); for (Role mention : mentions) { String mentionString = ConfigUtil.get(config.roleTemplate, "@%s").replace("%s", mention.getName()); Text.Builder builder = Text.builder().append(TextSerializers.FORMATTING_CODE.deserialize(mentionString)) .onHover(TextActions.showText(Text.of("Mentioning role " + mention.getName() + "."))); if (mention.getColor() != null) { builder.color(ColorUtil.getColor(mention.getColor())); } formattedMentioning.put(mention, builder); } for (Role mention : mentions) { String mentionString = "<@&" + mention.getId() + ">"; texts = replaceMention(texts, mentionString, formattedMentioning.get(mention)); } return texts; } /** * @param texts The message that may contain everyone mentions * @param config The mention config to be used for formatting * @param mention Whether everyone was mentioned * @return The final message with everyone mentions formatted */ private static List<Text> formatEveryoneMentions(List<Text> texts, ChannelMinecraftMentionConfig config, boolean mention) { if (!mention) return texts; String mentionText = ConfigUtil.get(config.everyoneTemplate, "@%s").replace("%s", "everyone"); Text.Builder builder = Text.builder().append(TextSerializers.FORMATTING_CODE.deserialize(mentionText)) .onHover(TextActions.showText(Text.of("Mentioning everyone."))); texts = replaceMention(texts, "(@(everyone))", builder); mentionText = ConfigUtil.get(config.everyoneTemplate, "@%s").replace("%s", "here"); builder = Text.builder().append(TextSerializers.FORMATTING_CODE.deserialize(mentionText)) .onHover(TextActions.showText(Text.of("Mentioning online people."))); texts = replaceMention(texts, "(@(here))", builder); return texts; } private static Pattern channelPattern = Pattern.compile("<#[0-9]+>"); /** * @param texts The message that may contain channel mentions * @param config The mention config to be used for formatting * @return The final message with channel mentions formatted */ private static List<Text> formatChannelMentions(List<Text> texts, ChannelMinecraftMentionConfig config) { Map<String, Text.Builder> formattedMentions = new HashMap<>(); for (Text text : texts) { String serialized = TextSerializers.FORMATTING_CODE.serialize(text); Matcher matcher = channelPattern.matcher(serialized); while (matcher.find()) { String channelId = serialized.substring(matcher.start() + 2, matcher.end() - 1); if (!formattedMentions.containsKey(channelId)) { Channel channel = DiscordBridge.getInstance().getBotClient().getChannelById(channelId); String mentionText = ConfigUtil.get(config.channelTemplate, "#%s").replace("%s", channel.getName()); Text.Builder builder = Text.builder().append(TextSerializers.FORMATTING_CODE.deserialize(mentionText)) .onHover(TextActions.showText(Text.of("Mentioning channel " + channel.getName() + "."))); formattedMentions.put(channelId, builder); } } } for (String channelId : formattedMentions.keySet()) { texts = replaceMention(texts, "<#" + channelId + ">", formattedMentions.get(channelId)); } return texts; } private static Pattern customEmoji = Pattern.compile("<:([a-z]+):([0-9]+)>", Pattern.CASE_INSENSITIVE); /** * @param texts The message that may contain custom emoji * @param config The mention config to be used for formatting * @return The final message with custom emoji formatted */ private static List<Text> formatCustomEmoji(List<Text> texts, ChannelMinecraftEmojiConfig config) { for(Text text : texts){ String serialized = TextSerializers.FORMATTING_CODE.serialize(text); Matcher matcher = customEmoji.matcher(serialized); while (matcher.find()) { String name = matcher.group(1); String id = matcher.group(2); Text.Builder builder = TextSerializers.FORMATTING_CODE.deserialize(config.template.replace("%n", name)).toBuilder(); if (config.allowLink) { try { builder = builder.onClick(TextActions.openUrl(new URL("https://cdn.discordapp.com/emojis/" + id + ".png"))); } catch (MalformedURLException ignored) { } } if (StringUtils.isNotBlank(config.hoverTemplate)) builder = builder.onHover(TextActions.showText(Text.of(config.hoverTemplate))); texts = replaceMention(texts, "<:"+name+":"+id+">", builder); } } return texts; } public static List<Text> formatUrl(String message) { Preconditions.checkNotNull(message, "message"); List<Text> texts = Lists.newArrayList(); if (message.isEmpty()) { texts.add(Text.EMPTY); return texts; } Matcher m = urlPattern.matcher(message); if (!m.find()) { texts.add(TextSerializers.FORMATTING_CODE.deserialize(message)); return texts; } String remaining = message; StyleTuple st = EMPTY; do { // We found a URL. We split on the URL that we have. String[] textArray = remaining.split(urlPattern.pattern(), 2); Text first = Text.builder().color(st.colour).style(st.style) .append(TextSerializers.FORMATTING_CODE.deserialize(textArray[0])).build(); // Add this text to the list regardless. texts.add(first); // If we have more to do, shove it into the "remaining" variable. if (textArray.length == 2) { remaining = textArray[1]; } else { remaining = null; } // Get the last colour & styles String colourMatch = m.group("colour"); if (colourMatch != null && !colourMatch.isEmpty()) { first = TextSerializers.FORMATTING_CODE.deserialize(m.group("colour") + " "); } st = getLastColourAndStyle(first, st); // Build the URL String url = m.group("url"); String toParse = TextSerializers.FORMATTING_CODE.stripCodes(url); String whiteSpace = m.group("first"); texts.add(Text.of(whiteSpace)); try { URL urlObj; if (!toParse.startsWith("http://") && !toParse.startsWith("https://")) { urlObj = new URL("http://" + toParse); } else { urlObj = new URL(toParse); } texts.add(Text.builder(url).color(TextColors.DARK_AQUA).style(TextStyles.UNDERLINE) .onHover(TextActions.showText(Text.of("Click to open " + url))) .onClick(TextActions.openUrl(urlObj)) .build()); } catch (MalformedURLException e) { // URL parsing failed, just put the original text in here. DiscordBridge.getInstance().getLogger().warn("Malform: " + url); texts.add(Text.builder(url).color(st.colour).style(st.style).build()); } } while (remaining != null && m.find()); // Add the last bit. if (remaining != null) { texts.add(Text.builder().color(st.colour).style(st.style) .append(TextSerializers.FORMATTING_CODE.deserialize(remaining)).build()); } return texts; } private static List<Text> replaceMention(List<Text> texts, String mentionString, Text.Builder mentionBuilder) { List<Text> result = Lists.newArrayList(); StyleTuple st = EMPTY; for (Text text : texts) { Text remaining = text; while (remaining != null) { String serialized = TextSerializers.FORMATTING_CODE.serialize(remaining); String[] splitted = serialized.split(mentionString, 2); if (splitted.length == 2) { // Add first part Text first = TextSerializers.FORMATTING_CODE.deserialize(splitted[0]); result.add(first); // Add the mention result.add(mentionBuilder.build()); // Calculate the remaining st = TextUtil.getLastColourAndStyle(first, st); remaining = Text.builder().color(st.colour).style(st.style) .append(TextSerializers.FORMATTING_CODE.deserialize(splitted[1])).build(); } else { result.add(remaining); break; } } } return result; } private static StyleTuple getLastColourAndStyle(Text text, StyleTuple current) { List<Text> texts = flatten(text); TextColor tc = TextColors.NONE; TextStyle ts = TextStyles.NONE; for (int i = texts.size() - 1; i > -1; i--) { // If we have both a Text Colour and a Text Style, then break out. if (tc != TextColors.NONE && ts != TextStyles.NONE) { break; } if (tc == TextColors.NONE) { tc = texts.get(i).getColor(); } if (ts == TextStyles.NONE) { ts = texts.get(i).getStyle(); } } if (current == null) { return new StyleTuple(tc, ts); } return new StyleTuple(tc != TextColors.NONE ? tc : current.colour, ts != TextStyles.NONE ? ts : current.style); } private static List<Text> flatten(Text text) { List<Text> texts = Lists.newArrayList(text); if (!text.getChildren().isEmpty()) { text.getChildren().forEach(x -> texts.addAll(flatten(x))); } return texts; } /** * @param user * @param server * @return */ public static Optional<Role> getHighestRole(User user, Server server) { int position = 0; Optional<Role> highestRole = Optional.empty(); for (Role role : user.getRoles(server)) { if (role.getPosition() > position) { position = role.getPosition(); highestRole = Optional.of(role); } } return highestRole; } private static final class StyleTuple { final TextColor colour; final TextStyle style; StyleTuple(TextColor colour, TextStyle style) { this.colour = colour; this.style = style; } } }
/** * Copyright 2012 Netflix, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.netflix.hystrix; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import rx.Observable; import rx.Observable.OnSubscribe; import rx.Subscriber; import com.netflix.hystrix.exception.HystrixBadRequestException; import com.netflix.hystrix.exception.HystrixRuntimeException; import com.netflix.hystrix.exception.HystrixRuntimeException.FailureType; import com.netflix.hystrix.strategy.executionhook.HystrixCommandExecutionHook; import com.netflix.hystrix.strategy.properties.HystrixPropertiesStrategy; /** * Used to wrap code that will execute potentially risky functionality (typically meaning a service call over the network) * with fault and latency tolerance, statistics and performance metrics capture, circuit breaker and bulkhead functionality. * This command is essentially a blocking command but provides an Observable facade if used with observe() * * @param <R> * the return type * * @ThreadSafe */ public abstract class HystrixCommand<R> extends AbstractCommand<R> implements HystrixExecutable<R>, HystrixInvokableInfo<R>, HystrixObservable<R> { /** * Construct a {@link HystrixCommand} with defined {@link HystrixCommandGroupKey}. * <p> * The {@link HystrixCommandKey} will be derived from the implementing class name. * * @param group * {@link HystrixCommandGroupKey} used to group together multiple {@link HystrixCommand} objects. * <p> * The {@link HystrixCommandGroupKey} is used to represent a common relationship between commands. For example, a library or team name, the system all related commands interact with, * common business purpose etc. */ protected HystrixCommand(HystrixCommandGroupKey group) { super(group, null, null, null, null, null, null, null, null, null, null, null); } /** * Construct a {@link HystrixCommand} with defined {@link HystrixCommandGroupKey} and {@link HystrixThreadPoolKey}. * <p> * The {@link HystrixCommandKey} will be derived from the implementing class name. * * @param group * {@link HystrixCommandGroupKey} used to group together multiple {@link HystrixCommand} objects. * <p> * The {@link HystrixCommandGroupKey} is used to represent a common relationship between commands. For example, a library or team name, the system all related commands interact with, * common business purpose etc. * @param threadPool * {@link HystrixThreadPoolKey} used to identify the thread pool in which a {@link HystrixCommand} executes. */ protected HystrixCommand(HystrixCommandGroupKey group, HystrixThreadPoolKey threadPool) { super(group, null, threadPool, null, null, null, null, null, null, null, null, null); } /** * Construct a {@link HystrixCommand} with defined {@link HystrixCommandGroupKey} and thread timeout * <p> * The {@link HystrixCommandKey} will be derived from the implementing class name. * * @param group * {@link HystrixCommandGroupKey} used to group together multiple {@link HystrixCommand} objects. * <p> * The {@link HystrixCommandGroupKey} is used to represent a common relationship between commands. For example, a library or team name, the system all related commands interact with, * common business purpose etc. * @param executionIsolationThreadTimeoutInMilliseconds * Time in milliseconds at which point the calling thread will timeout (using {@link Future#get}) and walk away from the executing thread. */ protected HystrixCommand(HystrixCommandGroupKey group, int executionIsolationThreadTimeoutInMilliseconds) { super(group, null, null, null, null, HystrixCommandProperties.Setter().withExecutionTimeoutInMilliseconds(executionIsolationThreadTimeoutInMilliseconds), null, null, null, null, null, null); } /** * Construct a {@link HystrixCommand} with defined {@link HystrixCommandGroupKey}, {@link HystrixThreadPoolKey}, and thread timeout. * <p> * The {@link HystrixCommandKey} will be derived from the implementing class name. * * @param group * {@link HystrixCommandGroupKey} used to group together multiple {@link HystrixCommand} objects. * <p> * The {@link HystrixCommandGroupKey} is used to represent a common relationship between commands. For example, a library or team name, the system all related commands interact with, * common business purpose etc. * @param threadPool * {@link HystrixThreadPool} used to identify the thread pool in which a {@link HystrixCommand} executes. * @param executionIsolationThreadTimeoutInMilliseconds * Time in milliseconds at which point the calling thread will timeout (using {@link Future#get}) and walk away from the executing thread. */ protected HystrixCommand(HystrixCommandGroupKey group, HystrixThreadPoolKey threadPool, int executionIsolationThreadTimeoutInMilliseconds) { super(group, null, threadPool, null, null, HystrixCommandProperties.Setter().withExecutionTimeoutInMilliseconds(executionIsolationThreadTimeoutInMilliseconds), null, null, null, null, null, null); } /** * Construct a {@link HystrixCommand} with defined {@link Setter} that allows injecting property and strategy overrides and other optional arguments. * <p> * NOTE: The {@link HystrixCommandKey} is used to associate a {@link HystrixCommand} with {@link HystrixCircuitBreaker}, {@link HystrixCommandMetrics} and other objects. * <p> * Do not create multiple {@link HystrixCommand} implementations with the same {@link HystrixCommandKey} but different injected default properties as the first instantiated will win. * <p> * Properties passed in via {@link Setter#andCommandPropertiesDefaults} or {@link Setter#andThreadPoolPropertiesDefaults} are cached for the given {@link HystrixCommandKey} for the life of the JVM * or until {@link Hystrix#reset()} is called. Dynamic properties allow runtime changes. Read more on the <a href="https://github.com/Netflix/Hystrix/wiki/Configuration">Hystrix Wiki</a>. * * @param setter * Fluent interface for constructor arguments */ protected HystrixCommand(Setter setter) { // use 'null' to specify use the default this(setter.groupKey, setter.commandKey, setter.threadPoolKey, null, null, setter.commandPropertiesDefaults, setter.threadPoolPropertiesDefaults, null, null, null, null, null); } /** * Allow constructing a {@link HystrixCommand} with injection of most aspects of its functionality. * <p> * Some of these never have a legitimate reason for injection except in unit testing. * <p> * Most of the args will revert to a valid default if 'null' is passed in. */ /* package for testing */HystrixCommand(HystrixCommandGroupKey group, HystrixCommandKey key, HystrixThreadPoolKey threadPoolKey, HystrixCircuitBreaker circuitBreaker, HystrixThreadPool threadPool, HystrixCommandProperties.Setter commandPropertiesDefaults, HystrixThreadPoolProperties.Setter threadPoolPropertiesDefaults, HystrixCommandMetrics metrics, TryableSemaphore fallbackSemaphore, TryableSemaphore executionSemaphore, HystrixPropertiesStrategy propertiesStrategy, HystrixCommandExecutionHook executionHook) { super(group, key, threadPoolKey, circuitBreaker, threadPool, commandPropertiesDefaults, threadPoolPropertiesDefaults, metrics, fallbackSemaphore, executionSemaphore, propertiesStrategy, executionHook); } /** * Fluent interface for arguments to the {@link HystrixCommand} constructor. * <p> * The required arguments are set via the 'with' factory method and optional arguments via the 'and' chained methods. * <p> * Example: * <pre> {@code * Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("GroupName")) .andCommandKey(HystrixCommandKey.Factory.asKey("CommandName")); * } </pre> * * @NotThreadSafe */ final public static class Setter { protected final HystrixCommandGroupKey groupKey; protected HystrixCommandKey commandKey; protected HystrixThreadPoolKey threadPoolKey; protected HystrixCommandProperties.Setter commandPropertiesDefaults; protected HystrixThreadPoolProperties.Setter threadPoolPropertiesDefaults; /** * Setter factory method containing required values. * <p> * All optional arguments can be set via the chained methods. * * @param groupKey * {@link HystrixCommandGroupKey} used to group together multiple {@link HystrixCommand} objects. * <p> * The {@link HystrixCommandGroupKey} is used to represent a common relationship between commands. For example, a library or team name, the system all related commands interace * with, * common business purpose etc. */ protected Setter(HystrixCommandGroupKey groupKey) { this.groupKey = groupKey; } /** * Setter factory method with required values. * <p> * All optional arguments can be set via the chained methods. * * @param groupKey * {@link HystrixCommandGroupKey} used to group together multiple {@link HystrixCommand} objects. * <p> * The {@link HystrixCommandGroupKey} is used to represent a common relationship between commands. For example, a library or team name, the system all related commands interace * with, * common business purpose etc. */ public static Setter withGroupKey(HystrixCommandGroupKey groupKey) { return new Setter(groupKey); } /** * @param commandKey * {@link HystrixCommandKey} used to identify a {@link HystrixCommand} instance for statistics, circuit-breaker, properties, etc. * <p> * By default this will be derived from the instance class name. * <p> * NOTE: Every unique {@link HystrixCommandKey} will result in new instances of {@link HystrixCircuitBreaker}, {@link HystrixCommandMetrics} and {@link HystrixCommandProperties}. * Thus, * the number of variants should be kept to a finite and reasonable number to avoid high-memory usage or memory leacks. * <p> * Hundreds of keys is fine, tens of thousands is probably not. * @return Setter for fluent interface via method chaining */ public Setter andCommandKey(HystrixCommandKey commandKey) { this.commandKey = commandKey; return this; } /** * @param threadPoolKey * {@link HystrixThreadPoolKey} used to define which thread-pool this command should run in (when configured to run on separate threads via * {@link HystrixCommandProperties#executionIsolationStrategy()}). * <p> * By default this is derived from the {@link HystrixCommandGroupKey} but if injected this allows multiple commands to have the same {@link HystrixCommandGroupKey} but different * thread-pools. * @return Setter for fluent interface via method chaining */ public Setter andThreadPoolKey(HystrixThreadPoolKey threadPoolKey) { this.threadPoolKey = threadPoolKey; return this; } /** * Optional * * @param commandPropertiesDefaults * {@link HystrixCommandProperties.Setter} with property overrides for this specific instance of {@link HystrixCommand}. * <p> * See the {@link HystrixPropertiesStrategy} JavaDocs for more information on properties and order of precedence. * @return Setter for fluent interface via method chaining */ public Setter andCommandPropertiesDefaults(HystrixCommandProperties.Setter commandPropertiesDefaults) { this.commandPropertiesDefaults = commandPropertiesDefaults; return this; } /** * Optional * * @param threadPoolPropertiesDefaults * {@link HystrixThreadPoolProperties.Setter} with property overrides for the {@link HystrixThreadPool} used by this specific instance of {@link HystrixCommand}. * <p> * See the {@link HystrixPropertiesStrategy} JavaDocs for more information on properties and order of precedence. * @return Setter for fluent interface via method chaining */ public Setter andThreadPoolPropertiesDefaults(HystrixThreadPoolProperties.Setter threadPoolPropertiesDefaults) { this.threadPoolPropertiesDefaults = threadPoolPropertiesDefaults; return this; } } /** * Implement this method with code to be executed when {@link #execute()} or {@link #queue()} are invoked. * * @return R response type * @throws Exception * if command execution fails */ protected abstract R run() throws Exception; /** * If {@link #execute()} or {@link #queue()} fails in any way then this method will be invoked to provide an opportunity to return a fallback response. * <p> * This should do work that does not require network transport to produce. * <p> * In other words, this should be a static or cached result that can immediately be returned upon failure. * <p> * If network traffic is wanted for fallback (such as going to MemCache) then the fallback implementation should invoke another {@link HystrixCommand} instance that protects against that network * access and possibly has another level of fallback that does not involve network access. * <p> * DEFAULT BEHAVIOR: It throws UnsupportedOperationException. * * @return R or throw UnsupportedOperationException if not implemented */ protected R getFallback() { throw new UnsupportedOperationException("No fallback available."); } @Override final protected Observable<R> getExecutionObservable() { return Observable.create(new OnSubscribe<R>() { @Override public void call(Subscriber<? super R> s) { try { s.onNext(run()); s.onCompleted(); } catch (Throwable e) { s.onError(e); } } }); } @Override final protected Observable<R> getFallbackObservable() { return Observable.create(new OnSubscribe<R>() { @Override public void call(Subscriber<? super R> s) { try { s.onNext(getFallback()); s.onCompleted(); } catch (Throwable e) { s.onError(e); } } }); } /** * Used for synchronous execution of command. * * @return R * Result of {@link #run()} execution or a fallback from {@link #getFallback()} if the command fails for any reason. * @throws HystrixRuntimeException * if a failure occurs and a fallback cannot be retrieved * @throws HystrixBadRequestException * if invalid arguments or state were used representing a user failure, not a system failure * @throws IllegalStateException * if invoked more than once */ public R execute() { try { return queue().get(); } catch (Exception e) { throw decomposeException(e); } } /** * Used for asynchronous execution of command. * <p> * This will queue up the command on the thread pool and return an {@link Future} to get the result once it completes. * <p> * NOTE: If configured to not run in a separate thread, this will have the same effect as {@link #execute()} and will block. * <p> * We don't throw an exception but just flip to synchronous execution so code doesn't need to change in order to switch a command from running on a separate thread to the calling thread. * * @return {@code Future<R>} Result of {@link #run()} execution or a fallback from {@link #getFallback()} if the command fails for any reason. * @throws HystrixRuntimeException * if a fallback does not exist * <p> * <ul> * <li>via {@code Future.get()} in {@link ExecutionException#getCause()} if a failure occurs</li> * <li>or immediately if the command can not be queued (such as short-circuited, thread-pool/semaphore rejected)</li> * </ul> * @throws HystrixBadRequestException * via {@code Future.get()} in {@link ExecutionException#getCause()} if invalid arguments or state were used representing a user failure, not a system failure * @throws IllegalStateException * if invoked more than once */ public Future<R> queue() { /* * --- Schedulers.immediate() * * We use the 'immediate' schedule since Future.get() is blocking so we don't want to bother doing the callback to the Future on a separate thread * as we don't need to separate the Hystrix thread from user threads since they are already providing it via the Future.get() call. * * We pass 'false' to tell the Observable we will block on it so it doesn't schedule an async timeout. * * This optimizes for using the calling thread to do the timeout rather than scheduling another thread. * * In a tight-loop of executing commands this optimization saves a few microseconds per execution. * It also just makes no sense to use a separate thread to timeout the command when the calling thread * is going to sit waiting on it. */ final Observable<R> o = toObservable(); final Future<R> f = o.toBlocking().toFuture(); /* special handling of error states that throw immediately */ if (f.isDone()) { try { f.get(); return f; } catch (Exception e) { RuntimeException re = decomposeException(e); if (re instanceof HystrixBadRequestException) { return f; } else if (re instanceof HystrixRuntimeException) { HystrixRuntimeException hre = (HystrixRuntimeException) re; if (hre.getFailureType() == FailureType.COMMAND_EXCEPTION || hre.getFailureType() == FailureType.TIMEOUT) { // we don't throw these types from queue() only from queue().get() as they are execution errors return f; } else { // these are errors we throw from queue() as they as rejection type errors throw hre; } } else { throw re; } } } return f; } @Override protected String getFallbackMethodName() { return "getFallback"; } }
package com.planet_ink.coffee_mud.CharClasses; import com.planet_ink.coffee_mud.core.interfaces.*; import com.planet_ink.coffee_mud.core.*; import com.planet_ink.coffee_mud.core.collections.*; import com.planet_ink.coffee_mud.Abilities.interfaces.*; import com.planet_ink.coffee_mud.Areas.interfaces.*; import com.planet_ink.coffee_mud.Behaviors.interfaces.*; import com.planet_ink.coffee_mud.CharClasses.interfaces.*; import com.planet_ink.coffee_mud.Commands.interfaces.*; import com.planet_ink.coffee_mud.Common.interfaces.*; import com.planet_ink.coffee_mud.Exits.interfaces.*; import com.planet_ink.coffee_mud.Items.interfaces.*; import com.planet_ink.coffee_mud.Libraries.interfaces.*; import com.planet_ink.coffee_mud.Locales.interfaces.*; import com.planet_ink.coffee_mud.MOBS.interfaces.*; import com.planet_ink.coffee_mud.Races.interfaces.*; import java.util.*; /* Copyright 2001-2015 Bo Zimmerman Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ @SuppressWarnings({"unchecked","rawtypes"}) public class Paladin extends StdCharClass { @Override public String ID(){return "Paladin";} private final static String localizedStaticName = CMLib.lang().L("Paladin"); @Override public String name() { return localizedStaticName; } @Override public String baseClass(){return "Fighter";} @Override public int getBonusPracLevel(){return 0;} @Override public int getBonusAttackLevel(){return 0;} @Override public String getMovementFormula(){return "12*((@x2<@x3)/18)"; } @Override public int getAttackAttribute(){return CharStats.STAT_STRENGTH;} @Override public int getLevelsPerBonusDamage(){ return 30;} @Override public int getPracsFirstLevel(){return 3;} @Override public int getTrainsFirstLevel(){return 4;} @Override public String getHitPointsFormula(){return "((@x6<@x7)/2)+(2*(1?6))"; } @Override public String getManaFormula(){return "((@x4<@x5)/8)+(1*(1?3))"; } @Override public int allowedArmorLevel(){return CharClass.ARMOR_ANY;} public Paladin() { super(); maxStatAdj[CharStats.STAT_STRENGTH]=4; maxStatAdj[CharStats.STAT_WISDOM]=4; } @Override public void initializeClass() { super.initializeClass(); CMLib.ableMapper().addCharAbilityMapping(ID(),1,"Skill_Write",50,true); CMLib.ableMapper().addCharAbilityMapping(ID(),1,"Specialization_Axe",false); CMLib.ableMapper().addCharAbilityMapping(ID(),1,"Specialization_BluntWeapon",false); CMLib.ableMapper().addCharAbilityMapping(ID(),1,"Specialization_EdgedWeapon",false); CMLib.ableMapper().addCharAbilityMapping(ID(),1,"Specialization_FlailedWeapon",false); CMLib.ableMapper().addCharAbilityMapping(ID(),1,"Specialization_Hammer",false); CMLib.ableMapper().addCharAbilityMapping(ID(),1,"Specialization_Natural",false); CMLib.ableMapper().addCharAbilityMapping(ID(),1,"Specialization_Polearm",false); CMLib.ableMapper().addCharAbilityMapping(ID(),1,"Specialization_Ranged",false); CMLib.ableMapper().addCharAbilityMapping(ID(),1,"Specialization_Sword",true); CMLib.ableMapper().addCharAbilityMapping(ID(),1,"Specialization_Armor",true); CMLib.ableMapper().addCharAbilityMapping(ID(),1,"Specialization_Shield",true); CMLib.ableMapper().addCharAbilityMapping(ID(),1,"Skill_Recall",75,true); CMLib.ableMapper().addCharAbilityMapping(ID(),1,"Skill_Swim",false); CMLib.ableMapper().addCharAbilityMapping(ID(),1,"Paladin_HealingHands",true); CMLib.ableMapper().addCharAbilityMapping(ID(),2,"Fighter_Rescue",false); CMLib.ableMapper().addCharAbilityMapping(ID(),2,"Paladin_ImprovedResists",false); CMLib.ableMapper().addCharAbilityMapping(ID(),3,"Skill_Parry",true); CMLib.ableMapper().addCharAbilityMapping(ID(),3,"Fighter_ArmorTweaking",false); CMLib.ableMapper().addCharAbilityMapping(ID(),4,"Skill_Bash",false); CMLib.ableMapper().addCharAbilityMapping(ID(),4,"Paladin_HolyStrike",false); CMLib.ableMapper().addCharAbilityMapping(ID(),5,"Paladin_SummonMount",false); CMLib.ableMapper().addCharAbilityMapping(ID(),5,"Prayer_CureLight",false); CMLib.ableMapper().addCharAbilityMapping(ID(),6,"Skill_Revoke",false); CMLib.ableMapper().addCharAbilityMapping(ID(),6,"Prayer_SenseEvil",true); CMLib.ableMapper().addCharAbilityMapping(ID(),7,"Skill_Dodge",false); CMLib.ableMapper().addCharAbilityMapping(ID(),7,"Skill_WandUse",false); CMLib.ableMapper().addCharAbilityMapping(ID(),7,"Paladin_DiseaseImmunity",true); CMLib.ableMapper().addCharAbilityMapping(ID(),7,"Paladin_PaladinsMount",false); CMLib.ableMapper().addCharAbilityMapping(ID(),8,"Skill_Disarm",false); CMLib.ableMapper().addCharAbilityMapping(ID(),8,"Prayer_ProtEvil",false); CMLib.ableMapper().addCharAbilityMapping(ID(),9,"Skill_Attack2",true); CMLib.ableMapper().addCharAbilityMapping(ID(),9,"Prayer_CureDeafness",false); CMLib.ableMapper().addCharAbilityMapping(ID(),10,"Prayer_CureSerious",false,CMParms.parseSemicolons("Prayer_CureLight",true)); CMLib.ableMapper().addCharAbilityMapping(ID(),10,"Prayer_HealMount",false); CMLib.ableMapper().addCharAbilityMapping(ID(),11,"Skill_MountedCombat",false); CMLib.ableMapper().addCharAbilityMapping(ID(),11,"Paladin_Defend",true); CMLib.ableMapper().addCharAbilityMapping(ID(),11,"Prayer_Bless",false); CMLib.ableMapper().addCharAbilityMapping(ID(),12,"Fighter_BlindFighting",false); CMLib.ableMapper().addCharAbilityMapping(ID(),12,"Prayer_Freedom",false); CMLib.ableMapper().addCharAbilityMapping(ID(),13,"Paladin_Courage",true); CMLib.ableMapper().addCharAbilityMapping(ID(),13,"Prayer_DispelEvil",false); CMLib.ableMapper().addCharAbilityMapping(ID(),14,"Prayer_RestoreVoice",false); CMLib.ableMapper().addCharAbilityMapping(ID(),14,"Paladin_Purity",false); CMLib.ableMapper().addCharAbilityMapping(ID(),15,"Fighter_Cleave",false); CMLib.ableMapper().addCharAbilityMapping(ID(),15,"Skill_Climb",false); CMLib.ableMapper().addCharAbilityMapping(ID(),15,"Prayer_RemovePoison",false); CMLib.ableMapper().addCharAbilityMapping(ID(),15,"Paladin_Breakup",true); CMLib.ableMapper().addCharAbilityMapping(ID(),16,"Prayer_CureDisease",false); CMLib.ableMapper().addCharAbilityMapping(ID(),16,"Paladin_MountedCharge",false); CMLib.ableMapper().addCharAbilityMapping(ID(),17,"Paladin_PoisonImmunity",true); CMLib.ableMapper().addCharAbilityMapping(ID(),17,"Prayer_Sanctuary",false); CMLib.ableMapper().addCharAbilityMapping(ID(),18,"Prayer_CureCritical",false,CMParms.parseSemicolons("Prayer_CureSerious",true)); CMLib.ableMapper().addCharAbilityMapping(ID(),18,"Skill_Trip",false); CMLib.ableMapper().addCharAbilityMapping(ID(),19,"Paladin_Aura",true); CMLib.ableMapper().addCharAbilityMapping(ID(),19,"Prayer_HolyAura",false,CMParms.parseSemicolons("Prayer_Bless",true)); CMLib.ableMapper().addCharAbilityMapping(ID(),20,"Skill_AttackHalf",false); CMLib.ableMapper().addCharAbilityMapping(ID(),20,"Prayer_Calm",false); CMLib.ableMapper().addCharAbilityMapping(ID(),21,"Prayer_CureBlindness",true); CMLib.ableMapper().addCharAbilityMapping(ID(),21,"Prayer_ResurrectMount",false); CMLib.ableMapper().addCharAbilityMapping(ID(),22,"Prayer_BladeBarrier",false); CMLib.ableMapper().addCharAbilityMapping(ID(),22,"Prayer_CureFatigue",false); CMLib.ableMapper().addCharAbilityMapping(ID(),22,"Paladin_CommandHorse",false); CMLib.ableMapper().addCharAbilityMapping(ID(),23,"Prayer_LightHammer",false); CMLib.ableMapper().addCharAbilityMapping(ID(),23,"Fighter_Sweep",true); CMLib.ableMapper().addCharAbilityMapping(ID(),24,"Paladin_Goodness",false); CMLib.ableMapper().addCharAbilityMapping(ID(),24,"Prayer_MassFreedom",false,CMParms.parseSemicolons("Prayer_Freedom",true)); CMLib.ableMapper().addCharAbilityMapping(ID(),25,"Paladin_AbidingAura",false); CMLib.ableMapper().addCharAbilityMapping(ID(),25,"Prayer_Heal",false,CMParms.parseSemicolons("Prayer_CureCritical",true)); CMLib.ableMapper().addCharAbilityMapping(ID(),30,"Paladin_CraftHolyAvenger",true,CMParms.parseSemicolons("Specialization_Sword;Weaponsmithing",true)); } @Override public int availabilityCode(){return Area.THEME_FANTASY;} @Override public void grantAbilities(MOB mob, boolean isBorrowedClass) { super.grantAbilities(mob,isBorrowedClass); if(mob.playerStats()==null) { final List<AbilityMapper.AbilityMapping> V=CMLib.ableMapper().getUpToLevelListings(ID(), mob.charStats().getClassLevel(ID()), false, false); for(final AbilityMapper.AbilityMapping able : V) { final Ability A=CMClass.getAbility(able.abilityID); if((A!=null) &&(!CMLib.ableMapper().getAllQualified(ID(),true,A.ID())) &&(!CMLib.ableMapper().getDefaultGain(ID(),true,A.ID()))) giveMobAbility(mob,A,CMLib.ableMapper().getDefaultProficiency(ID(),true,A.ID()),CMLib.ableMapper().getDefaultParm(ID(),true,A.ID()),isBorrowedClass); } } } @Override public void executeMsg(Environmental host, CMMsg msg) { super.executeMsg(host,msg); Fighter.conquestExperience(this,host,msg); Fighter.duelExperience(this, host, msg); } @Override public String getOtherLimitsDesc(){return "Must remain good to avoid spell/skill failure chance.";} @Override public String getOtherBonusDesc() { return "Receives bonus conquest and duel experience."; } @Override public boolean okMessage(final Environmental myHost, final CMMsg msg) { if(!(myHost instanceof MOB)) return super.okMessage(myHost,msg); final MOB myChar=(MOB)myHost; if((msg.amISource(myChar)) &&(msg.sourceMinor()==CMMsg.TYP_CAST_SPELL) &&(!CMLib.flags().isGood(myChar)) &&((msg.tool()==null)||((CMLib.ableMapper().getQualifyingLevel(ID(),true,msg.tool().ID())>0) &&(myChar.isMine(msg.tool())))) &&(CMLib.dice().rollPercentage()>myChar.charStats().getStat(CharStats.STAT_WISDOM)*2)) { myChar.location().show(myChar,null,CMMsg.MSG_OK_VISUAL,L("<S-NAME> watch(es) <S-HIS-HER> angry god absorb <S-HIS-HER> magical energy!")); return false; } return super.okMessage(myChar, msg); } private final String[] raceRequiredList=new String[]{"Human"}; @Override public String[] getRequiredRaceList(){ return raceRequiredList; } private final Pair<String,Integer>[] minimumStatRequirements=new Pair[]{ new Pair<String,Integer>("Wisdom",Integer.valueOf(9)), new Pair<String,Integer>("Strength",Integer.valueOf(9)) }; @Override public Pair<String,Integer>[] getMinimumStatRequirements() { return minimumStatRequirements; } @Override public List<Item> outfit(MOB myChar) { if(outfitChoices==null) { final Weapon w=CMClass.getWeapon("Shortsword"); if(w == null) return new Vector<Item>(); outfitChoices=new Vector(); outfitChoices.add(w); } return outfitChoices; } }
/** * Copyright (C) 2011-2012 Turn, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.turn.ttorrent.tracker; import com.turn.ttorrent.protocol.tracker.Peer; import com.turn.ttorrent.protocol.TorrentUtils; import com.turn.ttorrent.protocol.torrent.Torrent; import com.turn.ttorrent.protocol.tracker.TrackerMessage.AnnounceEvent; import io.netty.util.internal.PlatformDependent; import java.io.UnsupportedEncodingException; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; import javax.annotation.CheckForNull; import javax.annotation.Nonnegative; import javax.annotation.Nonnull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Tracked torrents are torrent for which we don't expect to have data files * for. * * <p> * {@link TrackedTorrent} objects are used by the BitTorrent tracker to * represent a torrent that is announced by the tracker. As such, it is not * expected to point to any valid local data like. It also contains some * additional information used by the tracker to keep track of which peers * exchange on it, etc. * </p> * * @author mpetazzoni */ public class TrackedTorrent { private static final Logger LOG = LoggerFactory.getLogger(TrackedTorrent.class); /** Minimum announce interval requested from peers, in seconds. */ public static final int MIN_ANNOUNCE_INTERVAL_SECONDS = 5; /** Default number of peers included in a tracker response. */ private static final int DEFAULT_ANSWER_NUM_PEERS = 30; /** Default announce interval requested from peers, in seconds. */ private static final int DEFAULT_ANNOUNCE_INTERVAL_SECONDS = 10; @CheckForNull private final String name; @Nonnull private final String infoHash; private long announceInterval; /** Peers currently exchanging on this torrent. */ private final ConcurrentMap<String, TrackedPeer> peers = PlatformDependent.newConcurrentHashMap(); public TrackedTorrent(@CheckForNull String name, @Nonnull byte[] infoHash) { this.name = name; this.infoHash = TorrentUtils.toHex(infoHash); setAnnounceInterval(DEFAULT_ANNOUNCE_INTERVAL_SECONDS, TimeUnit.SECONDS); } public TrackedTorrent(@Nonnull Torrent torrent) { this(torrent.getName(), torrent.getInfoHash()); } @CheckForNull public String getName() { return name; } @Nonnull public String getHexInfoHash() { return infoHash; } /** * Returns the map of all peers currently exchanging on this torrent. */ @Nonnull public Iterable<? extends TrackedPeer> getPeers() { return peers.values(); } /** * Retrieve a peer exchanging on this torrent. * * @param peerId The hexadecimal representation of the peer's ID. */ @CheckForNull public TrackedPeer getPeer(@Nonnull byte[] peerId) { return peers.get(TorrentUtils.toHex(peerId)); } /** * Add a peer exchanging on this torrent. * * @param peer The new Peer involved with this torrent. */ public void addPeer(@Nonnull TrackedPeer peer) { this.peers.put(TorrentUtils.toHex(peer.getPeerId()), peer); } /** * Remove a peer from this torrent's swarm. * * @param peerId The hexadecimal representation of the peer's ID. */ public TrackedPeer removePeer(@Nonnull byte[] peerId) { return peers.remove(TorrentUtils.toHex(peerId)); } /** * Count the number of seeders (peers in the COMPLETED state) on this * torrent. */ public int seeders() { int count = 0; for (TrackedPeer peer : this.peers.values()) { if (peer.isCompleted()) { count++; } } return count; } /** * Count the number of leechers (non-COMPLETED peers) on this torrent. */ public int leechers() { int count = 0; for (TrackedPeer peer : this.peers.values()) { if (!peer.isCompleted()) { count++; } } return count; } /** * Returns the announce interval for this torrent, in milliseconds. */ @Nonnegative public long getAnnounceInterval() { return this.announceInterval; } public long getPeerExpiryInterval() { return getAnnounceInterval() * 2; } /** * Set the announce interval for this torrent. * * @param interval New announce interval, in seconds. */ public void setAnnounceInterval(int interval, @Nonnull TimeUnit unit) { if (interval <= 0) { throw new IllegalArgumentException("Invalid announce interval"); } long announceInterval = unit.toMillis(interval); if (announceInterval < 0 || announceInterval > Integer.MAX_VALUE) throw new IllegalArgumentException("Illegal (overflow) timeunit " + announceInterval); this.announceInterval = announceInterval; } /** * Update this torrent's swarm from an announce event. * * <p> * This will automatically create a new peer on a 'started' announce event, * and remove the peer on a 'stopped' announce event. * </p> * * @param event The reported event. If <em>null</em>, means a regular * interval announce event, as defined in the BitTorrent specification. * @param peerId The byte-encoded peer ID. * @param hexPeerId The hexadecimal representation of the peer's ID. * @param ip The peer's IP address. * @param port The peer's inbound port. * @param uploaded The peer's reported uploaded byte count. * @param downloaded The peer's reported downloaded byte count. * @param left The peer's reported left to download byte count. * @return The peer that sent us the announce request. */ @CheckForNull public TrackedPeer update(AnnounceEvent event, byte[] peerId, List<? extends InetSocketAddress> peerAddresses, long uploaded, long downloaded, long left) throws UnsupportedEncodingException { TrackedPeerState state = TrackedPeerState.UNKNOWN; TrackedPeer trackedPeer; if (AnnounceEvent.STARTED.equals(event)) { trackedPeer = new TrackedPeer(peerId); state = TrackedPeerState.STARTED; this.addPeer(trackedPeer); } else if (AnnounceEvent.STOPPED.equals(event)) { trackedPeer = removePeer(peerId); state = TrackedPeerState.STOPPED; } else if (AnnounceEvent.COMPLETED.equals(event)) { trackedPeer = getPeer(peerId); state = TrackedPeerState.COMPLETED; } else if (AnnounceEvent.NONE.equals(event)) { trackedPeer = getPeer(peerId); // TODO: There is a chance this will change COMPLETED -> STARTED state = TrackedPeerState.STARTED; } else { throw new IllegalArgumentException("Unexpected announce event type!"); } // This can be null if we STOPPED an unknown peer. if (trackedPeer != null) trackedPeer.update(this, state, peerAddresses, uploaded, downloaded, left); return trackedPeer; } /** * Get a list of peers we can return in an announce response for this * torrent. * * @param peer The peer making the request, so we can exclude it from the * list of returned peers. * @return A list of peers we can include in an announce response. */ public List<? extends Peer> getSomePeers(TrackedPeer client, int numWant) { numWant = Math.min(numWant, DEFAULT_ANSWER_NUM_PEERS); // Extract answerPeers random peers List<TrackedPeer> candidates = new ArrayList<TrackedPeer>(peers.values()); Collections.shuffle(candidates); List<Peer> out = new ArrayList<Peer>(numWant); long now = System.currentTimeMillis(); // LOG.info("Client PeerAddress is " + client.getPeerAddress()); for (TrackedPeer candidate : candidates) { // LOG.info("Candidate PeerAddress is " + candidate.getPeerAddress()); // Collect unfresh peers, and obviously don't serve them as well. if (!candidate.isFresh(now, getPeerExpiryInterval())) { LOG.debug("Collecting stale peer {}...", candidate.getPeerAddresses()); peers.remove(TorrentUtils.toHex(candidate.getPeerId()), candidate); continue; } // Don't include the requesting peer in the answer. if (Arrays.equals(client.getPeerId(), candidate.getPeerId())) { if (!client.equals(candidate)) { LOG.debug("Collecting superceded peer {}...", candidate); removePeer(candidate.getPeerId()); } continue; } for (InetSocketAddress peerAddress : candidate.getPeerAddresses()) out.add(new Peer(peerAddress, candidate.getPeerId())); if (out.size() >= numWant) break; } LOG.trace("Some peers are {}", out); return out; } /** * Remove unfresh peers from this torrent. * * <p> * Collect and remove all non-fresh peers from this torrent. This is * usually called by the periodic peer collector of the BitTorrent tracker. * </p> */ @Nonnegative public int collectUnfreshPeers() { long now = System.currentTimeMillis(); int count = 0; for (TrackedPeer peer : peers.values()) { if (!peer.isFresh(now, getPeerExpiryInterval())) { peers.remove(TorrentUtils.toHex(peer.getPeerId()), peer); count++; } } return count; } @Override public String toString() { return getName() + " (" + peers.size() + " peers, interval=" + getAnnounceInterval() + ")"; } }
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.spellchecker.inspections; import com.intellij.codeInspection.*; import com.intellij.codeInspection.ui.SingleCheckboxOptionsPanel; import com.intellij.lang.*; import com.intellij.lang.refactoring.NamesValidator; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiElementVisitor; import com.intellij.psi.tree.IElementType; import com.intellij.spellchecker.SpellCheckerManager; import com.intellij.spellchecker.quickfixes.SpellCheckerQuickFix; import com.intellij.spellchecker.tokenizer.*; import com.intellij.spellchecker.util.SpellCheckerBundle; import com.intellij.util.Consumer; import gnu.trove.THashSet; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.awt.*; import java.util.Set; public class SpellCheckingInspection extends LocalInspectionTool { public static final String SPELL_CHECKING_INSPECTION_TOOL_NAME = "SpellCheckingInspection"; @NotNull @Override public SuppressQuickFix[] getBatchSuppressActions(@Nullable PsiElement element) { if (element != null) { final Language language = element.getLanguage(); SpellcheckingStrategy strategy = getSpellcheckingStrategy(element, language); if(strategy instanceof SuppressibleSpellcheckingStrategy) { return ((SuppressibleSpellcheckingStrategy)strategy).getSuppressActions(element, getShortName()); } } return super.getBatchSuppressActions(element); } private static SpellcheckingStrategy getSpellcheckingStrategy(@NotNull PsiElement element, @NotNull Language language) { for (SpellcheckingStrategy strategy : LanguageSpellchecking.INSTANCE.allForLanguage(language)) { if (strategy.isMyContext(element)) { return strategy; } } return null; } @Override public boolean isSuppressedFor(@NotNull PsiElement element) { final Language language = element.getLanguage(); SpellcheckingStrategy strategy = getSpellcheckingStrategy(element, language); if (strategy instanceof SuppressibleSpellcheckingStrategy) { return ((SuppressibleSpellcheckingStrategy)strategy).isSuppressedFor(element, getShortName()); } return super.isSuppressedFor(element); } @Override @NonNls @NotNull public String getShortName() { return SPELL_CHECKING_INSPECTION_TOOL_NAME; } @Override @NotNull public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder holder, final boolean isOnTheFly) { final SpellCheckerManager manager = SpellCheckerManager.getInstance(holder.getProject()); return new PsiElementVisitor() { @Override public void visitElement(final PsiElement element) { if (holder.getResultCount()>1000) return; final ASTNode node = element.getNode(); if (node == null) { return; } // Extract parser definition from element final Language language = element.getLanguage(); final IElementType elementType = node.getElementType(); final ParserDefinition parserDefinition = LanguageParserDefinitions.INSTANCE.forLanguage(language); // Handle selected options if (parserDefinition != null) { if (parserDefinition.getStringLiteralElements().contains(elementType)) { if (!processLiterals) { return; } } else if (parserDefinition.getCommentTokens().contains(elementType)) { if (!processComments) { return; } } else if (!processCode) { return; } } tokenize(element, language, new MyTokenConsumer(manager, holder, LanguageNamesValidation.INSTANCE.forLanguage(language))); } }; } /** * Splits element text in tokens according to spell checker strategy of given language * @param element Psi element * @param language Usually element.getLanguage() * @param consumer the consumer of tokens */ public static void tokenize(@NotNull final PsiElement element, @NotNull final Language language, TokenConsumer consumer) { final SpellcheckingStrategy factoryByLanguage = getSpellcheckingStrategy(element, language); if(factoryByLanguage==null) return; Tokenizer tokenizer = factoryByLanguage.getTokenizer(element); //noinspection unchecked tokenizer.tokenize(element, consumer); } private static void addBatchDescriptor(PsiElement element, int offset, @NotNull TextRange textRange, @NotNull ProblemsHolder holder) { SpellCheckerQuickFix[] fixes = SpellcheckingStrategy.getDefaultBatchFixes(); ProblemDescriptor problemDescriptor = createProblemDescriptor(element, offset, textRange, fixes, false); holder.registerProblem(problemDescriptor); } private static void addRegularDescriptor(PsiElement element, int offset, @NotNull TextRange textRange, @NotNull ProblemsHolder holder, boolean useRename, String wordWithTypo) { SpellcheckingStrategy strategy = getSpellcheckingStrategy(element, element.getLanguage()); SpellCheckerQuickFix[] fixes = strategy != null ? strategy.getRegularFixes(element, offset, textRange, useRename, wordWithTypo) : SpellcheckingStrategy.getDefaultRegularFixes(useRename, wordWithTypo, element); final ProblemDescriptor problemDescriptor = createProblemDescriptor(element, offset, textRange, fixes, true); holder.registerProblem(problemDescriptor); } private static ProblemDescriptor createProblemDescriptor(PsiElement element, int offset, TextRange textRange, SpellCheckerQuickFix[] fixes, boolean onTheFly) { SpellcheckingStrategy strategy = getSpellcheckingStrategy(element, element.getLanguage()); final Tokenizer tokenizer = strategy != null ? strategy.getTokenizer(element) : null; if (tokenizer != null) { textRange = tokenizer.getHighlightingRange(element, offset, textRange); } assert textRange.getStartOffset() >= 0; final String description = SpellCheckerBundle.message("typo.in.word.ref"); return new ProblemDescriptorBase(element, element, description, fixes, ProblemHighlightType.GENERIC_ERROR_OR_WARNING, false, textRange, onTheFly, onTheFly); } @SuppressWarnings({"PublicField"}) public boolean processCode = true; public boolean processLiterals = true; public boolean processComments = true; @Override public JComponent createOptionsPanel() { final Box verticalBox = Box.createVerticalBox(); verticalBox.add(new SingleCheckboxOptionsPanel(SpellCheckerBundle.message("process.code"), this, "processCode")); verticalBox.add(new SingleCheckboxOptionsPanel(SpellCheckerBundle.message("process.literals"), this, "processLiterals")); verticalBox.add(new SingleCheckboxOptionsPanel(SpellCheckerBundle.message("process.comments"), this, "processComments")); /*HyperlinkLabel linkToSettings = new HyperlinkLabel(SpellCheckerBundle.message("link.to.settings")); linkToSettings.addHyperlinkListener(new HyperlinkListener() { public void hyperlinkUpdate(final HyperlinkEvent e) { if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { final OptionsEditor optionsEditor = OptionsEditor.KEY.getData(DataManager.getInstance().getDataContext()); // ??project? } } }); verticalBox.add(linkToSettings);*/ final JPanel panel = new JPanel(new BorderLayout()); panel.add(verticalBox, BorderLayout.NORTH); return panel; } private static class MyTokenConsumer extends TokenConsumer implements Consumer<TextRange> { private final Set<String> myAlreadyChecked = new THashSet<>(); private final SpellCheckerManager myManager; private final ProblemsHolder myHolder; private final NamesValidator myNamesValidator; private PsiElement myElement; private String myText; private boolean myUseRename; private int myOffset; public MyTokenConsumer(SpellCheckerManager manager, ProblemsHolder holder, NamesValidator namesValidator) { myManager = manager; myHolder = holder; myNamesValidator = namesValidator; } @Override public void consumeToken(final PsiElement element, final String text, final boolean useRename, final int offset, TextRange rangeToCheck, Splitter splitter) { myElement = element; myText = text; myUseRename = useRename; myOffset = offset; splitter.split(text, rangeToCheck, this); } @Override public void consume(TextRange textRange) { String word = textRange.substring(myText); if (!myHolder.isOnTheFly() && myAlreadyChecked.contains(word)) { return; } boolean keyword = myNamesValidator.isKeyword(word, myElement.getProject()); if (keyword) { return; } boolean hasProblems = myManager.hasProblem(word); if (hasProblems) { int aposIndex = word.indexOf('\''); if (aposIndex != -1) { word = word.substring(0, aposIndex); // IdentifierSplitter.WORD leaves &apos; } hasProblems = myManager.hasProblem(word); } if (hasProblems) { if (myHolder.isOnTheFly()) { addRegularDescriptor(myElement, myOffset, textRange, myHolder, myUseRename, word); } else { myAlreadyChecked.add(word); addBatchDescriptor(myElement, myOffset, textRange, myHolder); } } } } }
/* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is part of dcm4che, an implementation of DICOM(TM) in * Java(TM), available at http://sourceforge.net/projects/dcm4che. * * The Initial Developer of the Original Code is * TIANI Medgraph AG. * Portions created by the Initial Developer are Copyright (C) 2003-2005 * the Initial Developer. All Rights Reserved. * * Contributor(s): * Gunter Zeilinger <gunter.zeilinger@tiani.com> * Franz Willer <franz.willer@gwi-ag.com> * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ package org.dcm4chex.archive.web.maverick.gppps.model; import java.text.SimpleDateFormat; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.dcm4che.data.Dataset; import org.dcm4che.dict.Tags; import org.dcm4chex.archive.web.maverick.BasicFormPagingModel; import org.dcm4chex.archive.web.maverick.gppps.GPPPSConsoleCtrl; import org.dcm4chex.archive.web.maverick.gppps.PPSFilter; /** * @author franz.willer * * The Model for Modality Performed Procedure Steps WEB interface. */ public class GPPPSModel extends BasicFormPagingModel { /** The session attribute name to store the model in http session. */ public static final String GPPPS_MODEL_ATTR_NAME = "gpppsModel"; /** Errorcode: unsupported action */ public static final String ERROR_UNSUPPORTED_ACTION = "UNSUPPORTED_ACTION"; private static final SimpleDateFormat dFormatter = new SimpleDateFormat("yyyy/MM/dd"); private String[] gpppsIDs = null; //Holds GPPPSEntries with sticky Map stickyList; /** Holds list of GPPPSEntries */ private Map gpppsEntries = new HashMap(); private PPSFilter ppsFilter; /** Comparator to sort list of GPPPS datasets. */ private Comparator comparator = new GpppsDSComparator(); /** * Creates the model. * <p> * Creates the filter instance for this model. */ private GPPPSModel(HttpServletRequest request) { super(request); getFilter(); } /** * Get the model for an http request. * <p> * Look in the session for an associated model via <code>GPPPS_MODEL_ATTR_NAME</code><br> * If there is no model stored in session (first request) a new model is created and stored in session. * * @param request A http request. * * @return The model for given request. */ public static final GPPPSModel getModel( HttpServletRequest request ) { GPPPSModel model = (GPPPSModel) request.getSession().getAttribute(GPPPS_MODEL_ATTR_NAME); if (model == null) { model = new GPPPSModel(request); request.getSession().setAttribute(GPPPS_MODEL_ATTR_NAME, model); model.setErrorCode( NO_ERROR ); //reset error code model.filterWorkList( true ); } return model; } public String getModelName() { return "GPPPS"; } /** * Returns the Filter of this model. * * @return PPSFilter instance that hold filter criteria values. */ public PPSFilter getFilter() { if ( ppsFilter == null ) { ppsFilter = new PPSFilter(); try { String d = dFormatter.format(new Date()); ppsFilter.setStartDate( d ); ppsFilter.setEndDate(d+" 23:59"); } catch ( Exception ignore ) { } } return ppsFilter; } /** * @return Returns the stickies. */ public String[] getGpppsIUIDs() { return gpppsIDs; } /** * @param stickies The stickies to set. * @param check */ public void setGpppsIUIDs(String[] stickies, boolean check) { this.gpppsIDs = stickies; stickyList = new HashMap(); if ( gpppsEntries.isEmpty() || gpppsIDs == null || gpppsIDs.length < 1) return; GPPPSEntry stickyEntry = (GPPPSEntry) gpppsEntries.get(gpppsIDs[0]); String patID = stickyEntry.getPatientID(); stickyList.put( gpppsIDs[0], stickyEntry ); for ( int i = 1; i < gpppsIDs.length ; i++ ) { stickyEntry = (GPPPSEntry) gpppsEntries.get(gpppsIDs[i]); if ( check && ! patID.equals( stickyEntry.getPatientID() )) { throw new IllegalArgumentException("All selected GPPPS must have the same patient!"); } stickyList.put( gpppsIDs[i], stickyEntry ); } } /** * Return a list of GPPPSEntries for display. * * @return Returns the gpppsEntries. */ public Collection getGpppsEntries() { return gpppsEntries.values(); } /** * Update the list of GPPPSEntries for the view. * <p> * The query use the search criteria values from the filter and use offset and limit for paging. * <p> * if <code>newSearch is true</code> will reset paging (set <code>offset</code> to 0!) * @param newSearch */ public void filterWorkList(boolean newSearch) { if ( newSearch ) setOffset(0); List l = GPPPSConsoleCtrl.getGPPPSDelegate().findGPPPSEntries( this.ppsFilter ); Collections.sort( l, comparator ); int total = l.size(); int offset = getOffset(); int limit = getLimit(); int end; if ( offset >= total ) { offset = 0; setOffset(0); end = limit < total ? limit : total; } else { end = offset + limit; if ( end > total ) end = total; } Dataset ds; gpppsEntries.clear(); if ( stickyList != null ) { gpppsEntries.putAll(stickyList); } int countNull = 0; GPPPSEntry entry; for ( int i = offset ; i < end ; i++ ){ ds = (Dataset) l.get( i ); if ( ds != null ) { entry = new GPPPSEntry( ds ); gpppsEntries.put( entry.getGpppsIUID(), entry ); } else { countNull++; } } setTotal(total - countNull); // the real total (without null entries!) } /** * Inner class that compares two datasets for sorting Performed Procedure Steps * according Performed Procedure step start date/time. * * @author franz.willer * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class GpppsDSComparator implements Comparator { public GpppsDSComparator() { } /** * Compares the performed procedure step start date and time of two Dataset objects. * <p> * USe PPSStartDate and PPSStartTime to get the date. * <p> * Use the '0' Date (new Date(0l)) if the date is not in the Dataset. * <p> * Compares its two arguments for order. Returns a negative integer, zero, or a positive integer * as the first argument is less than, equal to, or greater than the second. * <p> * Throws an Exception if one of the arguments is null or not a Dataset object. * * @param arg0 First argument * @param arg1 Second argument * * @return <0 if arg0<arg1, 0 if equal and >0 if arg0>arg1 */ public int compare(Object arg0, Object arg1) { Dataset ds1 = (Dataset) arg0; Dataset ds2 = (Dataset) arg1; Date d1 = _getStartDateAsLong( ds1 ); return d1.compareTo( _getStartDateAsLong( ds2 ) ); } /** * @param ds1 The dataset * * @return the date of this PPS Dataset. */ private Date _getStartDateAsLong(Dataset ds) { if ( ds == null ) return new Date( 0l ); Date d = ds.getDateTime( Tags.PPSStartDate, Tags.PPSStartTime ); if ( d == null ) d = new Date(0l); return d; } } /* (non-Javadoc) * @see org.dcm4chex.archive.web.maverick.BasicFormPagingModel#gotoCurrentPage() */ public void gotoCurrentPage() { filterWorkList(false); } }
/* * Copyright 2000-2012 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.plugins.groovy.mvc; import java.awt.BorderLayout; import java.io.OutputStreamWriter; import java.util.LinkedList; import java.util.List; import java.util.Queue; import javax.annotation.Nonnull; import javax.annotation.Nullable; import javax.swing.JComponent; import javax.swing.JPanel; import org.jetbrains.annotations.NonNls; import com.intellij.execution.configurations.GeneralCommandLine; import com.intellij.execution.filters.TextConsoleBuilderFactory; import com.intellij.execution.impl.ConsoleViewImpl; import com.intellij.execution.process.OSProcessHandler; import com.intellij.execution.process.ProcessAdapter; import com.intellij.execution.process.ProcessEvent; import com.intellij.execution.process.ProcessListener; import com.intellij.execution.process.ProcessOutputTypes; import com.intellij.execution.ui.ConsoleViewContentType; import com.intellij.execution.ui.RunnerLayoutUi; import com.intellij.execution.ui.layout.PlaceInGrid; import com.intellij.icons.AllIcons; import com.intellij.openapi.actionSystem.ActionPlaces; import com.intellij.openapi.actionSystem.AnAction; import com.intellij.openapi.actionSystem.AnActionEvent; import com.intellij.openapi.actionSystem.DefaultActionGroup; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ModalityState; import com.intellij.openapi.components.ServiceManager; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.fileEditor.FileDocumentManager; import com.intellij.openapi.module.Module; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.Messages; import consulo.disposer.Disposable; import consulo.disposer.Disposer; import consulo.util.dataholder.Key; import com.intellij.openapi.util.Ref; import com.intellij.openapi.vfs.LocalFileSystem; import com.intellij.openapi.wm.ToolWindow; import com.intellij.openapi.wm.ToolWindowAnchor; import com.intellij.openapi.wm.ToolWindowManager; import com.intellij.ui.content.Content; import com.intellij.ui.content.ContentFactory; import com.intellij.ui.content.ContentManager; import com.intellij.util.containers.ContainerUtil; import icons.JetgroovyIcons; public class MvcConsole implements Disposable { private static final Key<Boolean> UPDATING_BY_CONSOLE_PROCESS = Key.create("UPDATING_BY_CONSOLE_PROCESS"); private static final Logger LOG = Logger.getInstance("#org.jetbrains.plugins.groovy.mvc.MvcConsole"); private final ConsoleViewImpl myConsole; private final Project myProject; private final ToolWindow myToolWindow; private final JPanel myPanel = new JPanel(new BorderLayout()); private final Queue<MyProcessInConsole> myProcessQueue = new LinkedList<MyProcessInConsole>(); @NonNls private static final String CONSOLE_ID = "Groovy MVC Console"; @NonNls public static final String TOOL_WINDOW_ID = "Console"; private final MyKillProcessAction myKillAction = new MyKillProcessAction(); private boolean myExecuting = false; private final Content myContent; public MvcConsole(Project project, TextConsoleBuilderFactory consoleBuilderFactory) { myProject = project; myConsole = (ConsoleViewImpl)consoleBuilderFactory.createBuilder(myProject).getConsole(); Disposer.register(this, myConsole); myToolWindow = ToolWindowManager.getInstance(myProject).registerToolWindow(TOOL_WINDOW_ID, false, ToolWindowAnchor.BOTTOM, this, true); myToolWindow.setIcon(JetgroovyIcons.Groovy.Groovy_13x13); myContent = setUpToolWindow(); } public static MvcConsole getInstance(@Nonnull Project project) { return ServiceManager.getService(project, MvcConsole.class); } public static boolean isUpdatingVfsByConsoleProcess(@Nonnull Module module) { Boolean flag = module.getUserData(UPDATING_BY_CONSOLE_PROCESS); return flag != null && flag; } private Content setUpToolWindow() { //Create runner UI layout final RunnerLayoutUi.Factory factory = RunnerLayoutUi.Factory.getInstance(myProject); final RunnerLayoutUi layoutUi = factory.create("", "", "session", myProject); // Adding actions DefaultActionGroup group = new DefaultActionGroup(); group.add(myKillAction); group.addSeparator(); layoutUi.getOptions().setLeftToolbar(group, ActionPlaces.UNKNOWN); final Content console = layoutUi.createContent(CONSOLE_ID, myConsole.getComponent(), "", null, null); layoutUi.addContent(console, 0, PlaceInGrid.right, false); final JComponent uiComponent = layoutUi.getComponent(); myPanel.add(uiComponent, BorderLayout.CENTER); final ContentManager manager = myToolWindow.getContentManager(); final ContentFactory contentFactory = ContentFactory.SERVICE.getInstance(); final Content content = contentFactory.createContent(uiComponent, null, true); manager.addContent(content); return content; } public void show(@javax.annotation.Nullable final Runnable runnable, boolean focus) { Runnable r = null; if (runnable != null) { r = new Runnable() { public void run() { if (myProject.isDisposed()) return; runnable.run(); } }; } myToolWindow.activate(r, focus); } private static class MyProcessInConsole implements ConsoleProcessDescriptor { final Module module; final GeneralCommandLine commandLine; final @javax.annotation.Nullable Runnable onDone; final boolean closeOnDone; final boolean showConsole; final String[] input; private final List<ProcessListener> myListeners = ContainerUtil.createLockFreeCopyOnWriteList(); private OSProcessHandler myHandler; public MyProcessInConsole(final Module module, final GeneralCommandLine commandLine, final Runnable onDone, final boolean showConsole, final boolean closeOnDone, final String[] input) { this.module = module; this.commandLine = commandLine; this.onDone = onDone; this.closeOnDone = closeOnDone; this.input = input; this.showConsole = showConsole; } public ConsoleProcessDescriptor addProcessListener(@Nonnull ProcessListener listener) { if (myHandler != null) { myHandler.addProcessListener(listener); } else { myListeners.add(listener); } return this; } public ConsoleProcessDescriptor waitWith(ProgressIndicator progressIndicator) { if (myHandler != null) { doWait(progressIndicator); } return this; } private void doWait(ProgressIndicator progressIndicator) { while (!myHandler.waitFor(500)) { if (progressIndicator.isCanceled()) { myHandler.destroyProcess(); break; } } } public void setHandler(OSProcessHandler handler) { myHandler = handler; for (final ProcessListener listener : myListeners) { handler.addProcessListener(listener); } } } public static ConsoleProcessDescriptor executeProcess(final Module module, final GeneralCommandLine commandLine, final @Nullable Runnable onDone, final boolean closeOnDone, final String... input) { return getInstance(module.getProject()).executeProcess(module, commandLine, onDone, true, closeOnDone, input); } public ConsoleProcessDescriptor executeProcess(final Module module, final GeneralCommandLine commandLine, final @Nullable Runnable onDone, boolean showConsole, final boolean closeOnDone, final String... input) { ApplicationManager.getApplication().assertIsDispatchThread(); assert module.getProject() == myProject; final MyProcessInConsole process = new MyProcessInConsole(module, commandLine, onDone, showConsole, closeOnDone, input); if (isExecuting()) { myProcessQueue.add(process); } else { executeProcessImpl(process, true); } return process; } public boolean isExecuting() { return myExecuting; } private void executeProcessImpl(final MyProcessInConsole pic, boolean toFocus) { final Module module = pic.module; final GeneralCommandLine commandLine = pic.commandLine; final String[] input = pic.input; final boolean closeOnDone = pic.closeOnDone; final Runnable onDone = pic.onDone; assert module.getProject() == myProject; myExecuting = true; // Module creation was cancelled if (module.isDisposed()) return; final ModalityState modalityState = ModalityState.current(); final boolean modalContext = modalityState != ModalityState.NON_MODAL; if (!modalContext && pic.showConsole) { show(null, toFocus); } FileDocumentManager.getInstance().saveAllDocuments(); myConsole.print(commandLine.getCommandLineString(), ConsoleViewContentType.SYSTEM_OUTPUT); final OSProcessHandler handler; try { Process process = commandLine.createProcess(); handler = new OSProcessHandler(process, commandLine.toString()); @SuppressWarnings("IOResourceOpenedButNotSafelyClosed") OutputStreamWriter writer = new OutputStreamWriter(process.getOutputStream()); for (String s : input) { writer.write(s); } writer.flush(); final Ref<Boolean> gotError = new Ref<Boolean>(false); handler.addProcessListener(new ProcessAdapter() { public void onTextAvailable(ProcessEvent event, Key key) { if (key == ProcessOutputTypes.STDERR) gotError.set(true); LOG.debug("got text: " + event.getText()); } public void processTerminated(ProcessEvent event) { final int exitCode = event.getExitCode(); if (exitCode == 0 && !gotError.get().booleanValue()) { ApplicationManager.getApplication().invokeLater(new Runnable() { public void run() { if (myProject.isDisposed() || !closeOnDone) return; myToolWindow.hide(null); } }, modalityState); } } }); } catch (final Exception e) { ApplicationManager.getApplication().invokeLater(new Runnable() { public void run() { Messages.showErrorDialog(e.getMessage(), "Cannot Start Process"); try { if (onDone != null && !module.isDisposed()) onDone.run(); } catch (Exception e) { LOG.error(e); } } }, modalityState); return; } pic.setHandler(handler); myKillAction.setHandler(handler); final MvcFramework framework = MvcFramework.getInstance(module); myToolWindow.setIcon(framework == null ? JetgroovyIcons.Groovy.Groovy_13x13 : framework.getToolWindowIcon()); myContent.setDisplayName((framework == null ? "" : framework.getDisplayName() + ":") + "Executing..."); myConsole.scrollToEnd(); myConsole.attachToProcess(handler); ApplicationManager.getApplication().executeOnPooledThread(new Runnable() { public void run() { handler.startNotify(); handler.waitFor(); ApplicationManager.getApplication().invokeLater(new Runnable() { public void run() { if (myProject.isDisposed()) return; module.putUserData(UPDATING_BY_CONSOLE_PROCESS, true); LocalFileSystem.getInstance().refresh(false); module.putUserData(UPDATING_BY_CONSOLE_PROCESS, null); try { if (onDone != null && !module.isDisposed()) onDone.run(); } catch (Exception e) { LOG.error(e); } myConsole.print("\n", ConsoleViewContentType.NORMAL_OUTPUT); myKillAction.setHandler(null); myContent.setDisplayName(""); myExecuting = false; final MyProcessInConsole pic = myProcessQueue.poll(); if (pic != null) { executeProcessImpl(pic, false); } } }, modalityState); } }); } public void dispose() { } private class MyKillProcessAction extends AnAction { private OSProcessHandler myHandler = null; public MyKillProcessAction() { super("Kill process", "Kill process", AllIcons.Debugger.KillProcess); } public void setHandler(@javax.annotation.Nullable OSProcessHandler handler) { myHandler = handler; } @Override public void update(final AnActionEvent e) { super.update(e); e.getPresentation().setEnabled(isEnabled()); } public void actionPerformed(final AnActionEvent e) { if (myHandler != null) { final Process process = myHandler.getProcess(); process.destroy(); myConsole.print("Process terminated", ConsoleViewContentType.ERROR_OUTPUT); } } public boolean isEnabled() { return myHandler != null; } } public ConsoleViewImpl getConsole() { return myConsole; } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v10/common/criteria.proto package com.google.ads.googleads.v10.common; /** * <pre> * An audience criterion. * </pre> * * Protobuf type {@code google.ads.googleads.v10.common.AudienceInfo} */ public final class AudienceInfo extends com.google.protobuf.GeneratedMessageV3 implements // @@protoc_insertion_point(message_implements:google.ads.googleads.v10.common.AudienceInfo) AudienceInfoOrBuilder { private static final long serialVersionUID = 0L; // Use AudienceInfo.newBuilder() to construct. private AudienceInfo(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) { super(builder); } private AudienceInfo() { audience_ = ""; } @java.lang.Override @SuppressWarnings({"unused"}) protected java.lang.Object newInstance( UnusedPrivateParameter unused) { return new AudienceInfo(); } @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private AudienceInfo( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { this(); if (extensionRegistry == null) { throw new java.lang.NullPointerException(); } com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; case 10: { java.lang.String s = input.readStringRequireUtf8(); audience_ = s; break; } default: { if (!parseUnknownField( input, unknownFields, extensionRegistry, tag)) { done = true; } break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v10.common.CriteriaProto.internal_static_google_ads_googleads_v10_common_AudienceInfo_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v10.common.CriteriaProto.internal_static_google_ads_googleads_v10_common_AudienceInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v10.common.AudienceInfo.class, com.google.ads.googleads.v10.common.AudienceInfo.Builder.class); } public static final int AUDIENCE_FIELD_NUMBER = 1; private volatile java.lang.Object audience_; /** * <pre> * The Audience resource name. * </pre> * * <code>string audience = 1;</code> * @return The audience. */ @java.lang.Override public java.lang.String getAudience() { java.lang.Object ref = audience_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); audience_ = s; return s; } } /** * <pre> * The Audience resource name. * </pre> * * <code>string audience = 1;</code> * @return The bytes for audience. */ @java.lang.Override public com.google.protobuf.ByteString getAudienceBytes() { java.lang.Object ref = audience_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); audience_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private byte memoizedIsInitialized = -1; @java.lang.Override public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } @java.lang.Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(audience_)) { com.google.protobuf.GeneratedMessageV3.writeString(output, 1, audience_); } unknownFields.writeTo(output); } @java.lang.Override public int getSerializedSize() { int size = memoizedSize; if (size != -1) return size; size = 0; if (!com.google.protobuf.GeneratedMessageV3.isStringEmpty(audience_)) { size += com.google.protobuf.GeneratedMessageV3.computeStringSize(1, audience_); } size += unknownFields.getSerializedSize(); memoizedSize = size; return size; } @java.lang.Override public boolean equals(final java.lang.Object obj) { if (obj == this) { return true; } if (!(obj instanceof com.google.ads.googleads.v10.common.AudienceInfo)) { return super.equals(obj); } com.google.ads.googleads.v10.common.AudienceInfo other = (com.google.ads.googleads.v10.common.AudienceInfo) obj; if (!getAudience() .equals(other.getAudience())) return false; if (!unknownFields.equals(other.unknownFields)) return false; return true; } @java.lang.Override public int hashCode() { if (memoizedHashCode != 0) { return memoizedHashCode; } int hash = 41; hash = (19 * hash) + getDescriptor().hashCode(); hash = (37 * hash) + AUDIENCE_FIELD_NUMBER; hash = (53 * hash) + getAudience().hashCode(); hash = (29 * hash) + unknownFields.hashCode(); memoizedHashCode = hash; return hash; } public static com.google.ads.googleads.v10.common.AudienceInfo parseFrom( java.nio.ByteBuffer data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v10.common.AudienceInfo parseFrom( java.nio.ByteBuffer data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v10.common.AudienceInfo parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v10.common.AudienceInfo parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v10.common.AudienceInfo parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static com.google.ads.googleads.v10.common.AudienceInfo parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static com.google.ads.googleads.v10.common.AudienceInfo parseFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.ads.googleads.v10.common.AudienceInfo parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } public static com.google.ads.googleads.v10.common.AudienceInfo parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input); } public static com.google.ads.googleads.v10.common.AudienceInfo parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseDelimitedWithIOException(PARSER, input, extensionRegistry); } public static com.google.ads.googleads.v10.common.AudienceInfo parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input); } public static com.google.ads.googleads.v10.common.AudienceInfo parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return com.google.protobuf.GeneratedMessageV3 .parseWithIOException(PARSER, input, extensionRegistry); } @java.lang.Override public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder() { return DEFAULT_INSTANCE.toBuilder(); } public static Builder newBuilder(com.google.ads.googleads.v10.common.AudienceInfo prototype) { return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype); } @java.lang.Override public Builder toBuilder() { return this == DEFAULT_INSTANCE ? new Builder() : new Builder().mergeFrom(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * <pre> * An audience criterion. * </pre> * * Protobuf type {@code google.ads.googleads.v10.common.AudienceInfo} */ public static final class Builder extends com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:google.ads.googleads.v10.common.AudienceInfo) com.google.ads.googleads.v10.common.AudienceInfoOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return com.google.ads.googleads.v10.common.CriteriaProto.internal_static_google_ads_googleads_v10_common_AudienceInfo_descriptor; } @java.lang.Override protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internalGetFieldAccessorTable() { return com.google.ads.googleads.v10.common.CriteriaProto.internal_static_google_ads_googleads_v10_common_AudienceInfo_fieldAccessorTable .ensureFieldAccessorsInitialized( com.google.ads.googleads.v10.common.AudienceInfo.class, com.google.ads.googleads.v10.common.AudienceInfo.Builder.class); } // Construct using com.google.ads.googleads.v10.common.AudienceInfo.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessageV3.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessageV3 .alwaysUseFieldBuilders) { } } @java.lang.Override public Builder clear() { super.clear(); audience_ = ""; return this; } @java.lang.Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return com.google.ads.googleads.v10.common.CriteriaProto.internal_static_google_ads_googleads_v10_common_AudienceInfo_descriptor; } @java.lang.Override public com.google.ads.googleads.v10.common.AudienceInfo getDefaultInstanceForType() { return com.google.ads.googleads.v10.common.AudienceInfo.getDefaultInstance(); } @java.lang.Override public com.google.ads.googleads.v10.common.AudienceInfo build() { com.google.ads.googleads.v10.common.AudienceInfo result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } @java.lang.Override public com.google.ads.googleads.v10.common.AudienceInfo buildPartial() { com.google.ads.googleads.v10.common.AudienceInfo result = new com.google.ads.googleads.v10.common.AudienceInfo(this); result.audience_ = audience_; onBuilt(); return result; } @java.lang.Override public Builder clone() { return super.clone(); } @java.lang.Override public Builder setField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.setField(field, value); } @java.lang.Override public Builder clearField( com.google.protobuf.Descriptors.FieldDescriptor field) { return super.clearField(field); } @java.lang.Override public Builder clearOneof( com.google.protobuf.Descriptors.OneofDescriptor oneof) { return super.clearOneof(oneof); } @java.lang.Override public Builder setRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, int index, java.lang.Object value) { return super.setRepeatedField(field, index, value); } @java.lang.Override public Builder addRepeatedField( com.google.protobuf.Descriptors.FieldDescriptor field, java.lang.Object value) { return super.addRepeatedField(field, value); } @java.lang.Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof com.google.ads.googleads.v10.common.AudienceInfo) { return mergeFrom((com.google.ads.googleads.v10.common.AudienceInfo)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(com.google.ads.googleads.v10.common.AudienceInfo other) { if (other == com.google.ads.googleads.v10.common.AudienceInfo.getDefaultInstance()) return this; if (!other.getAudience().isEmpty()) { audience_ = other.audience_; onChanged(); } this.mergeUnknownFields(other.unknownFields); onChanged(); return this; } @java.lang.Override public final boolean isInitialized() { return true; } @java.lang.Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { com.google.ads.googleads.v10.common.AudienceInfo parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (com.google.ads.googleads.v10.common.AudienceInfo) e.getUnfinishedMessage(); throw e.unwrapIOException(); } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private java.lang.Object audience_ = ""; /** * <pre> * The Audience resource name. * </pre> * * <code>string audience = 1;</code> * @return The audience. */ public java.lang.String getAudience() { java.lang.Object ref = audience_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); audience_ = s; return s; } else { return (java.lang.String) ref; } } /** * <pre> * The Audience resource name. * </pre> * * <code>string audience = 1;</code> * @return The bytes for audience. */ public com.google.protobuf.ByteString getAudienceBytes() { java.lang.Object ref = audience_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); audience_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <pre> * The Audience resource name. * </pre> * * <code>string audience = 1;</code> * @param value The audience to set. * @return This builder for chaining. */ public Builder setAudience( java.lang.String value) { if (value == null) { throw new NullPointerException(); } audience_ = value; onChanged(); return this; } /** * <pre> * The Audience resource name. * </pre> * * <code>string audience = 1;</code> * @return This builder for chaining. */ public Builder clearAudience() { audience_ = getDefaultInstance().getAudience(); onChanged(); return this; } /** * <pre> * The Audience resource name. * </pre> * * <code>string audience = 1;</code> * @param value The bytes for audience to set. * @return This builder for chaining. */ public Builder setAudienceBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } checkByteStringIsUtf8(value); audience_ = value; onChanged(); return this; } @java.lang.Override public final Builder setUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.setUnknownFields(unknownFields); } @java.lang.Override public final Builder mergeUnknownFields( final com.google.protobuf.UnknownFieldSet unknownFields) { return super.mergeUnknownFields(unknownFields); } // @@protoc_insertion_point(builder_scope:google.ads.googleads.v10.common.AudienceInfo) } // @@protoc_insertion_point(class_scope:google.ads.googleads.v10.common.AudienceInfo) private static final com.google.ads.googleads.v10.common.AudienceInfo DEFAULT_INSTANCE; static { DEFAULT_INSTANCE = new com.google.ads.googleads.v10.common.AudienceInfo(); } public static com.google.ads.googleads.v10.common.AudienceInfo getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<AudienceInfo> PARSER = new com.google.protobuf.AbstractParser<AudienceInfo>() { @java.lang.Override public AudienceInfo parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new AudienceInfo(input, extensionRegistry); } }; public static com.google.protobuf.Parser<AudienceInfo> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<AudienceInfo> getParserForType() { return PARSER; } @java.lang.Override public com.google.ads.googleads.v10.common.AudienceInfo getDefaultInstanceForType() { return DEFAULT_INSTANCE; } }
package com.hmsonline.storm.cassandra.bolt; import static com.hmsonline.storm.cassandra.bolt.AstyanaxUtil.createColumnFamily; import static com.hmsonline.storm.cassandra.bolt.AstyanaxUtil.newClusterContext; import static com.hmsonline.storm.cassandra.bolt.AstyanaxUtil.newContext; import static org.junit.Assert.assertFalse; import static org.junit.Assert.fail; import java.io.IOException; import java.util.ArrayList; import java.util.List; import org.apache.cassandra.config.ConfigurationException; import org.apache.thrift.transport.TTransportException; import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.netflix.astyanax.AstyanaxContext; import com.netflix.astyanax.Cluster; import com.netflix.astyanax.Keyspace; import com.netflix.astyanax.MutationBatch; import com.netflix.astyanax.model.AbstractComposite.ComponentEquality; import com.netflix.astyanax.model.Column; import com.netflix.astyanax.model.ColumnFamily; import com.netflix.astyanax.model.ColumnList; import com.netflix.astyanax.model.Composite; import com.netflix.astyanax.query.ColumnFamilyQuery; import com.netflix.astyanax.serializers.CompositeSerializer; import com.netflix.astyanax.serializers.StringSerializer; public class AstyanaxComposites { private static final Logger LOG = LoggerFactory.getLogger(AstyanaxComposites.class); private static String KEYSPACE = AstyanaxComposites.class.getSimpleName(); @BeforeClass public static void setupCassandra() throws TTransportException, IOException, InterruptedException, ConfigurationException, Exception { SingletonEmbeddedCassandra.getInstance(); try { AstyanaxContext<Cluster> clusterContext = newClusterContext("localhost:9160"); createColumnFamily(clusterContext, KEYSPACE, "composite", "CompositeType(UTF8Type, UTF8Type)", "UTF8Type", "UTF8Type"); createColumnFamily(clusterContext, KEYSPACE, "composite2", "CompositeType(UTF8Type, UTF8Type, UTF8Type)", "UTF8Type", "UTF8Type"); } catch (Exception e) { LOG.warn("Couldn't setup cassandra.", e); throw e; } } // @Test @SuppressWarnings("unchecked") public void simpleReadWriteCompositeTest() { boolean fail = false; try { AstyanaxContext<Keyspace> context = newContext("localhost:9160", KEYSPACE); Keyspace ks = context.getEntity(); ColumnFamily<String, Composite> cf = new ColumnFamily<String, Composite>("composite", StringSerializer.get(), CompositeSerializer.get()); MutationBatch mutation = ks.prepareMutationBatch(); mutation.withRow(cf, "mykey").putColumn(makeStringComposite("foo", "bar"), "Hello Composite Column Range Query"); mutation.withRow(cf, "mykey").putColumn(makeStringComposite("foo", "baz"), "My dog has fleas"); mutation.withRow(cf, "mykey").putColumn(makeStringComposite("fzz", "baz"), "It is snowing"); mutation.execute(); // simple column fetch ColumnFamilyQuery<String, Composite> query = ks.prepareQuery(cf); Column<Composite> result = query.getKey("mykey").getColumn(makeStringComposite("foo", "bar")).execute() .getResult(); LOG.debug(result.getStringValue()); // build up a composite range query Composite start = makeStringEqualityComposite(new String[] { "foo" }, new ComponentEquality[] { ComponentEquality.EQUAL }); // Composite end = new Composite(); // end.addComponent("fyy", StringSerializer.get(), // ComponentEquality.GREATER_THAN_EQUAL); Composite end = makeStringEqualityComposite(new String[] { "fyy" }, new ComponentEquality[] { ComponentEquality.GREATER_THAN_EQUAL }); ColumnList<Composite> results = query.getKey("mykey") .withColumnRange(start.serialize(), end.serialize(), false, 100).execute().getResult(); LOG.debug("Query matched {} results.", results.size()); for (Composite columnKey : results.getColumnNames()) { LOG.debug("Component(0): {}", columnKey.getComponent(0).getValue(StringSerializer.get())); LOG.debug("Component(1): {}", columnKey.getComponent(1).getValue(StringSerializer.get())); LOG.debug("Value: {}", results.getValue(columnKey, StringSerializer.get(), "")); if (results.getValue(columnKey, StringSerializer.get(), "").equals("It is snowing")) { fail = true; } } } catch (Exception e) { e.printStackTrace(); fail(); } assertFalse("unexpected result", fail); } @Test public void twoDimensionalCompositeRangeTest() { boolean fail = false; try { final String rowkey = "mykey2"; AstyanaxContext<Keyspace> context = newContext("localhost:9160", KEYSPACE); Keyspace ks = context.getEntity(); ColumnFamily<String, Composite> cf = new ColumnFamily<String, Composite>("composite2", StringSerializer.get(), CompositeSerializer.get()); MutationBatch mutation = ks.prepareMutationBatch(); List<String> combinations = combinationsWithRepitition("abcdef", 3); for(String str : combinations){ LOG.debug("Will insert '{}'", str); mutation.withRow(cf, rowkey).putColumn(makeStringComposite(str.substring(0,1), str.substring(1,2), str.substring(2,3)), str); } mutation.execute(); // build up a composite range query Composite start = makeStringEqualityComposite(new String[] { "a", "a", "a"}, new ComponentEquality[] { ComponentEquality.EQUAL,ComponentEquality.EQUAL, ComponentEquality.EQUAL }); Composite end = makeStringEqualityComposite(new String[] { "a", "a", "b"}, new ComponentEquality[] { ComponentEquality.EQUAL,ComponentEquality.EQUAL, ComponentEquality.EQUAL }); ColumnFamilyQuery<String, Composite> query = ks.prepareQuery(cf); ColumnList<Composite> results = query.getKey(rowkey) .withColumnRange(start.serialize(), end.serialize(), false, 100).execute().getResult(); LOG.debug("Query matched {} results.", results.size()); for (Composite columnKey : results.getColumnNames()) { // LOG.debug("Component(0): {}", columnKey.getComponent(0).getValue(StringSerializer.get())); // LOG.debug("Component(1): {}", columnKey.getComponent(1).getValue(StringSerializer.get())); // LOG.debug("Component(2): {}", columnKey.getComponent(2).getValue(StringSerializer.get())); LOG.debug("Value: {}", results.getValue(columnKey, StringSerializer.get(), "")); } } catch (Exception e) { e.printStackTrace(); fail(); } assertFalse("unexpected result", fail); } public static Composite makeStringComposite(String... values) { Composite comp = new Composite(); for (String value : values) { comp.addComponent(value, StringSerializer.get()); } return comp; } public static Composite makeStringEqualityComposite(String[] values, ComponentEquality[] equalities) { if (values.length != equalities.length) { throw new IllegalArgumentException("Number of values and equalities must match."); } Composite comp = new Composite(); for (int i = 0; i < values.length; i++) { comp.addComponent(values[i], StringSerializer.get(), equalities[i]); } return comp; } public static void main(String[] args) throws Exception { List<String> perms = permutaions("aaa"); System.out.println("Found " + perms.size() + " permutatons."); for(String perm : perms){ System.out.println(perm); } } public static List<String> combinationsWithRepitition(String input){ return combinationsWithRepitition(input, input.length()); } public static List<String> combinationsWithRepitition(String input, int depth){ return combinationWithRepitition(new ArrayList<String>(), input, depth, new StringBuffer()); } static List<String> combinationWithRepitition(List<String> result, String input, int depth, StringBuffer output) { if (depth == 0) { result.add(output.toString()); } else { for (int i = 0; i < input.length(); i++) { output.append(input.charAt(i)); combinationWithRepitition(result, input, depth - 1, output); output.deleteCharAt(output.length() - 1); } } return result; } public static List<String> permutaions(String input) { return permutaions("", input, new ArrayList<String>()); } public static List<String> permutaions(String prefix, String input, List<String> result) { int n = input.length(); if (n == 0) { result.add(prefix); } else { for (int i = 0; i < n; i++){ permutaions(prefix + input.charAt(i), input.substring(0, i) + input.substring(i + 1, n), result); } } return result; } }
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.idea.maven.dom; import java.io.IOException; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.jdom.Element; import javax.annotation.Nullable; import org.jetbrains.idea.maven.compiler.MavenEscapeWindowsCharacterUtils; import org.jetbrains.idea.maven.dom.model.MavenDomProfile; import org.jetbrains.idea.maven.dom.model.MavenDomProjectModel; import org.jetbrains.idea.maven.dom.model.MavenDomProperties; import org.jetbrains.idea.maven.dom.references.MavenFilteredPropertyPsiReferenceProvider; import org.jetbrains.idea.maven.model.MavenId; import org.jetbrains.idea.maven.project.MavenProject; import org.jetbrains.idea.maven.project.MavenProjectsManager; import org.jetbrains.idea.maven.server.MavenServerUtil; import org.jetbrains.idea.maven.utils.MavenJDOMUtil; import org.jetbrains.idea.maven.utils.MavenUtil; import com.intellij.openapi.module.Module; import com.intellij.openapi.module.ModuleUtilCore; import com.intellij.openapi.projectRoots.Sdk; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.psi.xml.XmlElement; import com.intellij.psi.xml.XmlTag; import consulo.java.module.extension.JavaModuleExtensionImpl; public class MavenPropertyResolver { public static final Pattern PATTERN = Pattern.compile("\\$\\{(.+?)\\}|@(.+?)@"); public static void doFilterText(Module module, String text, Properties additionalProperties, String propertyEscapeString, Appendable out) throws IOException { MavenProjectsManager manager = MavenProjectsManager.getInstance(module.getProject()); MavenProject mavenProject = manager.findProject(module); if(mavenProject == null) { out.append(text); return; } Element pluginConfiguration = mavenProject.getPluginConfiguration("org.apache.maven.plugins", "maven-resources-plugin"); String escapeWindowsPathsStr = MavenJDOMUtil.findChildValueByPath(pluginConfiguration, "escapeWindowsPaths"); boolean escapeWindowsPath = escapeWindowsPathsStr == null || Boolean.parseBoolean(escapeWindowsPathsStr); doFilterText(MavenFilteredPropertyPsiReferenceProvider.getDelimitersPattern(mavenProject), manager, mavenProject, text, additionalProperties, propertyEscapeString, escapeWindowsPath, null, out); } private static void doFilterText(Pattern pattern, MavenProjectsManager mavenProjectsManager, MavenProject mavenProject, String text, Properties additionalProperties, @javax.annotation.Nullable String escapeString, boolean escapeWindowsPath, @javax.annotation.Nullable Map<String, String> resolvedPropertiesParam, Appendable out) throws IOException { Map<String, String> resolvedProperties = resolvedPropertiesParam; Matcher matcher = pattern.matcher(text); int groupCount = matcher.groupCount(); int last = 0; while(matcher.find()) { if(escapeString != null) { int escapeStringStartIndex = matcher.start() - escapeString.length(); if(escapeStringStartIndex >= last) { if(text.startsWith(escapeString, escapeStringStartIndex)) { out.append(text, last, escapeStringStartIndex); out.append(matcher.group()); last = matcher.end(); continue; } } } out.append(text, last, matcher.start()); last = matcher.end(); String propertyName = null; for(int i = 0; i < groupCount; i++) { propertyName = matcher.group(i + 1); if(propertyName != null) { break; } } assert propertyName != null; if(resolvedProperties == null) { resolvedProperties = new HashMap<String, String>(); } String propertyValue = resolvedProperties.get(propertyName); if(propertyValue == null) { if(resolvedProperties.containsKey(propertyName)) { // if cyclic property dependencies out.append(matcher.group()); continue; } String resolved = doResolveProperty(propertyName, mavenProjectsManager, mavenProject, additionalProperties); if(resolved == null) { out.append(matcher.group()); continue; } resolvedProperties.put(propertyName, null); StringBuilder sb = new StringBuilder(); doFilterText(pattern, mavenProjectsManager, mavenProject, resolved, additionalProperties, null, escapeWindowsPath, resolvedProperties, sb); propertyValue = sb.toString(); resolvedProperties.put(propertyName, propertyValue); } if(escapeWindowsPath) { MavenEscapeWindowsCharacterUtils.escapeWindowsPath(out, propertyValue); } else { out.append(propertyValue); } } out.append(text, last, text.length()); } public static String resolve(String text, MavenDomProjectModel projectDom) { XmlElement element = projectDom.getXmlElement(); if(element == null) { return text; } VirtualFile file = MavenDomUtil.getVirtualFile(element); if(file == null) { return text; } MavenProjectsManager manager = MavenProjectsManager.getInstance(projectDom.getManager().getProject()); MavenProject mavenProject = manager.findProject(file); if(mavenProject == null) { return text; } StringBuilder res = new StringBuilder(); try { doFilterText(PATTERN, manager, mavenProject, text, collectPropertiesFromDOM(mavenProject, projectDom), null, false, null, res); } catch(IOException e) { throw new RuntimeException(e); // never thrown } return res.toString(); } private static Properties collectPropertiesFromDOM(MavenProject project, MavenDomProjectModel projectDom) { Properties result = new Properties(); collectPropertiesFromDOM(projectDom.getProperties(), result); Collection<String> activeProfiles = project.getActivatedProfilesIds().getEnabledProfiles(); for(MavenDomProfile each : projectDom.getProfiles().getProfiles()) { XmlTag idTag = each.getId().getXmlTag(); if(idTag == null || !activeProfiles.contains(idTag.getValue().getTrimmedText())) { continue; } collectPropertiesFromDOM(each.getProperties(), result); } return result; } private static void collectPropertiesFromDOM(MavenDomProperties props, Properties result) { XmlTag propsTag = props.getXmlTag(); if(propsTag != null) { for(XmlTag each : propsTag.getSubTags()) { result.setProperty(each.getName(), each.getValue().getTrimmedText()); } } } @Nullable private static String doResolveProperty(String propName, MavenProjectsManager projectsManager, MavenProject mavenProject, Properties additionalProperties) { boolean hasPrefix = false; String unprefixed = propName; if(propName.startsWith("pom.")) { unprefixed = propName.substring("pom.".length()); hasPrefix = true; } else if(propName.startsWith("project.")) { unprefixed = propName.substring("project.".length()); hasPrefix = true; } MavenProject selectedProject = mavenProject; while(unprefixed.startsWith("parent.")) { MavenId parentId = selectedProject.getParentId(); if(parentId == null) { return null; } unprefixed = unprefixed.substring("parent.".length()); if(unprefixed.equals("groupId")) { return parentId.getGroupId(); } if(unprefixed.equals("artifactId")) { return parentId.getArtifactId(); } selectedProject = projectsManager.findProject(parentId); if(selectedProject == null) { return null; } } if(unprefixed.equals("basedir") || (hasPrefix && mavenProject == selectedProject && unprefixed.equals("baseUri"))) { return selectedProject.getDirectory(); } if("java.home".equals(propName)) { Module module = projectsManager.findModule(mavenProject); if(module != null) { Sdk sdk = ModuleUtilCore.getSdk(module, JavaModuleExtensionImpl.class); if(sdk != null) { VirtualFile homeDirectory = sdk.getHomeDirectory(); if(homeDirectory != null) { VirtualFile jreDir = homeDirectory.findChild("jre"); if(jreDir != null) { return jreDir.getPath(); } } } } } String result; result = MavenUtil.getPropertiesFromMavenOpts().get(propName); if(result != null) { return result; } result = MavenServerUtil.collectSystemProperties().getProperty(propName); if(result != null) { return result; } result = selectedProject.getModelMap().get(unprefixed); if(result != null) { return result; } result = additionalProperties.getProperty(propName); if(result != null) { return result; } result = mavenProject.getProperties().getProperty(propName); if(result != null) { return result; } if("settings.localRepository".equals(propName)) { return mavenProject.getLocalRepository().getAbsolutePath(); } return null; } }
package mil.nga.giat.geowave.vector.transaction; import java.io.IOException; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.UUID; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.ZooDefs; import org.apache.zookeeper.ZooKeeper; /** * Use ZooKeeper to maintain the population of Transaction IDs. * ZooKeeper's ephemeral nodes are ideal for lock management. * and TXID is a node. It is locked if it has a child ephemeral node * called 'lock'. If the client dies, the node is deleted, releasing the * Transaction ID. The protocol that guarantees one client locks a TX node follows * the recipe for locking, where the ephemeral node with the smallest sequence number wins. * */ public class ZooKeeperTransactionsAllocater implements Watcher, TransactionsAllocater { private ZooKeeper zk; private final String clientID; private final String clientTXPath; private final String hostPort; private final TransactionNotification notificationRequester; private Set<String> lockPaths = Collections.synchronizedSet(new HashSet<String>()); public ZooKeeperTransactionsAllocater( final String clientID, final ZooKeeper zk, TransactionNotification notificationRequester ) { super(); this.zk = zk; this.hostPort = null; this.clientID = clientID; this.clientTXPath = "/" + clientID + "/tx"; this.notificationRequester = notificationRequester; } public ZooKeeperTransactionsAllocater( String hostPort, String clientID, TransactionNotification notificationRequester ) throws IOException { this.hostPort = hostPort; zk = new ZooKeeper( hostPort, 5000, this); this.clientID = clientID; this.clientTXPath = "/" + clientID + "/tx"; this.notificationRequester = notificationRequester; try { init(); } catch (InterruptedException | KeeperException e) { throw new IOException( e); } } public void close() throws InterruptedException { this.zk.close(); } public void releaseTransaction( String txID ) throws IOException { try { for (String child : zk.getChildren( clientTXPath + "/" + txID, false)) { String childPath = clientTXPath + "/" + txID + "/" + child; // only remove paths that have associated with a return of // a transaction ID to the client/caller. // Other paths may exist temporarily during the // capture process. if (this.lockPaths.contains(childPath)) { try { zk.delete( childPath, -1); } catch (KeeperException.NoNodeException ex) { // someone else beat us to it } lockPaths.remove(childPath); } } } catch (KeeperException.NoNodeException | KeeperException.ConnectionLossException | KeeperException.SessionExpiredException ex) { // in these cases, the ephemeral nodes are removed by the server // if the parent txID, does not exist (odd case, then zookeeper failed to sync prior to its // untimely departure } catch (Exception ex) { throw new IOException( ex); } } public String getTransaction() throws IOException { try { int count = 0; boolean ok = false; while (!ok) { try { // find all tx IDs available! for (String childTXID : zk.getChildren( clientTXPath, false)) { List<String> children = zk.getChildren( clientTXPath + "/" + childTXID, false); // if there are already locks, continue to the next if (children.size() > 0) continue; // create a lock String lockPath = create( clientTXPath + "/" + childTXID + "/lock", new byte[] { 0x01 }, CreateMode.EPHEMERAL_SEQUENTIAL); // now, double check that this client got the 'first' // one children = zk.getChildren( clientTXPath + "/" + childTXID, false); ok = true; for (String lockChild : children) { final String lockObj = lockPath.substring(lockPath.lastIndexOf('/') + 1); // smallest sequence wins ok &= (lockChild.compareTo(lockObj) >= 0); } // found a transaction if (ok) { this.lockPaths.add(lockPath); return childTXID; } try { // delete the attempt and try another child zk.delete( lockPath, -1); } catch (Exception ex) { // may get deleted by the release, so an error can // be ignored } } ok = false; // not found, so create a new one AND try to win it String transId = UUID.randomUUID().toString(); this.notificationRequester.transactionCreated( clientID, transId); // If 'create' fails, then the transaction id is 'lost'. // // NOTE: Notifying the requester after the 'create' step // would be worse // than prior to 'create'. An error from ZK does not // indicate if the node creation // worked or not. // Failing to report a new transaction id to the requester // is more damaging // than a lost transaction ID (which means it never gets // used again). zk.create( clientTXPath + "/" + transId, new byte[0], ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT); } catch (KeeperException.ConnectionLossException | KeeperException.SessionExpiredException ex) { if (hostPort != null) reconnect(); count++; if (count >= 5) throw ex; } } } catch (Exception ex) { throw new IOException( ex); } return null; } @Override public void process( WatchedEvent event ) { // TODO Auto-generated method stub } private String create( String path, byte[] value, CreateMode mode ) throws KeeperException, InterruptedException { try { return zk.create( path, value, ZooDefs.Ids.OPEN_ACL_UNSAFE, mode); } catch (KeeperException.NodeExistsException ex) { // do nothing } return path; } private void init() throws KeeperException, InterruptedException { if (zk.exists( "/" + clientID, false) == null) { try { create( "/" + clientID, new byte[0], CreateMode.PERSISTENT); } catch (KeeperException.NodeExistsException ex) { } } if (zk.exists( clientTXPath, false) == null) { create( clientTXPath, new byte[0], CreateMode.PERSISTENT); } } private void reconnect() throws IOException, KeeperException, InterruptedException { zk = new ZooKeeper( hostPort, 5000, this); init(); } }
/* The MIT License Copyright (c) 2009-2021 Paul R. Holser, Jr. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ package com.pholser.util.properties.it; import com.pholser.util.properties.it.boundtypes.ArrayProperties; import com.pholser.util.properties.it.boundtypes.Ternary; import org.junit.jupiter.api.Test; import java.math.BigDecimal; import java.math.BigInteger; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.UUID; import static com.pholser.util.properties.it.boundtypes.Ternary.MAYBE; import static com.pholser.util.properties.it.boundtypes.Ternary.NO; import static com.pholser.util.properties.it.boundtypes.Ternary.YES; import static org.junit.jupiter.api.Assertions.assertArrayEquals; class BindingArrayPropertiesToTypedInterfacesTest extends TypedStringBindingTestSupport<ArrayProperties> { BindingArrayPropertiesToTypedInterfacesTest() { super("/test.properties", "test", "properties"); } @Test void separatedStringPropertyToStringArrayMethod() { assertArrayEquals( new String[] {"aaa", "bbb", "ccc"}, bound.stringArrayProperty()); } @Test void separatedStringPropertyWithCustomSeparatorToStringArrayMethod() { assertArrayEquals( new String[] {"dd", "eeee", "fffff"}, bound.stringArrayPropertyWithCustomSeparator()); } @Test void defaultForStringArrayProperty() { assertArrayEquals( new String[] {"g", "hh", "iii"}, bound.stringArrayPropertyWithDefault()); } @Test void defaultForStringArrayPropertyWithCustomSeparator() { assertArrayEquals( new String[] {"jjj", "kk", "L"}, bound.stringArrayPropertyWithDefaultAndSeparator()); } @Test void separatedBooleanPropertyToPrimitiveBooleanArrayMethod() { assertArrayEquals( new boolean[] {true, false, false, true}, bound.primitiveBooleanArrayProperty()); } @Test void booleanPropertyWithCustomSeparatorToPrimitiveBooleanArrayMethod() { assertArrayEquals( new boolean[] {false, true}, bound.primitiveBooleanArrayPropertyWithCustomSeparator()); } @Test void defaultForPrimitiveBooleanArrayProperty() { assertArrayEquals( new boolean[] {false, false, true, false, true}, bound.primitiveBooleanArrayPropertyWithDefault()); } @Test void defaultForPrimitiveBooleanArrayPropertyWithSeparator() { assertArrayEquals( new boolean[] {true, true, true, false}, bound.primitiveBooleanArrayPropertyWithDefaultAndSeparator()); } @Test void separatedBooleanPropertyToBooleanWrapperArrayMethod() { assertArrayEquals( new Boolean[] {true, false, false, true}, bound.wrappedBooleanArrayProperty()); } @Test void booleanPropertyWithCustomSeparatorToBooleanWrapperArrayMethod() { assertArrayEquals( new Boolean[] {false, true}, bound.wrappedBooleanArrayPropertyWithCustomSeparator()); } @Test void defaultForBooleanWrapperArrayProperty() { assertArrayEquals( new Boolean[] {false, false, true, false, true}, bound.wrappedBooleanArrayPropertyWithDefault()); } @Test void defaultForBooleanWrapperArrayPropertyWithSeparator() { assertArrayEquals( new Boolean[] {true, true, true, false}, bound.wrappedBooleanArrayPropertyWithDefaultAndSeparator()); } @Test void separatedBytePropertyToPrimitiveByteArrayMethod() { assertArrayEquals( new byte[] {0x1, 0x2, 0x3}, bound.primitiveByteArrayProperty()); } @Test void bytePropertyWithCustomSeparatorToPrimitiveByteArrayMethod() { assertArrayEquals( new byte[] {0x0, 0x4}, bound.primitiveByteArrayPropertyWithCustomSeparator()); } @Test void defaultForPrimitiveByteArrayProperty() { assertArrayEquals( new byte[] {0x18, 0x19, 0x1A, 0x1B, 0x1C}, bound.primitiveByteArrayPropertyWithDefault()); } @Test void defaultForPrimitiveByteArrayPropertyWithSeparator() { assertArrayEquals( new byte[] {0x1D, 0x1E, 0x1F, 0x20}, bound.primitiveByteArrayPropertyWithDefaultAndSeparator()); } @Test void separatedBytePropertyToByteWrapperArrayMethod() { assertArrayEquals( new Byte[] {0x6, 0x7, 0x8, 0x9}, bound.wrappedByteArrayProperty()); } @Test void bytePropertyWithCustomSeparatorToByteWrapperArrayMethod() { assertArrayEquals( new Byte[] {0x2D, 0x39}, bound.wrappedByteArrayPropertyWithCustomSeparator()); } @Test void defaultForByteWrapperArrayProperty() { assertArrayEquals( new Byte[] {0x21, 0x22, 0x23}, bound.wrappedByteArrayPropertyWithDefault()); } @Test void defaultForByteWrapperArrayPropertyWithSeparator() { assertArrayEquals( new Byte[] {0x24, 0x25, 0x26, 0x27}, bound.wrappedByteArrayPropertyWithDefaultAndSeparator()); } @Test void separatedCharacterPropertyToPrimitiveCharacterArrayMethod() { assertArrayEquals( new char[] {'c', 'd', 'e', 'f'}, bound.primitiveCharacterArrayProperty()); } @Test void characterPropertyWithCustomSeparatorToPrimitiveCharacterArrayMethod() { assertArrayEquals( new char[] {'g', 'h'}, bound.primitiveCharacterArrayPropertyWithCustomSeparator()); } @Test void defaultForPrimitiveCharacterArrayProperty() { assertArrayEquals( new char[] {'h', 'i', 'j', 'k', 'l'}, bound.primitiveCharacterArrayPropertyWithDefault()); } @Test void defaultForPrimitiveCharacterArrayPropertyWithSeparator() { assertArrayEquals( new char[] {'m', 'n', 'o', 'p'}, bound.primitiveCharacterArrayPropertyWithDefaultAndSeparator()); } @Test void separatedCharacterPropertyToCharacterWrapperArrayMethod() { assertArrayEquals( new Character[] {'q', 'r', 's', 't'}, bound.wrappedCharacterArrayProperty()); } @Test void characterPropertyWithCustomSeparatorToCharacterWrapperArrayMethod() { assertArrayEquals( new Character[] {'u', 'v'}, bound.wrappedCharacterArrayPropertyWithCustomSeparator()); } @Test void defaultForCharacterWrapperArrayProperty() { assertArrayEquals( new Character[] {'w', 'x', 'y'}, bound.wrappedCharacterArrayPropertyWithDefault()); } @Test void defaultForCharacterWrapperArrayPropertyWithSeparator() { assertArrayEquals( new Character[] {'z', '0', '1', '2'}, bound.wrappedCharacterArrayPropertyWithDefaultAndSeparator()); } @Test void separatedDoublePropertyToPrimitiveDoubleArrayMethod() { assertArrayEquals( new double[] {3.0, 4.0, 5.0, 6.0}, bound.primitiveDoubleArrayProperty(), 0); } @Test void doublePropertyWithCustomSeparatorToPrimitiveDoubleArrayMethod() { assertArrayEquals( new double[] {7.0, 8.0}, bound.primitiveDoubleArrayPropertyWithCustomSeparator(), 0); } @Test void defaultForPrimitiveDoubleArrayProperty() { assertArrayEquals( new double[] {-1.0, -2.0, -3.0, -4.0, -5.0}, bound.primitiveDoubleArrayPropertyWithDefault(), 0); } @Test void defaultForPrimitiveDoubleArrayPropertyWithSeparator() { assertArrayEquals( new double[] {-6.0, -7.0, -8.0, -9.0}, bound.primitiveDoubleArrayPropertyWithDefaultAndSeparator(), 0); } @Test void separatedDoublePropertyToDoubleWrapperArrayMethod() { assertArrayEquals( new Double[] {-1.0, -2.0, -3.0, -4.0}, bound.wrappedDoubleArrayProperty()); } @Test void doublePropertyWithCustomSeparatorToDoubleWrapperArrayMethod() { assertArrayEquals( new Double[] {-5.0, -6.0}, bound.wrappedDoubleArrayPropertyWithCustomSeparator()); } @Test void defaultForDoubleWrapperArrayProperty() { assertArrayEquals( new Double[] {-10.0, -11.0, -12.0}, bound.wrappedDoubleArrayPropertyWithDefault()); } @Test void defaultForDoubleWrapperArrayPropertyWithSeparator() { assertArrayEquals( new Double[] {-13.0, -14.0, -15.0, -16.0}, bound.wrappedDoubleArrayPropertyWithDefaultAndSeparator()); } @Test void separatedFloatPropertyToPrimitiveFloatArrayMethod() { assertArrayEquals( new float[] {3.3F, 3.4F, 3.5F, 3.6F}, bound.primitiveFloatArrayProperty(), 0); } @Test void floatPropertyWithCustomSeparatorToPrimitiveFloatArrayMethod() { assertArrayEquals( new float[] {3.7F, 3.8F}, bound.primitiveFloatArrayPropertyWithCustomSeparator(), 0); } @Test void defaultForPrimitiveFloatArrayProperty() { assertArrayEquals( new float[] {1.1F, 1.2F, 1.3F, 1.4F, 1.5F}, bound.primitiveFloatArrayPropertyWithDefault(), 0); } @Test void defaultForPrimitiveFloatArrayPropertyWithSeparator() { assertArrayEquals( new float[] {1.6F, 1.7F, 1.8F, 1.9F}, bound.primitiveFloatArrayPropertyWithDefaultAndSeparator(), 0); } @Test void separatedFloatPropertyToFloatWrapperArrayMethod() { assertArrayEquals( new Float[] {4.8F, 4.9F, 5.0F, 5.1F}, bound.wrappedFloatArrayProperty()); } @Test void floatPropertyWithCustomSeparatorToFloatWrapperArrayMethod() { assertArrayEquals( new Float[] {5.2F, 5.3F}, bound.wrappedFloatArrayPropertyWithCustomSeparator()); } @Test void defaultForFloatWrapperArrayProperty() { assertArrayEquals( new Float[] {2.0F, 2.1F, 2.2F}, bound.wrappedFloatArrayPropertyWithDefault()); } @Test void defaultForFloatWrapperArrayPropertyWithSeparator() { assertArrayEquals( new Float[] {2.3F, 2.4F, 2.5F, 2.6F}, bound.wrappedFloatArrayPropertyWithDefaultAndSeparator()); } @Test void separatedIntegerPropertyToPrimitiveIntegerArrayMethod() { assertArrayEquals( new int[] {-3, -4, -5, -6}, bound.primitiveIntegerArrayProperty()); } @Test void integerPropertyWithCustomSeparatorToPrimitiveIntegerArrayMethod() { assertArrayEquals( new int[] {-7, -8}, bound.primitiveIntegerArrayPropertyWithCustomSeparator()); } @Test void defaultForPrimitiveIntegerArrayProperty() { assertArrayEquals( new int[] {-1, -2, -3, -4, -5}, bound.primitiveIntegerArrayPropertyWithDefault()); } @Test void defaultForPrimitiveIntegerArrayPropertyWithSeparator() { assertArrayEquals( new int[] {-6, -7, -8, -9}, bound.primitiveIntegerArrayPropertyWithDefaultAndSeparator()); } @Test void separatedIntegerPropertyToIntegerWrapperArrayMethod() { assertArrayEquals( new Integer[] {-18, -19, -20, -21}, bound.wrappedIntegerArrayProperty()); } @Test void integerPropertyWithCustomSeparatorToIntegerWrapperArrayMethod() { assertArrayEquals( new Integer[] {-22, -23}, bound.wrappedIntegerArrayPropertyWithCustomSeparator()); } @Test void defaultForIntegerWrapperArrayProperty() { assertArrayEquals( new Integer[] {-10, -11, -12}, bound.wrappedIntegerArrayPropertyWithDefault()); } @Test void defaultForIntegerWrapperArrayPropertyWithSeparator() { assertArrayEquals( new Integer[] {-13, -14, -15, -16}, bound.wrappedIntegerArrayPropertyWithDefaultAndSeparator()); } @Test void separatedLongPropertyToPrimitiveLongArrayMethod() { assertArrayEquals( new long[] {3, 4, 5, 6}, bound.primitiveLongArrayProperty()); } @Test void longPropertyWithCustomSeparatorToPrimitiveLongArrayMethod() { assertArrayEquals( new long[] {7, 8}, bound.primitiveLongArrayPropertyWithCustomSeparator()); } @Test void defaultForPrimitiveLongArrayProperty() { assertArrayEquals( new long[] {44, 45, 46, 47, 48}, bound.primitiveLongArrayPropertyWithDefault()); } @Test void defaultForPrimitiveLongArrayPropertyWithSeparator() { assertArrayEquals( new long[] {49, 50, 51, 52}, bound.primitiveLongArrayPropertyWithDefaultAndSeparator()); } @Test void separatedLongPropertyToLongWrapperArrayMethod() { assertArrayEquals( new Long[] {18L, 19L, 20L, 21L}, bound.wrappedLongArrayProperty()); } @Test void longPropertyWithCustomSeparatorToLongWrapperArrayMethod() { assertArrayEquals( new Long[] {22L, 23L}, bound.wrappedLongArrayPropertyWithCustomSeparator()); } @Test void defaultForLongWrapperArrayProperty() { assertArrayEquals( new Long[] {53L, 54L, 55L}, bound.wrappedLongArrayPropertyWithDefault()); } @Test void defaultForLongWrapperArrayPropertyWithSeparator() { assertArrayEquals( new Long[] {56L, 57L, 58L, 59L}, bound.wrappedLongArrayPropertyWithDefaultAndSeparator()); } @Test void separatedShortPropertyToPrimitiveShortArrayMethod() { assertArrayEquals( new short[] {51, 52, 53, 54}, bound.primitiveShortArrayProperty()); } @Test void shortPropertyWithCustomSeparatorToPrimitiveShortArrayMethod() { assertArrayEquals( new short[] {55, 56}, bound.primitiveShortArrayPropertyWithCustomSeparator()); } @Test void defaultForPrimitiveShortArrayProperty() { assertArrayEquals( new short[] {-20, -21, -22, -23, -24}, bound.primitiveShortArrayPropertyWithDefault()); } @Test void defaultForPrimitiveShortArrayPropertyWithSeparator() { assertArrayEquals( new short[] {-25, -26, -27, -28}, bound.primitiveShortArrayPropertyWithDefaultAndSeparator()); } @Test void separatedShortPropertyToShortWrapperArrayMethod() { assertArrayEquals( new Short[] {66, 67, 68, 69}, bound.wrappedShortArrayProperty()); } @Test void shortPropertyWithCustomSeparatorToShortWrapperArrayMethod() { assertArrayEquals( new Short[] {70, 71}, bound.wrappedShortArrayPropertyWithCustomSeparator()); } @Test void defaultForShortWrapperArrayProperty() { assertArrayEquals( new Short[] {-29, -30, -31}, bound.wrappedShortArrayPropertyWithDefault()); } @Test void defaultForShortWrapperArrayPropertyWithSeparator() { assertArrayEquals( new Short[] {-32, -33, -34, -35}, bound.wrappedShortArrayPropertyWithDefaultAndSeparator()); } @Test void separatedBigIntegerPropertyToBigIntegerArrayMethod() { assertArrayEquals( new BigInteger[] {BigInteger.valueOf(124), BigInteger.valueOf(125)}, bound.bigIntegerArrayProperty()); } @Test void bigIntegerPropertyWithCustomSeparatorToBigIntegerArrayMethod() { assertArrayEquals( new BigInteger[] {BigInteger.valueOf(126), BigInteger.valueOf(127)}, bound.bigIntegerArrayPropertyWithCustomSeparator()); } @Test void defaultForBigIntegerArrayProperty() { assertArrayEquals( new BigInteger[] { BigInteger.valueOf(128), BigInteger.valueOf(129), BigInteger.valueOf(130) }, bound.bigIntegerArrayPropertyWithDefault()); } @Test void defaultForBigIntegerArrayPropertyWithSeparator() { assertArrayEquals( new BigInteger[] { BigInteger.valueOf(131), BigInteger.valueOf(132), BigInteger.valueOf(133) }, bound.bigIntegerArrayPropertyWithDefaultAndSeparator()); } @Test void separatedBigDecimalPropertyToBigDecimalArrayMethod() { assertArrayEquals( new BigDecimal[] { new BigDecimal("56.78"), new BigDecimal("90.12") }, bound.bigDecimalArrayProperty()); } @Test void bigDecimalPropertyWithCustomSeparatorToBigDecimalArrayMethod() { assertArrayEquals( new BigDecimal[] { new BigDecimal("34.567"), new BigDecimal("89.012") }, bound.bigDecimalArrayPropertyWithCustomSeparator()); } @Test void defaultForBigDecimalArrayProperty() { assertArrayEquals( new BigDecimal[] { new BigDecimal("345.67"), new BigDecimal("890.12") }, bound.bigDecimalArrayPropertyWithDefault()); } @Test void defaultForBigDecimalArrayPropertyWithSeparator() { assertArrayEquals( new BigDecimal[] { new BigDecimal("3456.78"), new BigDecimal("9012.34") }, bound.bigDecimalArrayPropertyWithDefaultAndSeparator()); } @Test void separatedEnumPropertyToEnumArrayMethod() { assertArrayEquals( new Ternary[] {YES, YES, NO, MAYBE, YES}, bound.enumArrayProperty()); } @Test void enumPropertyWithCustomSeparatorToEnumArrayMethod() { assertArrayEquals( new Ternary[] {NO, NO, MAYBE, MAYBE}, bound.enumArrayPropertyWithCustomSeparator()); } @Test void defaultForEnumArrayProperty() { assertArrayEquals( new Ternary[] {YES, NO, NO, MAYBE, YES}, bound.enumArrayPropertyWithDefault()); } @Test void defaultForEnumArrayPropertyWithSeparator() { assertArrayEquals( new Ternary[] {NO, MAYBE, YES, MAYBE}, bound.enumArrayPropertyWithDefaultAndSeparator()); } @Test void separatedDatePropertyToDateArrayMethodWithParsePatterns() throws Exception { assertArrayEquals( new Date[] {MMM("Jan"), MMM("Feb"), MMM("Mar")}, bound.dateArrayPropertyWithParsePatterns()); } @Test void datePropertyWithCustomSeparatorToDateArrayMethod() throws Exception { assertArrayEquals( new Date[] {MMM("Apr"), MMM("May"), MMM("Jun")}, bound.dateArrayPropertyWithCustomSeparatorWithParsePatterns()); } @Test void defaultForDateArrayProperty() throws Exception { assertArrayEquals( new Date[] {MMM("Sep"), MMM("Oct")}, bound.dateArrayPropertyWithDefaultWithParsePatterns()); } @Test void defaultForDateArrayPropertyWithSeparator() throws Exception { assertArrayEquals( new Date[] {MMM("Nov"), MMM("Dec")}, bound.dateArrayPropertyWithDefaultAndSeparatorWithParsePatterns()); } @Test void separatedUuidPropertyToUuidArrayMethod() { assertArrayEquals( new UUID[] { UUID.fromString("f7b469d0-0074-405c-ad55-3a0c76f98144"), UUID.fromString("f5d1128e-eb65-4d9d-8fdf-3df474e39e82") }, bound.uuidArrayProperty()); } @Test void separatedUuidPropertyWithCustomSeparatorToUuidArrayMethod() { assertArrayEquals( new UUID[] { UUID.fromString("f85b6a7e-5b40-437b-8e5f-a3b453ec13b9"), UUID.fromString("738708df-fadd-4a3c-b263-34166764add5"), UUID.fromString("cb56f88d-f545-4574-b3f3-1f708afc85ac") }, bound.uuidArrayPropertyWithCustomSeparator()); } @Test void defaultForUuidArrayProperty() { assertArrayEquals( new UUID[] { UUID.fromString("4abfa655-eabe-4699-9ea9-d7651244c4f9"), UUID.fromString("d432a18b-cf25-4221-a206-2d44728f1165") }, bound.uuidArrayPropertyWithDefault()); } @Test void defaultForUuidArrayPropertyWithCustomSeparator() { assertArrayEquals( new UUID[] { UUID.fromString("00d72078-51c6-4686-93d3-d4ee3cc342ce"), UUID.fromString("3fab0521-d395-44dd-8464-e88b2c4ff3dc"), UUID.fromString("83107da3-4f70-4873-b8df-373b44c3f6db") }, bound.uuidArrayPropertyWithDefaultAndSeparator()); } @Test void givingZeroLengthArrayForMissingPrimitiveArrayProperty() { assertArrayEquals(new int[0], bound.missingPrimitiveArrayProperty()); } @Test void givingZeroLengthArrayForMissingObjectArrayProperty() { assertArrayEquals(new String[0], bound.missingObjectArrayProperty()); } @Override protected Class<ArrayProperties> boundType() { return ArrayProperties.class; } private static Date MMM(String raw) throws ParseException { return new SimpleDateFormat("MMM").parse(raw); } }
/** * Copyright (c) 2013-2020 Contributors to the Eclipse Foundation * * <p> See the NOTICE file distributed with this work for additional information regarding copyright * ownership. All rights reserved. This program and the accompanying materials are made available * under the terms of the Apache License, Version 2.0 which accompanies this distribution and is * available at http://www.apache.org/licenses/LICENSE-2.0.txt */ package org.locationtech.geowave.core.store.statistics.field; import java.nio.ByteBuffer; import java.util.Date; import org.locationtech.geowave.core.index.Mergeable; import org.locationtech.geowave.core.index.VarintUtils; import org.locationtech.geowave.core.store.adapter.statistics.histogram.FixedBinNumericHistogram; import org.locationtech.geowave.core.store.api.DataTypeAdapter; import org.locationtech.geowave.core.store.api.FieldStatistic; import org.locationtech.geowave.core.store.api.StatisticValue; import org.locationtech.geowave.core.store.entities.GeoWaveRow; import org.locationtech.geowave.core.store.statistics.StatisticsIngestCallback; import com.beust.jcommander.Parameter; /** * Fixed number of bins for a histogram. Unless configured, the range will expand dynamically, * redistributing the data as necessary into the wider bins. * * <p> The advantage of constraining the range of the statistic is to ignore values outside the * range, such as erroneous values. Erroneous values force extremes in the histogram. For example, * if the expected range of values falls between 0 and 1 and a value of 10000 occurs, then a single * bin contains the entire population between 0 and 1, a single bin represents the single value of * 10000. If there are extremes in the data, then use {@link NumericHistogramStatistic} instead. * * <p> The default number of bins is 32. */ public class FixedBinNumericHistogramStatistic extends FieldStatistic<FixedBinNumericHistogramStatistic.FixedBinNumericHistogramValue> { public static final FieldStatisticType<FixedBinNumericHistogramValue> STATS_TYPE = new FieldStatisticType<>("FIXED_BIN_NUMERIC_HISTOGRAM"); @Parameter(names = "--numBins", description = "The number of bins for the histogram.") private int numBins = 1024; @Parameter( names = "--minValue", description = "The minimum value for the histogram. If both min and max are not specified, the range will be unconstrained.") private Double minValue = null; @Parameter( names = "--maxValue", description = "The maximum value for the histogram. If both min and max are not specified, the range will be unconstrained.") private Double maxValue = null; public FixedBinNumericHistogramStatistic() { super(STATS_TYPE); } public FixedBinNumericHistogramStatistic(final String typeName, final String fieldName) { this(typeName, fieldName, 1024); } public FixedBinNumericHistogramStatistic( final String typeName, final String fieldName, final int bins) { super(STATS_TYPE, typeName, fieldName); this.numBins = bins; } public FixedBinNumericHistogramStatistic( final String typeName, final String fieldName, final int bins, final double minValue, final double maxValue) { super(STATS_TYPE, typeName, fieldName); this.numBins = bins; this.minValue = minValue; this.maxValue = maxValue; } public void setNumBins(final int numBins) { this.numBins = numBins; } public int getNumBins() { return numBins; } public void setMinValue(final Double minValue) { this.minValue = minValue; } public Double getMinValue() { return minValue; } public void setMaxValue(final Double maxValue) { this.maxValue = maxValue; } public Double getMaxValue() { return maxValue; } @Override public boolean isCompatibleWith(Class<?> fieldClass) { return Number.class.isAssignableFrom(fieldClass) || Date.class.isAssignableFrom(fieldClass); } @Override public String getDescription() { return "A numeric histogram with a fixed number of bins."; } @Override public FixedBinNumericHistogramValue createEmpty() { return new FixedBinNumericHistogramValue(this); } @Override protected int byteLength() { int length = super.byteLength() + VarintUtils.unsignedIntByteLength(numBins) + 2; length += minValue == null ? 0 : Double.BYTES; length += maxValue == null ? 0 : Double.BYTES; return length; } @Override protected void writeBytes(ByteBuffer buffer) { super.writeBytes(buffer); VarintUtils.writeUnsignedInt(numBins, buffer); if (minValue == null) { buffer.put((byte) 0); } else { buffer.put((byte) 1); buffer.putDouble(minValue); } if (maxValue == null) { buffer.put((byte) 0); } else { buffer.put((byte) 1); buffer.putDouble(maxValue); } } @Override protected void readBytes(ByteBuffer buffer) { super.readBytes(buffer); numBins = VarintUtils.readUnsignedInt(buffer); if (buffer.get() == 1) { minValue = buffer.getDouble(); } else { minValue = null; } if (buffer.get() == 1) { maxValue = buffer.getDouble(); } else { maxValue = null; } } public static class FixedBinNumericHistogramValue extends StatisticValue<FixedBinNumericHistogram> implements StatisticsIngestCallback { private FixedBinNumericHistogram histogram; public FixedBinNumericHistogramValue() { super(null); histogram = null; } public FixedBinNumericHistogramValue(FixedBinNumericHistogramStatistic statistic) { super(statistic); if (statistic.minValue == null || statistic.maxValue == null) { histogram = new FixedBinNumericHistogram(statistic.numBins); } else { histogram = new FixedBinNumericHistogram(statistic.numBins, statistic.minValue, statistic.maxValue); } } @Override public void merge(Mergeable merge) { if (merge != null && merge instanceof FixedBinNumericHistogramValue) { histogram.merge(((FixedBinNumericHistogramValue) merge).getValue()); } } @Override public <T> void entryIngested(DataTypeAdapter<T> adapter, T entry, GeoWaveRow... rows) { final Object o = adapter.getFieldValue( entry, ((FixedBinNumericHistogramStatistic) getStatistic()).getFieldName()); if (o == null) { return; } double value; if (o instanceof Date) { value = ((Date) o).getTime(); } else if (o instanceof Number) { value = ((Number) o).doubleValue(); } else { return; } histogram.add(1, value); } @Override public FixedBinNumericHistogram getValue() { return histogram; } @Override public byte[] toBinary() { final ByteBuffer buffer = ByteBuffer.allocate(histogram.bufferSize()); histogram.toBinary(buffer); return buffer.array(); } @Override public void fromBinary(byte[] bytes) { histogram = new FixedBinNumericHistogram(); histogram.fromBinary(ByteBuffer.wrap(bytes)); } public double[] quantile(final int bins) { return histogram.quantile(bins); } public double cdf(final double val) { return histogram.cdf(val); } public double quantile(final double percentage) { return histogram.quantile(percentage); } public double percentPopulationOverRange(final double start, final double stop) { return cdf(stop) - cdf(start); } public long totalSampleSize() { return histogram.getTotalCount(); } public long[] count(final int binSize) { return histogram.count(binSize); } } }
/* * Copyright (c) 2009-2020 jMonkeyEngine * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are * met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * * Neither the name of 'jMonkeyEngine' nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.jme3.system; import com.jme3.asset.AssetManager; import com.jme3.asset.DesktopAssetManager; import com.jme3.audio.AudioRenderer; import com.jme3.input.SoftTextDialogInput; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.nio.ByteBuffer; import java.util.EnumMap; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; /** * * @author Kirill Vainer, normenhansen */ public abstract class JmeSystemDelegate { protected final Logger logger = Logger.getLogger(JmeSystem.class.getName()); protected boolean initialized = false; protected boolean lowPermissions = false; protected Map<JmeSystem.StorageFolderType, File> storageFolders = new EnumMap<JmeSystem.StorageFolderType, File>(JmeSystem.StorageFolderType.class); protected SoftTextDialogInput softTextDialogInput = null; public synchronized File getStorageFolder(JmeSystem.StorageFolderType type) { File storageFolder = null; switch (type) { // Internal and External are currently the same folder case Internal: case External: if (lowPermissions) { throw new UnsupportedOperationException("File system access restricted"); } storageFolder = storageFolders.get(type); if (storageFolder == null) { // Initialize storage folder storageFolder = new File(System.getProperty("user.home"), ".jme3"); if (!storageFolder.exists()) { storageFolder.mkdir(); } storageFolders.put(type, storageFolder); } break; default: break; } if (storageFolder != null) { logger.log(Level.FINE, "Storage Folder Path: {0}", storageFolder.getAbsolutePath()); } else { logger.log(Level.FINE, "Storage Folder not found!"); } return storageFolder; } public String getFullName() { return JmeVersion.FULL_NAME; } public InputStream getResourceAsStream(String name) { return this.getClass().getResourceAsStream(name); } public URL getResource(String name) { return this.getClass().getResource(name); } public boolean trackDirectMemory() { return false; } public void setLowPermissions(boolean lowPerm) { lowPermissions = lowPerm; } public boolean isLowPermissions() { return lowPermissions; } public void setSoftTextDialogInput(SoftTextDialogInput input) { softTextDialogInput = input; } public SoftTextDialogInput getSoftTextDialogInput() { return softTextDialogInput; } public final AssetManager newAssetManager(URL configFile) { return new DesktopAssetManager(configFile); } public final AssetManager newAssetManager() { return new DesktopAssetManager(null); } public abstract void writeImageFile(OutputStream outStream, String format, ByteBuffer imageData, int width, int height) throws IOException; public abstract void showErrorDialog(String message); public abstract boolean showSettingsDialog(AppSettings sourceSettings, boolean loadFromRegistry); private boolean is64Bit(String arch) { if (arch.equals("x86")) { return false; } else if (arch.equals("amd64")) { return true; } else if (arch.equals("x86_64")) { return true; } else if (arch.equals("ppc") || arch.equals("PowerPC")) { return false; } else if (arch.equals("ppc64")) { return true; } else if (arch.equals("i386") || arch.equals("i686")) { return false; } else if (arch.equals("universal")) { return false; } else if (arch.equals("aarch32")) { return false; } else if (arch.equals("aarch64")) { return true; } else if (arch.equals("armv7") || arch.equals("armv7l")) { return false; } else if (arch.equals("arm")) { return false; } else { throw new UnsupportedOperationException("Unsupported architecture: " + arch); } } public Platform getPlatform() { String os = System.getProperty("os.name").toLowerCase(); String arch = System.getProperty("os.arch").toLowerCase(); boolean is64 = is64Bit(arch); if (os.contains("windows")) { return is64 ? Platform.Windows64 : Platform.Windows32; } else if (os.contains("linux") || os.contains("freebsd") || os.contains("sunos") || os.contains("unix")) { if (arch.startsWith("arm") || arch.startsWith("aarch")) { return is64 ? Platform.Linux_ARM64 : Platform.Linux_ARM32; } else { return is64 ? Platform.Linux64 : Platform.Linux32; } } else if (os.contains("mac os x") || os.contains("darwin")) { if (arch.startsWith("ppc")) { return is64 ? Platform.MacOSX_PPC64 : Platform.MacOSX_PPC32; } else { return is64 ? Platform.MacOSX64 : Platform.MacOSX32; } } else { throw new UnsupportedOperationException("The specified platform: " + os + " is not supported."); } } public String getBuildInfo() { StringBuilder sb = new StringBuilder(); sb.append("Running on ").append(getFullName()).append("\n"); sb.append(" * Branch: ").append(JmeVersion.BRANCH_NAME).append("\n"); sb.append(" * Git Hash: ").append(JmeVersion.GIT_SHORT_HASH).append("\n"); sb.append(" * Build Date: ").append(JmeVersion.BUILD_DATE); return sb.toString(); } public abstract URL getPlatformAssetConfigURL(); public abstract JmeContext newContext(AppSettings settings, JmeContext.Type contextType); public abstract AudioRenderer newAudioRenderer(AppSettings settings); public abstract void initialize(AppSettings settings); public abstract void showSoftKeyboard(boolean show); }
package tests.fixedtile; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import org.junit.Test; import code.model.AbstractTile; import code.model.FixedTile; import code.model.Player; public class FixedTileStringParamaterConstructorTests { @Test public void TStringArgument() { AbstractTile aT = new FixedTile("T"); //test behavior of AbstractTile to make sure //it has been successfully instantiated by the //constructor boolean e1 = true; Player p1 = new Player("Blue"); aT.addPlayer(p1); boolean a2 = aT.hasPlayer(); ArrayList<Player> aL = aT.getPlayers(); Player p2 = aL.get(0); boolean a3 = aT.checkLegalDirectionsInput(1, 0, 1, 1); //a4 should be false boolean a4 = aT.setDirections(1, 0, 1, 1); aT.rotate(90); int a5 = aT.getTop(); int e2 = 1; int a6 = aT.getBottom(); int e3 = 1; int a7 = aT.getLeft(); int e4 = 1; int a8 = aT.getRight(); int e5 = 0; aT.removePlayer(p1); boolean a9 = aT.hasPlayer(); boolean e6 = false; assertTrue("",e1==a2 && e1==a3 && e1!=a4 && p1==p2 && a5==e2 && a6==e3 && a7==e4 && a8==e5 && a9==e6); } @Test public void LStringArgument() { AbstractTile aT = new FixedTile("L"); //test behavior of AbstractTile to make sure //it has been successfully instantiated by the //constructor boolean e1 = true; Player p1 = new Player("Blue"); aT.addPlayer(p1); boolean a2 = aT.hasPlayer(); ArrayList<Player> aL = aT.getPlayers(); Player p2 = aL.get(0); boolean a3 = aT.checkLegalDirectionsInput(1, 0, 1, 1); //a4 should be false boolean a4 = aT.setDirections(1, 0, 1, 1); aT.rotate(90); int a5 = aT.getTop(); int e2 = 1; int a6 = aT.getBottom(); int e3 = 0; int a7 = aT.getLeft(); int e4 = 1; int a8 = aT.getRight(); int e5 = 0; aT.removePlayer(p1); boolean a9 = aT.hasPlayer(); boolean e6 = false; assertTrue("",e1==a2 && e1==a3 && e1!=a4 && p1==p2 && a5==e2 && a6==e3 && a7==e4 && a8==e5 && a9==e6); } @Test public void IStringArgument() { AbstractTile aT = new FixedTile("I"); //test behavior of AbstractTile to make sure //it has been successfully instantiated by the //constructor boolean e1 = true; Player p1 = new Player("Blue"); aT.addPlayer(p1); boolean a2 = aT.hasPlayer(); ArrayList<Player> aL = aT.getPlayers(); Player p2 = aL.get(0); boolean a3 = aT.checkLegalDirectionsInput(1, 0, 1, 1); //a4 should be false boolean a4 = aT.setDirections(1, 0, 1, 1); aT.rotate(90); int a5 = aT.getTop(); int e2 = 1; int a6 = aT.getBottom(); int e3 = 1; int a7 = aT.getLeft(); int e4 = 0; int a8 = aT.getRight(); int e5 = 0; aT.removePlayer(p1); boolean a9 = aT.hasPlayer(); boolean e6 = false; assertTrue("",e1==a2 && e1==a3 && e1!=a4 && p1==p2 && a5==e2 && a6==e3 && a7==e4 && a8==e5 && a9==e6); } @Test public void invalidStringArgument() { AbstractTile aT = new FixedTile("G"); //test behavior of AbstractTile to make sure //it has been successfully instantiated by the //constructor boolean e1 = true; Player p1 = new Player("Blue"); aT.addPlayer(p1); boolean a2 = aT.hasPlayer(); ArrayList<Player> aL = aT.getPlayers(); Player p2 = aL.get(0); boolean a3 = aT.checkLegalDirectionsInput(1, 0, 1, 1); //a4 should be false boolean a4 = aT.setDirections(1, 0, 1, 1); aT.rotate(90); int a5 = aT.getTop(); int e2 = 1; int a6 = aT.getBottom(); int e3 = 1; int a7 = aT.getLeft(); int e4 = 1; int a8 = aT.getRight(); int e5 = 0; aT.removePlayer(p1); boolean a9 = aT.hasPlayer(); boolean e6 = false; assertTrue("",e1==a2 && e1==a3 && e1==a4 && p1==p2 && a5==e2 && a6==e3 && a7==e4 && a8==e5 && a9==e6); } @Test public void emptyStringArgument() { AbstractTile aT = new FixedTile(""); //test behavior of AbstractTile to make sure //it has been successfully instantiated by the //constructor boolean e1 = true; Player p1 = new Player("Blue"); aT.addPlayer(p1); boolean a2 = aT.hasPlayer(); ArrayList<Player> aL = aT.getPlayers(); Player p2 = aL.get(0); boolean a3 = aT.checkLegalDirectionsInput(1, 0, 1, 1); //a4 should be false boolean a4 = aT.setDirections(1, 0, 1, 1); aT.rotate(90); int a5 = aT.getTop(); int e2 = 1; int a6 = aT.getBottom(); int e3 = 1; int a7 = aT.getLeft(); int e4 = 1; int a8 = aT.getRight(); int e5 = 0; aT.removePlayer(p1); boolean a9 = aT.hasPlayer(); boolean e6 = false; assertTrue("",e1==a2 && e1==a3 && e1==a4 && p1==p2 && a5==e2 && a6==e3 && a7==e4 && a8==e5 && a9==e6); } @Test public void nullStringArgument() { AbstractTile aT = new FixedTile(null); //test behavior of AbstractTile to make sure //it has been successfully instantiated by the //constructor boolean e1 = true; Player p1 = new Player("Blue"); aT.addPlayer(p1); boolean a2 = aT.hasPlayer(); ArrayList<Player> aL = aT.getPlayers(); Player p2 = aL.get(0); boolean a3 = aT.checkLegalDirectionsInput(1, 0, 1, 1); //a4 should be false boolean a4 = aT.setDirections(1, 0, 1, 1); aT.rotate(90); int a5 = aT.getTop(); int e2 = 1; int a6 = aT.getBottom(); int e3 = 1; int a7 = aT.getLeft(); int e4 = 1; int a8 = aT.getRight(); int e5 = 0; aT.removePlayer(p1); boolean a9 = aT.hasPlayer(); boolean e6 = false; assertTrue("",e1==a2 && e1==a3 && e1==a4 && p1==p2 && a5==e2 && a6==e3 && a7==e4 && a8==e5 && a9==e6); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.wicket.markup.html.form; import java.util.Collection; import org.apache.wicket.Component; import org.apache.wicket.IGenericComponent; import org.apache.wicket.WicketRuntimeException; import org.apache.wicket.markup.ComponentTag; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.model.IModel; import org.apache.wicket.request.mapper.parameter.PageParameters; import org.apache.wicket.util.string.Strings; /** * Component representing a single checkbox choice in a * org.apache.wicket.markup.html.form.CheckGroup. * * Must be attached to an &lt;input type=&quot;checkbox&quot; ... &gt; markup. * <p> * STATELESS NOTES: By default this component cannot be used inside a stateless form. If it is * desirable to use this inside a stateless form then * <ul> * <li> * override #getValue() and return some stateless value to uniquely identify this radio (eg relative * component path from group to this radio)</li> * <li> * override {@link #getStatelessHint()} and return <code>true</code></li> * </ul> * </p> * * @see org.apache.wicket.markup.html.form.CheckGroup * * @author Igor Vaynberg * * @param <T> * The model object type */ public class Check<T> extends LabeledWebMarkupContainer implements IGenericComponent<T> { private static final long serialVersionUID = 1L; private static final String ATTR_DISABLED = "disabled"; /** * page-scoped uuid of this check. this property must not be accessed directly, instead * {@link #getValue()} must be used */ private int uuid = -1; private final CheckGroup<T> group; /** * @see WebMarkupContainer#WebMarkupContainer(String) */ public Check(String id) { this(id, null, null); } /** * @param id * @param model * @see WebMarkupContainer#WebMarkupContainer(String, IModel) */ public Check(String id, IModel<T> model) { this(id, model, null); } /** * @param id * @param group * parent {@link CheckGroup} of this check * @see WebMarkupContainer#WebMarkupContainer(String) */ public Check(String id, CheckGroup<T> group) { this(id, null, group); } /** * @param id * @param model * @param group * parent {@link CheckGroup} of this check * @see WebMarkupContainer#WebMarkupContainer(String, IModel) */ public Check(String id, IModel<T> model, CheckGroup<T> group) { super(id, model); this.group = group; setOutputMarkupId(true); } /** * Form submission value used for this radio component. This string will appear as the value of * the <code>value</code> html attribute for the <code>input</code> tag. * * @return form submission value */ public String getValue() { if (uuid < 0) { uuid = getPage().getAutoIndex(); } return "check" + uuid; } @SuppressWarnings("unchecked") protected CheckGroup<T> getGroup() { CheckGroup<T> group = this.group; if (group == null) { group = findParent(CheckGroup.class); if (group == null) { throw new WicketRuntimeException("Check component [" + getPath() + "] cannot find its parent CheckGroup"); } } return group; } /** * @see Component#onComponentTag(ComponentTag) * @param tag * the abstraction representing html tag of this component */ @Override protected void onComponentTag(final ComponentTag tag) { // Default handling for component tag super.onComponentTag(tag); // must be attached to <input type="checkbox" .../> tag checkComponentTag(tag, "input"); checkComponentTagAttribute(tag, "type", "checkbox"); CheckGroup<?> group = getGroup(); final String uuid = getValue(); // assign name and value tag.put("name", group.getInputName()); tag.put("value", uuid); // check if the model collection of the group contains the model object. // if it does check the check box. Collection<?> collection = (Collection<?>)group.getDefaultModelObject(); // check for npe in group's model object if (collection == null) { throw new WicketRuntimeException("CheckGroup [" + group.getPath() + "] contains a null model object, must be an object of type java.util.Collection"); } if (group.hasRawInput()) { final String raw = group.getRawInput(); if (!Strings.isEmpty(raw)) { final String[] values = raw.split(FormComponent.VALUE_SEPARATOR); for (String value : values) { if (uuid.equals(value)) { tag.put("checked", "checked"); } } } } else if (collection.contains(getDefaultModelObject())) { tag.put("checked", "checked"); } if (group.wantOnSelectionChangedNotifications()) { // url that points to this components IOnChangeListener method CharSequence url = group.urlFor(IOnChangeListener.INTERFACE, new PageParameters()); Form<?> form = group.findParent(Form.class); if (form != null) { tag.put("onclick", form.getJsForInterfaceUrl(url)); } else { // NOTE: do not encode the url as that would give invalid JavaScript tag.put("onclick", "window.location.href='" + url + (url.toString().indexOf('?') > -1 ? "&" : "?") + group.getInputName() + "=' + this.value;"); } } if (!isActionAuthorized(ENABLE) || !isEnabledInHierarchy() || !group.isEnabledInHierarchy()) { tag.put(ATTR_DISABLED, ATTR_DISABLED); } // put group id into the class so we can easily identify all radios belonging to the group final String marker = "wicket-" + getGroup().getMarkupId(); String clazz = tag.getAttribute("class"); if (Strings.isEmpty(clazz)) { clazz = marker; } else { clazz = clazz + " " + marker; } tag.put("class", clazz); } /** * The value will be made available to the validator property by means of ${label}. It does not * have any specific meaning to Check itself. * * @param labelModel * @return this for chaining */ @Override public Check<T> setLabel(IModel<String> labelModel) { super.setLabel(labelModel); return this; } @Override @SuppressWarnings("unchecked") public final IModel<T> getModel() { return (IModel<T>)getDefaultModel(); } @Override public final void setModel(IModel<T> model) { setDefaultModel(model); } @Override @SuppressWarnings("unchecked") public final T getModelObject() { return (T)getDefaultModelObject(); } @Override public final void setModelObject(T object) { setDefaultModelObject(object); } /** {@inheritDoc} */ @Override protected boolean getStatelessHint() { // because this component uses uuid field it cannot be stateless return false; } }
/* *============================================================================ * This library is free software; you can redistribute it and/or * modify it under the terms of version 2.1 of the GNU Lesser General Public * License as published by the Free Software Foundation. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA *============================================================================ * Copyright (C) 2007 XenSource Inc. *============================================================================ */ package com.xensource.xenapi; import java.util.Map; import java.util.Set; import java.util.Date; import java.lang.ref.SoftReference; import java.util.HashMap; import java.util.HashSet; import java.io.PrintWriter; import java.io.StringWriter; import org.apache.xmlrpc.XmlRpcException; /** * Represents a patch stored on a server * * @author XenSource Inc. */ public class HostPatch extends XenAPIObject { /** * The XenAPI reference to this object. */ protected final String ref; private HostPatch(String ref) { this.ref = ref; } public String toWireString() { return this.ref; } /** * This code helps ensure there is only one * HostPatch instance per XenAPI reference. */ private static final Map<String,SoftReference<HostPatch>> cache = new HashMap<String,SoftReference<HostPatch>>(); protected static synchronized HostPatch getInstFromRef(String ref) { if(HostPatch.cache.containsKey(ref)) { HostPatch instance = HostPatch.cache.get(ref).get(); if(instance != null) { return instance; } } HostPatch instance = new HostPatch(ref); HostPatch.cache.put(ref, new SoftReference<HostPatch>(instance)); return instance; } /** * Represents all the fields in a HostPatch */ public static class Record implements Types.Record{ public String toString() { StringWriter writer = new StringWriter(); PrintWriter print = new PrintWriter(writer); print.printf("%1$20s: %2$s\n", "uuid", this.uuid); print.printf("%1$20s: %2$s\n", "nameLabel", this.nameLabel); print.printf("%1$20s: %2$s\n", "nameDescription", this.nameDescription); print.printf("%1$20s: %2$s\n", "version", this.version); print.printf("%1$20s: %2$s\n", "host", this.host); print.printf("%1$20s: %2$s\n", "applied", this.applied); print.printf("%1$20s: %2$s\n", "timestampApplied", this.timestampApplied); print.printf("%1$20s: %2$s\n", "size", this.size); print.printf("%1$20s: %2$s\n", "poolPatch", this.poolPatch); print.printf("%1$20s: %2$s\n", "otherConfig", this.otherConfig); return writer.toString(); } /** * Convert a host_patch.Record to a Map */ public Map<String,Object> toMap() { Map<String,Object> map = new HashMap<String,Object>(); map.put("uuid", this.uuid == null ? "" : this.uuid); map.put("name_label", this.nameLabel == null ? "" : this.nameLabel); map.put("name_description", this.nameDescription == null ? "" : this.nameDescription); map.put("version", this.version == null ? "" : this.version); map.put("host", this.host == null ? com.xensource.xenapi.Host.getInstFromRef("OpaqueRef:NULL") : this.host); map.put("applied", this.applied == null ? false : this.applied); map.put("timestamp_applied", this.timestampApplied == null ? new Date(0) : this.timestampApplied); map.put("size", this.size == null ? 0 : this.size); map.put("pool_patch", this.poolPatch == null ? com.xensource.xenapi.PoolPatch.getInstFromRef("OpaqueRef:NULL") : this.poolPatch); map.put("other_config", this.otherConfig == null ? new HashMap<String, String>() : this.otherConfig); return map; } /** * unique identifier/object reference */ public String uuid; /** * a human-readable name */ public String nameLabel; /** * a notes field containg human-readable description */ public String nameDescription; /** * Patch version number */ public String version; /** * Host the patch relates to */ public Host host; /** * True if the patch has been applied */ public Boolean applied; /** * Time the patch was applied */ public Date timestampApplied; /** * Size of the patch */ public Long size; /** * The patch applied */ public PoolPatch poolPatch; /** * additional configuration */ public Map<String, String> otherConfig; } /** * Get a record containing the current state of the given host_patch. * * @return all fields from the object */ public HostPatch.Record getRecord(Connection c) throws Types.BadServerResponse, XmlRpcException { String method_call = "host_patch.get_record"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); if(response.get("Status").equals("Success")) { Object result = response.get("Value"); return Types.toHostPatchRecord(result); } throw new Types.BadServerResponse(response); } /** * Get a reference to the host_patch instance with the specified UUID. * * @param uuid UUID of object to return * @return reference to the object */ public static HostPatch getByUuid(Connection c, String uuid) throws Types.BadServerResponse, XmlRpcException { String method_call = "host_patch.get_by_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(uuid)}; Map response = c.dispatch(method_call, method_params); if(response.get("Status").equals("Success")) { Object result = response.get("Value"); return Types.toHostPatch(result); } throw new Types.BadServerResponse(response); } /** * Get all the host_patch instances with the given label. * * @param label label of object to return * @return references to objects with matching names */ public static Set<HostPatch> getByNameLabel(Connection c, String label) throws Types.BadServerResponse, XmlRpcException { String method_call = "host_patch.get_by_name_label"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(label)}; Map response = c.dispatch(method_call, method_params); if(response.get("Status").equals("Success")) { Object result = response.get("Value"); return Types.toSetOfHostPatch(result); } throw new Types.BadServerResponse(response); } /** * Get the uuid field of the given host_patch. * * @return value of the field */ public String getUuid(Connection c) throws Types.BadServerResponse, XmlRpcException { String method_call = "host_patch.get_uuid"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); if(response.get("Status").equals("Success")) { Object result = response.get("Value"); return Types.toString(result); } throw new Types.BadServerResponse(response); } /** * Get the name/label field of the given host_patch. * * @return value of the field */ public String getNameLabel(Connection c) throws Types.BadServerResponse, XmlRpcException { String method_call = "host_patch.get_name_label"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); if(response.get("Status").equals("Success")) { Object result = response.get("Value"); return Types.toString(result); } throw new Types.BadServerResponse(response); } /** * Get the name/description field of the given host_patch. * * @return value of the field */ public String getNameDescription(Connection c) throws Types.BadServerResponse, XmlRpcException { String method_call = "host_patch.get_name_description"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); if(response.get("Status").equals("Success")) { Object result = response.get("Value"); return Types.toString(result); } throw new Types.BadServerResponse(response); } /** * Get the version field of the given host_patch. * * @return value of the field */ public String getVersion(Connection c) throws Types.BadServerResponse, XmlRpcException { String method_call = "host_patch.get_version"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); if(response.get("Status").equals("Success")) { Object result = response.get("Value"); return Types.toString(result); } throw new Types.BadServerResponse(response); } /** * Get the host field of the given host_patch. * * @return value of the field */ public Host getHost(Connection c) throws Types.BadServerResponse, XmlRpcException { String method_call = "host_patch.get_host"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); if(response.get("Status").equals("Success")) { Object result = response.get("Value"); return Types.toHost(result); } throw new Types.BadServerResponse(response); } /** * Get the applied field of the given host_patch. * * @return value of the field */ public Boolean getApplied(Connection c) throws Types.BadServerResponse, XmlRpcException { String method_call = "host_patch.get_applied"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); if(response.get("Status").equals("Success")) { Object result = response.get("Value"); return Types.toBoolean(result); } throw new Types.BadServerResponse(response); } /** * Get the timestamp_applied field of the given host_patch. * * @return value of the field */ public Date getTimestampApplied(Connection c) throws Types.BadServerResponse, XmlRpcException { String method_call = "host_patch.get_timestamp_applied"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); if(response.get("Status").equals("Success")) { Object result = response.get("Value"); return Types.toDate(result); } throw new Types.BadServerResponse(response); } /** * Get the size field of the given host_patch. * * @return value of the field */ public Long getSize(Connection c) throws Types.BadServerResponse, XmlRpcException { String method_call = "host_patch.get_size"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); if(response.get("Status").equals("Success")) { Object result = response.get("Value"); return Types.toLong(result); } throw new Types.BadServerResponse(response); } /** * Get the pool_patch field of the given host_patch. * * @return value of the field */ public PoolPatch getPoolPatch(Connection c) throws Types.BadServerResponse, XmlRpcException { String method_call = "host_patch.get_pool_patch"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); if(response.get("Status").equals("Success")) { Object result = response.get("Value"); return Types.toPoolPatch(result); } throw new Types.BadServerResponse(response); } /** * Get the other_config field of the given host_patch. * * @return value of the field */ public Map<String, String> getOtherConfig(Connection c) throws Types.BadServerResponse, XmlRpcException { String method_call = "host_patch.get_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); if(response.get("Status").equals("Success")) { Object result = response.get("Value"); return Types.toMapOfStringString(result); } throw new Types.BadServerResponse(response); } /** * Set the other_config field of the given host_patch. * * @param otherConfig New value to set */ public void setOtherConfig(Connection c, Map<String, String> otherConfig) throws Types.BadServerResponse, XmlRpcException { String method_call = "host_patch.set_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(otherConfig)}; Map response = c.dispatch(method_call, method_params); if(response.get("Status").equals("Success")) { Object result = response.get("Value"); return; } throw new Types.BadServerResponse(response); } /** * Add the given key-value pair to the other_config field of the given host_patch. * * @param key Key to add * @param value Value to add */ public void addToOtherConfig(Connection c, String key, String value) throws Types.BadServerResponse, XmlRpcException { String method_call = "host_patch.add_to_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key), Marshalling.toXMLRPC(value)}; Map response = c.dispatch(method_call, method_params); if(response.get("Status").equals("Success")) { Object result = response.get("Value"); return; } throw new Types.BadServerResponse(response); } /** * Remove the given key and its corresponding value from the other_config field of the given host_patch. If the key is not in that Map, then do nothing. * * @param key Key to remove */ public void removeFromOtherConfig(Connection c, String key) throws Types.BadServerResponse, XmlRpcException { String method_call = "host_patch.remove_from_other_config"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref), Marshalling.toXMLRPC(key)}; Map response = c.dispatch(method_call, method_params); if(response.get("Status").equals("Success")) { Object result = response.get("Value"); return; } throw new Types.BadServerResponse(response); } /** * Destroy the specified host patch, removing it from the disk. This does NOT reverse the patch * @deprecated * * @return Task */ @Deprecated public Task destroyAsync(Connection c) throws Types.BadServerResponse, XmlRpcException { String method_call = "Async.host_patch.destroy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); if(response.get("Status").equals("Success")) { Object result = response.get("Value"); return Types.toTask(result); } throw new Types.BadServerResponse(response); } /** * Destroy the specified host patch, removing it from the disk. This does NOT reverse the patch * @deprecated * */ @Deprecated public void destroy(Connection c) throws Types.BadServerResponse, XmlRpcException { String method_call = "host_patch.destroy"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); if(response.get("Status").equals("Success")) { Object result = response.get("Value"); return; } throw new Types.BadServerResponse(response); } /** * Apply the selected patch and return its output * @deprecated * * @return Task */ @Deprecated public Task applyAsync(Connection c) throws Types.BadServerResponse, XmlRpcException { String method_call = "Async.host_patch.apply"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); if(response.get("Status").equals("Success")) { Object result = response.get("Value"); return Types.toTask(result); } throw new Types.BadServerResponse(response); } /** * Apply the selected patch and return its output * @deprecated * * @return the output of the patch application process */ @Deprecated public String apply(Connection c) throws Types.BadServerResponse, XmlRpcException { String method_call = "host_patch.apply"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session), Marshalling.toXMLRPC(this.ref)}; Map response = c.dispatch(method_call, method_params); if(response.get("Status").equals("Success")) { Object result = response.get("Value"); return Types.toString(result); } throw new Types.BadServerResponse(response); } /** * Return a list of all the host_patchs known to the system. * * @return references to all objects */ public static Set<HostPatch> getAll(Connection c) throws Types.BadServerResponse, XmlRpcException { String method_call = "host_patch.get_all"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); if(response.get("Status").equals("Success")) { Object result = response.get("Value"); return Types.toSetOfHostPatch(result); } throw new Types.BadServerResponse(response); } /** * Return a map of host_patch references to host_patch records for all host_patchs known to the system. * * @return records of all objects */ public static Map<HostPatch, HostPatch.Record> getAllRecords(Connection c) throws Types.BadServerResponse, XmlRpcException { String method_call = "host_patch.get_all_records"; String session = c.getSessionReference(); Object[] method_params = {Marshalling.toXMLRPC(session)}; Map response = c.dispatch(method_call, method_params); if(response.get("Status").equals("Success")) { Object result = response.get("Value"); return Types.toMapOfHostPatchHostPatchRecord(result); } throw new Types.BadServerResponse(response); } }
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.plugins.groovy.codeInsight; import com.intellij.codeInsight.daemon.DaemonBundle; import com.intellij.codeInsight.daemon.impl.GutterIconTooltipHelper; import com.intellij.codeInsight.daemon.impl.LineMarkerNavigator; import com.intellij.codeInsight.daemon.impl.MarkerType; import com.intellij.codeInsight.daemon.impl.PsiElementListNavigator; import com.intellij.codeInsight.navigation.ListBackgroundUpdaterTask; import com.intellij.ide.util.MethodCellRenderer; import com.intellij.ide.util.PsiElementListCellRenderer; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.application.ReadActionProcessor; import com.intellij.openapi.progress.ProgressIndicator; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.DumbService; import com.intellij.psi.*; import com.intellij.psi.presentation.java.ClassPresentationUtil; import com.intellij.psi.search.PsiElementProcessor; import com.intellij.psi.search.PsiElementProcessorAdapter; import com.intellij.psi.search.searches.OverridingMethodsSearch; import com.intellij.psi.util.PsiUtil; import com.intellij.util.CommonProcessors; import com.intellij.util.Function; import com.intellij.util.NullableFunction; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.containers.HashSet; import gnu.trove.THashSet; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrField; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrAccessorMethod; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod; import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrReflectedMethod; import org.jetbrains.plugins.groovy.lang.psi.impl.PsiImplUtil; import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrTraitMethod; import org.jetbrains.plugins.groovy.lang.psi.util.GroovyPropertyUtils; import javax.swing.*; import java.awt.event.MouseEvent; import java.text.MessageFormat; import java.util.*; /** * @author Max Medvedev */ public class GroovyMarkerTypes { static final MarkerType OVERRIDING_PROPERTY_TYPE = new MarkerType("OVERRIDING_PROPERTY_TYPE",new Function<PsiElement, String>() { @Nullable @Override public String fun(PsiElement psiElement) { final PsiElement parent = psiElement.getParent(); if (!(parent instanceof GrField)) return null; final GrField field = (GrField)parent; final List<GrAccessorMethod> accessors = GroovyPropertyUtils.getFieldAccessors(field); StringBuilder builder = new StringBuilder(); builder.append("<html><body>"); int count = 0; String sep = ""; for (GrAccessorMethod method : accessors) { PsiMethod[] superMethods = method.findSuperMethods(false); count += superMethods.length; if (superMethods.length == 0) continue; PsiMethod superMethod = superMethods[0]; boolean isAbstract = method.hasModifierProperty(PsiModifier.ABSTRACT); boolean isSuperAbstract = superMethod.hasModifierProperty(PsiModifier.ABSTRACT); @NonNls final String key; if (isSuperAbstract && !isAbstract) { key = "method.implements.in"; } else { key = "method.overrides.in"; } builder.append(sep); sep = "<br>"; composeText(superMethods, DaemonBundle.message(key), builder); } if (count == 0) return null; builder.append("</html></body>"); return builder.toString(); } }, new LineMarkerNavigator() { @Override public void browse(MouseEvent e, PsiElement element) { PsiElement parent = element.getParent(); if (!(parent instanceof GrField)) return; final GrField field = (GrField)parent; final List<GrAccessorMethod> accessors = GroovyPropertyUtils.getFieldAccessors(field); final ArrayList<PsiMethod> superMethods = new ArrayList<PsiMethod>(); for (GrAccessorMethod method : accessors) { Collections.addAll(superMethods, method.findSuperMethods(false)); } if (superMethods.isEmpty()) return; final PsiMethod[] supers = ContainerUtil.toArray(superMethods, new PsiMethod[superMethods.size()]); boolean showMethodNames = !PsiUtil.allMethodsHaveSameSignature(supers); PsiElementListNavigator.openTargets(e, supers, DaemonBundle.message("navigation.title.super.method", field.getName()), DaemonBundle.message("navigation.findUsages.title.super.method", field.getName()), new MethodCellRenderer(showMethodNames)); } }); static final MarkerType OVERRIDEN_PROPERTY_TYPE = new MarkerType("OVERRIDEN_PROPERTY_TYPE",new Function<PsiElement, String>() { @Nullable @Override public String fun(PsiElement element) { PsiElement parent = element.getParent(); if (!(parent instanceof GrField)) return null; final List<GrAccessorMethod> accessors = GroovyPropertyUtils.getFieldAccessors((GrField)parent); PsiElementProcessor.CollectElementsWithLimit<PsiMethod> processor = new PsiElementProcessor.CollectElementsWithLimit<PsiMethod>(5); for (GrAccessorMethod method : accessors) { OverridingMethodsSearch.search(method, true).forEach(new PsiElementProcessorAdapter<PsiMethod>(processor)); } if (processor.isOverflow()) { return DaemonBundle.message("method.is.overridden.too.many"); } PsiMethod[] overridings = processor.toArray(new PsiMethod[processor.getCollection().size()]); if (overridings.length == 0) return null; Comparator<PsiMethod> comparator = new MethodCellRenderer(false).getComparator(); Arrays.sort(overridings, comparator); String start = DaemonBundle.message("method.is.overriden.header"); @NonNls String pattern = "&nbsp;&nbsp;&nbsp;&nbsp;{1}"; return GutterIconTooltipHelper.composeText(overridings, start, pattern); } }, new LineMarkerNavigator() { @Override public void browse(MouseEvent e, PsiElement element) { PsiElement parent = element.getParent(); if (!(parent instanceof GrField)) return; if (DumbService.isDumb(element.getProject())) { DumbService.getInstance(element.getProject()).showDumbModeNotification("Navigation to overriding classes is not possible during index update"); return; } final GrField field = (GrField)parent; final CommonProcessors.CollectProcessor<PsiMethod> collectProcessor = new CommonProcessors.CollectProcessor<PsiMethod>(new THashSet<PsiMethod>()); if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { @Override public void run() { ApplicationManager.getApplication().runReadAction(new Runnable() { @Override public void run() { for (GrAccessorMethod method : GroovyPropertyUtils.getFieldAccessors(field)) { OverridingMethodsSearch.search(method, true).forEach(collectProcessor); } } }); } }, "Searching for overriding methods", true, field.getProject(), (JComponent)e.getComponent())) { return; } PsiMethod[] overridings = collectProcessor.toArray(PsiMethod.EMPTY_ARRAY); if (overridings.length == 0) return; String title = DaemonBundle.message("navigation.title.overrider.method", field.getName(), overridings.length); boolean showMethodNames = !PsiUtil.allMethodsHaveSameSignature(overridings); MethodCellRenderer renderer = new MethodCellRenderer(showMethodNames); Arrays.sort(overridings, renderer.getComparator()); PsiElementListNavigator.openTargets(e, overridings, title, "Overriding Methods of " + field.getName(), renderer); } } ); public static final MarkerType GR_OVERRIDING_METHOD = new MarkerType("GR_OVERRIDING_METHOD", new NullableFunction<PsiElement, String>() { @Override public String fun(PsiElement element) { PsiElement parent = element.getParent(); if (!(parent instanceof GrMethod)) return null; GrMethod method = (GrMethod)parent; Set<PsiMethod> superMethods = collectSuperMethods(method); if (superMethods.isEmpty()) return null; PsiMethod superMethod = superMethods.iterator().next(); boolean isAbstract = method.hasModifierProperty(PsiModifier.ABSTRACT); boolean isSuperAbstract = superMethod.hasModifierProperty(PsiModifier.ABSTRACT); final boolean sameSignature = superMethod.getSignature(PsiSubstitutor.EMPTY).equals(method.getSignature(PsiSubstitutor.EMPTY)); @NonNls final String key; if (isSuperAbstract && !isAbstract){ key = sameSignature ? "method.implements" : "method.implements.in"; } else{ key = sameSignature ? "method.overrides" : "method.overrides.in"; } return GutterIconTooltipHelper.composeText(superMethods, "", DaemonBundle.message(key)); } }, new LineMarkerNavigator(){ @Override public void browse(MouseEvent e, PsiElement element) { PsiElement parent = element.getParent(); if (!(parent instanceof GrMethod)) return; GrMethod method = (GrMethod)parent; Set<PsiMethod> superMethods = collectSuperMethods(method); if (superMethods.isEmpty()) return; PsiElementListNavigator.openTargets(e, superMethods.toArray(new NavigatablePsiElement[superMethods.size()]), DaemonBundle.message("navigation.title.super.method", method.getName()), DaemonBundle.message("navigation.findUsages.title.super.method", method.getName()), new MethodCellRenderer(true)); } }); public static final MarkerType GR_OVERRIDEN_METHOD = new MarkerType("GR_OVERRIDEN_METHOD",new NullableFunction<PsiElement, String>() { @Override public String fun(PsiElement element) { PsiElement parent = element.getParent(); if (!(parent instanceof GrMethod)) return null; GrMethod method = (GrMethod)parent; final PsiElementProcessor.CollectElementsWithLimit<PsiMethod> processor = new PsiElementProcessor.CollectElementsWithLimit<PsiMethod>(5); for (GrMethod m : PsiImplUtil.getMethodOrReflectedMethods(method)) { OverridingMethodsSearch.search(m, true).forEach(new ReadActionProcessor<PsiMethod>() { @Override public boolean processInReadAction(PsiMethod method) { if (method instanceof GrTraitMethod) { return true; } return processor.execute(method); } }); } boolean isAbstract = method.hasModifierProperty(PsiModifier.ABSTRACT); if (processor.isOverflow()){ return isAbstract ? DaemonBundle.message("method.is.implemented.too.many") : DaemonBundle.message("method.is.overridden.too.many"); } PsiMethod[] overridings = processor.toArray(new PsiMethod[processor.getCollection().size()]); if (overridings.length == 0) return null; Comparator<PsiMethod> comparator = new MethodCellRenderer(false).getComparator(); Arrays.sort(overridings, comparator); String start = isAbstract ? DaemonBundle.message("method.is.implemented.header") : DaemonBundle.message("method.is.overriden.header"); @NonNls String pattern = "&nbsp;&nbsp;&nbsp;&nbsp;{1}"; return GutterIconTooltipHelper.composeText(overridings, start, pattern); } }, new LineMarkerNavigator(){ @Override public void browse(MouseEvent e, PsiElement element) { PsiElement parent = element.getParent(); if (!(parent instanceof GrMethod)) return; if (DumbService.isDumb(element.getProject())) { DumbService.getInstance(element.getProject()).showDumbModeNotification("Navigation to overriding classes is not possible during index update"); return; } //collect all overrings (including fields with implicit accessors and method with default parameters) final GrMethod method = (GrMethod)parent; final PsiElementProcessor.CollectElementsWithLimit<PsiMethod> collectProcessor = new PsiElementProcessor.CollectElementsWithLimit<PsiMethod>(2, new THashSet<PsiMethod>()); if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(new Runnable() { @Override public void run() { ApplicationManager.getApplication().runReadAction(new Runnable() { @Override public void run() { for (GrMethod m : PsiImplUtil.getMethodOrReflectedMethods(method)) { OverridingMethodsSearch.search(m, true).forEach(new ReadActionProcessor<PsiMethod>() { @Override public boolean processInReadAction(PsiMethod psiMethod) { if (psiMethod instanceof GrReflectedMethod) { psiMethod = ((GrReflectedMethod)psiMethod).getBaseMethod(); } return collectProcessor.execute(psiMethod); } }); } } }); } }, MarkerType.SEARCHING_FOR_OVERRIDING_METHODS, true, method.getProject(), (JComponent)e.getComponent())) { return; } PsiMethod[] overridings = collectProcessor.toArray(PsiMethod.EMPTY_ARRAY); if (overridings.length == 0) return; PsiElementListCellRenderer<PsiMethod> renderer = new MethodCellRenderer(!PsiUtil.allMethodsHaveSameSignature(overridings)); Arrays.sort(overridings, renderer.getComparator()); final OverridingMethodsUpdater methodsUpdater = new OverridingMethodsUpdater(method, renderer); PsiElementListNavigator.openTargets(e, overridings, methodsUpdater.getCaption(overridings.length), "Overriding Methods of " + method.getName(), renderer, methodsUpdater); } }); private GroovyMarkerTypes() { } private static Set<PsiMethod> collectSuperMethods(GrMethod method) { Set<PsiMethod> superMethods = new HashSet<PsiMethod>(); for (GrMethod m : PsiImplUtil.getMethodOrReflectedMethods(method)) { for (PsiMethod superMethod : m.findSuperMethods(false)) { if (superMethod instanceof GrReflectedMethod) { superMethod = ((GrReflectedMethod)superMethod).getBaseMethod(); } superMethods.add(superMethod); } } return superMethods; } private static StringBuilder composeText(@NotNull PsiElement[] elements, final String pattern, StringBuilder result) { Set<String> names = new LinkedHashSet<String>(); for (PsiElement element : elements) { String methodName = ((PsiMethod)element).getName(); PsiClass aClass = ((PsiMethod)element).getContainingClass(); String className = aClass == null ? "" : ClassPresentationUtil.getNameForClass(aClass, true); names.add(MessageFormat.format(pattern, methodName, className)); } @NonNls String sep = ""; for (String name : names) { result.append(sep); sep = "<br>"; result.append(name); } return result; } private static class OverridingMethodsUpdater extends ListBackgroundUpdaterTask { private final GrMethod myMethod; private final PsiElementListCellRenderer myRenderer; public OverridingMethodsUpdater(GrMethod method, PsiElementListCellRenderer renderer) { super(method.getProject(), MarkerType.SEARCHING_FOR_OVERRIDING_METHODS); myMethod = method; myRenderer = renderer; } @Override public String getCaption(int size) { return myMethod.hasModifierProperty(PsiModifier.ABSTRACT) ? DaemonBundle.message("navigation.title.implementation.method", myMethod.getName(), size) : DaemonBundle.message("navigation.title.overrider.method", myMethod.getName(), size); } @Override public void run(@NotNull final ProgressIndicator indicator) { super.run(indicator); for (PsiMethod method : PsiImplUtil.getMethodOrReflectedMethods(myMethod)) { OverridingMethodsSearch.search(method, true).forEach( new CommonProcessors.CollectProcessor<PsiMethod>() { @Override public boolean process(PsiMethod psiMethod) { if (!updateComponent(com.intellij.psi.impl.PsiImplUtil.handleMirror(psiMethod), myRenderer.getComparator())) { indicator.cancel(); } indicator.checkCanceled(); return true; } }); } } } }
/** * Copyright 2009-2016 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.ibatis.reflection; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.GenericArrayType; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.ReflectPermission; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import org.apache.ibatis.reflection.invoker.GetFieldInvoker; import org.apache.ibatis.reflection.invoker.Invoker; import org.apache.ibatis.reflection.invoker.MethodInvoker; import org.apache.ibatis.reflection.invoker.SetFieldInvoker; import org.apache.ibatis.reflection.property.PropertyNamer; /** * This class represents a cached set of class definition information that * allows for easy mapping between property names and getter/setter methods. * * @author Clinton Begin */ public class Reflector { private static final String[] EMPTY_STRING_ARRAY = new String[0]; private Class<?> type; private String[] readablePropertyNames = EMPTY_STRING_ARRAY; private String[] writeablePropertyNames = EMPTY_STRING_ARRAY; private Map<String, Invoker> setMethods = new HashMap<String, Invoker>(); private Map<String, Invoker> getMethods = new HashMap<String, Invoker>(); private Map<String, Class<?>> setTypes = new HashMap<String, Class<?>>(); private Map<String, Class<?>> getTypes = new HashMap<String, Class<?>>(); private Constructor<?> defaultConstructor; private Map<String, String> caseInsensitivePropertyMap = new HashMap<String, String>(); public Reflector(Class<?> clazz) { type = clazz; addDefaultConstructor(clazz); addGetMethods(clazz); addSetMethods(clazz); addFields(clazz); readablePropertyNames = getMethods.keySet().toArray(new String[getMethods.keySet().size()]); writeablePropertyNames = setMethods.keySet().toArray(new String[setMethods.keySet().size()]); for (String propName : readablePropertyNames) { caseInsensitivePropertyMap.put(propName.toUpperCase(Locale.ENGLISH), propName); } for (String propName : writeablePropertyNames) { caseInsensitivePropertyMap.put(propName.toUpperCase(Locale.ENGLISH), propName); } } private void addDefaultConstructor(Class<?> clazz) { Constructor<?>[] consts = clazz.getDeclaredConstructors(); for (Constructor<?> constructor : consts) { if (constructor.getParameterTypes().length == 0) { if (canAccessPrivateMethods()) { try { constructor.setAccessible(true); } catch (Exception e) { // Ignored. This is only a final precaution, nothing we can do. } } if (constructor.isAccessible()) { this.defaultConstructor = constructor; } } } } private void addGetMethods(Class<?> cls) { Map<String, List<Method>> conflictingGetters = new HashMap<String, List<Method>>(); Method[] methods = getClassMethods(cls); for (Method method : methods) { String name = method.getName(); if (name.startsWith("get") && name.length() > 3) { if (method.getParameterTypes().length == 0) { name = PropertyNamer.methodToProperty(name); addMethodConflict(conflictingGetters, name, method); } } else if (name.startsWith("is") && name.length() > 2) { if (method.getParameterTypes().length == 0) { name = PropertyNamer.methodToProperty(name); addMethodConflict(conflictingGetters, name, method); } } } resolveGetterConflicts(conflictingGetters); } private void resolveGetterConflicts(Map<String, List<Method>> conflictingGetters) { for (String propName : conflictingGetters.keySet()) { List<Method> getters = conflictingGetters.get(propName); Iterator<Method> iterator = getters.iterator(); Method firstMethod = iterator.next(); if (getters.size() == 1) { addGetMethod(propName, firstMethod); } else { Method getter = firstMethod; Class<?> getterType = firstMethod.getReturnType(); while (iterator.hasNext()) { Method method = iterator.next(); Class<?> methodType = method.getReturnType(); if (methodType.equals(getterType)) { throw new ReflectionException("Illegal overloaded getter method with ambiguous type for property " + propName + " in class " + firstMethod.getDeclaringClass() + ". This breaks the JavaBeans " + "specification and can cause unpredicatble results."); } else if (methodType.isAssignableFrom(getterType)) { // OK getter type is descendant } else if (getterType.isAssignableFrom(methodType)) { getter = method; getterType = methodType; } else { throw new ReflectionException("Illegal overloaded getter method with ambiguous type for property " + propName + " in class " + firstMethod.getDeclaringClass() + ". This breaks the JavaBeans " + "specification and can cause unpredicatble results."); } } addGetMethod(propName, getter); } } } private void addGetMethod(String name, Method method) { if (isValidPropertyName(name)) { getMethods.put(name, new MethodInvoker(method)); Type returnType = TypeParameterResolver.resolveReturnType(method, type); getTypes.put(name, typeToClass(returnType)); } } private void addSetMethods(Class<?> cls) { Map<String, List<Method>> conflictingSetters = new HashMap<String, List<Method>>(); Method[] methods = getClassMethods(cls); for (Method method : methods) { String name = method.getName(); if (name.startsWith("set") && name.length() > 3) { if (method.getParameterTypes().length == 1) { name = PropertyNamer.methodToProperty(name); addMethodConflict(conflictingSetters, name, method); } } } resolveSetterConflicts(conflictingSetters); } private void addMethodConflict(Map<String, List<Method>> conflictingMethods, String name, Method method) { List<Method> list = conflictingMethods.get(name); if (list == null) { list = new ArrayList<Method>(); conflictingMethods.put(name, list); } list.add(method); } private void resolveSetterConflicts(Map<String, List<Method>> conflictingSetters) { for (String propName : conflictingSetters.keySet()) { List<Method> setters = conflictingSetters.get(propName); Method firstMethod = setters.get(0); if (setters.size() == 1) { addSetMethod(propName, firstMethod); } else { Class<?> expectedType = getTypes.get(propName); if (expectedType == null) { throw new ReflectionException("Illegal overloaded setter method with ambiguous type for property " + propName + " in class " + firstMethod.getDeclaringClass() + ". This breaks the JavaBeans " + "specification and can cause unpredicatble results."); } else { Iterator<Method> methods = setters.iterator(); Method setter = null; while (methods.hasNext()) { Method method = methods.next(); if (method.getParameterTypes().length == 1 && expectedType.equals(method.getParameterTypes()[0])) { setter = method; break; } } if (setter == null) { throw new ReflectionException("Illegal overloaded setter method with ambiguous type for property " + propName + " in class " + firstMethod.getDeclaringClass() + ". This breaks the JavaBeans " + "specification and can cause unpredicatble results."); } addSetMethod(propName, setter); } } } } private void addSetMethod(String name, Method method) { if (isValidPropertyName(name)) { setMethods.put(name, new MethodInvoker(method)); Type[] paramTypes = TypeParameterResolver.resolveParamTypes(method, type); setTypes.put(name, typeToClass(paramTypes[0])); } } private Class<?> typeToClass(Type src) { Class<?> result = null; if (src instanceof Class) { result = (Class<?>) src; } else if (src instanceof ParameterizedType) { result = (Class<?>) ((ParameterizedType) src).getRawType(); } else if (src instanceof GenericArrayType) { Type componentType = ((GenericArrayType) src).getGenericComponentType(); if (componentType instanceof Class) { result = Array.newInstance((Class<?>) componentType, 0).getClass(); } else { Class<?> componentClass = typeToClass(componentType); result = Array.newInstance((Class<?>) componentClass, 0).getClass(); } } if (result == null) { result = Object.class; } return result; } private void addFields(Class<?> clazz) { Field[] fields = clazz.getDeclaredFields(); for (Field field : fields) { if (canAccessPrivateMethods()) { try { field.setAccessible(true); } catch (Exception e) { // Ignored. This is only a final precaution, nothing we can do. } } if (field.isAccessible()) { if (!setMethods.containsKey(field.getName())) { // issue #379 - removed the check for final because JDK 1.5 allows // modification of final fields through reflection (JSR-133). (JGB) // pr #16 - final static can only be set by the classloader int modifiers = field.getModifiers(); if (!(Modifier.isFinal(modifiers) && Modifier.isStatic(modifiers))) { addSetField(field); } } if (!getMethods.containsKey(field.getName())) { addGetField(field); } } } if (clazz.getSuperclass() != null) { addFields(clazz.getSuperclass()); } } private void addSetField(Field field) { if (isValidPropertyName(field.getName())) { setMethods.put(field.getName(), new SetFieldInvoker(field)); Type fieldType = TypeParameterResolver.resolveFieldType(field, type); setTypes.put(field.getName(), typeToClass(fieldType)); } } private void addGetField(Field field) { if (isValidPropertyName(field.getName())) { getMethods.put(field.getName(), new GetFieldInvoker(field)); Type fieldType = TypeParameterResolver.resolveFieldType(field, type); getTypes.put(field.getName(), typeToClass(fieldType)); } } private boolean isValidPropertyName(String name) { return !(name.startsWith("$") || "serialVersionUID".equals(name) || "class".equals(name)); } /* * This method returns an array containing all methods * declared in this class and any superclass. * We use this method, instead of the simpler Class.getMethods(), * because we want to look for private methods as well. * * @param cls The class * @return An array containing all methods in this class */ private Method[] getClassMethods(Class<?> cls) { Map<String, Method> uniqueMethods = new HashMap<String, Method>(); Class<?> currentClass = cls; while (currentClass != null) { addUniqueMethods(uniqueMethods, currentClass.getDeclaredMethods()); // we also need to look for interface methods - // because the class may be abstract Class<?>[] interfaces = currentClass.getInterfaces(); for (Class<?> anInterface : interfaces) { addUniqueMethods(uniqueMethods, anInterface.getMethods()); } currentClass = currentClass.getSuperclass(); } Collection<Method> methods = uniqueMethods.values(); return methods.toArray(new Method[methods.size()]); } private void addUniqueMethods(Map<String, Method> uniqueMethods, Method[] methods) { for (Method currentMethod : methods) { if (!currentMethod.isBridge()) { String signature = getSignature(currentMethod); // check to see if the method is already known // if it is known, then an extended class must have // overridden a method if (!uniqueMethods.containsKey(signature)) { if (canAccessPrivateMethods()) { try { currentMethod.setAccessible(true); } catch (Exception e) { // Ignored. This is only a final precaution, nothing we can do. } } uniqueMethods.put(signature, currentMethod); } } } } private String getSignature(Method method) { StringBuilder sb = new StringBuilder(); Class<?> returnType = method.getReturnType(); if (returnType != null) { sb.append(returnType.getName()).append('#'); } sb.append(method.getName()); Class<?>[] parameters = method.getParameterTypes(); for (int i = 0; i < parameters.length; i++) { if (i == 0) { sb.append(':'); } else { sb.append(','); } sb.append(parameters[i].getName()); } return sb.toString(); } private static boolean canAccessPrivateMethods() { try { SecurityManager securityManager = System.getSecurityManager(); if (null != securityManager) { securityManager.checkPermission(new ReflectPermission("suppressAccessChecks")); } } catch (SecurityException e) { return false; } return true; } /* * Gets the name of the class the instance provides information for * * @return The class name */ public Class<?> getType() { return type; } public Constructor<?> getDefaultConstructor() { if (defaultConstructor != null) { return defaultConstructor; } else { throw new ReflectionException("There is no default constructor for " + type); } } public boolean hasDefaultConstructor() { return defaultConstructor != null; } public Invoker getSetInvoker(String propertyName) { Invoker method = setMethods.get(propertyName); if (method == null) { throw new ReflectionException("There is no setter for property named '" + propertyName + "' in '" + type + "'"); } return method; } public Invoker getGetInvoker(String propertyName) { Invoker method = getMethods.get(propertyName); if (method == null) { throw new ReflectionException("There is no getter for property named '" + propertyName + "' in '" + type + "'"); } return method; } /* * Gets the type for a property setter * * @param propertyName - the name of the property * @return The Class of the propery setter */ public Class<?> getSetterType(String propertyName) { Class<?> clazz = setTypes.get(propertyName); if (clazz == null) { throw new ReflectionException("There is no setter for property named '" + propertyName + "' in '" + type + "'"); } return clazz; } /* * Gets the type for a property getter * * @param propertyName - the name of the property * @return The Class of the propery getter */ public Class<?> getGetterType(String propertyName) { Class<?> clazz = getTypes.get(propertyName); if (clazz == null) { throw new ReflectionException("There is no getter for property named '" + propertyName + "' in '" + type + "'"); } return clazz; } /* * Gets an array of the readable properties for an object * * @return The array */ public String[] getGetablePropertyNames() { return readablePropertyNames; } /* * Gets an array of the writeable properties for an object * * @return The array */ public String[] getSetablePropertyNames() { return writeablePropertyNames; } /* * Check to see if a class has a writeable property by name * * @param propertyName - the name of the property to check * @return True if the object has a writeable property by the name */ public boolean hasSetter(String propertyName) { return setMethods.keySet().contains(propertyName); } /* * Check to see if a class has a readable property by name * * @param propertyName - the name of the property to check * @return True if the object has a readable property by the name */ public boolean hasGetter(String propertyName) { return getMethods.keySet().contains(propertyName); } public String findPropertyName(String name) { return caseInsensitivePropertyMap.get(name.toUpperCase(Locale.ENGLISH)); } }
/** * Copyright (C) 2013 - present by OpenGamma Inc. and the OpenGamma group of companies * * Please see distribution for license. */ package com.opengamma.strata.math.impl.interpolation; import java.util.Arrays; import com.google.common.primitives.Doubles; import com.opengamma.strata.collect.ArgChecker; import com.opengamma.strata.collect.DoubleArrayMath; import com.opengamma.strata.collect.array.DoubleMatrix; /** * Natural cubic spline interpolation. * <p> * C2 cubic spline interpolator with the natural endpoint condition, i.e., the second derivative values are zero * at the first data point and the last data point. */ public class NaturalSplineInterpolator extends PiecewisePolynomialInterpolator { private CubicSplineSolver _solver; /** * Constructor. */ public NaturalSplineInterpolator() { _solver = new CubicSplineNaturalSolver(); } /** * * @param inherit the solver */ public NaturalSplineInterpolator(final CubicSplineSolver inherit) { _solver = inherit; } /** * @param xValues X values of data * @param yValues Y values of data * @return {@link PiecewisePolynomialResult} containing knots, coefficients of piecewise polynomials, number of intervals, degree of polynomials, dimension of spline */ @Override public PiecewisePolynomialResult interpolate(final double[] xValues, final double[] yValues) { ArgChecker.notNull(xValues, "xValues"); ArgChecker.notNull(yValues, "yValues"); ArgChecker.isTrue(xValues.length == yValues.length, "xValues length = yValues length"); ArgChecker.isTrue(xValues.length > 1, "Data points should be more than 1"); final int nDataPts = xValues.length; for (int i = 0; i < nDataPts; ++i) { ArgChecker.isFalse(Double.isNaN(xValues[i]), "xData containing NaN"); ArgChecker.isFalse(Double.isInfinite(xValues[i]), "xData containing Infinity"); ArgChecker.isFalse(Double.isNaN(yValues[i]), "yData containing NaN"); ArgChecker.isFalse(Double.isInfinite(yValues[i]), "yData containing Infinity"); } for (int i = 0; i < nDataPts; ++i) { for (int j = i + 1; j < nDataPts; ++j) { ArgChecker.isFalse(xValues[i] == xValues[j], "Data should be distinct"); } } double[] xValuesSrt = new double[nDataPts]; double[] yValuesSrt = new double[nDataPts]; xValuesSrt = Arrays.copyOf(xValues, nDataPts); yValuesSrt = Arrays.copyOf(yValues, nDataPts); DoubleArrayMath.sortPairs(xValuesSrt, yValuesSrt); final DoubleMatrix coefMatrix = this._solver.solve(xValuesSrt, yValuesSrt); final int nCoefs = coefMatrix.columnCount(); final int nInts = this._solver.getKnotsMat1D(xValuesSrt).size() - 1; for (int i = 0; i < nInts; ++i) { for (int j = 0; j < nCoefs; ++j) { ArgChecker.isFalse(Double.isNaN(coefMatrix.get(i, j)), "Too large input"); ArgChecker.isFalse(Double.isInfinite(coefMatrix.get(i, j)), "Too large input"); } } return new PiecewisePolynomialResult(this._solver.getKnotsMat1D(xValuesSrt), coefMatrix, nCoefs, 1); } /** * @param xValues X values of data * @param yValuesMatrix Y values of data, where NumberOfRow defines dimension of the spline * @return {@link PiecewisePolynomialResult} containing knots, coefficients of piecewise polynomials, number of intervals, degree of polynomials, dimension of spline */ @Override public PiecewisePolynomialResult interpolate(final double[] xValues, final double[][] yValuesMatrix) { ArgChecker.notNull(xValues, "xValues"); ArgChecker.notNull(yValuesMatrix, "yValuesMatrix"); ArgChecker.isTrue(xValues.length == yValuesMatrix[0].length, "(xValues length = yValuesMatrix's row vector length)"); ArgChecker.isTrue(xValues.length > 1, "Data points should be more than 1"); final int nDataPts = xValues.length; final int dim = yValuesMatrix.length; for (int i = 0; i < nDataPts; ++i) { ArgChecker.isFalse(Double.isNaN(xValues[i]), "xData containing NaN"); ArgChecker.isFalse(Double.isInfinite(xValues[i]), "xData containing Infinity"); for (int j = 0; j < dim; ++j) { ArgChecker.isFalse(Double.isNaN(yValuesMatrix[j][i]), "yValuesMatrix containing NaN"); ArgChecker.isFalse(Double.isInfinite(yValuesMatrix[j][i]), "yValuesMatrix containing Infinity"); } } for (int k = 0; k < dim; ++k) { for (int i = 0; i < nDataPts; ++i) { for (int j = i + 1; j < nDataPts; ++j) { ArgChecker.isFalse(xValues[i] == xValues[j], "Data should be distinct"); } } } double[] xValuesSrt = new double[nDataPts]; double[][] yValuesMatrixSrt = new double[dim][nDataPts]; for (int i = 0; i < dim; ++i) { xValuesSrt = Arrays.copyOf(xValues, nDataPts); double[] yValuesSrt = Arrays.copyOf(yValuesMatrix[i], nDataPts); DoubleArrayMath.sortPairs(xValuesSrt, yValuesSrt); yValuesMatrixSrt[i] = Arrays.copyOf(yValuesSrt, nDataPts); } DoubleMatrix[] coefMatrix = this._solver.solveMultiDim(xValuesSrt, DoubleMatrix.copyOf(yValuesMatrixSrt)); final int nIntervals = coefMatrix[0].rowCount(); final int nCoefs = coefMatrix[0].columnCount(); double[][] resMatrix = new double[dim * nIntervals][nCoefs]; for (int i = 0; i < nIntervals; ++i) { for (int j = 0; j < dim; ++j) { resMatrix[dim * i + j] = coefMatrix[j].row(i).toArray(); } } for (int i = 0; i < dim * nIntervals; ++i) { for (int j = 0; j < nCoefs; ++j) { ArgChecker.isFalse(Double.isNaN(resMatrix[i][j]), "Too large input"); ArgChecker.isFalse(Double.isInfinite(resMatrix[i][j]), "Too large input"); } } return new PiecewisePolynomialResult(this._solver.getKnotsMat1D(xValuesSrt), DoubleMatrix.copyOf(resMatrix), nCoefs, dim); } @Override public PiecewisePolynomialResultsWithSensitivity interpolateWithSensitivity(final double[] xValues, final double[] yValues) { ArgChecker.notNull(xValues, "xValues"); ArgChecker.notNull(yValues, "yValues"); ArgChecker.isTrue(xValues.length == yValues.length, "(xValues length = yValues length)"); ArgChecker.isTrue(xValues.length > 1, "Data points should be more than 1"); final int nDataPts = xValues.length; final int nYdata = yValues.length; for (int i = 0; i < nDataPts; ++i) { ArgChecker.isFalse(Double.isNaN(xValues[i]), "xData containing NaN"); ArgChecker.isFalse(Double.isInfinite(xValues[i]), "xData containing Infinity"); } for (int i = 0; i < nYdata; ++i) { ArgChecker.isFalse(Double.isNaN(yValues[i]), "yData containing NaN"); ArgChecker.isFalse(Double.isInfinite(yValues[i]), "yData containing Infinity"); } for (int i = 0; i < nDataPts; ++i) { for (int j = i + 1; j < nDataPts; ++j) { ArgChecker.isFalse(xValues[i] == xValues[j], "Data should be distinct"); } } final DoubleMatrix[] resMatrix = this._solver.solveWithSensitivity(xValues, yValues); final int len = resMatrix.length; for (int k = 0; k < len; k++) { DoubleMatrix m = resMatrix[k]; final int rows = m.rowCount(); final int cols = m.columnCount(); for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { ArgChecker.isTrue(Doubles.isFinite(m.get(i, j)), "Matrix contains a NaN or infinite"); } } } final DoubleMatrix coefMatrix = resMatrix[0]; final DoubleMatrix[] coefSenseMatrix = new DoubleMatrix[len - 1]; System.arraycopy(resMatrix, 1, coefSenseMatrix, 0, len - 1); final int nCoefs = coefMatrix.columnCount(); return new PiecewisePolynomialResultsWithSensitivity(this._solver.getKnotsMat1D(xValues), coefMatrix, nCoefs, 1, coefSenseMatrix); } }
package hu.bme.mit.mobilgen.layoutgenerator.psdprocessor; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Iterator; import java.util.Locale; import java.util.Map.Entry; import psd.Layer; import psd.LayersContainer; import psdstructure.AdView; import psdstructure.BackgroundImage; import psdstructure.Button; import psdstructure.Checkbox; import psdstructure.DatePicker; import psdstructure.Grid; import psdstructure.Image; import psdstructure.Map; import psdstructure.ProgressBar; import psdstructure.ProgressSpinner; import psdstructure.PsdstructureFactory; import psdstructure.RadioButton; import psdstructure.Scroll; import psdstructure.Select; import psdstructure.SelectOption; import psdstructure.Slider; import psdstructure.Switch; import psdstructure.Text; import psdstructure.Vector; import psdstructure.View; import psdstructure.ViewGroup; import psdstructure.WebView; public class PsdStructureFactory { public View createView(LayerName name, LayersContainer layer){ View view = null; PsdstructureFactory factory = PsdstructureFactory.eINSTANCE; switch (name.getType()) { case LayerType.PROGRESS_SPINNER: view = factory.createProgressSpinner(); initView((ProgressSpinner)view, name); break; case LayerType.ADVIEW: view = factory.createAdView(); initView((AdView)view, name); break; case LayerType.BUTTON: view = factory.createButton(); initView((Button)view, name); break; case LayerType.CHECKBOX: view = factory.createCheckbox(); initView((Checkbox)view, name); break; case LayerType.DATEPICKER: view = factory.createDatePicker(); initView((DatePicker)view, name); break; case LayerType.GRID: view = factory.createGrid(); initView((Grid)view, name); break; case LayerType.IMAGE: view = factory.createImage(); initView((Image)view, name); break; case LayerType.MAP: view = factory.createMap(); initView((Map)view, name); break; case LayerType.PROGRESS_BAR: view = factory.createProgressBar(); initView((ProgressBar)view, name); break; case LayerType.RADIOBUTTON: view = factory.createRadioButton(); initView((RadioButton)view, name); break; case LayerType.SCROLL: view = factory.createScroll(); initView((Scroll)view, name); break; case LayerType.SELECT: view = factory.createSelect(); initView((Select)view, name); break; case LayerType.SLIDER: view = factory.createSlider(); initView((Slider)view, name); break; case LayerType.SWITCH: view = factory.createSwitch(); initView((Switch)view, name); break; case LayerType.TEXT: view = factory.createText(); initView((Text)view, name); break; case LayerType.WEBVIEW: view = factory.createWebView(); initView((WebView)view, name); break; default: if(layer.getLayersCount() > 0) { view = factory.createViewGroup(); initView((ViewGroup)view, name); } else { return view; } break; } setBaseProperties(view, name, layer); if(layer.getLayersCount() == 0) { // create background image with the content view.getBackgrounds().add(createBackgroundImage((Layer) layer)); } return view; } public BackgroundImage createBackgroundImage(Layer layer) { BackgroundImage image = PsdstructureFactory.eINSTANCE.createBackgroundImage(); image.setImage(LayerName.processLayerName(layer.toString()).getName().toLowerCase()); Vector size = PsdstructureFactory.eINSTANCE.createVector(); size.setX(layer.getWidth()); size.setY(layer.getHeight()); image.setSize(size); Vector pos = PsdstructureFactory.eINSTANCE.createVector(); pos.setX(layer.getX()); pos.setY(layer.getY()); image.setPos(pos); return image; } private void setBaseProperties(View view, LayerName name, LayersContainer layer) { // store id view.setID(name.getName()); // set position Vector pos = findTopLeftCorner(layer); view.setPos(pos); // set size Vector bottomRight = findBottomRightCorner(layer); Vector size = PsdstructureFactory.eINSTANCE.createVector(); size.setX(bottomRight.getX() - pos.getX()); size.setY(bottomRight.getY() - pos.getY()); view.setSize(size); } private void initView(ProgressSpinner view, LayerName name) { // no specific property yet } private void initView(AdView view, LayerName name) { if(name.getProperties().containsKey("unitid")){ view.setUnitid(name.getProperties().get("unitid")); } } private void initView(Button view, LayerName name) { if(name.getProperties().containsKey("text")){ view.setText(name.getProperties().get("text")); } } private void initView(Checkbox view, LayerName name) { if(name.getProperties().containsKey("value")){ view.setValue(name.getProperties().get("value")); } if(name.getProperties().containsKey("checked") || name.getProperties().containsKey("selected")){ view.setSelected(true); } } private void initView(DatePicker view, LayerName name) { if (name.getProperties().containsKey("min")) { try { view.setMin(new SimpleDateFormat("yyyy-MM-d", Locale.ENGLISH).parse(name.getProperties().get("min"))); } catch (ParseException e) { e.printStackTrace(); } } if (name.getProperties().containsKey("max")) { try { view.setMax(new SimpleDateFormat("yyyy-MM-d", Locale.ENGLISH).parse(name.getProperties().get("max"))); } catch (ParseException e) { e.printStackTrace(); } } if (name.getProperties().containsKey("default")) { try { view.setDefault(new SimpleDateFormat("yyyy-MM-d", Locale.ENGLISH).parse(name.getProperties().get("default"))); } catch (ParseException e) { e.printStackTrace(); } } } private void initView(Grid view, LayerName name) { if(name.getProperties().containsKey("cols")){ view.setCols(Integer.parseInt(name.getProperties().get("cols"))); } if(name.getProperties().containsKey("rows")){ view.setRows(Integer.parseInt(name.getProperties().get("rows"))); } } private void initView(Image view, LayerName name) { // no specific property yet } private void initView(Map view, LayerName name) { if(name.getProperties().containsKey("clickable")){ view.setClickable(true); } else { view.setClickable(false); } if(name.getProperties().containsKey("apikey")){ view.setApikey(name.getProperties().get("apikey")); } } private void initView(ProgressBar view, LayerName name) { // no specific property yet } private void initView(RadioButton view, LayerName name) { if(name.getProperties().containsKey("value")){ view.setValue(name.getProperties().get("value")); } if(name.getProperties().containsKey("selected")){ view.setSelected(true); } } private void initView(Scroll view, LayerName name) { // no specific property yet } private void initView(Select view, LayerName name) { for (String key : name.getProperties().keySet()) { if(!key.equals("default")){ SelectOption option = PsdstructureFactory.eINSTANCE.createSelectOption(); option.setLabel(key); option.setValue(name.getProperties().get(key)); view.getOptions().add(option); if(name.getProperties().containsKey("default") && name.getProperties().get("default").equals(key)){ view.setDefault(option); } } } } private void initView(Slider view, LayerName name) { if(name.getProperties().containsKey("max")){ view.setMax(Integer.parseInt(name.getProperties().get("max"))); } if(name.getProperties().containsKey("default")){ view.setDefault(Integer.parseInt(name.getProperties().get("default"))); } } private void initView(Switch view, LayerName name) { if(name.getProperties().containsKey("selected")){ view.setSelected(true); } else { view.setSelected(false); } } private void initView(Text view, LayerName name) { if(name.getProperties().containsKey("editable")){ view.setEditable(true); } else { view.setEditable(false); } if(name.getProperties().containsKey("text")){ view.setText(name.getProperties().get("text")); } if(name.getProperties().containsKey("type")){ switch(name.getProperties().get("type")){ case "textpassword": view.setType("textPassword"); break; default: view.setType(name.getProperties().get("type")); break; } } } private void initView(WebView view, LayerName name) { if(name.getProperties().containsKey("url")) { view.setUrl(name.getProperties().get("url")); } } private void initView(ViewGroup view, LayerName name) { } private Vector findTopLeftCorner(LayersContainer layer) { Vector pos = PsdstructureFactory.eINSTANCE.createVector(); pos.setX(999999999); pos.setY(999999999); if(layer.getLayersCount() == 0) { pos.setX(layer.getX()); pos.setY(layer.getY()); return pos; } for (int i = 0; i < layer.getLayersCount(); i++) { if(layer.getLayer(i).getLayersCount() > 0) { Vector tmppos = findTopLeftCorner(layer.getLayer(i)); if(tmppos.getX() < pos.getX()){ pos.setX(tmppos.getX()); } if(tmppos.getY() < pos.getY()){ pos.setY(tmppos.getY()); } } else { if(layer.getLayer(i).getX() < pos.getX() || i == 0){ pos.setX(layer.getLayer(i).getX()); } if(layer.getLayer(i).getY() < pos.getY() || i == 0){ pos.setY(layer.getLayer(i).getY()); } } } return pos; } private Vector findBottomRightCorner(LayersContainer layer) { Vector pos = PsdstructureFactory.eINSTANCE.createVector(); if(layer.getLayersCount() == 0) { pos.setX(layer.getRight()); pos.setY(layer.getBottom()); return pos; } for (int i = 0; i < layer.getLayersCount(); i++) { if(layer.getLayer(i).getLayersCount() > 0) { Vector tmppos = findBottomRightCorner(layer.getLayer(i)); if(tmppos.getX() > pos.getX()){ pos.setX(tmppos.getX()); } if(tmppos.getY() > pos.getY()){ pos.setY(tmppos.getY()); } } else { if(layer.getLayer(i).getRight() > pos.getX()){ pos.setX(layer.getLayer(i).getRight()); } if(layer.getLayer(i).getBottom() > pos.getY()){ pos.setY(layer.getLayer(i).getBottom()); } } } return pos; } public View createBaseView(LayerName name, LayersContainer layer) { View baseView = PsdstructureFactory.eINSTANCE.createViewGroup(); setBaseProperties(baseView, name, layer); initView((ViewGroup)baseView, name); return null; } }
/* * Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights * Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.amazonaws.services.iot.model; import java.io.Serializable; /** * <p> * The output of the CreateKeysAndCertificate operation. * </p> */ public class CreateKeysAndCertificateResult implements Serializable, Cloneable { /** * <p> * The ARN of the certificate. * </p> */ private String certificateArn; /** * <p> * The ID of the certificate. AWS IoT issues a default subject name for the * certificate (for example, AWS IoT Certificate). * </p> */ private String certificateId; /** * <p> * The certificate data, in PEM format. * </p> */ private String certificatePem; /** * <p> * The generated key pair. * </p> */ private KeyPair keyPair; /** * <p> * The ARN of the certificate. * </p> * * @param certificateArn * The ARN of the certificate. */ public void setCertificateArn(String certificateArn) { this.certificateArn = certificateArn; } /** * <p> * The ARN of the certificate. * </p> * * @return The ARN of the certificate. */ public String getCertificateArn() { return this.certificateArn; } /** * <p> * The ARN of the certificate. * </p> * * @param certificateArn * The ARN of the certificate. * @return Returns a reference to this object so that method calls can be * chained together. */ public CreateKeysAndCertificateResult withCertificateArn( String certificateArn) { setCertificateArn(certificateArn); return this; } /** * <p> * The ID of the certificate. AWS IoT issues a default subject name for the * certificate (for example, AWS IoT Certificate). * </p> * * @param certificateId * The ID of the certificate. AWS IoT issues a default subject name * for the certificate (for example, AWS IoT Certificate). */ public void setCertificateId(String certificateId) { this.certificateId = certificateId; } /** * <p> * The ID of the certificate. AWS IoT issues a default subject name for the * certificate (for example, AWS IoT Certificate). * </p> * * @return The ID of the certificate. AWS IoT issues a default subject name * for the certificate (for example, AWS IoT Certificate). */ public String getCertificateId() { return this.certificateId; } /** * <p> * The ID of the certificate. AWS IoT issues a default subject name for the * certificate (for example, AWS IoT Certificate). * </p> * * @param certificateId * The ID of the certificate. AWS IoT issues a default subject name * for the certificate (for example, AWS IoT Certificate). * @return Returns a reference to this object so that method calls can be * chained together. */ public CreateKeysAndCertificateResult withCertificateId(String certificateId) { setCertificateId(certificateId); return this; } /** * <p> * The certificate data, in PEM format. * </p> * * @param certificatePem * The certificate data, in PEM format. */ public void setCertificatePem(String certificatePem) { this.certificatePem = certificatePem; } /** * <p> * The certificate data, in PEM format. * </p> * * @return The certificate data, in PEM format. */ public String getCertificatePem() { return this.certificatePem; } /** * <p> * The certificate data, in PEM format. * </p> * * @param certificatePem * The certificate data, in PEM format. * @return Returns a reference to this object so that method calls can be * chained together. */ public CreateKeysAndCertificateResult withCertificatePem( String certificatePem) { setCertificatePem(certificatePem); return this; } /** * <p> * The generated key pair. * </p> * * @param keyPair * The generated key pair. */ public void setKeyPair(KeyPair keyPair) { this.keyPair = keyPair; } /** * <p> * The generated key pair. * </p> * * @return The generated key pair. */ public KeyPair getKeyPair() { return this.keyPair; } /** * <p> * The generated key pair. * </p> * * @param keyPair * The generated key pair. * @return Returns a reference to this object so that method calls can be * chained together. */ public CreateKeysAndCertificateResult withKeyPair(KeyPair keyPair) { setKeyPair(keyPair); return this; } /** * Returns a string representation of this object; useful for testing and * debugging. * * @return A string representation of this object. * * @see java.lang.Object#toString() */ @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("{"); if (getCertificateArn() != null) sb.append("CertificateArn: " + getCertificateArn() + ","); if (getCertificateId() != null) sb.append("CertificateId: " + getCertificateId() + ","); if (getCertificatePem() != null) sb.append("CertificatePem: " + getCertificatePem() + ","); if (getKeyPair() != null) sb.append("KeyPair: " + getKeyPair()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof CreateKeysAndCertificateResult == false) return false; CreateKeysAndCertificateResult other = (CreateKeysAndCertificateResult) obj; if (other.getCertificateArn() == null ^ this.getCertificateArn() == null) return false; if (other.getCertificateArn() != null && other.getCertificateArn().equals(this.getCertificateArn()) == false) return false; if (other.getCertificateId() == null ^ this.getCertificateId() == null) return false; if (other.getCertificateId() != null && other.getCertificateId().equals(this.getCertificateId()) == false) return false; if (other.getCertificatePem() == null ^ this.getCertificatePem() == null) return false; if (other.getCertificatePem() != null && other.getCertificatePem().equals(this.getCertificatePem()) == false) return false; if (other.getKeyPair() == null ^ this.getKeyPair() == null) return false; if (other.getKeyPair() != null && other.getKeyPair().equals(this.getKeyPair()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getCertificateArn() == null) ? 0 : getCertificateArn() .hashCode()); hashCode = prime * hashCode + ((getCertificateId() == null) ? 0 : getCertificateId() .hashCode()); hashCode = prime * hashCode + ((getCertificatePem() == null) ? 0 : getCertificatePem() .hashCode()); hashCode = prime * hashCode + ((getKeyPair() == null) ? 0 : getKeyPair().hashCode()); return hashCode; } @Override public CreateKeysAndCertificateResult clone() { try { return (CreateKeysAndCertificateResult) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException( "Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
/* * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* * RegOptimizer.java * Copyright (C) 2006 University of Waikato, Hamilton, New Zealand * */ package weka.classifiers.functions.supportVector; import weka.classifiers.functions.SMOreg; import weka.core.Instance; import weka.core.Instances; import weka.core.Option; import weka.core.OptionHandler; import weka.core.RevisionHandler; import weka.core.RevisionUtils; import weka.core.Utils; import java.io.Serializable; import java.util.Enumeration; import java.util.Random; import java.util.Vector; /** * Base class implementation for learning algorithm of SMOreg * <!-- options-start --> * Valid options are: <p/> * * <pre> -L &lt;double&gt; * The epsilon parameter in epsilon-insensitive loss function. * (default 1.0e-3)</pre> * * <pre> -W &lt;double&gt; * The random number seed. * (default 1)</pre> * <!-- options-end --> * * @author Remco Bouckaert (remco@cs.waikato.ac.nz,rrb@xm.co.nz) * @version $Revision: 6622 $ */ public class RegOptimizer implements OptionHandler, Serializable, RevisionHandler { /** for serialization */ private static final long serialVersionUID = -2198266997254461814L; /** loss type **/ //protected int m_nLossType = EPSILON; /** the loss type: L1 */ //public final static int L1 = 1; /** the loss type: L2 */ //public final static int L2 = 2; /** the loss type: HUBER */ //public final static int HUBER = 3; /** the loss type: EPSILON */ //public final static int EPSILON = 4; /** the loss type */ //public static final Tag[] TAGS_LOSS_TYPE = { // new Tag(L2, "L2"), // new Tag(L1, "L1"), // new Tag(HUBER, "Huber"), // new Tag(EPSILON, "EPSILON"), //}; /** alpha and alpha* arrays containing weights for solving dual problem **/ public double[] m_alpha; public double[] m_alphaStar; /** offset **/ protected double m_b; /** epsilon of epsilon-insensitive cost function **/ protected double m_epsilon = 1e-3; /** capacity parameter, copied from SMOreg **/ protected double m_C = 1.0; /** class values/desired output vector **/ protected double[] m_target; /** points to data set **/ protected Instances m_data; /** the kernel */ protected Kernel m_kernel; /** index of class variable in data set **/ protected int m_classIndex = -1; /** number of instances in data set **/ protected int m_nInstances = -1; /** random number generator **/ protected Random m_random; /** seed for initializing random number generator **/ protected int m_nSeed = 1; /** set of support vectors, that is, vectors with alpha(*)!=0 **/ protected SMOset m_supportVectors; /** number of kernel evaluations, used for printing statistics only **/ protected int m_nEvals = 0; /** number of kernel cache hits, used for printing statistics only **/ protected int m_nCacheHits = -1; /** weights for linear kernel **/ protected double[] m_weights; /** Variables to hold weight vector in sparse form. (To reduce storage requirements.) */ protected double[] m_sparseWeights; protected int[] m_sparseIndices; /** flag to indicate whether the model is built yet **/ protected boolean m_bModelBuilt = false; /** parent SMOreg class **/ protected SMOreg m_SVM = null; /** * the default constructor */ public RegOptimizer() { super(); m_random = new Random(m_nSeed); } /** * Gets an enumeration describing the available options. * * @return an enumeration of all the available options. */ public Enumeration listOptions() { Vector result = new Vector(); result.addElement(new Option( "\tThe epsilon parameter in epsilon-insensitive loss function.\n" + "\t(default 1.0e-3)", "L", 1, "-L <double>")); // result.addElement(new Option( // "\tLoss type (L1, L2, Huber, Epsilon insensitive loss)\n", // "L", 1, "-L [L1|L2|HUBER|EPSILON]")); result.addElement(new Option( "\tThe random number seed.\n" + "\t(default 1)", "W", 1, "-W <double>")); return result.elements(); } /** * Parses a given list of options. <p/> * <!-- options-start --> * Valid options are: <p/> * * <pre> -L &lt;double&gt; * The epsilon parameter in epsilon-insensitive loss function. * (default 1.0e-3)</pre> * * <pre> -W &lt;double&gt; * The random number seed. * (default 1)</pre> * <!-- options-end --> * * @param options the list of options as an array of strings * @throws Exception if an option is not supported */ public void setOptions(String[] options) throws Exception { String tmpStr; tmpStr = Utils.getOption('L', options); if (tmpStr.length() != 0) { setEpsilonParameter(Double.parseDouble(tmpStr)); } else { setEpsilonParameter(1.0e-3); } /* tmpStr = Utils.getOption('S', options); if (tmpStr.length() != 0) setLossType(new SelectedTag(tmpStr, TAGS_LOSS_TYPE)); else setLossType(new SelectedTag(EPSILON, TAGS_LOSS_TYPE)); */ tmpStr = Utils.getOption('W', options); if (tmpStr.length() != 0) { setSeed(Integer.parseInt(tmpStr)); } else { setSeed(1); } } /** * Gets the current settings of the classifier. * * @return an array of strings suitable for passing to setOptions */ public String[] getOptions() { Vector result; result = new Vector(); result.add("-L"); result.add("" + getEpsilonParameter()); result.add("-W"); result.add("" + getSeed()); //result.add("-S"; //result.add((new SelectedTag(m_nLossType, TAGS_LOSS_TYPE)).getSelectedTag().getReadable(); return (String[]) result.toArray(new String[result.size()]); } /** * flag to indicate whether the model was built yet * * @return true if the model was built */ public boolean modelBuilt() { return m_bModelBuilt; } /** * sets the parent SVM * * @param value the parent SVM */ public void setSMOReg(SMOreg value) { m_SVM = value; } /** * returns the number of kernel evaluations * * @return the number of kernel evaluations */ public int getKernelEvaluations() { return m_nEvals; } /** * return the number of kernel cache hits * * @return the number of hits */ public int getCacheHits() { return m_nCacheHits; } /** * initializes the algorithm * * @param data the data to work with * @throws Exception if m_SVM is null */ protected void init(Instances data) throws Exception { if (m_SVM == null) { throw new Exception ("SVM not initialized in optimizer. Use RegOptimizer.setSVMReg()"); } m_C = m_SVM.getC(); m_data = data; m_classIndex = data.classIndex(); m_nInstances = data.numInstances(); // Initialize kernel m_kernel = Kernel.makeCopy(m_SVM.getKernel()); m_kernel.buildKernel(data); //init m_target m_target = new double[m_nInstances]; for (int i = 0; i < m_nInstances; i++) { m_target[i] = data.instance(i).classValue(); } m_random = new Random(m_nSeed); // initialize alpha and alpha* array to all zero m_alpha = new double[m_target.length]; m_alphaStar = new double[m_target.length]; m_supportVectors = new SMOset(m_nInstances); m_b = 0.0; m_nEvals = 0; m_nCacheHits = -1; } /** * wrap up various variables to save memeory and do some housekeeping after optimization * has finished. * * @throws Exception if something goes wrong */ protected void wrapUp() throws Exception { m_target = null; m_nEvals = m_kernel.numEvals(); m_nCacheHits = m_kernel.numCacheHits(); if ((m_SVM.getKernel() instanceof PolyKernel) && ((PolyKernel) m_SVM.getKernel()).getExponent() == 1.0) { // convert alpha's to weights double [] weights = new double[m_data.numAttributes()]; for (int k = m_supportVectors.getNext(-1); k != -1; k = m_supportVectors.getNext(k)) { for (int j = 0; j < weights.length; j++) { if (j != m_classIndex) { weights[j] += (m_alpha[k] - m_alphaStar[k]) * m_data.instance(k).value(j); } } } m_weights = weights; // release memory m_alpha = null; m_alphaStar = null; m_kernel = null; } m_bModelBuilt = true; } /** * Compute the value of the objective function. * * @return the score * @throws Exception if something goes wrong */ protected double getScore() throws Exception { double res = 0; double t = 0, t2 = 0; double sumAlpha = 0.0; for (int i = 0; i < m_nInstances; i++) { sumAlpha += (m_alpha[i] - m_alphaStar[i]); for (int j = 0; j < m_nInstances; j++) { t += (m_alpha[i] - m_alphaStar[i]) * (m_alpha[j] - m_alphaStar[j]) * m_kernel.eval(i, j, m_data.instance(i)); } // switch(m_nLossType) { // case L1: // t2 += m_data.instance(i).classValue() * (m_alpha[i] - m_alpha_[i]); // break; // case L2: // t2 += m_data.instance(i).classValue() * (m_alpha[i] - m_alpha_[i]) - (0.5/m_SVM.getC()) * (m_alpha[i]*m_alpha[i] + m_alpha_[i]*m_alpha_[i]); // break; // case HUBER: // t2 += m_data.instance(i).classValue() * (m_alpha[i] - m_alpha_[i]) - (0.5*m_SVM.getEpsilon()/m_SVM.getC()) * (m_alpha[i]*m_alpha[i] + m_alpha_[i]*m_alpha_[i]); // break; // case EPSILON: //t2 += m_data.instance(i).classValue() * (m_alpha[i] - m_alphaStar[i]) - m_epsilon * (m_alpha[i] + m_alphaStar[i]); t2 += m_target[i] * (m_alpha[i] - m_alphaStar[i]) - m_epsilon * (m_alpha[i] + m_alphaStar[i]); // break; // } } res += -0.5 * t + t2; return res; } /** * learn SVM parameters from data. * Subclasses should implement something more interesting. * * @param data the data to work with * @throws Exception always an Exceoption since subclasses must override it */ public void buildClassifier(Instances data) throws Exception { throw new Exception("Don't call this directly, use subclass instead"); } /** * sets the loss type type to use * * @param newLossType the loss type to use */ //public void setLossType(SelectedTag newLossType) { // if (newLossType.getTags() == TAGS_LOSS_TYPE) { // m_nLossType = newLossType.getSelectedTag().getID(); // } //} /** * returns the current loss type * * @return the loss type */ //public SelectedTag getLossType() { // return new SelectedTag(m_nLossType, TAGS_LOSS_TYPE); //} /** * SVMOutput of an instance in the training set, m_data * This uses the cache, unlike SVMOutput(Instance) * * @param index index of the training instance in m_data * @return the SVM output * @throws Exception if something goes wrong */ protected double SVMOutput(int index) throws Exception { double result = -m_b; for (int i = m_supportVectors.getNext(-1); i != -1; i = m_supportVectors.getNext(i)) { result += (m_alpha[i] - m_alphaStar[i]) * m_kernel.eval(index, i, m_data.instance(index)); } return result; } /** * * @param inst * @return * @throws Exception */ public double SVMOutput(Instance inst) throws Exception { double result = -m_b; // Is the machine linear? if (m_weights != null) { // Is weight vector stored in sparse format? for (int i = 0; i < inst.numValues(); i++) { if (inst.index(i) != m_classIndex) { result += m_weights[inst.index(i)] * inst.valueSparse(i); } } } else { for (int i = m_supportVectors.getNext(-1); i != -1; i = m_supportVectors.getNext(i)) { result += (m_alpha[i] - m_alphaStar[i]) * m_kernel.eval(-1, i, inst); } } return result; } /** * Returns the tip text for this property * * @return tip text for this property suitable for * displaying in the explorer/experimenter gui */ public String seedTipText() { return "Seed for random number generator."; } /** * Gets the current seed value for the random number generator * * @return the seed value */ public int getSeed() { return m_nSeed; } /** * Sets the seed value for the random number generator * * @param value the seed value */ public void setSeed(int value) { m_nSeed = value; } /** * Returns the tip text for this property * * @return tip text for this property suitable for * displaying in the explorer/experimenter gui */ public String epsilonParameterTipText() { return "The epsilon parameter of the epsilon insensitive loss function.(default 0.001)."; } /** * Get the value of epsilon parameter of the epsilon insensitive loss function. * * @return Value of epsilon parameter. */ public double getEpsilonParameter() { return m_epsilon; } /** * Set the value of epsilon parameter of the epsilon insensitive loss function. * * @param v Value to assign to epsilon parameter. */ public void setEpsilonParameter(double v) { m_epsilon = v; } /** * Prints out the classifier. * * @return a description of the classifier as a string */ public String toString() { StringBuffer text = new StringBuffer(); text.append("SMOreg\n\n"); if (m_weights != null) { text.append("weights (not support vectors):\n"); // it's a linear machine for (int i = 0; i < m_data.numAttributes(); i++) { if (i != m_classIndex) { text.append((m_weights[i] >= 0 ? " + " : " - ") + Utils.doubleToString(Math.abs(m_weights[i]), 12, 4) + " * "); if (m_SVM.getFilterType().getSelectedTag().getID() == SMOreg.FILTER_STANDARDIZE) { text.append("(standardized) "); } else if (m_SVM.getFilterType().getSelectedTag().getID() == SMOreg.FILTER_NORMALIZE) { text.append("(normalized) "); } text.append(m_data.attribute(i).name() + "\n"); } } } else { // non linear, print out all supportvectors text.append("Support vectors:\n"); for (int i = 0; i < m_nInstances; i++) { if (m_alpha[i] > 0) { text.append("+" + m_alpha[i] + " * k[" + i + "]\n"); } if (m_alphaStar[i] > 0) { text.append("-" + m_alphaStar[i] + " * k[" + i + "]\n"); } } } text.append((m_b<=0?" + ":" - ") + Utils.doubleToString(Math.abs(m_b), 12, 4) + "\n\n"); text.append("\n\nNumber of kernel evaluations: " + m_nEvals); if (m_nCacheHits >= 0 && m_nEvals > 0) { double hitRatio = 1 - m_nEvals * 1.0 / (m_nCacheHits + m_nEvals); text.append(" (" + Utils.doubleToString(hitRatio * 100, 7, 3).trim() + "% cached)"); } return text.toString(); } /** * Returns the revision string. * * @return the revision */ public String getRevision() { return RevisionUtils.extract("$Revision: 6622 $"); } }
/* * ja, a Java-bytecode translator toolkit. * Copyright (C) 1999- Shigeru Chiba. All Rights Reserved. * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. Alternatively, the contents of this file may be used under * the terms of the GNU Lesser General Public License Version 2.1 or later, * or the Apache License Version 2.0. * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. */ package ja.tools.reflect; import java.lang.reflect.Method; import java.io.Serializable; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; /** * A runtime metaobject. * * <p> * A <code>Metaobject</code> is created for every object at the base level. A * different reflective object is associated with a different metaobject. * * <p> * The metaobject intercepts method calls on the reflective object at the * base-level. To change the behavior of the method calls, a subclass of * <code>Metaobject</code> should be defined. * * <p> * To obtain a metaobject, calls <code>_getMetaobject()</code> on a reflective * object. For example, * * <ul> * * <pre> * Metaobject m = ((Metalevel) reflectiveObject)._getMetaobject(); * </pre> * * </ul> * * @see ja.tools.reflect.ClassMetaobject * @see ja.tools.reflect.Metalevel */ public class Metaobject implements Serializable { protected ClassMetaobject classmetaobject; protected Metalevel baseobject; protected Method[] methods; /** * Constructs a <code>Metaobject</code>. The metaobject is constructed * before the constructor is called on the base-level object. * * @param self * the object that this metaobject is associated with. * @param args * the parameters passed to the constructor of <code>self</code>. */ public Metaobject(Object self, Object[] args) { baseobject = (Metalevel) self; classmetaobject = baseobject._getClass(); methods = classmetaobject.getReflectiveMethods(); } /** * Constructs a <code>Metaobject</code> without initialization. If calling * this constructor, a subclass should be responsible for initialization. */ protected Metaobject() { baseobject = null; classmetaobject = null; methods = null; } private void writeObject(ObjectOutputStream out) throws IOException { out.writeObject(baseobject); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { baseobject = (Metalevel) in.readObject(); classmetaobject = baseobject._getClass(); methods = classmetaobject.getReflectiveMethods(); } /** * Obtains the class metaobject associated with this metaobject. * * @see ja.tools.reflect.ClassMetaobject */ public final ClassMetaobject getClassMetaobject() { return classmetaobject; } /** * Obtains the object controlled by this metaobject. */ public final Object getObject() { return baseobject; } /** * Changes the object controlled by this metaobject. * * @param self * the object */ public final void setObject(Object self) { baseobject = (Metalevel) self; classmetaobject = baseobject._getClass(); methods = classmetaobject.getReflectiveMethods(); // call _setMetaobject() after the metaobject is settled. baseobject._setMetaobject(this); } /** * Returns the name of the method specified by <code>identifier</code>. */ public final String getMethodName(int identifier) { String mname = methods[identifier].getName(); int j = ClassMetaobject.methodPrefixLen; for (;;) { char c = mname.charAt(j++); if (c < '0' || '9' < c) break; } return mname.substring(j); } /** * Returns an array of <code>Class</code> objects representing the formal * parameter types of the method specified by <code>identifier</code>. */ public final Class[] getParameterTypes(int identifier) { return methods[identifier].getParameterTypes(); } /** * Returns a <code>Class</code> objects representing the return type of the * method specified by <code>identifier</code>. */ public final Class getReturnType(int identifier) { return methods[identifier].getReturnType(); } /** * Is invoked when public fields of the base-level class are read and the * runtime system intercepts it. This method simply returns the value of the * field. * * <p> * Every subclass of this class should redefine this method. */ public Object trapFieldRead(String name) { Class jc = getClassMetaobject().getJavaClass(); try { return jc.getField(name).get(getObject()); } catch (NoSuchFieldException e) { throw new RuntimeException(e.toString()); } catch (IllegalAccessException e) { throw new RuntimeException(e.toString()); } } /** * Is invoked when public fields of the base-level class are modified and * the runtime system intercepts it. This method simply sets the field to * the given value. * * <p> * Every subclass of this class should redefine this method. */ public void trapFieldWrite(String name, Object value) { Class jc = getClassMetaobject().getJavaClass(); try { jc.getField(name).set(getObject(), value); } catch (NoSuchFieldException e) { throw new RuntimeException(e.toString()); } catch (IllegalAccessException e) { throw new RuntimeException(e.toString()); } } /** * Is invoked when base-level method invocation is intercepted. This method * simply executes the intercepted method invocation with the original * parameters and returns the resulting value. * * <p> * Every subclass of this class should redefine this method. * * <p> * Note: this method is not invoked if the base-level method is invoked by a * constructor in the super class. For example, * * <ul> * * <pre> * abstract class A { * abstract void initialize(); * * A() { * initialize(); // not intercepted * } * } * * class B extends A { * void initialize() { * System.out.println(&quot;initialize()&quot;); * } * * B() { * super(); * initialize(); // intercepted * } * } * </pre> * * </ul> * * <p> * if an instance of B is created, the invocation of initialize() in B is * intercepted only once. The first invocation by the constructor in A is * not intercepted. This is because the link between a base-level object and * a metaobject is not created until the execution of a constructor of the * super class finishes. */ public Object trapMethodcall(int identifier, Object[] args) throws Throwable { try { return methods[identifier].invoke(getObject(), args); } catch (java.lang.reflect.InvocationTargetException e) { throw e.getTargetException(); } catch (java.lang.IllegalAccessException e) { throw new CannotInvokeException(e); } } }
package org.succlz123.okdownload; import android.content.Context; import android.util.Log; import com.squareup.okhttp.Call; import com.squareup.okhttp.Callback; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.squareup.okhttp.Response; import java.io.BufferedInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.RandomAccessFile; import java.util.List; /** * Created by succlz123 on 15/9/11. */ public class OkDownloadTask { private static final String TAG = "OkDownloadTask"; private Context mContext; private OkDatabaseHelp mOkDatabaseHelp; private OkHttpClient mOkHttpClient; private OkDownloadRequest mOkDownloadRequest; public OkDownloadTask(Context context, OkHttpClient okHttpClient, OkDatabaseHelp okDatabaseHelp) { if (context != null) { mContext = context; mOkDatabaseHelp = okDatabaseHelp; if (mOkDatabaseHelp == null) { mOkDatabaseHelp = OkDatabaseHelp.getInstance(mContext); } } if (okHttpClient != null) { mOkHttpClient = okHttpClient; } else { mOkHttpClient = OkHttpClientManager.getsInstance(); } } public void start(OkDownloadRequest okDownloadRequest, final OkDownloadEnqueueListener listener) { if (okDownloadRequest == null) { return; } mOkDownloadRequest = okDownloadRequest; final String url = mOkDownloadRequest.getUrl(); final String filePath = mOkDownloadRequest.getFilePath(); // get to write to the local file length // if the length is equals 0 , no such cached file // if the length is greater than 0 is already cached file size final File file = new File(filePath); final long range = file.length(); Request.Builder builder = new Request.Builder(); builder.url(url) .tag(url) .addHeader("User-Agent", "OkDownload") .addHeader("Connection", "Keep-Alive"); if (range > 0) { builder.addHeader("Range", "bytes=" + range + "-"); } Request okHttpRequest = builder.build(); Call call = mOkHttpClient.newCall(okHttpRequest); call.enqueue(new Callback() { @Override public void onFailure(final Request request, final IOException e) { listener.onError(new OkDownloadError(OkDownloadError.OKHTTP_ONFAILURE)); } @Override public void onResponse(Response response) { // code 2xx boolean isSuccessful = response.isSuccessful(); // code 3xx is url redirect boolean isRedirect = response.isRedirect(); Log.w(TAG, "OkDownload : http status code: " + response.code()); if (!isSuccessful && !isRedirect) { listener.onError(new OkDownloadError(OkDownloadError.OKHTTP_ONRESPONSE_FAIL)); return; } InputStream in = null; RandomAccessFile out = null; long fileLength = mOkDownloadRequest.getFileSize(); if (fileLength == 0) { mOkDownloadRequest.setStatus(OkDownloadStatus.START); mOkDownloadRequest.setStartTime(System.currentTimeMillis()); if (response.header("Content-Length") != null) { fileLength = Long.valueOf(response.header("Content-Length")); mOkDownloadRequest.setFileSize(fileLength); } writeDatabase(); listener.onStart(mOkDownloadRequest.getId()); } else { switch (mOkDownloadRequest.getStatus()) { case OkDownloadStatus.START: mOkDownloadRequest.setStatus(OkDownloadStatus.PAUSE); break; case OkDownloadStatus.PAUSE: mOkDownloadRequest.setStatus(OkDownloadStatus.START); listener.onRestart(); break; default: break; } updateDownloadStatus(); } if (filePath.startsWith("/data/data/")) { if (OkDownloadManager.getAvailableInternalMemorySize() - fileLength < 100 * 1024 * 1024) { listener.onError(new OkDownloadError(OkDownloadError.ANDROID_MEMORY_SIZE_IS_TOO_LOW)); return; } } else { if (OkDownloadManager.getAvailableExternalMemorySize() - fileLength < 100 * 1024 * 1024) { listener.onError(new OkDownloadError(OkDownloadError.ANDROID_MEMORY_SIZE_IS_TOO_LOW)); return; } } byte[] bytes = new byte[2048]; int len = 0; long curSize = 0; try { in = new BufferedInputStream(response.body().byteStream()); out = new RandomAccessFile(filePath, "rwd"); out.seek(range); while ((len = in.read(bytes)) != -1) { out.write(bytes, 0, len); curSize += len; if (fileLength != 0) { long cacheSize = file.length(); int progress = (int) (cacheSize * 100 / fileLength); listener.onProgress(progress, cacheSize, fileLength); } } if (fileLength != 0 && curSize == fileLength) { long finishTime = System.currentTimeMillis(); mOkDownloadRequest.setFinishTime(finishTime); mOkDownloadRequest.setFileSize(fileLength); mOkDownloadRequest.setStatus(OkDownloadStatus.FINISH); updateDatabase(); listener.onFinish(); } } catch (IOException e) { } finally { try { if (in != null) in.close(); } catch (IOException e) { } try { if (out != null) out.close(); } catch (IOException e) { } } } }); } public void pause(OkDownloadRequest okDownloadRequest, OkDownloadEnqueueListener okDownloadEnqueueListener) { mOkDownloadRequest = okDownloadRequest; mOkHttpClient.cancel(mOkDownloadRequest.getUrl()); mOkDownloadRequest.setStatus(OkDownloadStatus.PAUSE); updateDownloadStatus(); okDownloadEnqueueListener.onPause(); } public void cancel(String url, OkDownloadCancelListener listener) { mOkHttpClient.cancel(url); List<OkDownloadRequest> requestList = mOkDatabaseHelp.execQuery("url", url); if (requestList.size() > 0) { OkDownloadRequest queryRequest = requestList.get(0); if (queryRequest.getFilePath() == null) { return; } mOkDownloadRequest = queryRequest; deleteFile(); } mOkDatabaseHelp.execDelete("url", url); listener.onCancel(); } private void writeDatabase() { mOkDatabaseHelp.execInsert(mOkDownloadRequest); } private void updateDatabase() { mOkDatabaseHelp.execUpdate(mOkDownloadRequest); } private void updateDownloadStatus() { mOkDatabaseHelp.execUpdateDownloadStatus(mOkDownloadRequest); } private void deleteFile() { File file = new File(mOkDownloadRequest.getFilePath()); if (file.delete()) { Log.w(file.getName(), " is deleted!"); } else { Log.w(file.getName(), " delete operation is failed!"); } } }
package global.wrappers; import base.ElementVisitor; import com.intellij.icons.AllIcons; import com.intellij.ide.fileTemplates.FileTemplate; import com.intellij.openapi.project.Project; import com.intellij.openapi.ui.JBMenuItem; import com.intellij.openapi.ui.JBPopupMenu; import com.intellij.openapi.ui.ValidationInfo; import com.intellij.ui.EditorTextField; import core.actions.newPackageTemplate.dialogs.select.binaryFile.SelectBinaryFileDialog; import core.actions.newPackageTemplate.dialogs.select.fileTemplate.SelectFileTemplateDialog; import core.script.ScriptDialog; import core.search.customPath.CustomPath; import core.search.customPath.dialog.CustomPathDialog; import core.writeRules.dialog.WriteRulesDialog; import global.listeners.ClickListener; import global.models.BaseElement; import core.writeRules.WriteRules; import global.models.BinaryFile; import global.models.File; import global.utils.Logger; import global.utils.factories.GsonFactory; import global.utils.factories.WrappersFactory; import global.utils.i18n.Localizer; import global.utils.templates.FileTemplateHelper; import global.views.IconLabel; import global.views.IconLabelCustom; import icons.PluginIcons; import javax.swing.*; import java.awt.event.MouseEvent; /** * Created by CeH9 on 06.07.2016. */ public abstract class ElementWrapper extends BaseWrapper { private DirectoryWrapper parent; private PackageTemplateWrapper packageTemplateWrapper; //================================================================= // Abstraction //================================================================= public abstract void accept(ElementVisitor visitor); public abstract void buildView(Project project, JPanel container); public abstract void removeMyself(); public abstract void addElement(ElementWrapper element); public abstract BaseElement getElement(); public abstract boolean isDirectory(); public abstract ValidationInfo validateFields(); public abstract void setEnabled(boolean isEnabled); //================================================================= // UI //================================================================= public JLabel jlName; public EditorTextField etfDescription; public IconLabel jlCustomPath; public IconLabelCustom<? extends BaseElement> jlWriteRules; private void createPopupForEditMode(MouseEvent mouseEvent) { JPopupMenu popupMenu = new JBPopupMenu(); JMenuItem itemAddFile = new JBMenuItem(Localizer.get("AddFile"), AllIcons.FileTypes.Text); JMenuItem itemAddDirectory = new JBMenuItem(Localizer.get("AddDirectory"), AllIcons.Nodes.Package); JMenuItem itemAddBinaryFile = new JBMenuItem(Localizer.get("action.AddBinaryFile"), AllIcons.FileTypes.Text); JMenuItem itemEditSourcePath = new JBMenuItem(Localizer.get("action.EditSourcePath"), AllIcons.FileTypes.Text); JMenuItem itemChangeFileTemplate = new JBMenuItem(Localizer.get("action.ChangeFileTemplate"), AllIcons.Actions.Edit); JMenuItem itemDelete = new JBMenuItem(Localizer.get("Delete"), AllIcons.Actions.Delete); itemAddFile.addActionListener(e -> AddFile()); itemAddDirectory.addActionListener(e -> addDirectory()); itemAddBinaryFile.addActionListener(e -> addBinaryFile()); itemDelete.addActionListener(e -> deleteElement()); popupMenu.add(itemAddFile); popupMenu.add(itemAddDirectory); popupMenu.add(itemAddBinaryFile); // if NOT root element if (getParent() != null) { popupMenu.add(itemDelete); } // Dir Specific if (isDirectory()) { //nothing } else { // File Specific if (this instanceof FileWrapper) { itemChangeFileTemplate.addActionListener(e -> changeFileTemplate()); popupMenu.add(itemChangeFileTemplate); } else if (this instanceof BinaryFileWrapper){ itemEditSourcePath.addActionListener(e -> changeFileTemplate()); popupMenu.add(itemEditSourcePath); } } addScriptMenuItems(popupMenu); addCustomPathMenuItems(popupMenu); addWriteRulesMenuItems(popupMenu); popupMenu.show(jlName, mouseEvent.getX(), mouseEvent.getY()); } public void reBuildEllements() { packageTemplateWrapper.reBuildElements(); } //================================================================= // Menu items //================================================================= private void addScriptMenuItems(JPopupMenu popupMenu) { // With Script if (getElement().getScript() != null && !getElement().getScript().isEmpty()) { JMenuItem itemEdit = new JBMenuItem(Localizer.get("EditScript"), PluginIcons.SCRIPT); JMenuItem itemDelete = new JBMenuItem(Localizer.get("DeleteScript"), AllIcons.Actions.Delete); itemEdit.addActionListener(e -> new ScriptDialog( getPackageTemplateWrapper().getProject(), getElement().getScript()) { @Override public void onSuccess(String code) { getElement().setScript(code); updateComponentsState(); } }.show()); itemDelete.addActionListener(e -> { getElement().setScript(""); updateComponentsState(); }); popupMenu.add(itemEdit); popupMenu.add(itemDelete); } else { // Without Script JMenuItem itemAddScript = new JBMenuItem(Localizer.get("AddScript"), PluginIcons.SCRIPT); itemAddScript.addActionListener(e -> new ScriptDialog(getPackageTemplateWrapper().getProject()) { @Override public void onSuccess(String code) { getElement().setScript(code); updateComponentsState(); } }.show()); popupMenu.add(itemAddScript); } } private void addCustomPathMenuItems(JPopupMenu popupMenu) { if (getElement().getCustomPath() != null) { JMenuItem itemEdit = new JBMenuItem(Localizer.get("EditCustomPath"), PluginIcons.CUSTOM_PATH); JMenuItem itemDelete = new JBMenuItem(Localizer.get("DeleteCustomPath"), AllIcons.Actions.Delete); CustomPath customPath = getElement().getCustomPath() == null ? null : GsonFactory.cloneObject(getElement().getCustomPath(), CustomPath.class); itemEdit.addActionListener(e -> new CustomPathDialog(getPackageTemplateWrapper().getProject(), customPath) { @Override public void onSuccess(CustomPath customPath) { getElement().setCustomPath(customPath); updateComponentsState(); } }.show()); itemDelete.addActionListener(e -> { getElement().setCustomPath(null); updateComponentsState(); }); popupMenu.add(itemEdit); popupMenu.add(itemDelete); } else { JMenuItem itemAdd = new JBMenuItem(Localizer.get("AddCustomPath"), PluginIcons.CUSTOM_PATH); itemAdd.addActionListener(e -> new CustomPathDialog(getPackageTemplateWrapper().getProject(), null) { @Override public void onSuccess(CustomPath customPath) { getElement().setCustomPath(customPath); updateComponentsState(); } }.show()); popupMenu.add(itemAdd); } } private void addWriteRulesMenuItems(JPopupMenu popupMenu) { WriteRules writeRules = getElement().getWriteRules(); if (writeRules == null) { Logger.log("ElementWrapper getWriteRules NULL"); return; } JMenuItem itemEdit = new JBMenuItem(Localizer.get("EditWriteRules"), writeRules.toIcon()); itemEdit.addActionListener(e -> new WriteRulesDialog(getPackageTemplateWrapper().getProject(), writeRules, getParent() != null) { @Override public void onSuccess(WriteRules writeRules) { getElement().setWriteRules(writeRules); updateComponentsState(); } }.show()); popupMenu.add(itemEdit); } protected void updateOptionIcons() { if (getElement().getScript() != null && !getElement().getScript().isEmpty()) { jlScript.enableIcon(); } else { jlScript.disableIcon(); } if (getElement().getCustomPath() != null) { jlCustomPath.enableIcon(); } else { jlCustomPath.disableIcon(); } if (getElement().getWriteRules() != null) { jlWriteRules.updateIcon(); } } //================================================================= // Utils //================================================================= public void addMouseListener() { jlName.addMouseListener(new ClickListener() { @Override public void mouseClicked(MouseEvent mouseEvent) { if (SwingUtilities.isRightMouseButton(mouseEvent)) { switch (getPackageTemplateWrapper().getMode()) { case EDIT: case CREATE: createPopupForEditMode(mouseEvent); break; case USAGE: break; } } } }); } public void addDirectory() { getPackageTemplateWrapper().collectDataFromFields(); DirectoryWrapper dirParent; if (isDirectory()) { dirParent = ((DirectoryWrapper) this); } else { dirParent = getParent(); } dirParent.addElement(WrappersFactory.createNewWrappedDirectory(dirParent)); dirParent.reBuildEllements(); } public void deleteElement() { removeMyself(); getParent().getPackageTemplateWrapper().collectDataFromFields(); getParent().reBuildEllements(); } public void AddFile() { if (!FileTemplateHelper.isCurrentSchemeValid(packageTemplateWrapper.getProject(), packageTemplateWrapper.getPackageTemplate().getFileTemplateSource())) { return; } SelectFileTemplateDialog dialog = new SelectFileTemplateDialog(getPackageTemplateWrapper().getProject(), getPackageTemplateWrapper()) { @Override public void onSuccess(FileTemplate fileTemplate) { getPackageTemplateWrapper().collectDataFromFields(); DirectoryWrapper parent; if (isDirectory()) { parent = ((DirectoryWrapper) ElementWrapper.this); } else { parent = getParent(); } parent.addElement(WrappersFactory.createNewWrappedFile(parent, fileTemplate.getName(), fileTemplate.getExtension())); parent.reBuildEllements(); } @Override public void onCancel() { } }; dialog.show(); } private void changeFileTemplate() { if (!FileTemplateHelper.isCurrentSchemeValid(packageTemplateWrapper.getProject(), packageTemplateWrapper.getPackageTemplate().getFileTemplateSource())) { return; } SelectFileTemplateDialog dialog = new SelectFileTemplateDialog(getPackageTemplateWrapper().getProject(), getPackageTemplateWrapper()) { @Override public void onSuccess(FileTemplate fileTemplate) { getPackageTemplateWrapper().collectDataFromFields(); File file = (File) getElement(); file.setTemplateName(fileTemplate.getName()); file.setExtension(fileTemplate.getExtension()); parent.reBuildEllements(); } @Override public void onCancel() { } }; dialog.show(); } public void addBinaryFile() { SelectBinaryFileDialog dialog = new SelectBinaryFileDialog(getPackageTemplateWrapper().getProject(), null) { @Override public void onSuccess(BinaryFile binaryFile) { Logger.log("onSuccess"); getPackageTemplateWrapper().collectDataFromFields(); DirectoryWrapper parent; if (isDirectory()) { parent = ((DirectoryWrapper) ElementWrapper.this); } else { parent = getParent(); } parent.addElement(WrappersFactory.wrapBinaryFile(parent, binaryFile)); parent.reBuildEllements(); } @Override public void onCancel() { } }; dialog.show(); } //================================================================= // Getters | Setters //================================================================= public DirectoryWrapper getParent() { return parent; } public void setParent(DirectoryWrapper parent) { this.parent = parent; } public PackageTemplateWrapper getPackageTemplateWrapper() { return packageTemplateWrapper; } public void setPackageTemplateWrapper(PackageTemplateWrapper packageTemplateWrapper) { this.packageTemplateWrapper = packageTemplateWrapper; } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package org.apache.geode.internal.cache.execute; import java.io.Serializable; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.Set; import org.junit.Test; import org.junit.experimental.categories.Category; import org.apache.geode.cache.AttributesFactory; import org.apache.geode.cache.PartitionAttributesFactory; import org.apache.geode.cache.Region; import org.apache.geode.cache.execute.FunctionAdapter; import org.apache.geode.cache.execute.FunctionContext; import org.apache.geode.cache.execute.FunctionService; import org.apache.geode.cache.execute.RegionFunctionContext; import org.apache.geode.cache.partition.PartitionRegionHelper; import org.apache.geode.cache.query.Index; import org.apache.geode.cache.query.IndexType; import org.apache.geode.cache.query.QueryService; import org.apache.geode.cache.query.SelectResults; import org.apache.geode.cache.query.internal.DefaultQuery; import org.apache.geode.cache.query.internal.QueryObserverAdapter; import org.apache.geode.cache.query.internal.QueryObserverHolder; import org.apache.geode.cache30.CacheSerializableRunnable; import org.apache.geode.distributed.ConfigurationProperties; import org.apache.geode.internal.Assert; import org.apache.geode.internal.cache.BucketRegion; import org.apache.geode.internal.cache.GemFireCacheImpl; import org.apache.geode.internal.cache.LocalDataSet; import org.apache.geode.internal.cache.PartitionedRegion; import org.apache.geode.test.dunit.Host; import org.apache.geode.test.dunit.VM; import org.apache.geode.test.dunit.cache.internal.JUnit4CacheTestCase; import org.apache.geode.test.junit.categories.FunctionServiceTest; @Category({FunctionServiceTest.class}) public class LocalDataSetIndexingDUnitTest extends JUnit4CacheTestCase { protected static VM dataStore1 = null; protected static VM dataStore2 = null; public LocalDataSetIndexingDUnitTest() { super(); } @Override public final void postSetUp() throws Exception { Host host = Host.getHost(0); dataStore1 = host.getVM(0); dataStore2 = host.getVM(1); } @Override public Properties getDistributedSystemProperties() { Properties result = super.getDistributedSystemProperties(); result.put(ConfigurationProperties.SERIALIZABLE_OBJECT_FILTER, "org.apache.geode.internal.cache.execute.**;org.apache.geode.test.dunit.**"); return result; } @Test public void testLocalDataSetIndexing() { final CacheSerializableRunnable createPRs = new CacheSerializableRunnable("create prs ") { public void run2() { AttributesFactory<Integer, RegionValue> factory = new AttributesFactory<Integer, RegionValue>(); factory.setPartitionAttributes(new PartitionAttributesFactory<Integer, RegionValue>() .setRedundantCopies(1).setTotalNumBuckets(8).create()); final PartitionedRegion pr1 = (PartitionedRegion) createRootRegion("pr1", factory.create()); factory = new AttributesFactory<Integer, RegionValue>(); factory.setPartitionAttributes(new PartitionAttributesFactory<Integer, RegionValue>() .setRedundantCopies(1).setTotalNumBuckets(8).setColocatedWith(pr1.getName()).create()); final PartitionedRegion pr2 = (PartitionedRegion) createRootRegion("pr2", factory.create()); } }; final CacheSerializableRunnable createIndexesOnPRs = new CacheSerializableRunnable("create prs ") { public void run2() { try { QueryService qs = getCache().getQueryService(); qs.createIndex("valueIndex1", IndexType.FUNCTIONAL, "e1.value", "/pr1 e1"); qs.createIndex("valueIndex2", IndexType.FUNCTIONAL, "e2.value", "/pr2 e2"); } catch (Exception e) { org.apache.geode.test.dunit.Assert .fail("Test failed due to Exception in index creation ", e); } } }; final CacheSerializableRunnable execute = new CacheSerializableRunnable("execute function") { public void run2() { final PartitionedRegion pr1 = (PartitionedRegion) getRootRegion("pr1"); final PartitionedRegion pr2 = (PartitionedRegion) getRootRegion("pr2"); final Set<Integer> filter = new HashSet<Integer>(); for (int i = 1; i <= 80; i++) { pr1.put(i, new RegionValue(i)); if (i <= 20) { pr2.put(i, new RegionValue(i)); if ((i % 5) == 0) { filter.add(i); } } } ArrayList<List> result = (ArrayList<List>) FunctionService.onRegion(pr1).withFilter(filter) .execute(new FunctionAdapter() { public void execute(FunctionContext context) { try { RegionFunctionContext rContext = (RegionFunctionContext) context; Region pr1 = rContext.getDataSet(); LocalDataSet localCust = (LocalDataSet) PartitionRegionHelper.getLocalDataForContext(rContext); Map<String, Region<?, ?>> colocatedRegions = PartitionRegionHelper.getColocatedRegions(pr1); Map<String, Region<?, ?>> localColocatedRegions = PartitionRegionHelper.getLocalColocatedRegions(rContext); Region pr2 = colocatedRegions.get("/pr2"); LocalDataSet localOrd = (LocalDataSet) localColocatedRegions.get("/pr2"); QueryObserverImpl observer = new QueryObserverImpl(); QueryObserverHolder.setInstance(observer); QueryService qs = pr1.getCache().getQueryService(); DefaultQuery query = (DefaultQuery) qs.newQuery( "select distinct e1.value from /pr1 e1, /pr2 e2 where e1.value=e2.value"); GemFireCacheImpl.getInstance().getLogger() .fine(" Num BUCKET SET: " + localCust.getBucketSet()); GemFireCacheImpl.getInstance().getLogger().fine("VALUES FROM PR1 bucket:"); for (Integer bId : localCust.getBucketSet()) { BucketRegion br = ((PartitionedRegion) pr1).getDataStore().getLocalBucketById(bId); String val = ""; for (Object e : br.values()) { val += (e + ","); } GemFireCacheImpl.getInstance().getLogger().fine(": " + val); } GemFireCacheImpl.getInstance().getLogger().fine("VALUES FROM PR2 bucket:"); for (Integer bId : localCust.getBucketSet()) { BucketRegion br = ((PartitionedRegion) pr2).getDataStore().getLocalBucketById(bId); String val = ""; for (Object e : br.values()) { val += (e + ","); } GemFireCacheImpl.getInstance().getLogger().fine(": " + val); } SelectResults r = (SelectResults) localCust.executeQuery(query, null, localCust.getBucketSet()); GemFireCacheImpl.getInstance().getLogger().fine("Result :" + r.asList()); Assert.assertTrue(observer.isIndexesUsed); pr1.getCache().getLogger().fine("Index Used: " + observer.numIndexesUsed()); Assert.assertTrue(2 == observer.numIndexesUsed()); context.getResultSender().lastResult((Serializable) r.asList()); } catch (Exception e) { context.getResultSender().lastResult(Boolean.TRUE); } } @Override public String getId() { return "ok"; } @Override public boolean optimizeForWrite() { return false; } }).getResult(); int numResults = 0; for (List oneNodeResult : result) { GemFireCacheImpl.getInstance().getLogger() .fine("Result :" + numResults + " oneNodeResult.size(): " + oneNodeResult.size() + " oneNodeResult :" + oneNodeResult); numResults = +oneNodeResult.size(); } Assert.assertTrue(10 == numResults); } }; dataStore1.invoke(createPRs); dataStore2.invoke(createPRs); dataStore1.invoke(createIndexesOnPRs); dataStore1.invoke(execute); } } class QueryObserverImpl extends QueryObserverAdapter { boolean isIndexesUsed = false; ArrayList<String> indexesUsed = new ArrayList<String>(); String indexName; public void beforeIndexLookup(Index index, int oper, Object key) { indexName = index.getName(); indexesUsed.add(index.getName()); } public void afterIndexLookup(Collection results) { if (results != null) { isIndexesUsed = true; } } public int numIndexesUsed() { return indexesUsed.size(); } } class RegionValue implements Serializable, Comparable<RegionValue> { private static final long serialVersionUID = 1L; public int value = 0; public int value2 = 0; public RegionValue(int value) { this.value = value; this.value2 = value; } public int compareTo(RegionValue o) { if (this.value > o.value) { return 1; } else if (this.value < o.value) { return -1; } else { return 0; } } public String toString() { return "" + value; } } /* * 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 * 36 37 38 39 * * 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 * * 5 10 15 20 - 4 buckets * * 5, 2, 7, 4 * * Result : 5, 13, 2, 10 , 18 , 7, 15, 4, 12, 20 */
/* * Copyright 2014 OSBI Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package bi.meteorite.pages; import net.thucydides.core.matchers.BeanMatcher; import org.apache.commons.lang3.StringUtils; import org.openqa.selenium.By; import org.openqa.selenium.WebElement; import java.util.*; import ch.lambdaj.function.convert.Converter; import static ch.lambdaj.Lambda.convert; public class SaikuTable { private final WebElement tableElement; private List<String> headings; public SaikuTable(final WebElement tableElement) { this.tableElement = tableElement; this.headings = null; } public SaikuTable(final WebElement tableElement, List<String> headings) { this.tableElement = tableElement; this.headings = headings; } public static SaikuTable inTable(final WebElement table) { return new SaikuTable(table); } public List<Map<Object, String>> getRows() { List<Map<Object, String>> results = new ArrayList<Map<Object, String>>(); List<String> headings = getHeadings(); List<WebElement> rows = getRowElementsFor(headings); for (WebElement row : rows) { List<WebElement> cells = cellsIn(row); if (enoughCellsFor(headings).in(cells)) { results.add(rowDataFrom(cells, headings)); } } return results; } public WebElement findFirstRowWhere(final BeanMatcher... matchers) { List<WebElement> rows = getRowElementsWhere(matchers); if (rows.isEmpty()) { throw new AssertionError("Expecting a table with at least one row where: " + Arrays.deepToString(matchers)); } return rows.get(0); } public boolean containsRowElementsWhere(BeanMatcher... matchers) { List<WebElement> rows = getRowElementsWhere(matchers); return (!rows.isEmpty()); } public void shouldHaveRowElementsWhere(BeanMatcher... matchers) { List<WebElement> rows = getRowElementsWhere(matchers); if (rows.isEmpty()) { throw new AssertionError("Expecting a table with at least one row where: " + Arrays.deepToString(matchers)); } } public void shouldNotHaveRowElementsWhere(BeanMatcher... matchers) { List<WebElement> rows = getRowElementsWhere(matchers); if (!rows.isEmpty()) { throw new AssertionError("Expecting a table with no rows where: " + Arrays.deepToString(matchers)); } } public static HtmlTableBuilder withColumns(String... headings) { return new HtmlTableBuilder(Arrays.asList(headings)); } public static class HtmlTableBuilder { private final List<String> headings; public HtmlTableBuilder(List<String> headings) { this.headings = headings; } public List<Map<Object, String>> readRowsFrom(WebElement table) { return new SaikuTable(table, headings).getRows(); } public SaikuTable inTable(WebElement table) { return new SaikuTable(table, headings); } } private class EnoughCellsCheck { private final int minimumNumberOfCells; private EnoughCellsCheck(List<String> headings) { this.minimumNumberOfCells = headings.size(); } public boolean in(List<WebElement> cells) { return (cells.size() >= minimumNumberOfCells); } } private EnoughCellsCheck enoughCellsFor(List<String> headings) { return new EnoughCellsCheck(headings); } public List<String> getHeadings() { if (headings == null) { List<String> thHeadings = convert(headingElements(), toTextValues()); if (thHeadings.isEmpty()) { headings = convert(firstRowElements(), toTextValues()); } else { headings = thHeadings; } } return headings; } public List<WebElement> headingElements() { return tableElement.findElements(By.xpath(".//th")); } public List<WebElement> firstRowElements() { return tableElement.findElement(By.tagName("tr")).findElements(By.xpath(".//td")); } public List<WebElement> getRowElementsFor(List<String> headings) { List<WebElement> rowCandidates = tableElement.findElements(By.xpath(".//tr[th][count(th|td)>=" + headings.size ()+ "]")); //rowCandidates = stripHeaderRowIfPresent(rowCandidates, headings); return rowCandidates; } public List<WebElement> getRowElements() { return getRowElementsFor(getHeadings()); } private List<WebElement> stripHeaderRowIfPresent(List<WebElement> rowCandidates, List<String> headings) { if (!rowCandidates.isEmpty()) { WebElement firstRow = rowCandidates.get(0); if (hasMatchingCellValuesIn(firstRow, headings)) { rowCandidates.remove(0); } } return rowCandidates; } private boolean hasMatchingCellValuesIn(WebElement firstRow, List<String> headings) { String html = firstRow.getAttribute("innerHTML"); List<WebElement> cells = firstRow.findElements(By.xpath("//td | //th")); for(int cellIndex = 0; cellIndex < headings.size(); cellIndex++) { if ((cells.size() < cellIndex) || (!cells.get(cellIndex).getText().equals(headings.get(cellIndex)))) { return false; } } return true; } public List<WebElement> getRowElementsWhere(BeanMatcher... matchers) { List<WebElement> rowElements = getRowElementsFor(getHeadings()); List<Integer> matchingRowIndexes = findMatchingIndexesFor(rowElements, matchers); List<WebElement> matchingElements = new ArrayList<WebElement>(); for(Integer index : matchingRowIndexes) { matchingElements.add(rowElements.get(index)); } return matchingElements; } private List<Integer> findMatchingIndexesFor(List<WebElement> rowElements, BeanMatcher[] matchers) { List<Integer> indexes = new ArrayList<Integer>(); List<String> headings = getHeadings(); int index = 0; for(WebElement row : rowElements) { List<WebElement> cells = cellsIn(row); Map<Object, String> rowData = rowDataFrom(cells, headings); if (matches(rowData, matchers)) { indexes.add(index); } index++; } return indexes; } private boolean matches(Map<Object, String> rowData, BeanMatcher[] matchers) { for(BeanMatcher matcher : matchers) { if (!matcher.matches(rowData)) { return false; } } return true; } private Map<Object,String> rowDataFrom(List<WebElement> cells, List<String> headings) { Map<Object,String> rowData = new HashMap<Object, String>(); int column = 0; for (String heading : headings) { String cell = cellValueAt(column++, cells); if (!StringUtils.isEmpty(heading)) { rowData.put(heading, cell); } //rowData.put(column, cell); } return rowData; } private List<WebElement> cellsIn(WebElement row) { return row.findElements(By.xpath("./td | ./th")); } private String cellValueAt(final int column, final List<WebElement> cells) { return cells.get(column).getText(); } private Converter<WebElement, String> toTextValues() { return new Converter<WebElement, String>() { public String convert(WebElement from) { return from.getText(); } }; } public static List<Map<Object, String>> rowsFrom(final WebElement table) { return new SaikuTable(table).getRows(); } public static List<WebElement> filterRows(final WebElement table, final BeanMatcher... matchers) { return new SaikuTable(table).getRowElementsWhere(matchers); } public List<WebElement> filterRows(final BeanMatcher... matchers) { return new SaikuTable(tableElement).getRowElementsWhere(matchers); } }
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.idea.maven.project; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.containers.ContainerUtil; import com.intellij.util.xmlb.annotations.Property; import org.jetbrains.annotations.NotNull; import org.jetbrains.idea.maven.execution.MavenRunnerSettings; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; public class MavenImportingSettings implements Cloneable { private static final String PROCESS_RESOURCES_PHASE = "process-resources"; public static final String[] UPDATE_FOLDERS_PHASES = new String[]{ "generate-sources", "process-sources", "generate-resources", PROCESS_RESOURCES_PHASE, "generate-test-sources", "process-test-sources", "generate-test-resources", "process-test-resources"}; public static final String UPDATE_FOLDERS_DEFAULT_PHASE = PROCESS_RESOURCES_PHASE; @NotNull private String dedicatedModuleDir = ""; private boolean lookForNested = false; private boolean importAutomatically = false; private boolean createModulesForAggregators = true; private boolean createModuleGroups = false; private boolean excludeTargetFolder = true; private boolean keepSourceFolders = true; private boolean useMavenOutput = true; private String updateFoldersOnImportPhase = UPDATE_FOLDERS_DEFAULT_PHASE; private boolean downloadSourcesAutomatically = false; private boolean downloadDocsAutomatically = false; private boolean downloadAnnotationsAutomatically = false; private GeneratedSourcesFolder generatedSourcesFolder = GeneratedSourcesFolder.AUTODETECT; private String dependencyTypes = "jar, test-jar, maven-plugin, ejb, ejb-client, jboss-har, jboss-sar, war, ear, bundle"; private Set<String> myDependencyTypesAsSet; @NotNull private String vmOptionsForImporter = ""; @NotNull private String jdkForImporter = MavenRunnerSettings.USE_INTERNAL_JAVA; private List<Listener> myListeners = ContainerUtil.createLockFreeCopyOnWriteList(); public enum GeneratedSourcesFolder { IGNORE("Don't detect"), AUTODETECT("Detect automatically"), GENERATED_SOURCE_FOLDER("target/generated-sources"), SUBFOLDER("subdirectories of \"target/generated-sources\""); public final String title; GeneratedSourcesFolder(String title) { this.title = title; } } @NotNull public String getDedicatedModuleDir() { return dedicatedModuleDir; } public void setDedicatedModuleDir(@NotNull String dedicatedModuleDir) { this.dedicatedModuleDir = dedicatedModuleDir; } public boolean isLookForNested() { return lookForNested; } public void setLookForNested(boolean lookForNested) { this.lookForNested = lookForNested; } public boolean isImportAutomatically() { return importAutomatically; } public void setImportAutomatically(boolean importAutomatically) { this.importAutomatically = importAutomatically; fireAutoImportChanged(); } @NotNull public String getDependencyTypes() { return dependencyTypes; } public void setDependencyTypes(@NotNull String dependencyTypes) { this.dependencyTypes = dependencyTypes; myDependencyTypesAsSet = null; } @NotNull public Set<String> getDependencyTypesAsSet() { if (myDependencyTypesAsSet == null) { Set<String> res = new LinkedHashSet<>(); for (String type : StringUtil.tokenize(dependencyTypes, " \n\r\t,;")) { res.add(type); } myDependencyTypesAsSet = res; } return myDependencyTypesAsSet; } public boolean isCreateModuleGroups() { return createModuleGroups; } public void setCreateModuleGroups(boolean createModuleGroups) { this.createModuleGroups = createModuleGroups; fireCreateModuleGroupsChanged(); } public boolean isCreateModulesForAggregators() { return createModulesForAggregators; } public void setCreateModulesForAggregators(boolean createModulesForAggregators) { this.createModulesForAggregators = createModulesForAggregators; fireCreateModuleForAggregatorsChanged(); } public boolean isKeepSourceFolders() { return keepSourceFolders; } public void setKeepSourceFolders(boolean keepSourceFolders) { this.keepSourceFolders = keepSourceFolders; } public boolean isExcludeTargetFolder() { return excludeTargetFolder; } public void setExcludeTargetFolder(boolean excludeTargetFolder) { this.excludeTargetFolder = excludeTargetFolder; } public boolean isUseMavenOutput() { return useMavenOutput; } public void setUseMavenOutput(boolean useMavenOutput) { this.useMavenOutput = useMavenOutput; } public String getUpdateFoldersOnImportPhase() { return updateFoldersOnImportPhase; } public void setUpdateFoldersOnImportPhase(String updateFoldersOnImportPhase) { this.updateFoldersOnImportPhase = updateFoldersOnImportPhase; } public boolean isDownloadSourcesAutomatically() { return downloadSourcesAutomatically; } public void setDownloadSourcesAutomatically(boolean Value) { this.downloadSourcesAutomatically = Value; } public boolean isDownloadDocsAutomatically() { return downloadDocsAutomatically; } public void setDownloadDocsAutomatically(boolean value) { this.downloadDocsAutomatically = value; } public boolean isDownloadAnnotationsAutomatically() { return downloadAnnotationsAutomatically; } public void setDownloadAnnotationsAutomatically(boolean value) { this.downloadAnnotationsAutomatically = value; } @Property @NotNull public GeneratedSourcesFolder getGeneratedSourcesFolder() { return generatedSourcesFolder; } public void setGeneratedSourcesFolder(GeneratedSourcesFolder generatedSourcesFolder) { if (generatedSourcesFolder == null) return; // null may come from deserializator this.generatedSourcesFolder = generatedSourcesFolder; } @NotNull public String getVmOptionsForImporter() { return vmOptionsForImporter; } public void setVmOptionsForImporter(String vmOptionsForImporter) { this.vmOptionsForImporter = StringUtil.notNullize(vmOptionsForImporter); } @NotNull public String getJdkForImporter() { return jdkForImporter; } public void setJdkForImporter(@NotNull String jdkForImporter) { this.jdkForImporter = jdkForImporter; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MavenImportingSettings that = (MavenImportingSettings)o; if (createModuleGroups != that.createModuleGroups) return false; if (createModulesForAggregators != that.createModulesForAggregators) return false; if (importAutomatically != that.importAutomatically) return false; if (!dependencyTypes.equals(that.dependencyTypes)) return false; if (downloadDocsAutomatically != that.downloadDocsAutomatically) return false; if (downloadSourcesAutomatically != that.downloadSourcesAutomatically) return false; if (downloadAnnotationsAutomatically != that.downloadAnnotationsAutomatically) return false; if (lookForNested != that.lookForNested) return false; if (keepSourceFolders != that.keepSourceFolders) return false; if (excludeTargetFolder != that.excludeTargetFolder) return false; if (useMavenOutput != that.useMavenOutput) return false; if (generatedSourcesFolder != that.generatedSourcesFolder) return false; if (!dedicatedModuleDir.equals(that.dedicatedModuleDir)) return false; if (!jdkForImporter.equals(that.jdkForImporter)) return false; if (!vmOptionsForImporter.equals(that.vmOptionsForImporter)) return false; if (updateFoldersOnImportPhase != null ? !updateFoldersOnImportPhase.equals(that.updateFoldersOnImportPhase) : that.updateFoldersOnImportPhase != null) { return false; } return true; } @Override public int hashCode() { int result = 0; if (lookForNested) result++; result <<= 1; if (importAutomatically) result++; result <<= 1; if (createModulesForAggregators) result++; result <<= 1; if (createModuleGroups) result++; result <<= 1; if (keepSourceFolders) result++; result <<= 1; if (useMavenOutput) result++; result <<= 1; if (downloadSourcesAutomatically) result++; result <<= 1; if (downloadDocsAutomatically) result++; result <<= 1; if (downloadAnnotationsAutomatically) result++; result <<= 1; result = 31 * result + (updateFoldersOnImportPhase != null ? updateFoldersOnImportPhase.hashCode() : 0); result = 31 * result + dedicatedModuleDir.hashCode(); result = 31 * result + generatedSourcesFolder.hashCode(); result = 31 * result + dependencyTypes.hashCode(); return result; } @Override public MavenImportingSettings clone() { try { MavenImportingSettings result = (MavenImportingSettings)super.clone(); result.myListeners = ContainerUtil.createLockFreeCopyOnWriteList(); return result; } catch (CloneNotSupportedException e) { throw new Error(e); } } public void addListener(Listener l) { myListeners.add(l); } public void removeListener(Listener l) { myListeners.remove(l); } private void fireAutoImportChanged() { for (Listener each : myListeners) { each.autoImportChanged(); } } private void fireCreateModuleGroupsChanged() { for (Listener each : myListeners) { each.createModuleGroupsChanged(); } } private void fireCreateModuleForAggregatorsChanged() { for (Listener each : myListeners) { each.createModuleForAggregatorsChanged(); } } public interface Listener { void autoImportChanged(); void createModuleGroupsChanged(); void createModuleForAggregatorsChanged(); } }
/* * #%L * BinaryElement.java - mongodb-async-driver - Allanbank Consulting, Inc. * %% * Copyright (C) 2011 - 2014 Allanbank Consulting, Inc. * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ package com.allanbank.mongodb.bson.element; import static com.allanbank.mongodb.util.Assertions.assertNotNull; import java.io.IOException; import java.util.Arrays; import javax.annotation.concurrent.Immutable; import javax.annotation.concurrent.ThreadSafe; import com.allanbank.mongodb.bson.Element; import com.allanbank.mongodb.bson.ElementType; import com.allanbank.mongodb.bson.Visitor; import com.allanbank.mongodb.bson.io.BsonInputStream; import com.allanbank.mongodb.bson.io.StringEncoder; /** * A wrapper for a BSON binary. * * @api.yes This class is part of the driver's API. Public and protected members * will be deprecated for at least 1 non-bugfix release (version * numbers are &lt;major&gt;.&lt;minor&gt;.&lt;bugfix&gt;) before being * removed or modified. * @copyright 2011-2013, Allanbank Consulting, Inc., All Rights Reserved */ @Immutable @ThreadSafe public class BinaryElement extends AbstractElement { /** * The {@link BinaryElement}'s class to avoid the * {@link Class#forName(String) Class.forName(...)} overhead. */ public static final Class<BinaryElement> BINARY_CLASS = BinaryElement.class; /** The sub type used when no sub type is specified. */ public static final byte DEFAULT_SUB_TYPE = 0; /** The BSON type for a binary. */ public static final ElementType TYPE = ElementType.BINARY; /** Serialization version for the class. */ private static final long serialVersionUID = 5864918707454038001L; /** * Computes and returns the number of bytes that are used to encode the * element. * * @param name * The name for the BSON array. * @param subType * The sub-type of the binary data. * @param bytesLength * The length of the binary array. * @return The size of the element when encoded in bytes. */ private static long computeSize(final String name, final byte subType, final int bytesLength) { long result = 7; // type (1) + name null byte (1) + data length (4) + // subtype (1). result += StringEncoder.utf8Size(name); result += bytesLength; if (subType == 2) { // Extra length field in subtype 2. result += 4; } return result; } /** The sub-type of the binary data. */ private final byte mySubType; /** The BSON binary value. */ private final byte[] myValue; /** * Constructs a new {@link BinaryElement}. * * @param name * The name for the BSON binary. * @param subType * The sub-type of the binary data. * @param input * The stream to read the data from. * @param length * The number of bytes of data to read. * @throws IllegalArgumentException * If the {@code name} is <code>null</code>. * @throws IOException * If there is an error reading from {@code input} stream. */ public BinaryElement(final String name, final byte subType, final BsonInputStream input, final int length) throws IOException { this(name, subType, input, length, computeSize(name, subType, length)); } /** * Constructs a new {@link BinaryElement}. * * @param name * The name for the BSON binary. * @param subType * The sub-type of the binary data. * @param input * The stream to read the data from. * @param length * The number of bytes of data to read. * @param size * The size of the element when encoded in bytes. If not known * then use the * {@link BinaryElement#BinaryElement(String, byte, BsonInputStream, int)} * constructor instead. * @throws IllegalArgumentException * If the {@code name} is <code>null</code>. * @throws IOException * If there is an error reading from {@code input} stream. */ public BinaryElement(final String name, final byte subType, final BsonInputStream input, final int length, final long size) throws IOException { super(name, size); mySubType = subType; myValue = new byte[length]; input.readFully(myValue); } /** * Constructs a new {@link BinaryElement}. * * @param name * The name for the BSON binary. * @param subType * The sub-type of the binary data. * @param value * The BSON binary value. * @throws IllegalArgumentException * If the {@code name} or {@code value} is <code>null</code>. */ public BinaryElement(final String name, final byte subType, final byte[] value) { this(name, subType, value, computeSize(name, subType, (value == null) ? 0 : value.length)); } /** * Constructs a new {@link BinaryElement}. * * @param name * The name for the BSON binary. * @param subType * The sub-type of the binary data. * @param value * The BSON binary value. * @param size * The size of the element when encoded in bytes. If not known * then use the * {@link BinaryElement#BinaryElement(String, byte, byte[])} * constructor instead. * @throws IllegalArgumentException * If the {@code name} or {@code value} is <code>null</code>. */ public BinaryElement(final String name, final byte subType, final byte[] value, final long size) { super(name, size); assertNotNull(value, "Binary element's value cannot be null. Add a null element instead."); mySubType = subType; myValue = value.clone(); } /** * Constructs a new {@link BinaryElement}. Uses the * {@link #DEFAULT_SUB_TYPE}. * * @param name * The name for the BSON binary. * @param value * The BSON binary value. * @throws IllegalArgumentException * If the {@code name} or {@code value} is <code>null</code>. */ public BinaryElement(final String name, final byte[] value) { this(name, DEFAULT_SUB_TYPE, value); } /** * Accepts the visitor and calls the {@link Visitor#visitBinary} method. * * @see Element#accept(Visitor) */ @Override public void accept(final Visitor visitor) { visitor.visitBinary(getName(), getSubType(), getValue()); } /** * {@inheritDoc} * <p> * Overridden to compare the sub-types and bytes if the base class * comparison is equals. * </p> */ @Override public int compareTo(final Element otherElement) { int result = super.compareTo(otherElement); if (result == 0) { final BinaryElement other = (BinaryElement) otherElement; result = mySubType - other.mySubType; if (result == 0) { final int length = Math.min(myValue.length, other.myValue.length); for (int i = 0; i < length; ++i) { result = myValue[i] - other.myValue[i]; if (result != 0) { return result; } } result = myValue.length - other.myValue.length; } } return result; } /** * Determines if the passed object is of this same type as this object and * if so that its fields are equal. * * @param object * The object to compare to. * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(final Object object) { boolean result = false; if (this == object) { result = true; } else if ((object != null) && (getClass() == object.getClass())) { final BinaryElement other = (BinaryElement) object; result = super.equals(object) && (mySubType == other.mySubType) && Arrays.equals(myValue, other.myValue); } return result; } /** * Returns the byte value at the specified offset. * * @param offset * The offset of the desired value. * @return The byte value at the offset. * @throws ArrayIndexOutOfBoundsException * If the offset is not in the range [0, {@link #length()}). */ public final byte get(final int offset) { return myValue[offset]; } /** * Return the binary sub-type. * * @return The binary sub-type. */ public byte getSubType() { return mySubType; } /** * {@inheritDoc} */ @Override public ElementType getType() { return TYPE; } /** * Returns the BSON binary value. For safety reasons this method clones the * internal byte array. To avoid the copying of the bytes use the * {@link #length()} and {@link #get(int)} methods to access each byte * value. * * @return The BSON binary value. */ public byte[] getValue() { return myValue.clone(); } /** * {@inheritDoc} * <p> * Returns a byte[]. * </p> * <p> * <b>Note:</b> This value will not be recreated is a Object-->Element * conversion. The sub type is lost in this conversion to an {@link Object}. * </p> * <p> * <em>Implementation Note:</em> The return type cannot be a byte[] here as * {@link UuidElement} returns a {@link java.util.UUID}. * </p> */ @Override public Object getValueAsObject() { return getValue(); } /** * Computes a reasonable hash code. * * @return The hash code value. */ @Override public int hashCode() { int result = 1; result = (31 * result) + super.hashCode(); result = (31 * result) + mySubType; result = (31 * result) + Arrays.hashCode(myValue); return result; } /** * Returns the length of the contained byte array. * * @return The length of the contained byte array. */ public final int length() { return myValue.length; } /** * {@inheritDoc} * <p> * Returns a new {@link BinaryElement}. * </p> */ @Override public BinaryElement withName(final String name) { if (getName().equals(name)) { return this; } return new BinaryElement(name, mySubType, myValue); } }
/* Copyright 2014 Olga Miller <olga.rgb@googlemail.com> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package om.sstvencoder; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.BitmapRegionDecoder; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.RectF; import android.support.annotation.NonNull; import android.support.v4.view.GestureDetectorCompat; import android.util.AttributeSet; import android.view.GestureDetector; import android.view.MotionEvent; import android.view.ScaleGestureDetector; import android.widget.ImageView; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import om.sstvencoder.Modes.ModeSize; import om.sstvencoder.TextOverlay.*; public class CropView extends ImageView { private class GestureListener extends GestureDetector.SimpleOnGestureListener { @Override public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) { if (!mLongPress) { moveImage(distanceX, distanceY); return true; } return false; } @Override public void onLongPress(MotionEvent e) { mLongPress = false; if (!mInScale && mLabelHandler.dragLabel(e.getX(), e.getY())) { // Utility.vibrate(100, getContext()); invalidate(); mLongPress = true; } } @Override public boolean onSingleTapConfirmed(MotionEvent e) { if (!mLongPress) { sendLabelSettings(e.getX(), e.getY()); return true; } return false; } } private class ScaleGestureListener extends ScaleGestureDetector.SimpleOnScaleGestureListener { @Override public boolean onScaleBegin(ScaleGestureDetector detector) { if (!mLongPress) { mInScale = true; return true; } return false; } @Override public boolean onScale(ScaleGestureDetector detector) { scaleImage(detector.getScaleFactor()); return true; } @Override public void onScaleEnd(ScaleGestureDetector detector) { mInScale = false; } } private GestureDetectorCompat mDetectorCompat; private ScaleGestureDetector mScaleDetector; private boolean mLongPress, mInScale; private ModeSize mModeSize; private final Paint mPaint, mRectPaint, mBorderPaint; private RectF mInputRect; private Rect mOutputRect; private BitmapRegionDecoder mRegionDecoder; private int mImageWidth, mImageHeight; private Bitmap mCacheBitmap; private boolean mSmallImage; private boolean mImageOK; private final Rect mCanvasDrawRect, mImageDrawRect; private int mOrientation; private Rect mCacheRect; private int mCacheSampleSize; private final BitmapFactory.Options mBitmapOptions; private LabelHandler mLabelHandler; public CropView(Context context, AttributeSet attrs) { super(context, attrs); mDetectorCompat = new GestureDetectorCompat(getContext(), new GestureListener()); mScaleDetector = new ScaleGestureDetector(getContext(), new ScaleGestureListener()); mBitmapOptions = new BitmapFactory.Options(); mPaint = new Paint(Paint.FILTER_BITMAP_FLAG); mRectPaint = new Paint(); mRectPaint.setStyle(Paint.Style.STROKE); mBorderPaint = new Paint(); mBorderPaint.setColor(Color.BLACK); mCanvasDrawRect = new Rect(); mImageDrawRect = new Rect(); mCacheRect = new Rect(); mSmallImage = false; mImageOK = false; mLabelHandler = new LabelHandler(); } public void setModeSize(ModeSize size) { mModeSize = size; mOutputRect = Utility.getEmbeddedRect(getWidth(), getHeight(), mModeSize.getWidth(), mModeSize.getHeight()); if (mImageOK) { resetInputRect(); invalidate(); } } private void resetInputRect() { float iw = mModeSize.getWidth(); float ih = mModeSize.getHeight(); float ow = mImageWidth; float oh = mImageHeight; if (iw * oh > ow * ih) { mInputRect = new RectF(0.0f, 0.0f, (iw * oh) / ih, oh); mInputRect.offset((ow - (iw * oh) / ih) / 2.0f, 0.0f); } else { mInputRect = new RectF(0.0f, 0.0f, ow, (ih * ow) / iw); mInputRect.offset(0.0f, (oh - (ih * ow) / iw) / 2.0f); } } public void rotateImage(int orientation) { mOrientation += orientation; mOrientation %= 360; if (orientation == 90 || orientation == 270) { int tmp = mImageWidth; //noinspection SuspiciousNameCombination mImageWidth = mImageHeight; mImageHeight = tmp; } if (mImageOK) { resetInputRect(); invalidate(); } } public void setBitmapStream(InputStream stream) throws IOException { mImageOK = false; mOrientation = 0; recycle(); // app6 + exif int bufferBytes = 1048576; if (!stream.markSupported()) stream = new BufferedInputStream(stream, bufferBytes); stream.mark(bufferBytes); BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeStream(new BufferedInputStream(stream), null, options); stream.reset(); mImageWidth = options.outWidth; mImageHeight = options.outHeight; if (mImageWidth * mImageHeight < 1024 * 1024) { mCacheBitmap = BitmapFactory.decodeStream(stream); mSmallImage = true; } else { mRegionDecoder = BitmapRegionDecoder.newInstance(stream, true); mCacheRect.setEmpty(); mSmallImage = false; } if (mCacheBitmap == null && mRegionDecoder == null) { String size = options.outWidth + "x" + options.outHeight; throw new IOException("Stream could not be decoded. Image size: " + size); } mImageOK = true; resetInputRect(); invalidate(); } private void recycle() { if (mRegionDecoder != null) { mRegionDecoder.recycle(); mRegionDecoder = null; } if (mCacheBitmap != null) { mCacheBitmap.recycle(); mCacheBitmap = null; } } public void scaleImage(float scaleFactor) { float newW = mInputRect.width() / scaleFactor; float newH = mInputRect.height() / scaleFactor; float dx = 0.5f * (mInputRect.width() - newW); float dy = 0.5f * (mInputRect.height() - newH); float max = 2.0f * Math.max(mImageWidth, mImageHeight); if (Math.min(newW, newH) >= 4.0f && Math.max(newW, newH) <= max) { mInputRect.inset(dx, dy); invalidate(); } } public void moveImage(float distanceX, float distanceY) { float dx = (mInputRect.width() * distanceX) / mOutputRect.width(); float dy = (mInputRect.height() * distanceY) / mOutputRect.height(); dx = Math.max(mInputRect.width() * 0.1f, mInputRect.right + dx) - mInputRect.right; dy = Math.max(mInputRect.height() * 0.1f, mInputRect.bottom + dy) - mInputRect.bottom; dx = Math.min(mImageWidth - mInputRect.width() * 0.1f, mInputRect.left + dx) - mInputRect.left; dy = Math.min(mImageHeight - mInputRect.height() * 0.1f, mInputRect.top + dy) - mInputRect.top; mInputRect.offset(dx, dy); invalidate(); } @Override public boolean onTouchEvent(@NonNull MotionEvent e) { boolean consumed = false; if (mLongPress) { switch (e.getAction()) { case MotionEvent.ACTION_MOVE: mLabelHandler.moveLabel(e.getX(), e.getY()); invalidate(); consumed = true; break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: mLabelHandler.dropLabel(); invalidate(); mLongPress = false; consumed = true; break; } } consumed = mScaleDetector.onTouchEvent(e) || consumed; return mDetectorCompat.onTouchEvent(e) || consumed || super.onTouchEvent(e); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); if (mModeSize != null) mOutputRect = Utility.getEmbeddedRect(w, h, mModeSize.getWidth(), mModeSize.getHeight()); mLabelHandler.update(w, h); } @Override protected void onDraw(@NonNull Canvas canvas) { if (!mImageOK) return; maximizeImageToCanvasRect(); adjustCanvasAndImageRect(getWidth(), getHeight()); canvas.drawRect(mOutputRect, mBorderPaint); drawBitmap(canvas); mLabelHandler.drawLabels(canvas); drawModeRect(canvas); } private void maximizeImageToCanvasRect() { mImageDrawRect.left = Math.round(mInputRect.left - mOutputRect.left * mInputRect.width() / mOutputRect.width()); mImageDrawRect.top = Math.round(mInputRect.top - mOutputRect.top * mInputRect.height() / mOutputRect.height()); mImageDrawRect.right = Math.round(mInputRect.right - (mOutputRect.right - getWidth()) * mInputRect.width() / mOutputRect.width()); mImageDrawRect.bottom = Math.round(mInputRect.bottom - (mOutputRect.bottom - getHeight()) * mInputRect.height() / mOutputRect.height()); } private void adjustCanvasAndImageRect(int width, int height) { mCanvasDrawRect.set(0, 0, width, height); if (mImageDrawRect.left < 0) { mCanvasDrawRect.left -= (mImageDrawRect.left * mCanvasDrawRect.width()) / mImageDrawRect.width(); mImageDrawRect.left = 0; } if (mImageDrawRect.top < 0) { mCanvasDrawRect.top -= (mImageDrawRect.top * mCanvasDrawRect.height()) / mImageDrawRect.height(); mImageDrawRect.top = 0; } if (mImageDrawRect.right > mImageWidth) { mCanvasDrawRect.right -= ((mImageDrawRect.right - mImageWidth) * mCanvasDrawRect.width()) / mImageDrawRect.width(); mImageDrawRect.right = mImageWidth; } if (mImageDrawRect.bottom > mImageHeight) { mCanvasDrawRect.bottom -= ((mImageDrawRect.bottom - mImageHeight) * mCanvasDrawRect.height()) / mImageDrawRect.height(); mImageDrawRect.bottom = mImageHeight; } } private void drawModeRect(Canvas canvas) { mRectPaint.setColor(Color.BLUE); canvas.drawRect(mOutputRect, mRectPaint); mRectPaint.setColor(Color.GREEN); drawRectInset(canvas, mOutputRect, -1); mRectPaint.setColor(Color.RED); drawRectInset(canvas, mOutputRect, -2); } private void drawRectInset(Canvas canvas, Rect rect, int inset) { canvas.drawRect(rect.left + inset, rect.top + inset, rect.right - inset, rect.bottom - inset, mRectPaint); } private Rect getIntRect(RectF rect) { return new Rect(Math.round(rect.left), Math.round(rect.top), Math.round(rect.right), Math.round(rect.bottom)); } private int getSampleSize() { int sx = Math.round(mInputRect.width() / mModeSize.getWidth()); int sy = Math.round(mInputRect.height() / mModeSize.getHeight()); int scale = Math.max(1, Math.max(sx, sy)); return Integer.highestOneBit(scale); } public Bitmap getBitmap() { if (!mImageOK) return null; Bitmap result = Bitmap.createBitmap(mModeSize.getWidth(), mModeSize.getHeight(), Bitmap.Config.ARGB_8888); mImageDrawRect.set(getIntRect(mInputRect)); adjustCanvasAndImageRect(mModeSize.getWidth(), mModeSize.getHeight()); Canvas canvas = new Canvas(result); canvas.drawColor(Color.BLACK); drawBitmap(canvas); mLabelHandler.drawLabels(canvas, mOutputRect, new Rect(0, 0, mModeSize.getWidth(), mModeSize.getHeight())); return result; } private void drawBitmap(Canvas canvas) { int w = mImageWidth; int h = mImageHeight; for (int i = 0; i < mOrientation / 90; ++i) { int tmp = w; w = h; h = tmp; //noinspection SuspiciousNameCombination mImageDrawRect.set(mImageDrawRect.top, h - mImageDrawRect.left, mImageDrawRect.bottom, h - mImageDrawRect.right); //noinspection SuspiciousNameCombination mCanvasDrawRect.set(mCanvasDrawRect.top, -mCanvasDrawRect.right, mCanvasDrawRect.bottom, -mCanvasDrawRect.left); } mImageDrawRect.sort(); canvas.save(); canvas.rotate(mOrientation); if (!mSmallImage) { int sampleSize = getSampleSize(); if (sampleSize < mCacheSampleSize || !mCacheRect.contains(mImageDrawRect)) { if (mCacheBitmap != null) mCacheBitmap.recycle(); int cacheWidth = mImageDrawRect.width(); int cacheHeight = mImageDrawRect.height(); while (cacheWidth * cacheHeight < (sampleSize * 1024 * sampleSize * 1024)) { cacheWidth += mImageDrawRect.width(); cacheHeight += mImageDrawRect.height(); } mCacheRect.set( Math.max(0, ~(sampleSize - 1) & (mImageDrawRect.centerX() - cacheWidth / 2)), Math.max(0, ~(sampleSize - 1) & (mImageDrawRect.centerY() - cacheHeight / 2)), Math.min(mRegionDecoder.getWidth(), ~(sampleSize - 1) & (mImageDrawRect.centerX() + cacheWidth / 2 + sampleSize - 1)), Math.min(mRegionDecoder.getHeight(), ~(sampleSize - 1) & (mImageDrawRect.centerY() + cacheHeight / 2 + sampleSize - 1))); mBitmapOptions.inSampleSize = mCacheSampleSize = sampleSize; mCacheBitmap = mRegionDecoder.decodeRegion(mCacheRect, mBitmapOptions); } mImageDrawRect.offset(-mCacheRect.left, -mCacheRect.top); mImageDrawRect.left /= mCacheSampleSize; mImageDrawRect.top /= mCacheSampleSize; mImageDrawRect.right /= mCacheSampleSize; mImageDrawRect.bottom /= mCacheSampleSize; } canvas.drawBitmap(mCacheBitmap, mImageDrawRect, mCanvasDrawRect, mPaint); canvas.restore(); } private void sendLabelSettings(float x, float y) { LabelSettings settings = mLabelHandler.editLabelBegin(x, y, getWidth(), getHeight()); ((MainActivity) getContext()).startEditTextActivity(settings); } public void loadLabelSettings(LabelSettings settings) { if (mLabelHandler.editLabelEnd(settings)) invalidate(); } }
package org.bouncycastle.crypto.signers; import java.security.SecureRandom; import java.util.Hashtable; import org.bouncycastle.crypto.AsymmetricBlockCipher; import org.bouncycastle.crypto.CipherParameters; import org.bouncycastle.crypto.CryptoException; import org.bouncycastle.crypto.Digest; import org.bouncycastle.crypto.InvalidCipherTextException; import org.bouncycastle.crypto.SignerWithRecovery; import org.bouncycastle.crypto.params.ParametersWithRandom; import org.bouncycastle.crypto.params.ParametersWithSalt; import org.bouncycastle.crypto.params.RSAKeyParameters; import org.bouncycastle.util.Arrays; import org.bouncycastle.util.Integers; /** * ISO9796-2 - mechanism using a hash function with recovery (scheme 2 and 3). * <p> * Note: the usual length for the salt is the length of the hash * function used in bytes. */ public class ISO9796d2PSSSigner implements SignerWithRecovery { static final public int TRAILER_IMPLICIT = 0xBC; static final public int TRAILER_RIPEMD160 = 0x31CC; static final public int TRAILER_RIPEMD128 = 0x32CC; static final public int TRAILER_SHA1 = 0x33CC; static final public int TRAILER_SHA256 = 0x34CC; static final public int TRAILER_SHA512 = 0x35CC; static final public int TRAILER_SHA384 = 0x36CC; static final public int TRAILER_WHIRLPOOL = 0x37CC; private static Hashtable trailerMap = new Hashtable(); static { trailerMap.put("RIPEMD128", Integers.valueOf(TRAILER_RIPEMD128)); trailerMap.put("RIPEMD160", Integers.valueOf(TRAILER_RIPEMD160)); trailerMap.put("SHA-1", Integers.valueOf(TRAILER_SHA1)); trailerMap.put("SHA-256", Integers.valueOf(TRAILER_SHA256)); trailerMap.put("SHA-384", Integers.valueOf(TRAILER_SHA384)); trailerMap.put("SHA-512", Integers.valueOf(TRAILER_SHA512)); trailerMap.put("Whirlpool", Integers.valueOf(TRAILER_WHIRLPOOL)); } private Digest digest; private AsymmetricBlockCipher cipher; private SecureRandom random; private byte[] standardSalt; private int hLen; private int trailer; private int keyBits; private byte[] block; private byte[] mBuf; private int messageLength; private int saltLength; private boolean fullMessage; private byte[] recoveredMessage; private byte[] preSig; private byte[] preBlock; private int preMStart; private int preTLength; /** * Generate a signer for the with either implicit or explicit trailers * for ISO9796-2, scheme 2 or 3. * * @param cipher base cipher to use for signature creation/verification * @param digest digest to use. * @param saltLength length of salt in bytes. * @param implicit whether or not the trailer is implicit or gives the hash. */ public ISO9796d2PSSSigner( AsymmetricBlockCipher cipher, Digest digest, int saltLength, boolean implicit) { this.cipher = cipher; this.digest = digest; this.hLen = digest.getDigestSize(); this.saltLength = saltLength; if (implicit) { trailer = TRAILER_IMPLICIT; } else { Integer trailerObj = (Integer)trailerMap.get(digest.getAlgorithmName()); if (trailerObj != null) { trailer = trailerObj.intValue(); } else { throw new IllegalArgumentException("no valid trailer for digest"); } } } /** * Constructor for a signer with an explicit digest trailer. * * @param cipher cipher to use. * @param digest digest to sign with. * @param saltLength length of salt in bytes. */ public ISO9796d2PSSSigner( AsymmetricBlockCipher cipher, Digest digest, int saltLength) { this(cipher, digest, saltLength, false); } /** * Initialise the signer. * * @param forSigning true if for signing, false if for verification. * @param param parameters for signature generation/verification. If the * parameters are for generation they should be a ParametersWithRandom, * a ParametersWithSalt, or just an RSAKeyParameters object. If RSAKeyParameters * are passed in a SecureRandom will be created. * @throws IllegalArgumentException if wrong parameter type or a fixed * salt is passed in which is the wrong length. */ public void init( boolean forSigning, CipherParameters param) { RSAKeyParameters kParam; int lengthOfSalt = saltLength; if (param instanceof ParametersWithRandom) { ParametersWithRandom p = (ParametersWithRandom)param; kParam = (RSAKeyParameters)p.getParameters(); if (forSigning) { random = p.getRandom(); } } else if (param instanceof ParametersWithSalt) { ParametersWithSalt p = (ParametersWithSalt)param; kParam = (RSAKeyParameters)p.getParameters(); standardSalt = p.getSalt(); lengthOfSalt = standardSalt.length; if (standardSalt.length != saltLength) { throw new IllegalArgumentException("Fixed salt is of wrong length"); } } else { kParam = (RSAKeyParameters)param; if (forSigning) { random = new SecureRandom(); } } cipher.init(forSigning, kParam); keyBits = kParam.getModulus().bitLength(); block = new byte[(keyBits + 7) / 8]; if (trailer == TRAILER_IMPLICIT) { mBuf = new byte[block.length - digest.getDigestSize() - lengthOfSalt - 1 - 1]; } else { mBuf = new byte[block.length - digest.getDigestSize() - lengthOfSalt - 1 - 2]; } reset(); } /** * compare two byte arrays - constant time */ private boolean isSameAs( byte[] a, byte[] b) { boolean isOkay = true; if (messageLength != b.length) { isOkay = false; } for (int i = 0; i != b.length; i++) { if (a[i] != b[i]) { isOkay = false; } } return isOkay; } /** * clear possible sensitive data */ private void clearBlock( byte[] block) { for (int i = 0; i != block.length; i++) { block[i] = 0; } } public void updateWithRecoveredMessage(byte[] signature) throws InvalidCipherTextException { byte[] block = cipher.processBlock(signature, 0, signature.length); // // adjust block size for leading zeroes if necessary // if (block.length < (keyBits + 7) / 8) { byte[] tmp = new byte[(keyBits + 7) / 8]; System.arraycopy(block, 0, tmp, tmp.length - block.length, block.length); clearBlock(block); block = tmp; } int tLength; if (((block[block.length - 1] & 0xFF) ^ 0xBC) == 0) { tLength = 1; } else { int sigTrail = ((block[block.length - 2] & 0xFF) << 8) | (block[block.length - 1] & 0xFF); Integer trailerObj = (Integer)trailerMap.get(digest.getAlgorithmName()); if (trailerObj != null) { if (sigTrail != trailerObj.intValue()) { throw new IllegalStateException("signer initialised with wrong digest for trailer " + sigTrail); } } else { throw new IllegalArgumentException("unrecognised hash in signature"); } tLength = 2; } // // calculate H(m2) // byte[] m2Hash = new byte[hLen]; digest.doFinal(m2Hash, 0); // // remove the mask // byte[] dbMask = maskGeneratorFunction1(block, block.length - hLen - tLength, hLen, block.length - hLen - tLength); for (int i = 0; i != dbMask.length; i++) { block[i] ^= dbMask[i]; } block[0] &= 0x7f; // // find out how much padding we've got // int mStart = 0; for (; mStart != block.length; mStart++) { if (block[mStart] == 0x01) { break; } } mStart++; if (mStart >= block.length) { clearBlock(block); } fullMessage = (mStart > 1); recoveredMessage = new byte[dbMask.length - mStart - saltLength]; System.arraycopy(block, mStart, recoveredMessage, 0, recoveredMessage.length); System.arraycopy(recoveredMessage, 0, mBuf, 0, recoveredMessage.length); preSig = signature; preBlock = block; preMStart = mStart; preTLength = tLength; } /** * update the internal digest with the byte b */ public void update( byte b) { if (preSig == null && messageLength < mBuf.length) { mBuf[messageLength++] = b; } else { digest.update(b); } } /** * update the internal digest with the byte array in */ public void update( byte[] in, int off, int len) { if (preSig == null) { while (len > 0 && messageLength < mBuf.length) { this.update(in[off]); off++; len--; } } if (len > 0) { digest.update(in, off, len); } } /** * reset the internal state */ public void reset() { digest.reset(); messageLength = 0; if (mBuf != null) { clearBlock(mBuf); } if (recoveredMessage != null) { clearBlock(recoveredMessage); recoveredMessage = null; } fullMessage = false; if (preSig != null) { preSig = null; clearBlock(preBlock); preBlock = null; } } /** * generate a signature for the loaded message using the key we were * initialised with. */ public byte[] generateSignature() throws CryptoException { int digSize = digest.getDigestSize(); byte[] m2Hash = new byte[digSize]; digest.doFinal(m2Hash, 0); byte[] C = new byte[8]; LtoOSP(messageLength * 8, C); digest.update(C, 0, C.length); digest.update(mBuf, 0, messageLength); digest.update(m2Hash, 0, m2Hash.length); byte[] salt; if (standardSalt != null) { salt = standardSalt; } else { salt = new byte[saltLength]; random.nextBytes(salt); } digest.update(salt, 0, salt.length); byte[] hash = new byte[digest.getDigestSize()]; digest.doFinal(hash, 0); int tLength = 2; if (trailer == TRAILER_IMPLICIT) { tLength = 1; } int off = block.length - messageLength - salt.length - hLen - tLength - 1; block[off] = 0x01; System.arraycopy(mBuf, 0, block, off + 1, messageLength); System.arraycopy(salt, 0, block, off + 1 + messageLength, salt.length); byte[] dbMask = maskGeneratorFunction1(hash, 0, hash.length, block.length - hLen - tLength); for (int i = 0; i != dbMask.length; i++) { block[i] ^= dbMask[i]; } System.arraycopy(hash, 0, block, block.length - hLen - tLength, hLen); if (trailer == TRAILER_IMPLICIT) { block[block.length - 1] = (byte)TRAILER_IMPLICIT; } else { block[block.length - 2] = (byte)(trailer >>> 8); block[block.length - 1] = (byte)trailer; } block[0] &= 0x7f; byte[] b = cipher.processBlock(block, 0, block.length); clearBlock(mBuf); clearBlock(block); messageLength = 0; return b; } /** * return true if the signature represents a ISO9796-2 signature * for the passed in message. */ public boolean verifySignature( byte[] signature) { // // calculate H(m2) // byte[] m2Hash = new byte[hLen]; digest.doFinal(m2Hash, 0); byte[] block; int tLength; int mStart = 0; if (preSig == null) { try { updateWithRecoveredMessage(signature); } catch (Exception e) { return false; } } else { if (!Arrays.areEqual(preSig, signature)) { throw new IllegalStateException("updateWithRecoveredMessage called on different signature"); } } block = preBlock; mStart = preMStart; tLength = preTLength; preSig = null; preBlock = null; // // check the hashes // byte[] C = new byte[8]; LtoOSP(recoveredMessage.length * 8, C); digest.update(C, 0, C.length); if (recoveredMessage.length != 0) { digest.update(recoveredMessage, 0, recoveredMessage.length); } digest.update(m2Hash, 0, m2Hash.length); // Update for the salt digest.update(block, mStart + recoveredMessage.length, saltLength); byte[] hash = new byte[digest.getDigestSize()]; digest.doFinal(hash, 0); int off = block.length - tLength - hash.length; boolean isOkay = true; for (int i = 0; i != hash.length; i++) { if (hash[i] != block[off + i]) { isOkay = false; } } clearBlock(block); clearBlock(hash); if (!isOkay) { fullMessage = false; clearBlock(recoveredMessage); return false; } // // if they've input a message check what we've recovered against // what was input. // if (messageLength != 0) { if (!isSameAs(mBuf, recoveredMessage)) { clearBlock(mBuf); return false; } messageLength = 0; } clearBlock(mBuf); return true; } /** * Return true if the full message was recoveredMessage. * * @return true on full message recovery, false otherwise, or if not sure. * @see org.bouncycastle.crypto.SignerWithRecovery#hasFullMessage() */ public boolean hasFullMessage() { return fullMessage; } /** * Return a reference to the recoveredMessage message. * * @return the full/partial recoveredMessage message. * @see org.bouncycastle.crypto.SignerWithRecovery#getRecoveredMessage() */ public byte[] getRecoveredMessage() { return recoveredMessage; } /** * int to octet string. */ private void ItoOSP( int i, byte[] sp) { sp[0] = (byte)(i >>> 24); sp[1] = (byte)(i >>> 16); sp[2] = (byte)(i >>> 8); sp[3] = (byte)(i >>> 0); } /** * long to octet string. */ private void LtoOSP( long l, byte[] sp) { sp[0] = (byte)(l >>> 56); sp[1] = (byte)(l >>> 48); sp[2] = (byte)(l >>> 40); sp[3] = (byte)(l >>> 32); sp[4] = (byte)(l >>> 24); sp[5] = (byte)(l >>> 16); sp[6] = (byte)(l >>> 8); sp[7] = (byte)(l >>> 0); } /** * mask generator function, as described in PKCS1v2. */ private byte[] maskGeneratorFunction1( byte[] Z, int zOff, int zLen, int length) { byte[] mask = new byte[length]; byte[] hashBuf = new byte[hLen]; byte[] C = new byte[4]; int counter = 0; digest.reset(); while (counter < (length / hLen)) { ItoOSP(counter, C); digest.update(Z, zOff, zLen); digest.update(C, 0, C.length); digest.doFinal(hashBuf, 0); System.arraycopy(hashBuf, 0, mask, counter * hLen, hLen); counter++; } if ((counter * hLen) < length) { ItoOSP(counter, C); digest.update(Z, zOff, zLen); digest.update(C, 0, C.length); digest.doFinal(hashBuf, 0); System.arraycopy(hashBuf, 0, mask, counter * hLen, mask.length - (counter * hLen)); } return mask; } }
package com.didgeridone.didgeridone_andriod; import android.app.PendingIntent; import android.content.Intent; import android.content.SharedPreferences; import android.graphics.Color; import android.os.Bundle; import android.os.AsyncTask; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.ListView; import android.widget.ArrayAdapter; import android.widget.AdapterView; import android.widget.Toast; import com.google.android.gms.common.ConnectionResult; import com.google.android.gms.common.api.GoogleApiClient; import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks; import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener; import com.google.android.gms.common.api.ResultCallback; import com.google.android.gms.common.api.Status; import com.google.android.gms.location.Geofence; import com.google.android.gms.location.GeofencingRequest; import com.google.android.gms.location.LocationRequest; import com.google.android.gms.location.LocationServices; import com.google.android.gms.location.GeofencingApi; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.location.sample.geofencing.Constants; import com.google.android.gms.location.sample.geofencing.GeofenceErrorMessages; import com.google.android.gms.location.sample.geofencing.GeofenceTransitionsIntentService; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import java.io.UnsupportedEncodingException; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import org.json.JSONObject; import org.json.JSONArray; public class MainActivity extends AppCompatActivity implements ConnectionCallbacks, OnConnectionFailedListener, ResultCallback<Status> { private static final String TAG = MainActivity.class.getSimpleName(); private String User_ID = ""; private ArrayList<String> allTasks = new ArrayList<String>(); private ArrayAdapter<String> adapter; HashMap<Integer, Object> mapper = new HashMap<Integer, Object>(); /** * Provides the entry point to Google Play services. */ protected GoogleApiClient mGoogleApiClient; /** * The list of geofences used in this sample. */ protected ArrayList<Geofence> mGeofenceList; /** * Used to keep track of whether geofences were added. */ private boolean mGeofencesAdded; /** * Used when requesting to add or remove geofences. */ private PendingIntent mGeofencePendingIntent; /** * Used to persist application state about whether geofences were added. */ private SharedPreferences mSharedPreferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); SharedPreferences prefs = getSharedPreferences("userInfo", MODE_PRIVATE); User_ID = prefs.getString("userID", "default user id"); System.out.println("USER ID HERE " + User_ID); FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent intent = new Intent(MainActivity.this, MapsActivity.class); intent.putExtra("Reminder_User_Id", User_ID); startActivity(intent); } }); new DownloadTask().execute("https://didgeridone.herokuapp.com/task/" + User_ID); final ListView myList; myList = (ListView) findViewById(R.id.listView); myList.setClickable(true); myList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { String obj = mapper.get((position)).toString(); try { JSONObject jsonObj = new JSONObject(obj); Intent intent = new Intent(MainActivity.this, MapsActivity.class); intent.putExtra("Reminder_User_Id", User_ID); intent.putExtra("Reminder_Task_Id", jsonObj.get("task_id").toString()); intent.putExtra("Reminder_Name", jsonObj.get("name").toString()); intent.putExtra("Reminder_Latitude", Double.parseDouble(jsonObj.get("lat").toString())); intent.putExtra("Reminder_Longitude", Double.parseDouble(jsonObj.get("long").toString())); intent.putExtra("Reminder_Radius", Double.parseDouble(jsonObj.get("radius").toString())); startActivity(intent); } catch (Exception e) { Log.d("Didgeridoo", "Exception", e); } } }); adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, allTasks); adapter.clear(); adapter.notifyDataSetChanged(); myList.setAdapter(adapter); // Empty list for storing geofences. mGeofenceList = new ArrayList<Geofence>(); // Initially set the PendingIntent used in addGeofences() and removeGeofences() to null. mGeofencePendingIntent = null; // Retrieve an instance of the SharedPreferences object. mSharedPreferences = getSharedPreferences(Constants.SHARED_PREFERENCES_NAME, MODE_PRIVATE); // Get the value of mGeofencesAdded from SharedPreferences. Set to false as a default. mGeofencesAdded = mSharedPreferences.getBoolean(Constants.GEOFENCES_ADDED_KEY, false); // Kick off the request to build GoogleApiClient. buildGoogleApiClient(); // This isn't working right now geofencesAddedButtonState(mGeofencesAdded); } public void geofencesEnableDisableButton(View view) { toggleGeofencesEnableDisable(); } public void toggleGeofencesEnableDisable() { if (mGeofencesAdded == true) { removeGeofences(); } else { addGeofences(); } } private void geofencesAddedButtonState(boolean state) { Button geofence_button = (Button) findViewById(R.id.button_geofence); if (state == true) { // Turn the button green geofence_button.setBackgroundColor(Color.parseColor("#ff669900")); geofence_button.setText("Geofences Enabled"); } else { // Turn the button red geofence_button.setBackgroundColor(Color.parseColor("#ffcc0000")); geofence_button.setText("Geofences Disabled"); } } /** * Adds geofences, which sets alerts to be notified when the device enters or exits one of the * specified geofences. Handles the success or failure results returned by addGeofences(). */ public void addGeofences() { if (!mGoogleApiClient.isConnected()) { Toast.makeText(this, getString(R.string.not_connected), Toast.LENGTH_SHORT).show(); return; } try { LocationServices.GeofencingApi.addGeofences( mGoogleApiClient, // The GeofenceRequest object. getGeofencingRequest(), // A pending intent that that is reused when calling removeGeofences(). This // pending intent is used to generate an intent when a matched geofence // transition is observed. getGeofencePendingIntent() ).setResultCallback(this); // Result processed in onResult(). geofencesAddedButtonState(true); } catch (SecurityException securityException) { // Catch exception generated if the app does not use ACCESS_FINE_LOCATION permission. logSecurityException(securityException); geofencesAddedButtonState(false); } } /** * Removes geofences, which stops further notifications when the device enters or exits * previously registered geofences. */ public void removeGeofences() { if (!mGoogleApiClient.isConnected()) { Toast.makeText(this, getString(R.string.not_connected), Toast.LENGTH_SHORT).show(); return; } try { // Remove geofences. LocationServices.GeofencingApi.removeGeofences( mGoogleApiClient, // This is the same pending intent that was used in addGeofences(). getGeofencePendingIntent() ).setResultCallback(this); // Result processed in onResult(). geofencesAddedButtonState(false); } catch (SecurityException securityException) { // Catch exception generated if the app does not use ACCESS_FINE_LOCATION permission. logSecurityException(securityException); geofencesAddedButtonState(true); } } private void logSecurityException(SecurityException securityException) { Log.e(TAG, "Invalid location permission. " + "You need to use ACCESS_FINE_LOCATION with geofences", securityException); } /** * Builds a GoogleApiClient. Uses the {@code #addApi} method to request the LocationServices API. */ protected synchronized void buildGoogleApiClient() { mGoogleApiClient = new GoogleApiClient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(LocationServices.API) .build(); } @Override protected void onStart() { super.onStart(); mGoogleApiClient.connect(); } @Override protected void onStop() { super.onStop(); mGoogleApiClient.disconnect(); } private class DownloadTask extends AsyncTask<String, Void, String> { @Override protected String doInBackground(String... params) { try { return downloadContent(params[0]); } catch (IOException e) { return "Unable to retrieve data. URL may be invalid."; } } @Override protected void onPostExecute(String result) { adapter.notifyDataSetChanged(); } } private String downloadContent(String myurl) throws IOException { InputStream is = null; try { URL url = new URL(myurl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(30000); conn.setConnectTimeout(30000); conn.setRequestMethod("GET"); conn.setDoInput(true); conn.connect(); int response = conn.getResponseCode(); Log.d(TAG, "HTTP Response: " + response); is = conn.getInputStream(); String contentAsString = convertStreamToString(is); try { // Parse the entire JSON string JSONObject root = new JSONObject(contentAsString); JSONObject user = root.getJSONObject("user"); JSONArray tasks = user.getJSONArray("tasks"); for(int i=0;i<tasks.length();i++) { // parse the JSON object into fields and values JSONObject jsonTasks = tasks.getJSONObject(i); String name = jsonTasks.getString("name"); allTasks.add(name); int position = allTasks.indexOf(name); mapper.put(position, jsonTasks); } } catch (Exception e) { Log.d("Didgeridoo","Exception",e); } // Populate our geofence array with all our tasks for (int allTaskIndex = 0; allTaskIndex < allTasks.size(); allTaskIndex++) { JSONObject mapperData; try { mapperData = new JSONObject(mapper.get(allTaskIndex).toString()); String taskName = mapperData.getString("name"); double taskLat = Double.parseDouble(mapperData.getString("lat")); double taskLng = Double.parseDouble(mapperData.getString("long")); float taskRadius = Float.parseFloat(mapperData.getString("radius")); Geofence.Builder newBuilder = new Geofence.Builder(); newBuilder.setRequestId(taskName); newBuilder.setCircularRegion(taskLat, taskLng, taskRadius); newBuilder.setExpirationDuration(Geofence.NEVER_EXPIRE); newBuilder.setLoiteringDelay(10000); newBuilder.setTransitionTypes(Geofence.GEOFENCE_TRANSITION_ENTER | Geofence.GEOFENCE_TRANSITION_EXIT | Geofence.GEOFENCE_TRANSITION_DWELL); mGeofenceList.add(newBuilder.build()); } catch (Exception ex) { ex.printStackTrace(); } } return contentAsString; } finally { if (is != null) { is.close(); } } } private String convertStreamToString(InputStream is) { BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { sb.append(line).append('\n'); } } catch (IOException e) { e.printStackTrace(); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); } /** * Runs when a GoogleApiClient object successfully connects. */ @Override public void onConnected(Bundle connectionHint) { Log.i(TAG, "Connected to GoogleApiClient"); } @Override public void onConnectionSuspended(int cause) { // The connection to Google Play services was lost for some reason. Log.i(TAG, "Connection suspended"); // onConnected() will be called again automatically when the service reconnects } /** * Builds and returns a GeofencingRequest. Specifies the list of geofences to be monitored. * Also specifies how the geofence notifications are initially triggered. */ private GeofencingRequest getGeofencingRequest() { GeofencingRequest.Builder builder = new GeofencingRequest.Builder(); // The INITIAL_TRIGGER_ENTER flag indicates that geofencing service should trigger a // GEOFENCE_TRANSITION_ENTER notification when the geofence is added and if the device // is already inside that geofence. builder.setInitialTrigger(GeofencingRequest.INITIAL_TRIGGER_ENTER); // Add the geofences to be monitored by geofencing service. builder.addGeofences(mGeofenceList); // Return a GeofencingRequest. return builder.build(); } /** * Runs when the result of calling addGeofences() and removeGeofences() becomes available. * Either method can complete successfully or with an error. * * Since this activity implements the {@link ResultCallback} interface, we are required to * define this method. * * @param status The Status returned through a PendingIntent when addGeofences() or * removeGeofences() get called. */ public void onResult(Status status) { if (status.isSuccess()) { // Update state and save in shared preferences. mGeofencesAdded = !mGeofencesAdded; SharedPreferences.Editor editor = mSharedPreferences.edit(); editor.putBoolean(Constants.GEOFENCES_ADDED_KEY, mGeofencesAdded); editor.apply(); Toast.makeText( this, getString(mGeofencesAdded ? R.string.geofences_added : R.string.geofences_removed), Toast.LENGTH_SHORT ).show(); } else { // Get the status code for the error and log it using a user-friendly message. String errorMessage = GeofenceErrorMessages.getErrorString(this, status.getStatusCode()); Log.e(TAG, errorMessage); } } /** * Gets a PendingIntent to send with the request to add or remove Geofences. Location Services * issues the Intent inside this PendingIntent whenever a geofence transition occurs for the * current list of geofences. * * @return A PendingIntent for the IntentService that handles geofence transitions. */ private PendingIntent getGeofencePendingIntent() { // Reuse the PendingIntent if we already have it. if (mGeofencePendingIntent != null) { return mGeofencePendingIntent; } Intent intent = new Intent(this, GeofenceTransitionsIntentService.class); // We use FLAG_UPDATE_CURRENT so that we get the same pending intent back when calling // addGeofences() and removeGeofences(). return PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); } @Override public void onConnectionFailed(ConnectionResult result) { // Refer to the javadoc for ConnectionResult to see what error codes might be returned in // onConnectionFailed. Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode()); } }
package org.apache.taverna.ui.perspectives.myexperiment; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.text.ParseException; import java.util.Collections; import java.util.LinkedList; import java.util.List; import java.util.Vector; import javax.swing.BorderFactory; import javax.swing.ImageIcon; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JSplitPane; import javax.swing.SwingUtilities; import org.apache.taverna.ui.perspectives.myexperiment.model.Base64; import org.apache.taverna.ui.perspectives.myexperiment.model.MyExperimentClient; import org.apache.taverna.ui.perspectives.myexperiment.model.SearchEngine; import org.apache.taverna.ui.perspectives.myexperiment.model.Util; import org.apache.taverna.ui.perspectives.myexperiment.model.SearchEngine.QuerySearchInstance; import org.apache.taverna.workbench.icons.WorkbenchIcons; import org.apache.log4j.Logger; /** * @author Sergejs Aleksejevs */ public class SearchTabContentPanel extends JPanel implements ActionListener { // CONSTANTS private final static int SEARCH_HISTORY_LENGTH = 50; private final static int SEARCH_FAVOURITES_LENGTH = 30; protected final static String SEARCH_FROM_FAVOURITES = "searchFromFavourites"; protected final static String SEARCH_FROM_HISTORY = "searchFromHistory"; protected final static String ADD_FAVOURITE_SEARCH_INSTANCE = "addFavouriteSearchInstance"; protected final static String REMOVE_FAVOURITE_SEARCH_INSTANCE = "removeFavouriteSearchInstance"; private final MainComponent pluginMainComponent; private final MyExperimentClient myExperimentClient; private final Logger logger; // COMPONENTS private JSplitPane spMainSplitPane; private SearchOptionsPanel jpSearchOptions; private JPanel jpFavouriteSearches; private JPanel jpSearchHistory; private SearchResultsPanel jpSearchResults; private final ImageIcon iconFavourite = new ImageIcon(MyExperimentPerspective.getLocalResourceURL("favourite_icon")); private final ImageIcon iconRemove = new ImageIcon(MyExperimentPerspective.getLocalResourceURL("destroy_icon")); // Data storage private QuerySearchInstance siPreviousSearch; private LinkedList<QuerySearchInstance> llFavouriteSearches; private LinkedList<QuerySearchInstance> llSearchHistory; // Search components private final SearchEngine searchEngine; // The search engine for executing keyword query searches private final Vector<Long> vCurrentSearchThreadID; // This will keep ID of the current search thread (there will only be one such thread) public SearchTabContentPanel(MainComponent component, MyExperimentClient client, Logger logger) { super(); // set main variables to ensure access to myExperiment, logger and the parent component this.pluginMainComponent = component; this.myExperimentClient = client; this.logger = logger; // initialise the favourite searches String strFavouriteSearches = (String) myExperimentClient.getSettings().get(MyExperimentClient.INI_FAVOURITE_SEARCHES); if (strFavouriteSearches != null) { Object oFavouriteSearches = Base64.decodeToObject(strFavouriteSearches); this.llFavouriteSearches = (LinkedList<QuerySearchInstance>) oFavouriteSearches; } else { this.llFavouriteSearches = new LinkedList<QuerySearchInstance>(); } // initialise the search history String strSearchHistory = (String) myExperimentClient.getSettings().get(MyExperimentClient.INI_SEARCH_HISTORY); if (strSearchHistory != null) { Object oSearchHistory = Base64.decodeToObject(strSearchHistory); this.llSearchHistory = (LinkedList<QuerySearchInstance>) oSearchHistory; } else { this.llSearchHistory = new LinkedList<QuerySearchInstance>(); } this.initialiseUI(); this.updateFavouriteSearches(); this.updateSearchHistory(); // initialise the search engine vCurrentSearchThreadID = new Vector<Long>(1); vCurrentSearchThreadID.add(null); // this is just a placeholder, so that it's possible to update this value instead of adding new ones later this.searchEngine = new SearchEngine(vCurrentSearchThreadID, false, jpSearchResults, pluginMainComponent, myExperimentClient, logger); SwingUtilities.invokeLater(new Runnable() { public void run() { // THIS MIGHT NOT BE NEEDED AS THE SEARCH OPTIONS BOX NOW // SETS THE MINIMUM SIZE OF THE SIDEBAR PROPERLY spMainSplitPane.setDividerLocation(390); spMainSplitPane.setOneTouchExpandable(true); spMainSplitPane.setDoubleBuffered(true); } }); } private void initialiseUI() { // create search options panel jpSearchOptions = new SearchOptionsPanel(this, this.pluginMainComponent, this.myExperimentClient, this.logger); jpSearchOptions.setMaximumSize(new Dimension(1024, 0)); // HACK: this is to make sure that search options box won't be stretched // create favourite searches panel jpFavouriteSearches = new JPanel(); jpFavouriteSearches.setMaximumSize(new Dimension(1024, 0)); // HACK: this is to make sure that favourite searches box won't be stretched jpFavouriteSearches.setLayout(new GridBagLayout()); jpFavouriteSearches.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), " Favourite Searches "), BorderFactory.createEmptyBorder(0, 5, 5, 5))); // create search history panel jpSearchHistory = new JPanel(); jpSearchHistory.setMaximumSize(new Dimension(1024, 0)); // HACK: this is to make sure that search history box won't be stretched jpSearchHistory.setLayout(new GridBagLayout()); jpSearchHistory.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder(BorderFactory.createEtchedBorder(), " Search History "), BorderFactory.createEmptyBorder(0, 5, 5, 5))); // create the search sidebar JPanel jpSearchSidebar = new JPanel(); jpSearchSidebar.setLayout(new GridBagLayout()); GridBagConstraints gbConstraints = new GridBagConstraints(); gbConstraints.anchor = GridBagConstraints.NORTHWEST; gbConstraints.fill = GridBagConstraints.BOTH; gbConstraints.weightx = 1; gbConstraints.gridx = 0; gbConstraints.gridy = 0; jpSearchSidebar.add(jpSearchOptions, gbConstraints); gbConstraints.gridy = 1; jpSearchSidebar.add(jpFavouriteSearches, gbConstraints); gbConstraints.gridy = 2; jpSearchSidebar.add(jpSearchHistory, gbConstraints); JPanel jpSidebarContainer = new JPanel(); jpSidebarContainer.setLayout(new BorderLayout()); jpSidebarContainer.add(jpSearchSidebar, BorderLayout.NORTH); // wrap sidebar in a scroll pane JScrollPane spSearchSidebar = new JScrollPane(jpSidebarContainer); spSearchSidebar.getVerticalScrollBar().setUnitIncrement(ResourcePreviewBrowser.PREFERRED_SCROLL); spSearchSidebar.setMinimumSize(new Dimension(jpSidebarContainer.getMinimumSize().width + 20, 0)); // create panel for search results this.jpSearchResults = new SearchResultsPanel(this, pluginMainComponent, myExperimentClient, logger); spMainSplitPane = new JSplitPane(); spMainSplitPane.setLeftComponent(spSearchSidebar); spMainSplitPane.setRightComponent(jpSearchResults); // PUT EVERYTHING TOGETHER this.setLayout(new BorderLayout()); this.add(spMainSplitPane); } private void addToSearchListQueue(LinkedList<QuerySearchInstance> searchInstanceList, QuerySearchInstance searchInstanceToAdd, int queueSize) { // check if such entry is already in the list int iDuplicateIdx = searchInstanceList.indexOf(searchInstanceToAdd); // only do the following if the new search instance list OR current instance is not the same // as the last one in the list if (searchInstanceList.size() == 0 || iDuplicateIdx != searchInstanceList.size() - 1) { // if the current item is already in the list, remove it (then re-add at the end of the list) if (iDuplicateIdx >= 0) searchInstanceList.remove(iDuplicateIdx); // we want to keep the history size constant, therefore when it reaches a certain // size, oldest element needs to be removed if (searchInstanceList.size() >= queueSize) searchInstanceList.remove(); // in either case, add the new element to the tail of the search history searchInstanceList.offer(searchInstanceToAdd); } } private void addToFavouriteSearches(QuerySearchInstance searchInstance) { this.addToSearchListQueue(this.llFavouriteSearches, searchInstance, SEARCH_FAVOURITES_LENGTH); Collections.sort(this.llFavouriteSearches); } // the method to update search history listing protected void updateFavouriteSearches() { this.jpFavouriteSearches.removeAll(); if (this.llFavouriteSearches.size() == 0) { GridBagConstraints c = new GridBagConstraints(); c.weightx = 1.0; c.anchor = GridBagConstraints.WEST; this.jpFavouriteSearches.add(Util.generateNoneTextLabel("No favourite searches"), c); } else { for (int i = this.llFavouriteSearches.size() - 1; i >= 0; i--) { addEntryToSearchListingPanel(this.llFavouriteSearches, i, SEARCH_FROM_FAVOURITES, this.jpFavouriteSearches, this.iconRemove, REMOVE_FAVOURITE_SEARCH_INSTANCE, "<html>Click to remove from your local favourite searches.<br>" + "(This will not affect your myExperiment profile settings.)</html>"); } } this.jpFavouriteSearches.repaint(); this.jpFavouriteSearches.revalidate(); } private void addToSearchHistory(QuerySearchInstance searchInstance) { this.addToSearchListQueue(this.llSearchHistory, searchInstance, SEARCH_HISTORY_LENGTH); } // the method to update search history listing protected void updateSearchHistory() { this.jpSearchHistory.removeAll(); if (this.llSearchHistory.size() == 0) { GridBagConstraints c = new GridBagConstraints(); c.weightx = 1.0; c.anchor = GridBagConstraints.WEST; this.jpSearchHistory.add(Util.generateNoneTextLabel(SearchResultsPanel.NO_SEARCHES_STATUS), c); } else { for (int i = this.llSearchHistory.size() - 1; i >= 0; i--) { addEntryToSearchListingPanel(this.llSearchHistory, i, SEARCH_FROM_HISTORY, this.jpSearchHistory, this.iconFavourite, ADD_FAVOURITE_SEARCH_INSTANCE, "<html>Click to add to your local favourite" + " searches - these will be available every time you use Taverna.<br>(This will not affect your" + " myExperiment profile settings.)</html>"); } } this.jpSearchHistory.repaint(); this.jpSearchHistory.revalidate(); // also update search history in History tab if (this.pluginMainComponent.getHistoryBrowser() != null) { this.pluginMainComponent.getHistoryBrowser().refreshSearchHistory(); } } private void addEntryToSearchListingPanel(List<QuerySearchInstance> searchInstanceList, int iIndex, String searchAction, JPanel panelToPopulate, ImageIcon entryIcon, String iconAction, String iconActionTooltip) { // labels with search query and search settings JClickableLabel jclCurrentEntryLabel = new JClickableLabel(searchInstanceList.get(iIndex).getSearchQuery(), searchAction + ":" + iIndex, this, WorkbenchIcons.findIcon, SwingUtilities.LEFT, searchInstanceList.get(iIndex).toString()); JLabel jlCurrentEntrySettings = new JLabel(searchInstanceList.get(iIndex).detailsAsString()); jlCurrentEntrySettings.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0)); // grouping search details and search settings together JPanel jpCurentEntryDetails = new JPanel(); jpCurentEntryDetails.setLayout(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.anchor = GridBagConstraints.WEST; jpCurentEntryDetails.add(jclCurrentEntryLabel, c); c.weightx = 1.0; jpCurentEntryDetails.add(jlCurrentEntrySettings, c); // creating a "button" to add current item to favourites JClickableLabel jclFavourite = new JClickableLabel("", iconAction + ":" + iIndex, this, entryIcon, SwingUtilities.LEFT, iconActionTooltip); jclFavourite.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 0)); // putting all pieces of current item together JPanel jpCurrentEntry = new JPanel(); jpCurrentEntry.setLayout(new GridBagLayout()); c.anchor = GridBagConstraints.WEST; c.weightx = 1.0; jpCurrentEntry.add(jpCurentEntryDetails, c); c.anchor = GridBagConstraints.WEST; c.weightx = 0; jpCurrentEntry.add(jclFavourite, c); // adding current item to the history list c.fill = GridBagConstraints.HORIZONTAL; c.weightx = 1.0; c.gridx = 0; c.gridy = GridBagConstraints.RELATIVE; panelToPopulate.add(jpCurrentEntry, c); } public void actionPerformed(ActionEvent e) { if (e.getSource().equals(this.jpSearchOptions.bSearch)) { // "Search" button was clicked // if no search query is specified, display error message if (jpSearchOptions.getSearchQuery().length() == 0) { javax.swing.JOptionPane.showMessageDialog(null, "Search query is empty. Please specify your search query and try again.", "Error", JOptionPane.WARNING_MESSAGE); jpSearchOptions.focusSearchQueryField(); } else { // will ensure that if the value in the search result limit editor // is invalid, it is processed properly try { this.jpSearchOptions.jsResultLimit.commitEdit(); } catch (ParseException ex) { JOptionPane.showMessageDialog(null, "Invalid search result limit value. This should be an\n" + "integer in the range of " + SearchOptionsPanel.SEARCH_RESULT_LIMIT_MIN + ".." + SearchOptionsPanel.SEARCH_RESULT_LIMIT_MAX, "MyExperiment Plugin - Error", JOptionPane.WARNING_MESSAGE); this.jpSearchOptions.tfResultLimitTextField.selectAll(); this.jpSearchOptions.tfResultLimitTextField.requestFocusInWindow(); return; } // all fine, settings present - store the settings.. siPreviousSearch = new SearchEngine.QuerySearchInstance(jpSearchOptions.getSearchQuery(), jpSearchOptions.getResultCountLimit(), jpSearchOptions.getSearchWorkflows(), jpSearchOptions.getSearchFiles(), jpSearchOptions.getSearchPacks(), jpSearchOptions.getSearchUsers(), jpSearchOptions.getSearchGroups()); // .. and execute the query this.jpSearchOptions.focusSearchQueryField(); this.runSearch(); } } else if (e.getSource() instanceof JClickableLabel) { if (e.getActionCommand().startsWith(SEARCH_FROM_HISTORY) || e.getActionCommand().startsWith(SEARCH_FROM_FAVOURITES)) { // the part of the action command that is following the prefix is the ID in the search history / favourites storage; // this search instance is removed from history and will be re-added at the top of it when search is launched int iEntryID = Integer.parseInt(e.getActionCommand().substring(e.getActionCommand().indexOf(":") + 1)); final QuerySearchInstance si = (e.getActionCommand().startsWith(SEARCH_FROM_HISTORY) ? this.llSearchHistory.remove(iEntryID) : this.llFavouriteSearches.get(iEntryID)); // in case of favourites, no need to remove the entry // re-set search options in the settings box and re-run the search SwingUtilities.invokeLater(new Runnable() { public void run() { jpSearchOptions.setSearchQuery(si.getSearchQuery()); jpSearchOptions.setSearchAllResourceTypes(false); // reset the 'all resource types' jpSearchOptions.setSearchWorkflows(si.getSearchWorkflows()); jpSearchOptions.setSearchFiles(si.getSearchFiles()); jpSearchOptions.setSearchPacks(si.getSearchPacks()); jpSearchOptions.setSearchUsers(si.getSearchUsers()); jpSearchOptions.setSearchGroups(si.getSearchGroups()); jpSearchOptions.setResultCountLimit(si.getResultCountLimit()); // set this as the 'latest' search siPreviousSearch = si; // run the search (and update the search history) runSearch(); } }); } else if (e.getActionCommand().startsWith(ADD_FAVOURITE_SEARCH_INSTANCE)) { // get the ID of the entry in the history listing first; then fetch the instance itself int iHistID = Integer.parseInt(e.getActionCommand().substring(e.getActionCommand().indexOf(":") + 1)); final QuerySearchInstance si = this.llSearchHistory.get(iHistID); // add item to favourites and re-draw the panel SwingUtilities.invokeLater(new Runnable() { public void run() { addToFavouriteSearches(si); updateFavouriteSearches(); } }); } else if (e.getActionCommand().startsWith(REMOVE_FAVOURITE_SEARCH_INSTANCE)) { // get the ID of the entry in the favourite searches listing first; then remove the instance with that ID from the list int iFavouriteID = Integer.parseInt(e.getActionCommand().substring(e.getActionCommand().indexOf(":") + 1)); this.llFavouriteSearches.remove(iFavouriteID); // item removed from favourites - re-draw the panel now SwingUtilities.invokeLater(new Runnable() { public void run() { updateFavouriteSearches(); } }); } } else if (e.getSource().equals(this.jpSearchResults.bRefresh)) { // "Refresh" button clicked; disable clearing results and re-run previous search this.jpSearchResults.bClear.setEnabled(false); this.rerunLastSearch(); } else if (e.getSource().equals(this.jpSearchResults.bClear)) { // "Clear" button clicked - clear last search and disable re-running it siPreviousSearch = null; vCurrentSearchThreadID.set(0, null); this.jpSearchResults.clear(); this.jpSearchResults.setStatus(SearchResultsPanel.NO_SEARCHES_STATUS); this.jpSearchResults.bClear.setEnabled(false); this.jpSearchResults.bRefresh.setEnabled(false); } } // search history will get updated by default private void runSearch() { runSearch(true); } // makes preparations and runs the current search // (has an option not to update the search history) private void runSearch(boolean bUpdateHistory) { if (bUpdateHistory) { // add current search to search history .. this.addToSearchHistory(siPreviousSearch); // .. update the search history box .. SwingUtilities.invokeLater(new Runnable() { public void run() { updateSearchHistory(); } }); } // ..and run the query this.searchEngine.searchAndPopulateResults(siPreviousSearch); } // re-executes the search for the most recent query // (if searches have already been done before or were not cleared) public void rerunLastSearch() { if (this.siPreviousSearch != null) { runSearch(); } } public SearchResultsPanel getSearchResultPanel() { return (this.jpSearchResults); } public LinkedList<QuerySearchInstance> getSearchFavouritesList() { return (this.llFavouriteSearches); } public LinkedList<QuerySearchInstance> getSearchHistory() { return (this.llSearchHistory); } }
/* * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.ads.googleads.v10.services.stub; import com.google.ads.googleads.v10.services.MutateAdGroupCriteriaRequest; import com.google.ads.googleads.v10.services.MutateAdGroupCriteriaResponse; import com.google.api.core.ApiFunction; import com.google.api.core.BetaApi; import com.google.api.gax.core.GaxProperties; import com.google.api.gax.core.GoogleCredentialsProvider; import com.google.api.gax.core.InstantiatingExecutorProvider; import com.google.api.gax.grpc.GaxGrpcProperties; import com.google.api.gax.grpc.GrpcTransportChannel; import com.google.api.gax.grpc.InstantiatingGrpcChannelProvider; import com.google.api.gax.retrying.RetrySettings; import com.google.api.gax.rpc.ApiClientHeaderProvider; import com.google.api.gax.rpc.ClientContext; import com.google.api.gax.rpc.StatusCode; import com.google.api.gax.rpc.StubSettings; import com.google.api.gax.rpc.TransportChannelProvider; import com.google.api.gax.rpc.UnaryCallSettings; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import java.io.IOException; import java.util.List; import javax.annotation.Generated; import org.threeten.bp.Duration; // AUTO-GENERATED DOCUMENTATION AND CLASS. /** * Settings class to configure an instance of {@link AdGroupCriterionServiceStub}. * * <p>The default instance has everything set to sensible defaults: * * <ul> * <li> The default service address (googleads.googleapis.com) and default port (443) are used. * <li> Credentials are acquired automatically through Application Default Credentials. * <li> Retries are configured for idempotent methods but not for non-idempotent methods. * </ul> * * <p>The builder of this class is recursive, so contained classes are themselves builders. When * build() is called, the tree of builders is called to create the complete settings object. * * <p>For example, to set the total timeout of mutateAdGroupCriteria to 30 seconds: * * <pre>{@code * AdGroupCriterionServiceStubSettings.Builder adGroupCriterionServiceSettingsBuilder = * AdGroupCriterionServiceStubSettings.newBuilder(); * adGroupCriterionServiceSettingsBuilder * .mutateAdGroupCriteriaSettings() * .setRetrySettings( * adGroupCriterionServiceSettingsBuilder * .mutateAdGroupCriteriaSettings() * .getRetrySettings() * .toBuilder() * .setTotalTimeout(Duration.ofSeconds(30)) * .build()); * AdGroupCriterionServiceStubSettings adGroupCriterionServiceSettings = * adGroupCriterionServiceSettingsBuilder.build(); * }</pre> */ @Generated("by gapic-generator-java") public class AdGroupCriterionServiceStubSettings extends StubSettings<AdGroupCriterionServiceStubSettings> { /** The default scopes of the service. */ private static final ImmutableList<String> DEFAULT_SERVICE_SCOPES = ImmutableList.<String>builder().add("https://www.googleapis.com/auth/adwords").build(); private final UnaryCallSettings<MutateAdGroupCriteriaRequest, MutateAdGroupCriteriaResponse> mutateAdGroupCriteriaSettings; /** Returns the object with the settings used for calls to mutateAdGroupCriteria. */ public UnaryCallSettings<MutateAdGroupCriteriaRequest, MutateAdGroupCriteriaResponse> mutateAdGroupCriteriaSettings() { return mutateAdGroupCriteriaSettings; } @BetaApi("A restructuring of stub classes is planned, so this may break in the future") public AdGroupCriterionServiceStub createStub() throws IOException { if (getTransportChannelProvider() .getTransportName() .equals(GrpcTransportChannel.getGrpcTransportName())) { return GrpcAdGroupCriterionServiceStub.create(this); } throw new UnsupportedOperationException( String.format( "Transport not supported: %s", getTransportChannelProvider().getTransportName())); } /** Returns a builder for the default ExecutorProvider for this service. */ public static InstantiatingExecutorProvider.Builder defaultExecutorProviderBuilder() { return InstantiatingExecutorProvider.newBuilder(); } /** Returns the default service endpoint. */ public static String getDefaultEndpoint() { return "googleads.googleapis.com:443"; } /** Returns the default mTLS service endpoint. */ public static String getDefaultMtlsEndpoint() { return "googleads.mtls.googleapis.com:443"; } /** Returns the default service scopes. */ public static List<String> getDefaultServiceScopes() { return DEFAULT_SERVICE_SCOPES; } /** Returns a builder for the default credentials for this service. */ public static GoogleCredentialsProvider.Builder defaultCredentialsProviderBuilder() { return GoogleCredentialsProvider.newBuilder() .setScopesToApply(DEFAULT_SERVICE_SCOPES) .setUseJwtAccessWithScope(true); } /** Returns a builder for the default ChannelProvider for this service. */ public static InstantiatingGrpcChannelProvider.Builder defaultGrpcTransportProviderBuilder() { return InstantiatingGrpcChannelProvider.newBuilder() .setMaxInboundMessageSize(Integer.MAX_VALUE); } public static TransportChannelProvider defaultTransportChannelProvider() { return defaultGrpcTransportProviderBuilder().build(); } @BetaApi("The surface for customizing headers is not stable yet and may change in the future.") public static ApiClientHeaderProvider.Builder defaultApiClientHeaderProviderBuilder() { return ApiClientHeaderProvider.newBuilder() .setGeneratedLibToken( "gapic", GaxProperties.getLibraryVersion(AdGroupCriterionServiceStubSettings.class)) .setTransportToken( GaxGrpcProperties.getGrpcTokenName(), GaxGrpcProperties.getGrpcVersion()); } /** Returns a new builder for this class. */ public static Builder newBuilder() { return Builder.createDefault(); } /** Returns a new builder for this class. */ public static Builder newBuilder(ClientContext clientContext) { return new Builder(clientContext); } /** Returns a builder containing all the values of this settings class. */ public Builder toBuilder() { return new Builder(this); } protected AdGroupCriterionServiceStubSettings(Builder settingsBuilder) throws IOException { super(settingsBuilder); mutateAdGroupCriteriaSettings = settingsBuilder.mutateAdGroupCriteriaSettings().build(); } /** Builder for AdGroupCriterionServiceStubSettings. */ public static class Builder extends StubSettings.Builder<AdGroupCriterionServiceStubSettings, Builder> { private final ImmutableList<UnaryCallSettings.Builder<?, ?>> unaryMethodSettingsBuilders; private final UnaryCallSettings.Builder< MutateAdGroupCriteriaRequest, MutateAdGroupCriteriaResponse> mutateAdGroupCriteriaSettings; private static final ImmutableMap<String, ImmutableSet<StatusCode.Code>> RETRYABLE_CODE_DEFINITIONS; static { ImmutableMap.Builder<String, ImmutableSet<StatusCode.Code>> definitions = ImmutableMap.builder(); definitions.put( "retry_policy_0_codes", ImmutableSet.copyOf( Lists.<StatusCode.Code>newArrayList( StatusCode.Code.UNAVAILABLE, StatusCode.Code.DEADLINE_EXCEEDED))); RETRYABLE_CODE_DEFINITIONS = definitions.build(); } private static final ImmutableMap<String, RetrySettings> RETRY_PARAM_DEFINITIONS; static { ImmutableMap.Builder<String, RetrySettings> definitions = ImmutableMap.builder(); RetrySettings settings = null; settings = RetrySettings.newBuilder() .setInitialRetryDelay(Duration.ofMillis(5000L)) .setRetryDelayMultiplier(1.3) .setMaxRetryDelay(Duration.ofMillis(60000L)) .setInitialRpcTimeout(Duration.ofMillis(3600000L)) .setRpcTimeoutMultiplier(1.0) .setMaxRpcTimeout(Duration.ofMillis(3600000L)) .setTotalTimeout(Duration.ofMillis(3600000L)) .build(); definitions.put("retry_policy_0_params", settings); RETRY_PARAM_DEFINITIONS = definitions.build(); } protected Builder() { this(((ClientContext) null)); } protected Builder(ClientContext clientContext) { super(clientContext); mutateAdGroupCriteriaSettings = UnaryCallSettings.newUnaryCallSettingsBuilder(); unaryMethodSettingsBuilders = ImmutableList.<UnaryCallSettings.Builder<?, ?>>of(mutateAdGroupCriteriaSettings); initDefaults(this); } protected Builder(AdGroupCriterionServiceStubSettings settings) { super(settings); mutateAdGroupCriteriaSettings = settings.mutateAdGroupCriteriaSettings.toBuilder(); unaryMethodSettingsBuilders = ImmutableList.<UnaryCallSettings.Builder<?, ?>>of(mutateAdGroupCriteriaSettings); } private static Builder createDefault() { Builder builder = new Builder(((ClientContext) null)); builder.setTransportChannelProvider(defaultTransportChannelProvider()); builder.setCredentialsProvider(defaultCredentialsProviderBuilder().build()); builder.setInternalHeaderProvider(defaultApiClientHeaderProviderBuilder().build()); builder.setEndpoint(getDefaultEndpoint()); builder.setMtlsEndpoint(getDefaultMtlsEndpoint()); builder.setSwitchToMtlsEndpointAllowed(true); return initDefaults(builder); } private static Builder initDefaults(Builder builder) { builder .mutateAdGroupCriteriaSettings() .setRetryableCodes(RETRYABLE_CODE_DEFINITIONS.get("retry_policy_0_codes")) .setRetrySettings(RETRY_PARAM_DEFINITIONS.get("retry_policy_0_params")); return builder; } /** * Applies the given settings updater function to all of the unary API methods in this service. * * <p>Note: This method does not support applying settings to streaming methods. */ public Builder applyToAllUnaryMethods( ApiFunction<UnaryCallSettings.Builder<?, ?>, Void> settingsUpdater) { super.applyToAllUnaryMethods(unaryMethodSettingsBuilders, settingsUpdater); return this; } public ImmutableList<UnaryCallSettings.Builder<?, ?>> unaryMethodSettingsBuilders() { return unaryMethodSettingsBuilders; } /** Returns the builder for the settings used for calls to mutateAdGroupCriteria. */ public UnaryCallSettings.Builder<MutateAdGroupCriteriaRequest, MutateAdGroupCriteriaResponse> mutateAdGroupCriteriaSettings() { return mutateAdGroupCriteriaSettings; } @Override public AdGroupCriterionServiceStubSettings build() throws IOException { return new AdGroupCriterionServiceStubSettings(this); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.arrow.vector; import static org.junit.Assert.*; import static org.junit.jupiter.api.Assertions.assertThrows; import org.apache.arrow.memory.BufferAllocator; import org.apache.arrow.vector.holders.FixedSizeBinaryHolder; import org.apache.arrow.vector.holders.NullableFixedSizeBinaryHolder; import org.junit.After; import org.junit.Before; import org.junit.Test; import io.netty.buffer.ArrowBuf; public class TestFixedSizeBinaryVector { private static final int numValues = 123; private static final int typeWidth = 9; private static final int smallDataSize = 6; private static final int largeDataSize = 12; private static byte[][] values; static { values = new byte[numValues][typeWidth]; for (int i = 0; i < numValues; i++) { for (int j = 0; j < typeWidth; j++) { values[i][j] = ((byte) i); } } } private ArrowBuf[] bufs = new ArrowBuf[numValues]; private FixedSizeBinaryHolder[] holders = new FixedSizeBinaryHolder[numValues]; private NullableFixedSizeBinaryHolder[] nullableHolders = new NullableFixedSizeBinaryHolder[numValues]; private static byte[] smallValue; static { smallValue = new byte[smallDataSize]; for (int i = 0; i < smallDataSize; i++) { smallValue[i] = ((byte) i); } } private ArrowBuf smallBuf; private FixedSizeBinaryHolder smallHolder; private NullableFixedSizeBinaryHolder smallNullableHolder; private static byte[] largeValue; static { largeValue = new byte[largeDataSize]; for (int i = 0; i < largeDataSize; i++) { largeValue[i] = ((byte) i); } } private ArrowBuf largeBuf; private FixedSizeBinaryHolder largeHolder; private NullableFixedSizeBinaryHolder largeNullableHolder; private BufferAllocator allocator; private FixedSizeBinaryVector vector; private static void failWithException(String message) throws Exception { throw new Exception(message); } @Before public void init() throws Exception { allocator = new DirtyRootAllocator(Integer.MAX_VALUE, (byte) 100); vector = new FixedSizeBinaryVector("fixedSizeBinary", allocator, typeWidth); vector.allocateNew(); for (int i = 0; i < numValues; i++) { bufs[i] = allocator.buffer(typeWidth); bufs[i].setBytes(0, values[i]); holders[i] = new FixedSizeBinaryHolder(); holders[i].byteWidth = typeWidth; holders[i].buffer = bufs[i]; nullableHolders[i] = new NullableFixedSizeBinaryHolder(); nullableHolders[i].byteWidth = typeWidth; nullableHolders[i].buffer = bufs[i]; nullableHolders[i].isSet = 1; } smallBuf = allocator.buffer(smallDataSize); smallBuf.setBytes(0, smallValue); smallHolder = new FixedSizeBinaryHolder(); smallHolder.byteWidth = smallDataSize; smallHolder.buffer = smallBuf; smallNullableHolder = new NullableFixedSizeBinaryHolder(); smallNullableHolder.byteWidth = smallDataSize; smallNullableHolder.buffer = smallBuf; largeBuf = allocator.buffer(largeDataSize); largeBuf.setBytes(0, largeValue); largeHolder = new FixedSizeBinaryHolder(); largeHolder.byteWidth = typeWidth; largeHolder.buffer = largeBuf; largeNullableHolder = new NullableFixedSizeBinaryHolder(); largeNullableHolder.byteWidth = typeWidth; largeNullableHolder.buffer = largeBuf; } @After public void terminate() throws Exception { for (int i = 0; i < numValues; i++) { bufs[i].close(); } smallBuf.close(); largeBuf.close(); vector.close(); allocator.close(); } @Test public void testSetUsingByteArray() { for (int i = 0; i < numValues; i++) { vector.set(i, values[i]); } vector.setValueCount(numValues); for (int i = 0; i < numValues; i++) { assertArrayEquals(values[i], vector.getObject(i)); } } @Test public void testSetUsingNull() { final byte[] value = null; for (int i = 0; i < numValues; i++) { final int index = i; Exception e = assertThrows(NullPointerException.class, () -> { vector.set(index, value); }); assertEquals("expecting a valid byte array", e.getMessage()); } } @Test public void testSetUsingHolder() { for (int i = 0; i < numValues; i++) { vector.set(i, holders[i]); } vector.setValueCount(numValues); for (int i = 0; i < numValues; i++) { assertArrayEquals(values[i], vector.getObject(i)); } } @Test public void testSetUsingNullableHolder() { for (int i = 0; i < numValues; i++) { vector.set(i, nullableHolders[i]); } vector.setValueCount(numValues); for (int i = 0; i < numValues; i++) { assertArrayEquals(values[i], vector.getObject(i)); } } @Test public void testGetUsingNullableHolder() { for (int i = 0; i < numValues; i++) { vector.set(i, holders[i]); } vector.setValueCount(numValues); for (int i = 0; i < numValues; i++) { vector.get(i, nullableHolders[i]); assertEquals(typeWidth, nullableHolders[i].byteWidth); assertTrue(nullableHolders[i].isSet > 0); byte[] actual = new byte[typeWidth]; nullableHolders[i].buffer.getBytes(0, actual, 0, typeWidth); assertArrayEquals(values[i], actual); } } @Test public void testSetWithInvalidInput() throws Exception { String errorMsg = "input data needs to be at least " + typeWidth + " bytes"; // test small inputs, byteWidth matches but value or buffer is too small try { vector.set(0, smallValue); failWithException(errorMsg); } catch (AssertionError ignore) { } try { vector.set(0, smallHolder); failWithException(errorMsg); } catch (AssertionError ignore) { } try { vector.set(0, smallNullableHolder); failWithException(errorMsg); } catch (AssertionError ignore) { } try { vector.set(0, smallBuf); failWithException(errorMsg); } catch (AssertionError ignore) { } // test large inputs, byteWidth matches but value or buffer is bigger than byteWidth vector.set(0, largeValue); vector.set(0, largeHolder); vector.set(0, largeNullableHolder); vector.set(0, largeBuf); } @Test public void setSetSafeWithInvalidInput() throws Exception { String errorMsg = "input data needs to be at least " + typeWidth + " bytes"; // test small inputs, byteWidth matches but value or buffer is too small try { vector.setSafe(0, smallValue); failWithException(errorMsg); } catch (AssertionError ignore) { } try { vector.setSafe(0, smallHolder); failWithException(errorMsg); } catch (AssertionError ignore) { } try { vector.setSafe(0, smallNullableHolder); failWithException(errorMsg); } catch (AssertionError ignore) { } try { vector.setSafe(0, smallBuf); failWithException(errorMsg); } catch (AssertionError ignore) { } // test large inputs, byteWidth matches but value or buffer is bigger than byteWidth vector.setSafe(0, largeValue); vector.setSafe(0, largeHolder); vector.setSafe(0, largeNullableHolder); vector.setSafe(0, largeBuf); } @Test public void testGetNull() { vector.setNull(0); assertNull(vector.get(0)); } }
package datagrant; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.zip.GZIPInputStream; import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; import org.json.JSONException; import classifiers.BayesDocument; import datagrant.sources.TweetSearchDataSource; import tools.Data; import tools.JSON; import tools.TweetWriter; public class Run { static <K,V extends Comparable<? super V>> SortedSet<Map.Entry<K,V>> entriesSortedByValues(Map<K,V> map) { Comparator<Map.Entry<K,V>> cmp = new Comparator<Map.Entry<K,V>>() { @Override public int compare(Map.Entry<K,V> e1, Map.Entry<K,V> e2) { int res = e1.getValue().compareTo(e2.getValue()); return res != 0 ? res : 1; } }; SortedSet<Map.Entry<K,V>> sortedEntries = new TreeSet<Map.Entry<K,V>>(cmp); sortedEntries.addAll(map.entrySet()); return sortedEntries; } public Map<String, Double> wordCountRelative = new HashMap<String, Double>(); public Map<String, Integer> wordCount = new TreeMap<String, Integer>(); public void add(String key) { if(key.length() > 1) { key = key.toLowerCase(); Integer count = wordCount.containsKey(key) ? wordCount.get(key) : 0; count++; wordCount.put(key, count); } } public void loadRelativeWordCount(String inputFile) throws IOException { FileInputStream fileStream = new FileInputStream(new File(inputFile)); InputStreamReader inputStream = new InputStreamReader(fileStream, "UTF-8"); BufferedReader reader = new BufferedReader(inputStream); String line; int lineCounter = 0; while((line = reader.readLine()) != null) { if(line.length() < 1) continue; String[] tokens = line.split("\\s+"); wordCountRelative.put(tokens[1].trim().toLowerCase(), Double.parseDouble(tokens[2]) / 1000000000.0); lineCounter++; if(lineCounter % 1000 == 0) System.out.println("relative Process "+lineCounter); } } public void printWordCounts() { System.out.println("Wordcounts"); Double defaultRelativeCount = 0.00001; try { loadRelativeWordCount("../data/wordCounts.txt"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } Map<String, Double> relativedWordCount = new HashMap<String, Double>(); int totalWords = 0; for(Integer count : wordCount.values()) { totalWords += count; } for(Entry<String, Integer> entry : wordCount.entrySet()) { Double tweetRelativeCount = (new Double(entry.getValue())/totalWords); Double normalRelativeCount = wordCountRelative.containsKey(entry.getKey()) ? wordCountRelative.get(entry.getKey()) : defaultRelativeCount; Double relative = tweetRelativeCount / normalRelativeCount; relativedWordCount.put(entry.getKey(), relative); } for(Entry<String, Double> entry : entriesSortedByValues(relativedWordCount)) { System.out.println(entry.getKey() + "\t"+entry.getValue()); } System.out.println("End"); } public void parse(String inputFile) throws FileNotFoundException, UnsupportedEncodingException { try { FileInputStream fileStream = new FileInputStream(new File(inputFile)); InputStreamReader inputStream = new InputStreamReader(fileStream, "UTF-8"); BufferedReader reader = new BufferedReader(inputStream); String line; int lineCounter = 0; while((line = reader.readLine()) != null) { String tweetText = JSON.parse(line).getString("text"); tweetText = tweetText.replaceAll("[^\\w\\#\\s]+"," "); for (String token : tweetText.split("\\s+")) { if(!token.equals("")) add(token); } lineCounter++; if(lineCounter % 1000 == 0) System.out.println("Process "+lineCounter); } fileStream.close(); inputStream.close(); reader.close(); } catch (JSONException | IOException e) { e.printStackTrace(); } printWordCounts(); } public static void getNormalTweets() { TweetWriter writer = new TweetWriter("../data/tweets_non_related_150615.json.gz"); List<TweetSearchDataSource> sources = new ArrayList<TweetSearchDataSource>(); sources.add(new TweetSearchDataSource("lang:nl")); sources.add(new TweetSearchDataSource("lang:en")); sources.add(new TweetSearchDataSource("lang:es")); sources.add(new TweetSearchDataSource("lang:fr")); sources.add(new TweetSearchDataSource("lang:de")); sources.add(new TweetSearchDataSource("lang:it")); for(TweetSearchDataSource s : sources) { int total = 3000; System.out.println("Source"); int i = 0; while(s.hasNext()) { i++; if(i > total) { break; } if(i % 100 == 0) System.out.println("progress "+i); writer.write(s.next()); } } writer.close(); } public static void main(String[] args) throws IOException { getNormalTweets(); /*String inputFile = "../data/frenchgp-live_compacted.json.gz"; String hashtag = "#frenchgp"; FileInputStream fileStream = new FileInputStream(new File(inputFile)); GZIPInputStream gzipStream = new GZIPInputStream(fileStream); InputStreamReader inputStream = new InputStreamReader(gzipStream, "UTF-8"); BufferedReader reader = new BufferedReader(inputStream); String line; int i = 0; int tweets = 0; while((line = reader.readLine()) != null) { BayesDocument doc = new BayesDocument(line); String tweetText = doc.getJson().optString("text").replace("\n", " "); if(Data.containsToken(tweetText, hashtag) && Math.random() < 0.5) { System.out.println(";\""+tweetText+"\""); tweets++; } if(tweets >= 100) break; i++; } reader.close(); */ } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.thrift; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.hbase.KeyValue; import org.apache.hadoop.hbase.client.Table; import org.apache.hadoop.hbase.thrift.ThriftServerRunner.HBaseHandler; import org.apache.hadoop.hbase.thrift.generated.TIncrement; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.util.Threads; import org.apache.hadoop.metrics2.util.MBeans; import org.apache.thrift.TException; /** * This class will coalesce increments from a thift server if * hbase.regionserver.thrift.coalesceIncrement is set to true. Turning this * config to true will cause the thrift server to queue increments into an * instance of this class. The thread pool associated with this class will drain * the coalesced increments as the thread is able. This can cause data loss if the * thrift server dies or is shut down before everything in the queue is drained. * */ public class IncrementCoalescer implements IncrementCoalescerMBean { /** * Used to identify a cell that will be incremented. * */ static class FullyQualifiedRow { private byte[] table; private byte[] rowKey; private byte[] family; private byte[] qualifier; public FullyQualifiedRow(byte[] table, byte[] rowKey, byte[] fam, byte[] qual) { super(); this.table = table; this.rowKey = rowKey; this.family = fam; this.qualifier = qual; } public byte[] getTable() { return table; } public void setTable(byte[] table) { this.table = table; } public byte[] getRowKey() { return rowKey; } public void setRowKey(byte[] rowKey) { this.rowKey = rowKey; } public byte[] getFamily() { return family; } public void setFamily(byte[] fam) { this.family = fam; } public byte[] getQualifier() { return qualifier; } public void setQualifier(byte[] qual) { this.qualifier = qual; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Arrays.hashCode(family); result = prime * result + Arrays.hashCode(qualifier); result = prime * result + Arrays.hashCode(rowKey); result = prime * result + Arrays.hashCode(table); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; FullyQualifiedRow other = (FullyQualifiedRow) obj; if (!Arrays.equals(family, other.family)) return false; if (!Arrays.equals(qualifier, other.qualifier)) return false; if (!Arrays.equals(rowKey, other.rowKey)) return false; if (!Arrays.equals(table, other.table)) return false; return true; } } static class DaemonThreadFactory implements ThreadFactory { static final AtomicInteger poolNumber = new AtomicInteger(1); final ThreadGroup group; final AtomicInteger threadNumber = new AtomicInteger(1); final String namePrefix; DaemonThreadFactory() { SecurityManager s = System.getSecurityManager(); group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup(); namePrefix = "ICV-" + poolNumber.getAndIncrement() + "-thread-"; } public Thread newThread(Runnable r) { Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0); if (!t.isDaemon()) t.setDaemon(true); if (t.getPriority() != Thread.NORM_PRIORITY) t.setPriority(Thread.NORM_PRIORITY); return t; } } private final AtomicLong failedIncrements = new AtomicLong(); private final AtomicLong successfulCoalescings = new AtomicLong(); private final AtomicLong totalIncrements = new AtomicLong(); private final ConcurrentMap<FullyQualifiedRow, Long> countersMap = new ConcurrentHashMap<>(100000, 0.75f, 1500); private final ThreadPoolExecutor pool; private final HBaseHandler handler; private int maxQueueSize = 500000; private static final int CORE_POOL_SIZE = 1; private static final Log LOG = LogFactory.getLog(FullyQualifiedRow.class); @SuppressWarnings("deprecation") public IncrementCoalescer(HBaseHandler hand) { this.handler = hand; LinkedBlockingQueue<Runnable> queue = new LinkedBlockingQueue<>(); pool = new ThreadPoolExecutor(CORE_POOL_SIZE, CORE_POOL_SIZE, 50, TimeUnit.MILLISECONDS, queue, Threads.newDaemonThreadFactory("IncrementCoalescer")); MBeans.register("thrift", "Thrift", this); } public boolean queueIncrement(TIncrement inc) throws TException { if (!canQueue()) { failedIncrements.incrementAndGet(); return false; } return internalQueueTincrement(inc); } public boolean queueIncrements(List<TIncrement> incs) throws TException { if (!canQueue()) { failedIncrements.incrementAndGet(); return false; } for (TIncrement tinc : incs) { internalQueueTincrement(tinc); } return true; } private boolean internalQueueTincrement(TIncrement inc) throws TException { byte[][] famAndQf = KeyValue.parseColumn(inc.getColumn()); if (famAndQf.length != 2) return false; return internalQueueIncrement(inc.getTable(), inc.getRow(), famAndQf[0], famAndQf[1], inc.getAmmount()); } private boolean internalQueueIncrement(byte[] tableName, byte[] rowKey, byte[] fam, byte[] qual, long ammount) throws TException { int countersMapSize = countersMap.size(); //Make sure that the number of threads is scaled. dynamicallySetCoreSize(countersMapSize); totalIncrements.incrementAndGet(); FullyQualifiedRow key = new FullyQualifiedRow(tableName, rowKey, fam, qual); long currentAmount = ammount; // Spin until able to insert the value back without collisions while (true) { Long value = countersMap.remove(key); if (value == null) { // There was nothing there, create a new value value = Long.valueOf(currentAmount); } else { value += currentAmount; successfulCoalescings.incrementAndGet(); } // Try to put the value, only if there was none Long oldValue = countersMap.putIfAbsent(key, value); if (oldValue == null) { // We were able to put it in, we're done break; } // Someone else was able to put a value in, so let's remember our // current value (plus what we picked up) and retry to add it in currentAmount = value; } // We limit the size of the queue simply because all we need is a // notification that something needs to be incremented. No need // for millions of callables that mean the same thing. if (pool.getQueue().size() <= 1000) { // queue it up Callable<Integer> callable = createIncCallable(); pool.submit(callable); } return true; } public boolean canQueue() { return countersMap.size() < maxQueueSize; } private Callable<Integer> createIncCallable() { return new Callable<Integer>() { @Override public Integer call() throws Exception { int failures = 0; Set<FullyQualifiedRow> keys = countersMap.keySet(); for (FullyQualifiedRow row : keys) { Long counter = countersMap.remove(row); if (counter == null) { continue; } Table table = null; try { table = handler.getTable(row.getTable()); if (failures > 2) { throw new IOException("Auto-Fail rest of ICVs"); } table.incrementColumnValue(row.getRowKey(), row.getFamily(), row.getQualifier(), counter); } catch (IOException e) { // log failure of increment failures++; LOG.error("FAILED_ICV: " + Bytes.toString(row.getTable()) + ", " + Bytes.toStringBinary(row.getRowKey()) + ", " + Bytes.toStringBinary(row.getFamily()) + ", " + Bytes.toStringBinary(row.getQualifier()) + ", " + counter, e); } finally{ if(table != null){ table.close(); } } } return failures; } }; } /** * This method samples the incoming requests and, if selected, will check if * the corePoolSize should be changed. * @param countersMapSize */ private void dynamicallySetCoreSize(int countersMapSize) { // Here we are using countersMapSize as a random number, meaning this // could be a Random object if (countersMapSize % 10 != 0) { return; } double currentRatio = (double) countersMapSize / (double) maxQueueSize; int newValue = 1; if (currentRatio < 0.1) { // it's 1 } else if (currentRatio < 0.3) { newValue = 2; } else if (currentRatio < 0.5) { newValue = 4; } else if (currentRatio < 0.7) { newValue = 8; } else if (currentRatio < 0.9) { newValue = 14; } else { newValue = 22; } if (pool.getCorePoolSize() != newValue) { pool.setCorePoolSize(newValue); } } // MBean get/set methods public int getQueueSize() { return pool.getQueue().size(); } public int getMaxQueueSize() { return this.maxQueueSize; } public void setMaxQueueSize(int newSize) { this.maxQueueSize = newSize; } public long getPoolCompletedTaskCount() { return pool.getCompletedTaskCount(); } public long getPoolTaskCount() { return pool.getTaskCount(); } public int getPoolLargestPoolSize() { return pool.getLargestPoolSize(); } public int getCorePoolSize() { return pool.getCorePoolSize(); } public void setCorePoolSize(int newCoreSize) { pool.setCorePoolSize(newCoreSize); } public int getMaxPoolSize() { return pool.getMaximumPoolSize(); } public void setMaxPoolSize(int newMaxSize) { pool.setMaximumPoolSize(newMaxSize); } public long getFailedIncrements() { return failedIncrements.get(); } public long getSuccessfulCoalescings() { return successfulCoalescings.get(); } public long getTotalIncrements() { return totalIncrements.get(); } public long getCountersMapSize() { return countersMap.size(); } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.gson.internal; import java.util.AbstractCollection; import java.util.AbstractMap; import java.util.AbstractSet; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Random; import java.util.Set; /** * A map of strings to values. Like LinkedHashMap, this map's iteration order is * well defined: it is the order that elements were inserted into the map. This * map does not support null keys. * * <p>This implementation was derived from Android 4.0's LinkedHashMap. */ public final class StringMap<V> extends AbstractMap<String, V> { /** * Min capacity (other than zero) for a HashMap. Must be a power of two * greater than 1 (and less than 1 << 30). */ private static final int MINIMUM_CAPACITY = 4; /** * Max capacity for a HashMap. Must be a power of two >= MINIMUM_CAPACITY. */ private static final int MAXIMUM_CAPACITY = 1 << 30; /** * A dummy entry in the circular linked list of entries in the map. * The first real entry is header.nxt, and the last is header.prv. * If the map is empty, header.nxt == header && header.prv == header. */ private LinkedEntry<V> header; /** * An empty table shared by all zero-capacity maps (typically from default * constructor). It is never written to, and replaced on first put. Its size * is set to half the minimum, so that the first resize will create a * minimum-sized table. */ @SuppressWarnings("rawtypes") private static final Entry[] EMPTY_TABLE = new LinkedEntry[MINIMUM_CAPACITY >>> 1]; /** * The hash table. If this hash map contains a mapping for null, it is * not represented this hash table. */ private LinkedEntry<V>[] table; /** * The number of mappings in this hash map. */ private int size; /** * The table is rehashed when its size exceeds this threshold. * The value of this field is generally .75 * capacity, except when * the capacity is zero, as described in the EMPTY_TABLE declaration * above. */ private int threshold; // Views - lazily initialized private Set<String> keySet; private Set<Entry<String, V>> entrySet; private Collection<V> values; @SuppressWarnings("unchecked") public StringMap() { table = (LinkedEntry<V>[]) EMPTY_TABLE; threshold = -1; // Forces first put invocation to replace EMPTY_TABLE header = new LinkedEntry<V>(); } @Override public int size() { return size; } @Override public boolean containsKey(Object key) { return key instanceof String && getEntry((String) key) != null; } @Override public V get(Object key) { if (key instanceof String) { LinkedEntry<V> entry = getEntry((String) key); return entry != null ? entry.value : null; } else { return null; } } private LinkedEntry<V> getEntry(String key) { if (key == null) { return null; } int hash = hash(key); LinkedEntry<V>[] tab = table; for (LinkedEntry<V> e = tab[hash & (tab.length - 1)]; e != null; e = e.next) { String eKey = e.key; if (eKey == key || (e.hash == hash && key.equals(eKey))) { return e; } } return null; } @Override public V put(String key, V value) { if (key == null) { throw new NullPointerException("key == null"); } int hash = hash(key); LinkedEntry<V>[] tab = table; int index = hash & (tab.length - 1); for (LinkedEntry<V> e = tab[index]; e != null; e = e.next) { if (e.hash == hash && key.equals(e.key)) { V oldValue = e.value; e.value = value; return oldValue; } } // No entry for (non-null) key is present; create one if (size++ > threshold) { tab = doubleCapacity(); index = hash & (tab.length - 1); } addNewEntry(key, value, hash, index); return null; } private void addNewEntry(String key, V value, int hash, int index) { LinkedEntry<V> header = this.header; // Create new entry, link it on to list, and put it into table LinkedEntry<V> oldTail = header.prv; LinkedEntry<V> newTail = new LinkedEntry<V>( key, value, hash, table[index], header, oldTail); table[index] = oldTail.nxt = header.prv = newTail; } /** * Allocate a table of the given capacity and set the threshold accordingly. * @param newCapacity must be a power of two */ private LinkedEntry<V>[] makeTable(int newCapacity) { @SuppressWarnings("unchecked") LinkedEntry<V>[] newTable = (LinkedEntry<V>[]) new LinkedEntry[newCapacity]; table = newTable; threshold = (newCapacity >> 1) + (newCapacity >> 2); // 3/4 capacity return newTable; } /** * Doubles the capacity of the hash table. Existing entries are placed in * the correct bucket on the enlarged table. If the current capacity is, * MAXIMUM_CAPACITY, this method is a no-op. Returns the table, which * will be new unless we were already at MAXIMUM_CAPACITY. */ private LinkedEntry<V>[] doubleCapacity() { LinkedEntry<V>[] oldTable = table; int oldCapacity = oldTable.length; if (oldCapacity == MAXIMUM_CAPACITY) { return oldTable; } int newCapacity = oldCapacity * 2; LinkedEntry<V>[] newTable = makeTable(newCapacity); if (size == 0) { return newTable; } for (int j = 0; j < oldCapacity; j++) { /* * Rehash the bucket using the minimum number of field writes. * This is the most subtle and delicate code in the class. */ LinkedEntry<V> e = oldTable[j]; if (e == null) { continue; } int highBit = e.hash & oldCapacity; LinkedEntry<V> broken = null; newTable[j | highBit] = e; for (LinkedEntry<V> n = e.next; n != null; e = n, n = n.next) { int nextHighBit = n.hash & oldCapacity; if (nextHighBit != highBit) { if (broken == null) { newTable[j | nextHighBit] = n; } else { broken.next = n; } broken = e; highBit = nextHighBit; } } if (broken != null) { broken.next = null; } } return newTable; } @Override public V remove(Object key) { if (key == null || !(key instanceof String)) { return null; } int hash = hash((String) key); LinkedEntry<V>[] tab = table; int index = hash & (tab.length - 1); for (LinkedEntry<V> e = tab[index], prev = null; e != null; prev = e, e = e.next) { if (e.hash == hash && key.equals(e.key)) { if (prev == null) { tab[index] = e.next; } else { prev.next = e.next; } size--; unlink(e); return e.value; } } return null; } private void unlink(LinkedEntry<V> e) { e.prv.nxt = e.nxt; e.nxt.prv = e.prv; e.nxt = e.prv = null; // Help the GC (for performance) } @Override public void clear() { if (size != 0) { Arrays.fill(table, null); size = 0; } // Clear all links to help GC LinkedEntry<V> header = this.header; for (LinkedEntry<V> e = header.nxt; e != header; ) { LinkedEntry<V> nxt = e.nxt; e.nxt = e.prv = null; e = nxt; } header.nxt = header.prv = header; } @Override public Set<String> keySet() { Set<String> ks = keySet; return (ks != null) ? ks : (keySet = new KeySet()); } @Override public Collection<V> values() { Collection<V> vs = values; return (vs != null) ? vs : (values = new Values()); } public Set<Entry<String, V>> entrySet() { Set<Entry<String, V>> es = entrySet; return (es != null) ? es : (entrySet = new EntrySet()); } static class LinkedEntry<V> implements Entry<String, V> { final String key; V value; final int hash; LinkedEntry<V> next; LinkedEntry<V> nxt; LinkedEntry<V> prv; /** Create the header entry */ LinkedEntry() { this(null, null, 0, null, null, null); nxt = prv = this; } LinkedEntry(String key, V value, int hash, LinkedEntry<V> next, LinkedEntry<V> nxt, LinkedEntry<V> prv) { this.key = key; this.value = value; this.hash = hash; this.next = next; this.nxt = nxt; this.prv = prv; } public final String getKey() { return key; } public final V getValue() { return value; } public final V setValue(V value) { V oldValue = this.value; this.value = value; return oldValue; } @Override public final boolean equals(Object o) { if (!(o instanceof Entry)) { return false; } Entry<?, ?> e = (Entry<?, ?>) o; Object eValue = e.getValue(); return key.equals(e.getKey()) && (value == null ? eValue == null : value.equals(eValue)); } @Override public final int hashCode() { return (key == null ? 0 : key.hashCode()) ^ (value == null ? 0 : value.hashCode()); } @Override public final String toString() { return key + "=" + value; } } /** * Removes the mapping from key to value and returns true if this mapping * exists; otherwise, returns does nothing and returns false. */ private boolean removeMapping(Object key, Object value) { if (key == null || !(key instanceof String)) { return false; } int hash = hash((String) key); LinkedEntry<V>[] tab = table; int index = hash & (tab.length - 1); for (LinkedEntry<V> e = tab[index], prev = null; e != null; prev = e, e = e.next) { if (e.hash == hash && key.equals(e.key)) { if (value == null ? e.value != null : !value.equals(e.value)) { return false; // Map has wrong value for key } if (prev == null) { tab[index] = e.next; } else { prev.next = e.next; } size--; unlink(e); return true; } } return false; // No entry for key } private abstract class LinkedHashIterator<T> implements Iterator<T> { LinkedEntry<V> next = header.nxt; LinkedEntry<V> lastReturned = null; public final boolean hasNext() { return next != header; } final LinkedEntry<V> nextEntry() { LinkedEntry<V> e = next; if (e == header) { throw new NoSuchElementException(); } next = e.nxt; return lastReturned = e; } public final void remove() { if (lastReturned == null) { throw new IllegalStateException(); } StringMap.this.remove(lastReturned.key); lastReturned = null; } } private final class KeySet extends AbstractSet<String> { public Iterator<String> iterator() { return new LinkedHashIterator<String>() { public final String next() { return nextEntry().key; } }; } public int size() { return size; } public boolean contains(Object o) { return containsKey(o); } public boolean remove(Object o) { int oldSize = size; StringMap.this.remove(o); return size != oldSize; } public void clear() { StringMap.this.clear(); } } private final class Values extends AbstractCollection<V> { public Iterator<V> iterator() { return new LinkedHashIterator<V>() { public final V next() { return nextEntry().value; } }; } public int size() { return size; } public boolean contains(Object o) { return containsValue(o); } public void clear() { StringMap.this.clear(); } } private final class EntrySet extends AbstractSet<Entry<String, V>> { public Iterator<Entry<String, V>> iterator() { return new LinkedHashIterator<Map.Entry<String, V>>() { public final Map.Entry<String, V> next() { return nextEntry(); } }; } public boolean contains(Object o) { if (!(o instanceof Entry)) { return false; } Entry<?, ?> e = (Entry<?, ?>) o; V mappedValue = get(e.getKey()); return mappedValue != null && mappedValue.equals(e.getValue()); } public boolean remove(Object o) { if (!(o instanceof Entry)) { return false; } Entry<?, ?> e = (Entry<?, ?>) o; return removeMapping(e.getKey(), e.getValue()); } public int size() { return size; } public void clear() { StringMap.this.clear(); } } private static final int seed = new Random().nextInt(); private static int hash(String key) { // Ensuring that the hash is unpredictable and well distributed. // // Finding unpredictable hash functions is a bit of a dark art as we need to balance // good unpredictability (to avoid DoS) and good distribution (for performance). // // We achieve this by using the same algorithm as the Perl version, but this implementation // is being written from scratch by inder who has never seen the // Perl version (for license compliance). // // TODO: investigate http://code.google.com/p/cityhash/ and http://code.google.com/p/smhasher/ // both of which may have better distribution and/or unpredictability. int h = seed; for (int i = 0; i < key.length(); ++i) { int h2 = h + key.charAt(i); int h3 = h2 + h2 << 10; // h2 * 1024 h = h3 ^ (h3 >>> 6); // h3 / 64 } /* * Apply Doug Lea's supplemental hash function to avoid collisions for * hashes that do not differ in lower or upper bits. */ h ^= (h >>> 20) ^ (h >>> 12); return h ^ (h >>> 7) ^ (h >>> 4); } }
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.explain; import org.apache.lucene.search.Explanation; import org.elasticsearch.action.admin.indices.alias.Alias; import org.elasticsearch.action.explain.ExplainResponse; import org.elasticsearch.common.io.stream.InputStreamStreamInput; import org.elasticsearch.common.io.stream.OutputStreamStreamOutput; import org.elasticsearch.common.lucene.Lucene; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.index.mapper.internal.TimestampFieldMapper; import org.elasticsearch.index.query.QueryBuilders; import org.elasticsearch.test.ESIntegTestCase; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.format.ISODateTimeFormat; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.util.HashSet; import java.util.Map; import java.util.Set; import static java.util.Collections.singleton; import static org.elasticsearch.common.xcontent.XContentFactory.jsonBuilder; import static org.elasticsearch.index.query.QueryBuilders.queryStringQuery; import static org.elasticsearch.test.hamcrest.ElasticsearchAssertions.assertAcked; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.notNullValue; /** */ public class ExplainActionIT extends ESIntegTestCase { public void testSimple() throws Exception { assertAcked(prepareCreate("test") .addAlias(new Alias("alias")) .setSettings(Settings.settingsBuilder().put("index.refresh_interval", -1))); ensureGreen("test"); client().prepareIndex("test", "test", "1").setSource("field", "value1").get(); ExplainResponse response = client().prepareExplain(indexOrAlias(), "test", "1") .setQuery(QueryBuilders.matchAllQuery()).get(); assertNotNull(response); assertFalse(response.isExists()); // not a match b/c not realtime assertThat(response.getIndex(), equalTo("test")); assertThat(response.getType(), equalTo("test")); assertThat(response.getId(), equalTo("1")); assertFalse(response.isMatch()); // not a match b/c not realtime refresh(); response = client().prepareExplain(indexOrAlias(), "test", "1") .setQuery(QueryBuilders.matchAllQuery()).get(); assertNotNull(response); assertTrue(response.isMatch()); assertNotNull(response.getExplanation()); assertTrue(response.getExplanation().isMatch()); assertThat(response.getIndex(), equalTo("test")); assertThat(response.getType(), equalTo("test")); assertThat(response.getId(), equalTo("1")); assertThat(response.getExplanation().getValue(), equalTo(1.0f)); response = client().prepareExplain(indexOrAlias(), "test", "1") .setQuery(QueryBuilders.termQuery("field", "value2")).get(); assertNotNull(response); assertTrue(response.isExists()); assertFalse(response.isMatch()); assertThat(response.getIndex(), equalTo("test")); assertThat(response.getType(), equalTo("test")); assertThat(response.getId(), equalTo("1")); assertNotNull(response.getExplanation()); assertFalse(response.getExplanation().isMatch()); response = client().prepareExplain(indexOrAlias(), "test", "1") .setQuery(QueryBuilders.boolQuery() .must(QueryBuilders.termQuery("field", "value1")) .must(QueryBuilders.termQuery("field", "value2"))).get(); assertNotNull(response); assertTrue(response.isExists()); assertFalse(response.isMatch()); assertThat(response.getIndex(), equalTo("test")); assertThat(response.getType(), equalTo("test")); assertThat(response.getId(), equalTo("1")); assertNotNull(response.getExplanation()); assertFalse(response.getExplanation().isMatch()); assertThat(response.getExplanation().getDetails().length, equalTo(2)); response = client().prepareExplain(indexOrAlias(), "test", "2") .setQuery(QueryBuilders.matchAllQuery()).get(); assertNotNull(response); assertFalse(response.isExists()); assertFalse(response.isMatch()); assertThat(response.getIndex(), equalTo("test")); assertThat(response.getType(), equalTo("test")); assertThat(response.getId(), equalTo("2")); } public void testExplainWithFields() throws Exception { assertAcked(prepareCreate("test").addAlias(new Alias("alias"))); ensureGreen("test"); client().prepareIndex("test", "test", "1") .setSource( jsonBuilder().startObject() .startObject("obj1") .field("field1", "value1") .field("field2", "value2") .endObject() .endObject()).get(); refresh(); ExplainResponse response = client().prepareExplain(indexOrAlias(), "test", "1") .setQuery(QueryBuilders.matchAllQuery()) .setFields("obj1.field1").get(); assertNotNull(response); assertTrue(response.isMatch()); assertNotNull(response.getExplanation()); assertTrue(response.getExplanation().isMatch()); assertThat(response.getExplanation().getValue(), equalTo(1.0f)); assertThat(response.getGetResult().isExists(), equalTo(true)); assertThat(response.getGetResult().getId(), equalTo("1")); Set<String> fields = new HashSet<>(response.getGetResult().getFields().keySet()); fields.remove(TimestampFieldMapper.NAME); // randomly added via templates assertThat(fields, equalTo(singleton("obj1.field1"))); assertThat(response.getGetResult().getFields().get("obj1.field1").getValue().toString(), equalTo("value1")); assertThat(response.getGetResult().isSourceEmpty(), equalTo(true)); refresh(); response = client().prepareExplain(indexOrAlias(), "test", "1") .setQuery(QueryBuilders.matchAllQuery()) .setFields("obj1.field1").setFetchSource(true).get(); assertNotNull(response); assertTrue(response.isMatch()); assertNotNull(response.getExplanation()); assertTrue(response.getExplanation().isMatch()); assertThat(response.getExplanation().getValue(), equalTo(1.0f)); assertThat(response.getGetResult().isExists(), equalTo(true)); assertThat(response.getGetResult().getId(), equalTo("1")); fields = new HashSet<>(response.getGetResult().getFields().keySet()); fields.remove(TimestampFieldMapper.NAME); // randomly added via templates assertThat(fields, equalTo(singleton("obj1.field1"))); assertThat(response.getGetResult().getFields().get("obj1.field1").getValue().toString(), equalTo("value1")); assertThat(response.getGetResult().isSourceEmpty(), equalTo(false)); response = client().prepareExplain(indexOrAlias(), "test", "1") .setQuery(QueryBuilders.matchAllQuery()) .setFields("obj1.field1", "obj1.field2").get(); assertNotNull(response); assertTrue(response.isMatch()); String v1 = (String) response.getGetResult().field("obj1.field1").getValue(); String v2 = (String) response.getGetResult().field("obj1.field2").getValue(); assertThat(v1, equalTo("value1")); assertThat(v2, equalTo("value2")); } @SuppressWarnings("unchecked") public void testExplainWitSource() throws Exception { assertAcked(prepareCreate("test").addAlias(new Alias("alias"))); ensureGreen("test"); client().prepareIndex("test", "test", "1") .setSource( jsonBuilder().startObject() .startObject("obj1") .field("field1", "value1") .field("field2", "value2") .endObject() .endObject()).get(); refresh(); ExplainResponse response = client().prepareExplain(indexOrAlias(), "test", "1") .setQuery(QueryBuilders.matchAllQuery()) .setFetchSource("obj1.field1", null).get(); assertNotNull(response); assertTrue(response.isMatch()); assertNotNull(response.getExplanation()); assertTrue(response.getExplanation().isMatch()); assertThat(response.getExplanation().getValue(), equalTo(1.0f)); assertThat(response.getGetResult().isExists(), equalTo(true)); assertThat(response.getGetResult().getId(), equalTo("1")); assertThat(response.getGetResult().getSource().size(), equalTo(1)); assertThat(((Map<String, Object>) response.getGetResult().getSource().get("obj1")).get("field1").toString(), equalTo("value1")); response = client().prepareExplain(indexOrAlias(), "test", "1") .setQuery(QueryBuilders.matchAllQuery()) .setFetchSource(null, "obj1.field2").get(); assertNotNull(response); assertTrue(response.isMatch()); assertThat(((Map<String, Object>) response.getGetResult().getSource().get("obj1")).get("field1").toString(), equalTo("value1")); } public void testExplainWithFilteredAlias() throws Exception { assertAcked(prepareCreate("test") .addMapping("test", "field2", "type=string") .addAlias(new Alias("alias1").filter(QueryBuilders.termQuery("field2", "value2")))); ensureGreen("test"); client().prepareIndex("test", "test", "1").setSource("field1", "value1", "field2", "value1").get(); refresh(); ExplainResponse response = client().prepareExplain("alias1", "test", "1") .setQuery(QueryBuilders.matchAllQuery()).get(); assertNotNull(response); assertTrue(response.isExists()); assertFalse(response.isMatch()); } public void testExplainWithFilteredAliasFetchSource() throws Exception { assertAcked(client().admin().indices().prepareCreate("test") .addMapping("test", "field2", "type=string") .addAlias(new Alias("alias1").filter(QueryBuilders.termQuery("field2", "value2")))); ensureGreen("test"); client().prepareIndex("test", "test", "1").setSource("field1", "value1", "field2", "value1").get(); refresh(); ExplainResponse response = client().prepareExplain("alias1", "test", "1") .setQuery(QueryBuilders.matchAllQuery()).setFetchSource(true).get(); assertNotNull(response); assertTrue(response.isExists()); assertFalse(response.isMatch()); assertThat(response.getIndex(), equalTo("test")); assertThat(response.getType(), equalTo("test")); assertThat(response.getId(), equalTo("1")); assertThat(response.getGetResult(), notNullValue()); assertThat(response.getGetResult().getIndex(), equalTo("test")); assertThat(response.getGetResult().getType(), equalTo("test")); assertThat(response.getGetResult().getId(), equalTo("1")); assertThat(response.getGetResult().getSource(), notNullValue()); assertThat((String)response.getGetResult().getSource().get("field1"), equalTo("value1")); } public void testExplainDateRangeInQueryString() { createIndex("test"); String aMonthAgo = ISODateTimeFormat.yearMonthDay().print(new DateTime(DateTimeZone.UTC).minusMonths(1)); String aMonthFromNow = ISODateTimeFormat.yearMonthDay().print(new DateTime(DateTimeZone.UTC).plusMonths(1)); client().prepareIndex("test", "type", "1").setSource("past", aMonthAgo, "future", aMonthFromNow).get(); refresh(); ExplainResponse explainResponse = client().prepareExplain("test", "type", "1").setQuery(queryStringQuery("past:[now-2M/d TO now/d]")).get(); assertThat(explainResponse.isExists(), equalTo(true)); assertThat(explainResponse.isMatch(), equalTo(true)); } private static String indexOrAlias() { return randomBoolean() ? "test" : "alias"; } public void testStreamExplain() throws Exception { Explanation exp = Explanation.match(2f, "some explanation"); // write ByteArrayOutputStream outBuffer = new ByteArrayOutputStream(); OutputStreamStreamOutput out = new OutputStreamStreamOutput(outBuffer); Lucene.writeExplanation(out, exp); // read ByteArrayInputStream esInBuffer = new ByteArrayInputStream(outBuffer.toByteArray()); InputStreamStreamInput esBuffer = new InputStreamStreamInput(esInBuffer); Explanation result = Lucene.readExplanation(esBuffer); assertThat(exp.toString(),equalTo(result.toString())); exp = Explanation.match(2.0f, "some explanation", Explanation.match(2.0f,"another explanation")); // write complex outBuffer = new ByteArrayOutputStream(); out = new OutputStreamStreamOutput(outBuffer); Lucene.writeExplanation(out, exp); // read complex esInBuffer = new ByteArrayInputStream(outBuffer.toByteArray()); esBuffer = new InputStreamStreamInput(esInBuffer); result = Lucene.readExplanation(esBuffer); assertThat(exp.toString(),equalTo(result.toString())); } }
/* * Copyright (C) 2010 Andrew P McSherry * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.andymcsherry.library; import com.andymcsherry.library.R; import android.content.Context; import android.content.Intent; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.text.ClipboardManager; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.RadioButton; import android.widget.TextView; import android.widget.Toast; import edu.hws.jcm.data.ParseError; public class DerivativeActivity extends AndyActivity { private Button addButton, insertButton, calButton, evalButton; private TextView DerText, evalOutput, tv04; private EditText FunText, FVarText, VarText, xtext; private RadioButton r1, r2, r3, r4; ClipboardManager clipboard; private boolean copyable = false; KeyboardView keyboard; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.derivative); clipboard = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE); keyboard = (KeyboardView) findViewById(R.id.derivativeKey); FunText = (EditText) findViewById(R.id.functionText); xtext = (EditText) findViewById(R.id.xText); VarText = (EditText) findViewById(R.id.varText); FVarText = (EditText) findViewById(R.id.fVarText); insertButton = (Button) findViewById(R.id.addButton); addButton = (Button) findViewById(R.id.addGraph); evalButton = (Button) findViewById(R.id.derEvaluate); tv04 = (TextView) findViewById(R.id.TextView04); evalOutput = (TextView) findViewById(R.id.evaluateText); DerText = (TextView) findViewById(R.id.derText); Intent intent = getIntent(); FunText.setText(intent.getStringExtra("function")); r1 = (RadioButton) findViewById(R.id.radio1); r2 = (RadioButton) findViewById(R.id.radio2); r3 = (RadioButton) findViewById(R.id.radio3); r4 = (RadioButton) findViewById(R.id.radio4); r1.toggle(); if (intent.getStringExtra("add") != null) { FunText.setText(FunText.getText().toString() + intent.getStringExtra("iFunction")); String s = null; intent.putExtra("add", s); } updateValidity(); setInvisible(); setUp(new EditText[]{FunText,VarText,FVarText,xtext},keyboard); insertButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent myIntent = new Intent(getApplicationContext(), InsertFunction.class); myIntent.putExtra("function", FunText.getText().toString()); myIntent.putExtra("prev", "DerivativeActivity"); myIntent.putExtra("motive", "insert"); myIntent.putExtra("motive", "insert"); startActivity(myIntent); finish(); } }); addButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { Intent myIntent = new Intent(getApplicationContext(), InsertFunction.class); myIntent.putExtra("function", DerText.getText().toString()); myIntent.putExtra("prev", "DerivativeActivity"); myIntent.putExtra("motive", "add"); startActivity(myIntent); finish(); } }); calButton = (Button) findViewById(R.id.calculate); calButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { keyboard.setVisibility(View.GONE); String funVars = FVarText.getText().toString(); int commas = 0; for(int i = 0; i < funVars.length(); i++){ if(funVars.charAt(i)==','){ commas++; } } String[] vars = new String[commas+1]; for(int i = 0; i <= commas; i++){ int count = 0; vars[i] = ""; for(int j = 0; j < funVars.length(); j++){ if(count == i){ if(funVars.charAt(j)==','){ count++; }else{ if(funVars.charAt(j) != ' '){ vars[count] += funVars.charAt(j); } } }else{ if(funVars.charAt(j)==','){ count++; } } } } try { String s = AndyMath.getDerivative(getApplicationContext(), FunText.getText().toString(), vars, VarText.getText().toString()); DerText.setText(s); if(r2.isChecked() || r3.isChecked() || r4.isChecked()){ s = AndyMath.getDerivative(getApplicationContext(), s, vars, VarText.getText().toString()); DerText.setText(s); } if(r3.isChecked() || r4.isChecked()){ s = AndyMath.getDerivative(getApplicationContext(), s, vars, VarText.getText().toString()); DerText.setText(s); } if(r4.isChecked()){ s = AndyMath.getDerivative(getApplicationContext(), s, vars, VarText.getText().toString()); DerText.setText(s); } copyable = true; setVisible(); } catch (ParseError e) { Toast.makeText(DerivativeActivity.this, e.getMessage(), Toast.LENGTH_LONG).show(); } } }); evalButton.setOnClickListener(new OnClickListener() { public void onClick(View v) { keyboard.setVisibility(View.GONE); String funVars = FVarText.getText().toString(); int commas = 0; for(int i = 0; i < funVars.length(); i++){ if(funVars.charAt(i)==','){ commas++; } } String[] vars = new String[commas+1]; for(int i = 0; i <= commas; i++){ int count = 0; vars[i] = ""; for(int j = 0; j < funVars.length(); j++){ if(count == i){ if(funVars.charAt(j)==','){ count++; }else{ if(funVars.charAt(j) != ' '){ vars[count] += funVars.charAt(j); } } }else{ if(funVars.charAt(j)==','){ count++; } } } } String funVals = xtext.getText().toString(); commas = 0; for(int i = 0; i < funVals.length(); i++){ if(funVals.charAt(i)==','){ commas++; } } String[] vals = new String[commas+1]; for(int i = 0; i <= commas; i++){ int count = 0; vals[i] = ""; for(int j = 0; j < funVals.length(); j++){ if(count == i){ if(funVals.charAt(j)==','){ count++; }else{ if(funVals.charAt(j) != ' '){ vals[count] += funVals.charAt(j); } } }else{ if(funVals.charAt(j)==','){ count++; } } } } try { evalOutput.setText(AndyMath.getFunctionVal(getApplicationContext(), DerText.getText().toString(), vars, VarText.getText().toString(),vals)); } catch (Exception e) { Toast.makeText(DerivativeActivity.this, e.getMessage(), Toast.LENGTH_LONG).show(); } } }); } @Override // Creates menu public boolean onPrepareOptionsMenu(Menu menu) { menu.clear(); if(copyable){ menu.add(Menu.NONE,1,Menu.NONE,getString(R.string.copy)); } menu.add(Menu.NONE, 0, Menu.NONE, getString(R.string.home)); menu.add(Menu.NONE, 99, Menu.NONE, getString(R.string.help)); return true; } @Override // Opens new activity based on user selection public boolean onOptionsItemSelected(MenuItem item) { Intent intent; if (item.getItemId() == 0) { intent = new Intent(getApplicationContext(), Derivative.class); intent.putExtra("function", FunText.getText().toString()); intent.putExtra("prev", "DerivativeActivity"); startActivity(intent); }else if(item.getItemId()==1){ clipboard.setText(DerText.getText().toString()); }else if (item.getItemId() == 99){ intent = new Intent(getApplicationContext(), Help.class); intent.putExtra("function", FunText.getText().toString()); intent.putExtra("prev", "DerivativeActivity"); startActivity(intent); } else { intent = new Intent(Intent.ACTION_VIEW,Uri.parse("market://details?id=com.andymc.calculuspaid")); intent.putExtra("function", FunText.getText().toString()); intent.putExtra("prev", "DerivativeActivity"); startActivity(intent); } return true; } // Makes views for the evaluation portion of activity invisible private void setInvisible() { tv04.setVisibility(View.GONE); xtext.setVisibility(View.GONE); evalButton.setVisibility(View.GONE); evalOutput.setVisibility(View.GONE); addButton.setVisibility(View.GONE); } // Makes views for the evaluation portion of activity visible private void setVisible() { addButton.setVisibility(View.VISIBLE); tv04.setVisibility(View.VISIBLE); evalButton.setVisibility(View.VISIBLE); xtext.setVisibility(View.VISIBLE); evalOutput.setVisibility(View.VISIBLE); } @Override protected void onEnter(){ if(FVarText.isFocused()){ FunText.requestFocus(); }else if(FunText.isFocused()){ VarText.requestFocus(); }else if(VarText.isFocused()){ calButton.performClick(); xtext.requestFocus(); }else if(xtext.isFocused()){ evalButton.performClick(); evalOutput.requestFocus(); } } @Override protected void updateValidity(){ String f = FunText.getText().toString(); String v = FVarText.getText().toString(); int commas = 0; for(int i = 0; i < v.length(); i++){ if(v.charAt(i)==','){ commas++; } } String[] vars = new String[commas+1]; for(int i = 0; i <= commas; i++){ int count = 0; vars[i] = ""; for(int j = 0; j < v.length(); j++){ if(count == i){ if(v.charAt(j)==','){ count++; }else{ if(v.charAt(j) != ' '){ vars[count] += v.charAt(j); } } }else{ if(v.charAt(j)==','){ count++; } } } } if(AndyMath.isValid(f,vars)){ FunText.setTextColor(Color.rgb(0,127,0)); }else{ FunText.setTextColor(Color.rgb(127,0,0)); } } }