answer
stringlengths
17
10.2M
package com.github.ansell.jdefaultdict; import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.IntStream; import org.junit.Test; /** * Tests for {@link JDefaultDict} * * @author Peter Ansell [email protected] */ public class JDefaultDictTest { @Test public final void testGetExists() { ConcurrentMap<String, List<String>> test = new JDefaultDict<>( k -> new ArrayList<>()); assertFalse(test.containsKey("test")); test.put("test", new ArrayList<>()); assertTrue(test.containsKey("test")); List<String> testList = test.get("test"); assertNotNull(testList); assertTrue(testList.isEmpty()); } @Test public final void testGetNotExists() { ConcurrentMap<String, List<String>> test = new JDefaultDict<>( k -> new ArrayList<>()); assertFalse(test.containsKey("test")); List<String> testList = test.get("test"); assertTrue(test.containsKey("test")); assertNotNull(testList); assertTrue(testList.isEmpty()); } @Test public final void testGetChained() { ConcurrentMap<String, ConcurrentMap<String, List<String>>> test = new JDefaultDict<>( k1 -> new JDefaultDict<>(k2 -> new ArrayList<>())); assertFalse(test.containsKey("test")); List<String> testList = test.get("test").get("test"); assertTrue(test.containsKey("test")); assertTrue(test.get("test").containsKey("test")); assertNotNull(testList); assertTrue(testList.isEmpty()); } @Test public final void testGetChainedAtomicIntegerSerial() { ConcurrentMap<String, ConcurrentMap<String, AtomicInteger>> test = new JDefaultDict<>( k1 -> new JDefaultDict<>(k2 -> new AtomicInteger(0))); assertFalse(test.containsKey("test")); for (int i = 1; i < 1000001; i++) { int testValue = test.get("test").get("test").incrementAndGet(); assertEquals(i, testValue); } assertEquals(1000000, test.get("test").get("test").intValue()); } @Test public final void testGetChainedAtomicIntegerParallel() { ConcurrentMap<String, ConcurrentMap<String, AtomicInteger>> test = new JDefaultDict<>( k1 -> new JDefaultDict<>(k2 -> new AtomicInteger(0))); assertFalse(test.containsKey("test")); IntStream.range(1, 1000001).parallel().forEach(i -> { int testValue = test.get("test").get("test").incrementAndGet(); assertTrue(testValue > 0); }); assertEquals(1000000, test.get("test").get("test").intValue()); } }
package com.tonybeltramelli.captcha; import org.json.simple.JSONObject; import java.io.File; import java.io.IOException; import java.util.ArrayList; import java.util.Scanner; public class CustomSimpleCaptcha { private String _challengePath; private String[] _questions; public CustomSimpleCaptcha(String challengePath) { _challengePath = challengePath; } public String getChallenge() throws IOException { String[] questions = _getQuestions(); int index = (int) Math.round(Math.random() * (questions.length - 1)); String challenge = questions[index]; challenge = challenge.substring(0, challenge.indexOf("=")); JSONObject result = new JSONObject(); result.put("index", index); result.put("challenge", challenge); return result.toJSONString(); } public String checkAnswer(int index, String providedAnswer) throws IOException { String[] questions = _getQuestions(); if(index >= questions.length) return _getStatusMessage(2); String expectedAnswer = questions[index]; expectedAnswer = expectedAnswer.substring(expectedAnswer.indexOf("=") + 1, expectedAnswer.length()); Boolean isMatched = providedAnswer.toLowerCase().equals(expectedAnswer.toLowerCase()); return _getStatusMessage(isMatched ? 1 : 0); } private String[] _getQuestions() throws IOException { if(_questions != null) return _questions; Scanner file = new Scanner(new File(_challengePath)).useDelimiter("\n"); ArrayList<String> questions = new ArrayList<String>(); Boolean isFirstLine = true; while (file.hasNext()) { if(!isFirstLine) { questions.add(file.next()); }else{ file.next(); isFirstLine = false; } } file.close(); _questions = questions.toArray(new String[0]); return _questions; } private String _getStatusMessage(int type) { String status = "error"; switch (type) { case 0: status = "fail"; break; case 1: status = "success"; break; default: status = "error"; } JSONObject result = new JSONObject(); result.put("status", status); return result.toJSONString(); } }
package com.github.mproberts.rxtools.map; import io.reactivex.Flowable; import io.reactivex.disposables.CompositeDisposable; import io.reactivex.disposables.Disposable; import io.reactivex.functions.Action; import io.reactivex.functions.Consumer; import io.reactivex.subscribers.DisposableSubscriber; import io.reactivex.subscribers.TestSubscriber; import org.junit.After; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.List; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import static org.junit.Assert.*; public class SubjectMapTest { private static final int runs = 100000; private static final int loop = 50; private static final String[] keys = new String[loop]; static { for (int i = 0; i < loop; ++i) { keys[i] = "run-" + i; } } private CompositeDisposable _subscription; private SubjectMap<String, Integer> source; private static class IncrementingFaultSatisfier<K> implements Consumer<K> { private final AtomicInteger _counter; private final SubjectMap<K, Integer> _source; IncrementingFaultSatisfier(SubjectMap<K, Integer> source, AtomicInteger counter) { _source = source; _counter = counter; } @Override public void accept(K key) { _source.onNext(key, _counter.incrementAndGet()); } } private <T> void subscribe(Flowable<T> observable, DisposableSubscriber<T> action) { _subscription.add(observable.subscribeWith(action)); } private <T> void subscribe(Flowable<T> observable, TestSubscriber<T> action) { _subscription.add(observable.subscribeWith(action)); } private <T> void subscribe(Flowable<T> observable, Consumer<T> action) { _subscription.add(observable.subscribe(action)); } private void unsubscribeAll() { _subscription.clear(); } @Before public void setup() { source = new SubjectMap<>(); _subscription = new CompositeDisposable(); } @After public void teardown() { unsubscribeAll(); } @Test public void testQueryAndIncrementOnFault() { // setup AtomicInteger counter = new AtomicInteger(0); Disposable faultSubscription = source.faults() .subscribe(new IncrementingFaultSatisfier<>(source, counter)); TestSubscriber<Integer> testSubscriber1 = new TestSubscriber<>(); TestSubscriber<Integer> testSubscriber2 = new TestSubscriber<>(); TestSubscriber<Integer> testSubscriber3 = new TestSubscriber<>(); subscribe(source.get("hello"), testSubscriber1); System.gc(); testSubscriber1.assertValues(1); subscribe(source.get("hello"), testSubscriber2); System.gc(); testSubscriber1.assertValues(1); testSubscriber2.assertValues(1); unsubscribeAll(); System.gc(); subscribe(source.get("hello"), testSubscriber3); testSubscriber3.assertValues(2); // cleanup faultSubscription.dispose(); } @Test public void testBattlingSubscribers1() throws InterruptedException { TestSubscriber<Integer> testSubscriber1 = new TestSubscriber<>(); TestSubscriber<Integer> testSubscriber2 = new TestSubscriber<>(); Flowable<Integer> value1 = source.get("hello"); Disposable s1 = value1.subscribeWith(testSubscriber1); source.onNext("hello", 3); s1.dispose(); testSubscriber1.assertValues(3); Flowable<Integer> value2 = source.get("hello"); Disposable s2 = value2.subscribeWith(testSubscriber2); Disposable s3 = value1.subscribeWith(testSubscriber1); source.onNext("hello", 4); s2.dispose(); s3.dispose(); testSubscriber2.assertValues(3, 4); } @Test public void testBattlingSubscribers() throws InterruptedException { // setup AtomicInteger counter = new AtomicInteger(0); Disposable faultSubscription = source.faults() .subscribe(new IncrementingFaultSatisfier<>(source, counter)); Flowable<Integer> retainedObservable = source.get("hello"); TestSubscriber<Integer> testSubscriber1 = new TestSubscriber<>(); TestSubscriber<Integer> testSubscriber2 = new TestSubscriber<>(); Disposable s1 = retainedObservable.subscribeWith(testSubscriber1); Disposable s2; testSubscriber1.assertValues(1); s1.dispose(); testSubscriber1.assertValues(1); Flowable<Integer> retainedObservable2 = source.get("hello"); s1 = retainedObservable.subscribeWith(testSubscriber1); testSubscriber1.assertValues(1); s2 = retainedObservable.subscribeWith(testSubscriber2); testSubscriber1.assertValues(1); s1.dispose(); s2.dispose(); // cleanup faultSubscription.dispose(); } public void testMissHandling() { // setup final AtomicBoolean missHandlerCalled = new AtomicBoolean(false); AtomicInteger counter = new AtomicInteger(0); Disposable faultSubscription = source.faults() .subscribe(new IncrementingFaultSatisfier<>(source, counter)); TestSubscriber<Integer> testSubscriber1 = new TestSubscriber<>(); subscribe(source.get("hello"), testSubscriber1); source.onNext("hello2", new Callable<Integer>() { @Override public Integer call() throws Exception { fail("Value should not be accessed"); return 13; } }, new Action() { @Override public void run() { missHandlerCalled.set(true); } }); assertTrue(missHandlerCalled.get()); testSubscriber1.assertValues(1); // cleanup faultSubscription.dispose(); } @Test public void testErrorHandlingInValueProvider() { // setup final AtomicBoolean missHandlerCalled = new AtomicBoolean(false); TestSubscriber<Integer> testSubscriber1 = new TestSubscriber<>(); subscribe(source.get("hello"), testSubscriber1); source.onNext("hello", new Callable<Integer>() { @Override public Integer call() throws Exception { throw new RuntimeException("Boom"); } }, new Action() { @Override public void run() { missHandlerCalled.set(true); } }); testSubscriber1.assertError(RuntimeException.class); } @Test public void testQueryAndUpdate() { // setup AtomicInteger counter = new AtomicInteger(0); Disposable faultSubscription = source.faults() .subscribe(new IncrementingFaultSatisfier<>(source, counter)); TestSubscriber<Integer> testSubscriber1 = new TestSubscriber<>(); TestSubscriber<Integer> testSubscriber2 = new TestSubscriber<>(); TestSubscriber<Integer> testSubscriber3 = new TestSubscriber<>(); subscribe(source.get("hello"), testSubscriber1); System.gc(); testSubscriber1.assertValues(1); subscribe(source.get("hello"), testSubscriber2); System.gc(); testSubscriber1.assertValues(1); testSubscriber2.assertValues(1); // send 10 to 2 already bound subscribers source.onNext("hello", 10); subscribe(source.get("hello"), testSubscriber3); // new subscriber 3 should only received the latest value of 10 testSubscriber1.assertValues(1, 10); testSubscriber2.assertValues(1, 10); testSubscriber3.assertValues(10); // all 3 subscribers should receive the new value of 11 source.onNext("hello", 11); testSubscriber1.assertValues(1, 10, 11); testSubscriber2.assertValues(1, 10, 11); testSubscriber3.assertValues(10, 11); // cleanup faultSubscription.dispose(); } @Test public void testExceptionHandlingFault() { // setup final AtomicBoolean exceptionEncountered = new AtomicBoolean(false); final AtomicInteger counter = new AtomicInteger(0); Disposable faultSubscription = source.faults() .subscribe(new Consumer<String>() { @Override public void accept(String key) { if (counter.incrementAndGet() <= 1) { throw new RuntimeException("Explosions!"); } source.onNext(key, counter.get()); } }, new Consumer<Throwable>() { @Override public void accept(Throwable throwable) { assertTrue(throwable instanceof RuntimeException); exceptionEncountered.set(true); } }); TestSubscriber<Integer> testSubscriber1 = new TestSubscriber<>(); Flowable<Integer> helloValue = source.get("hello"); subscribe(helloValue, testSubscriber1); testSubscriber1.assertNoValues(); assertTrue(exceptionEncountered.get()); // cleanup faultSubscription.dispose(); } @Test public void testPruningUnsubscribedObservables() { // setup AtomicInteger counter = new AtomicInteger(0); Disposable faultSubscription = source.faults() .subscribe(new IncrementingFaultSatisfier<>(source, counter)); TestSubscriber<Integer> testSubscriber = new TestSubscriber<>(); @SuppressWarnings("unused") Flowable<Integer> helloValue = source.get("hello"); helloValue = null; System.gc(); subscribe(source.get("hello"), testSubscriber); testSubscriber.assertValues(1); source.onNext("hello", 11); testSubscriber.assertValues(1, 11); // cleanup faultSubscription.dispose(); } @Test public void testSendBatchOfNoopsForUnobservedKey() { for (int i = 0; i < runs; ++i) { source.onNext(keys[i % 10], i); } } @Test public void testQueryBatchOfKeys() { final AtomicInteger counter = new AtomicInteger(0); for (int i = 0; i < loop; ++i) { final int index = i; keys[i] = "run-" + i; subscribe(source.get(keys[i]), new DisposableSubscriber<Integer>() { @Override public void onComplete() { fail("Unexpected completion on observable"); } @Override public void onError(Throwable e) { fail("Unexpected error on observable"); } @Override public void onNext(Integer value) { assertEquals(index, value % 10); counter.incrementAndGet(); } }); } for (int i = 0; i < runs; ++i) { source.onNext(keys[i % 10], i); } assertEquals(runs, counter.get()); } @Test public void testThrashSubscriptions() throws InterruptedException, ExecutionException { final AtomicInteger globalCounter = new AtomicInteger(0); final int subscriberCount = 25; ExecutorService executorService = Executors.newFixedThreadPool(subscriberCount); for (int j = 0; j < subscriberCount; ++j) { System.gc(); final AtomicInteger counter = new AtomicInteger(0); final Flowable<Integer> valueObservable = source.get("test"); final Callable<Disposable> queryCallable = new Callable<Disposable>() { final int index = globalCounter.incrementAndGet(); @Override public Disposable call() throws Exception { return valueObservable.subscribe(new Consumer<Integer>() { @Override public void accept(Integer integer) { counter.incrementAndGet(); } }); } }; List<Callable<Disposable>> callables = new ArrayList<>(); for (int i = 0; i < subscriberCount; ++i) { callables.add(queryCallable); } List<Future<Disposable>> futures = executorService.invokeAll(callables); List<Disposable> subscriptions = new ArrayList<>(); for (int i = 0; i < subscriberCount; ++i) { subscriptions.add(futures.get(i).get()); } source.onNext("test", 1); for (int i = 0; i < 10; ++i) { if (counter.get() != subscriberCount) { Thread.sleep(10); } } assertEquals(subscriberCount, counter.get()); for (int i = 0; i < subscriberCount; ++i) { Disposable subscription = subscriptions.get(i); subscription.dispose(); } } } @Test public void testThrashQuery() throws InterruptedException, ExecutionException { final int subscriberCount = 50; ExecutorService executorService = Executors.newFixedThreadPool(subscriberCount); for (int j = 0; j < 10; ++j) { System.gc(); final AtomicInteger counter = new AtomicInteger(0); Callable<Flowable<Integer>> queryCallable = new Callable<Flowable<Integer>>() { @Override public Flowable<Integer> call() throws Exception { return source.get("test"); } }; List<Callable<Flowable<Integer>>> callables = new ArrayList<>(); for (int i = 0; i < subscriberCount; ++i) { callables.add(queryCallable); } List<Future<Flowable<Integer>>> futures = executorService.invokeAll(callables); for (int i = 0; i < subscriberCount; ++i) { Flowable<Integer> observable = futures.get(i).get(); subscribe(observable, new Consumer<Integer>() { @Override public void accept(Integer value) { counter.incrementAndGet(); } }); } source.onNext("test", 1); for (int i = 0; i < 10; ++i) { if (counter.get() != subscriberCount) { Thread.sleep(10); } } assertEquals(subscriberCount, counter.get()); unsubscribeAll(); } } @Test public void testErrorEmission() { // setup AtomicInteger counter = new AtomicInteger(0); Disposable faultSubscription = source.faults() .subscribe(new IncrementingFaultSatisfier<>(source, counter)); TestSubscriber<Integer> testSubscriber1 = new TestSubscriber<>(); TestSubscriber<Integer> testSubscriber2 = new TestSubscriber<>(); TestSubscriber<Integer> testSubscriber3 = new TestSubscriber<>(); subscribe(source.get("hello"), testSubscriber1); System.gc(); testSubscriber1.assertValues(1); subscribe(source.get("hello"), testSubscriber2); System.gc(); testSubscriber1.assertValues(1); testSubscriber2.assertValues(1); // send error to 2 already bound subscribers RuntimeException error = new RuntimeException("whoops"); source.onError("hello", error); subscribe(source.get("hello"), testSubscriber3); testSubscriber1.assertError(error); testSubscriber2.assertError(error); // new subscriber 3 should fault in a new value after the error testSubscriber3.assertValues(2); // cleanup faultSubscription.dispose(); } }
package biz.netcentric.cq.tools.actool.authorizableutils.impl; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; import javax.jcr.AccessDeniedException; import javax.jcr.Node; import javax.jcr.PathNotFoundException; import javax.jcr.RepositoryException; import javax.jcr.Session; import javax.jcr.UnsupportedRepositoryOperationException; import javax.jcr.ValueFactory; import javax.jcr.ValueFormatException; import javax.jcr.lock.LockException; import javax.jcr.nodetype.ConstraintViolationException; import javax.jcr.version.VersionException; import org.apache.commons.lang.StringUtils; import org.apache.felix.scr.annotations.Component; import org.apache.felix.scr.annotations.Service; import org.apache.jackrabbit.api.JackrabbitSession; import org.apache.jackrabbit.api.security.user.Authorizable; import org.apache.jackrabbit.api.security.user.AuthorizableExistsException; import org.apache.jackrabbit.api.security.user.Group; import org.apache.jackrabbit.api.security.user.User; import org.apache.jackrabbit.api.security.user.UserManager; import org.apache.sling.jcr.api.SlingRepository; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import biz.netcentric.cq.tools.actool.authorizableutils.AuthorizableBean; import biz.netcentric.cq.tools.actool.authorizableutils.AuthorizableConfigBean; import biz.netcentric.cq.tools.actool.authorizableutils.AuthorizableCreatorException; import biz.netcentric.cq.tools.actool.authorizableutils.AuthorizableCreatorService; import biz.netcentric.cq.tools.actool.authorizableutils.AuthorizableInstallationHistory; import biz.netcentric.cq.tools.actool.installationhistory.AcInstallationHistoryPojo; @Service @Component(metatype = true, label = "AuthorizableCreatorService Service", description = "Service that installs groups according to textual configuration files") public class AuthorizableCreatorServiceImpl implements AuthorizableCreatorService { private static final String PATH_HOME_GROUPS = "/home/groups"; private static final String PATH_HOME_USERS = "/home/users"; private static final Logger LOG = LoggerFactory .getLogger(AuthorizableCreatorServiceImpl.class); AcInstallationHistoryPojo status; Map<String, LinkedHashSet<AuthorizableConfigBean>> principalMapFromConfig; AuthorizableInstallationHistory authorizableInstallationHistory; @Override public void createNewAuthorizables( Map<String, LinkedHashSet<AuthorizableConfigBean>> principalMapFromConfig, final Session session, AcInstallationHistoryPojo status, AuthorizableInstallationHistory authorizableInstallationHistory) throws AccessDeniedException, UnsupportedRepositoryOperationException, RepositoryException, AuthorizableCreatorException { this.status = status; this.principalMapFromConfig = principalMapFromConfig; this.authorizableInstallationHistory = authorizableInstallationHistory; Set<String> groupsFromConfigurations = principalMapFromConfig.keySet(); for (String principalId : groupsFromConfigurations) { LinkedHashSet<AuthorizableConfigBean> currentPrincipalData = principalMapFromConfig .get(principalId); Iterator<AuthorizableConfigBean> it = currentPrincipalData .iterator(); AuthorizableConfigBean tmpPricipalConfigBean = null; while (it.hasNext()) { tmpPricipalConfigBean = it.next(); status.addVerboseMessage("Starting installation of authorizable bean: " + tmpPricipalConfigBean.toString()); } installAuthorizableConfigurationBean(session, tmpPricipalConfigBean, status, authorizableInstallationHistory); } } private void installAuthorizableConfigurationBean(final Session session, AuthorizableConfigBean authorizableConfigBean, AcInstallationHistoryPojo history, AuthorizableInstallationHistory authorizableInstallationHistory) throws AccessDeniedException, UnsupportedRepositoryOperationException, RepositoryException, AuthorizableExistsException, AuthorizableCreatorException { String principalId = authorizableConfigBean.getPrincipalID(); LOG.info("- start installation of authorizable: {}", principalId); UserManager userManager = getUsermanager(session); ValueFactory vf = session.getValueFactory(); // if current authorizable from config doesn't exist yet Authorizable authorizableForPrincipalId = userManager.getAuthorizable(principalId); if (authorizableForPrincipalId == null) { createNewAuthorizable(authorizableConfigBean, history, authorizableInstallationHistory, userManager, vf); } // if current authorizable from config already exists in repository else { // update name for both groups and users setAuthorizableName(authorizableForPrincipalId, vf, authorizableConfigBean); // update password for users if (!authorizableForPrincipalId.isGroup() && !authorizableConfigBean.isSystemUser() && StringUtils.isNotBlank(authorizableConfigBean.getPassword())) { ((User) authorizableForPrincipalId).changePassword(authorizableConfigBean.getPassword()); } // move authorizable if path changed (retaining existing members) handleIntermediatePath(session, authorizableConfigBean, history, authorizableInstallationHistory, userManager); mergeGroup(history, authorizableInstallationHistory, authorizableConfigBean, userManager); } if (StringUtils.isNotBlank(authorizableConfigBean.getMigrateFrom()) && authorizableConfigBean.isGroup()) { migrateFromOldGroup(authorizableConfigBean, userManager); } } private void migrateFromOldGroup(AuthorizableConfigBean authorizableConfigBean, UserManager userManager) throws RepositoryException { Authorizable groupForMigration = userManager.getAuthorizable(authorizableConfigBean.getMigrateFrom()); String principalId = authorizableConfigBean.getPrincipalID(); if (groupForMigration == null) { status.addMessage("Group " + authorizableConfigBean.getMigrateFrom() + " does not exist (specified as migrateFrom in group " + principalId + ") - no action taken"); return; } if (!groupForMigration.isGroup()) { status.addWarning("Specifying a user in 'migrateFrom' does not make sense (migrateFrom=" + authorizableConfigBean.getMigrateFrom() + " in " + principalId + ")"); return; } status.addMessage("Migrating from group " + authorizableConfigBean.getMigrateFrom() + " to " + principalId); Set<Authorizable> usersFromGroupToTakeOver = new HashSet<Authorizable>(); Iterator<Authorizable> membersIt = ((Group) groupForMigration).getMembers(); while (membersIt.hasNext()) { Authorizable member = membersIt.next(); if (!member.isGroup()) { usersFromGroupToTakeOver.add(member); } } if (!usersFromGroupToTakeOver.isEmpty()) { status.addMessage("- Taking over " + usersFromGroupToTakeOver.size() + " member users from group " + authorizableConfigBean.getMigrateFrom() + " to group " + principalId); Group currentGroup = (Group) userManager.getAuthorizable(principalId); for (Authorizable user : usersFromGroupToTakeOver) { currentGroup.addMember(user); } } groupForMigration.remove(); status.addMessage("- Deleted group " + authorizableConfigBean.getMigrateFrom()); } private UserManager getUsermanager(Session session) throws AccessDeniedException, UnsupportedRepositoryOperationException, RepositoryException { JackrabbitSession js = (JackrabbitSession) session; UserManager userManager = js.getUserManager(); // Since the persistence of the installation should only take place if // no error occured and certain test were successful // the autosave gets disabled. Therefore an explicit session.save() is // necessary to persist the changes. // Try do disable the autosave only in case if changes are automatically persisted if (userManager.isAutoSave()) { try { userManager.autoSave(false); } catch (UnsupportedRepositoryOperationException e) { // check added for AEM 6.0 LOG.warn("disabling autoSave not possible with this user manager!"); } } return userManager; } private void handleIntermediatePath(final Session session, AuthorizableConfigBean principalConfigBean, AcInstallationHistoryPojo history, AuthorizableInstallationHistory authorizableInstallationHistory, UserManager userManager) throws RepositoryException, AuthorizableCreatorException { String principalId = principalConfigBean.getPrincipalID(); // compare intermediate paths Authorizable existingAuthorizable = userManager.getAuthorizable(principalId); String intermediatedPathOfExistingAuthorizable = existingAuthorizable.getPath() .substring(0, existingAuthorizable.getPath().lastIndexOf("/")); // Relative paths need to be prefixed with /home/groups (issue String authorizablePathFromBean = principalConfigBean.getPath(); if (authorizablePathFromBean.charAt(0) != '/') { authorizablePathFromBean = (principalConfigBean.isGroup() ? PATH_HOME_GROUPS : PATH_HOME_USERS) + "/" + authorizablePathFromBean; } if (!StringUtils.equals(intermediatedPathOfExistingAuthorizable, authorizablePathFromBean)) { StringBuilder message = new StringBuilder(); message.append("found change of intermediate path:\n" + "existing authorizable: " + existingAuthorizable.getID() + " has intermediate path: " + intermediatedPathOfExistingAuthorizable +"\n" + "authorizable from config: " + principalConfigBean.getPrincipalID() + " has intermediate path: " + authorizablePathFromBean + "\n"); // save members of existing group before deletion Set<Authorizable> membersOfDeletedGroup = new HashSet<Authorizable>(); if (existingAuthorizable.isGroup()) { Group existingGroup = (Group) existingAuthorizable; Iterator<Authorizable> memberIt = existingGroup.getDeclaredMembers(); while (memberIt.hasNext()) { membersOfDeletedGroup.add(memberIt.next()); } } // delete existingAuthorizable; existingAuthorizable.remove(); // create group again using values form config ValueFactory vf = session.getValueFactory(); Authorizable newAuthorizable = createNewAuthorizable( principalConfigBean, history, authorizableInstallationHistory, userManager, vf); int countMovedMembersOfGroup = 0; if (newAuthorizable.isGroup()) { Group newGroup = (Group) newAuthorizable; // add members of deleted group for (Authorizable authorizable : membersOfDeletedGroup) { newGroup.addMember(authorizable); countMovedMembersOfGroup++; } } deleteOldIntermediatePath(session, session.getNode(intermediatedPathOfExistingAuthorizable)); message.append("recreated authorizable with new intermediate path! " + (newAuthorizable.isGroup() ? "(retained " + countMovedMembersOfGroup + " members of group)" : "")); history.addMessage(message.toString()); LOG.warn(message.toString()); } } /** // deletes old intermediatePath parent node and all empty parent nodes up to /home/groups or /home/users * * @param session * @param oldIntermediateNode * @throws RepositoryException * @throws PathNotFoundException * @throws VersionException * @throws LockException * @throws ConstraintViolationException * @throws AccessDeniedException */ private void deleteOldIntermediatePath(final Session session, Node oldIntermediateNode) throws RepositoryException, PathNotFoundException, VersionException, LockException, ConstraintViolationException, AccessDeniedException { // if '/home/groups' or '/home/users' was intermediatedNode, these must // not get deleted! // also node to be deleted has to be empty, so no other authorizables // stored under this path get deleted while (!StringUtils.equals(PATH_HOME_GROUPS, oldIntermediateNode.getPath()) && !StringUtils.equals(PATH_HOME_USERS, oldIntermediateNode.getPath()) && !oldIntermediateNode.hasNodes()) { // delete old intermediatedPath Node parent = oldIntermediateNode.getParent(); session.removeItem(oldIntermediateNode.getPath()); // go one path level back for next iteration oldIntermediateNode = parent; } } private void mergeGroup(AcInstallationHistoryPojo status, AuthorizableInstallationHistory authorizableInstallationHistory, AuthorizableConfigBean principalConfigBean, UserManager userManager) throws RepositoryException, ValueFormatException, UnsupportedRepositoryOperationException, AuthorizableExistsException, AuthorizableCreatorException { String[] memberOf = principalConfigBean.getMemberOf(); String principalId = principalConfigBean.getPrincipalID(); LOG.debug("Authorizable {} already exists", principalId); Authorizable currentGroupFromRepository = userManager.getAuthorizable(principalId); Set<String> membershipGroupsFromConfig = getMembershipGroupsFromConfig(memberOf); Set<String> membershipGroupsFromRepository = getMembershipGroupsFromRepository(currentGroupFromRepository); // create snapshot bean authorizableInstallationHistory.addAuthorizable( currentGroupFromRepository.getID(), getAuthorizableName(currentGroupFromRepository), currentGroupFromRepository.getPath(), membershipGroupsFromRepository); mergeMemberOfGroups(principalId, status, userManager, currentGroupFromRepository, membershipGroupsFromConfig, membershipGroupsFromRepository); } private String getAuthorizableName(Authorizable currentGroupFromRepository) throws RepositoryException, ValueFormatException { String authorizableName = ""; if (currentGroupFromRepository.getProperty("profile/givenName") != null) { authorizableName = currentGroupFromRepository .getProperty("profile/givenName")[0].getString(); } return authorizableName; } private Authorizable createNewAuthorizable( AuthorizableConfigBean principalConfigBean, AcInstallationHistoryPojo status, AuthorizableInstallationHistory authorizableInstallationHistory, UserManager userManager, ValueFactory vf) throws AuthorizableExistsException, RepositoryException, AuthorizableCreatorException { boolean isGroup = principalConfigBean.isGroup(); String principalId = principalConfigBean.getPrincipalID(); Authorizable newAuthorizable = null; if (isGroup) { newAuthorizable = createNewGroup(userManager, principalConfigBean, status, authorizableInstallationHistory, vf, principalMapFromConfig); authorizableInstallationHistory .addNewCreatedAuthorizabe(principalId); LOG.info("Successfully created new Group: {}", principalId); } else { newAuthorizable = createNewUser(userManager, principalConfigBean, status, authorizableInstallationHistory, vf, principalMapFromConfig); LOG.info("Successfully created new User: {}", principalId); authorizableInstallationHistory .addNewCreatedAuthorizabe(principalId); } return newAuthorizable; } private Set<String> getMembershipGroupsFromRepository( Authorizable currentGroupFromRepository) throws RepositoryException { Set<String> membershipGroupsFromRepository = new HashSet<String>(); Iterator<Group> memberOfGroupsIterator = currentGroupFromRepository .declaredMemberOf(); // build Set which contains the all Groups of which the existingGroup is // a member of while (memberOfGroupsIterator.hasNext()) { Authorizable memberOfGroup = memberOfGroupsIterator.next(); membershipGroupsFromRepository.add(memberOfGroup.getID()); } return membershipGroupsFromRepository; } private Set<String> getMembershipGroupsFromConfig(String[] memberOf) { // Set which holds all other groups which the current Group from config // is a member of Set<String> membershipGroupsFromConfig = new HashSet<String>(); if (memberOf != null) { // member of at least one other groups for (String s : memberOf) { membershipGroupsFromConfig.add(s); } } return membershipGroupsFromConfig; } private void mergeMemberOfGroups(String principalId, AcInstallationHistoryPojo status, UserManager userManager, Authorizable currentGroupFromRepository, Set<String> membershipGroupsFromConfig, Set<String> membershipGroupsFromRepository) throws RepositoryException, AuthorizableExistsException, AuthorizableCreatorException { LOG.info("...checking differences"); // group in repo doesn't have any members and group in config doesn't // have any members // do nothing if (!isMemberOfOtherGroup(currentGroupFromRepository) && membershipGroupsFromConfig.isEmpty()) { LOG.info( "{}: authorizable in repo is not member of any other group and group in config is not member of any other group. No change necessary here!", principalId); } // group in repo is not member of any other group but group in config is // member of at least one other group // transfer members to group in repo else if (!isMemberOfOtherGroup(currentGroupFromRepository) && !membershipGroupsFromConfig.isEmpty()) { mergeMemberOfGroupsFromConfig(principalId, status, userManager, membershipGroupsFromConfig); // group in repo is member of at least one other group and group in // config is not member of any other group } else if (isMemberOfOtherGroup(currentGroupFromRepository) && membershipGroupsFromConfig.isEmpty()) { mergeMemberOfGroupsFromRepo(principalId, userManager, membershipGroupsFromRepository); } // group in repo does have members and group in config does have members else if (isMemberOfOtherGroup(currentGroupFromRepository) && !membershipGroupsFromConfig.isEmpty()) { mergeMultipleMembersOfBothGroups(principalId, status, userManager, membershipGroupsFromConfig, membershipGroupsFromRepository); } } private void mergeMemberOfGroupsFromRepo(String principalId, UserManager userManager, Set<String> membershipGroupsFromRepository) throws RepositoryException { LOG.info( "{}: authorizable in repo is member of at least one other group and authorizable in config is not member of any other group", principalId); // delete memberOf groups of that group in repo for (String group : membershipGroupsFromRepository) { LOG.info( "{}: delete authorizable from members of group {} in repository", principalId, group); ((Group) userManager.getAuthorizable(group)) .removeMember(userManager.getAuthorizable(principalId)); } } private void mergeMemberOfGroupsFromConfig(String principalId, AcInstallationHistoryPojo status, UserManager userManager, Set<String> membershipGroupsFromConfig) throws RepositoryException, AuthorizableExistsException, AuthorizableCreatorException { LOG.info( "{}: authorizable in repo is not member of any other group but authorizable in config is member of at least one other group", principalId); Set<Authorizable> validatedGroups = validateAssignedGroups(userManager, principalId, membershipGroupsFromConfig.toArray(new String[0])); for (Authorizable membershipGroup : validatedGroups) { LOG.info( "{}: add authorizable to members of group {} in repository", principalId, membershipGroup.getID()); // Group membershipGroup = // (Group)userManager.getAuthorizable(group); if (StringUtils.equals(membershipGroup.getID(), principalId)) { String warning = "Attempt to add a group as member of itself (" + membershipGroup.getID() + ")."; LOG.warn(warning); status.addWarning(warning); } else { ((Group) membershipGroup).addMember(userManager .getAuthorizable(principalId)); } } } private void mergeMultipleMembersOfBothGroups(String principalId, AcInstallationHistoryPojo status, UserManager userManager, Set<String> membershipGroupsFromConfig, Set<String> membershipGroupsFromRepository) throws RepositoryException, AuthorizableExistsException, AuthorizableCreatorException { // are both groups members of exactly the same groups? if (membershipGroupsFromRepository.equals(membershipGroupsFromConfig)) { // do nothing! LOG.info( "{}: authorizable in repo and authorizable in config are members of the same group(s). No change necessary here!", principalId); } else { LOG.info( "{}: authorizable in repo is member of at least one other group and authorizable in config is member of at least one other group", principalId); // loop through memberOf-groups of group from repo for (String authorizable : membershipGroupsFromRepository) { // is current a also contained in memberOf-groups property of // existing group? if (membershipGroupsFromConfig.contains(authorizable)) { continue; } else { // if not delete that group of membersOf-property of // existing group LOG.info( "delete {} from members of group {} in repository", principalId, authorizable); ((Group) userManager.getAuthorizable(authorizable)) .removeMember(userManager .getAuthorizable(principalId)); } } Set<Authorizable> validatedGroups = validateAssignedGroups( userManager, principalId, membershipGroupsFromConfig.toArray(new String[0])); for (Authorizable authorizable : validatedGroups) { // is current group also contained in memberOf-groups property // of repo group? if (membershipGroupsFromRepository.contains(authorizable .getID())) { continue; } else { // if not add that group to membersOf-property of existing // group LOG.info("add {} to members of group {} in repository", principalId, authorizable); if (StringUtils.equals(authorizable.getID(), principalId)) { String warning = "Attempt to add a group as member of itself (" + authorizable + ")."; LOG.warn(warning); status.addWarning(warning); } else { ((Group) authorizable).addMember(userManager .getAuthorizable(principalId)); } } } } } private boolean isMemberOfOtherGroup(Authorizable group) throws RepositoryException { Iterator<Group> it = group.declaredMemberOf(); if (!it.hasNext()) { return false; } return true; } private Authorizable createNewGroup( final UserManager userManager, AuthorizableConfigBean principalConfigBean, AcInstallationHistoryPojo status, AuthorizableInstallationHistory authorizableInstallationHistory, ValueFactory vf, Map<String, LinkedHashSet<AuthorizableConfigBean>> principalMapFromConfig) throws AuthorizableExistsException, RepositoryException, AuthorizableCreatorException { String groupID = principalConfigBean.getPrincipalID(); String[] memberOf = principalConfigBean.getMemberOf(); String intermediatePath = principalConfigBean.getPath(); // create new Group Group newGroup = null; try { newGroup = userManager.createGroup(new PrincipalImpl(groupID), intermediatePath); } catch (AuthorizableExistsException e) { LOG.warn("Group {} already exists in system!", groupID); newGroup = (Group) userManager.getAuthorizable(groupID); } // add group to groups according to configuration if ((memberOf != null) && (memberOf.length > 0)) { Set<Authorizable> assignedGroups = validateAssignedGroups( userManager, groupID, memberOf); if (!assignedGroups.isEmpty()) { LOG.info("start adding {} to assignedGroups", groupID); for (Authorizable authorizable : assignedGroups) { ((Group) authorizable).addMember(newGroup); LOG.info("added to {} ", authorizable); } } } setAuthorizableName(newGroup, vf, principalConfigBean); return newGroup; } private void setAuthorizableName(Authorizable authorizable, ValueFactory vf, AuthorizableConfigBean principalConfigBean) throws RepositoryException { String name = principalConfigBean.getPrincipalName(); if (StringUtils.isNotBlank(name)) { if (authorizable.isGroup()) { authorizable.setProperty("profile/givenName", vf.createValue(name)); } else { String givenName = StringUtils.substringBeforeLast(name, " "); String familyName = StringUtils.substringAfterLast(name, " "); authorizable.setProperty("profile/givenName", vf.createValue(givenName)); authorizable.setProperty("profile/familyName", vf.createValue(familyName)); } } } private Authorizable createNewUser( final UserManager userManager, AuthorizableConfigBean principalConfigBean, AcInstallationHistoryPojo status, AuthorizableInstallationHistory authorizableInstallationHistory, ValueFactory vf, Map<String, LinkedHashSet<AuthorizableConfigBean>> principalMapFromConfig) throws AuthorizableExistsException, RepositoryException, AuthorizableCreatorException { String principalId = principalConfigBean.getPrincipalID(); String[] memberOf = principalConfigBean.getMemberOf(); String password = principalConfigBean.getPassword(); boolean isSystemUser = principalConfigBean.isSystemUser(); String intermediatePath = principalConfigBean.getPath(); User newUser = null; if (isSystemUser) { newUser = userManagerCreateSystemUserViaReflection(userManager, principalId, intermediatePath, status); } else { newUser = userManager.createUser(principalId, password, new PrincipalImpl(principalId), intermediatePath); } setAuthorizableName(newUser, vf, principalConfigBean); if ((newUser != null) && (memberOf != null) && (memberOf.length > 0)) { // add group to groups according to configuration Set<Authorizable> authorizables = validateAssignedGroups( userManager, principalId, memberOf); if (!authorizables.isEmpty()) { for (Authorizable authorizable : authorizables) { ((Group) authorizable).addMember(newUser); } } } return newUser; } // using reflection with fallback to create a system user in order to be backwards compatible public User userManagerCreateSystemUserViaReflection(UserManager userManager, String userID, String intermediatePath, AcInstallationHistoryPojo status) throws RepositoryException { // make sure all relative intermediate paths get the prefix suffix (but don't touch absolute paths) String systemPrefix = "system/"; if ((intermediatePath != null) && !intermediatePath.startsWith(systemPrefix) && !intermediatePath.startsWith("/")) { intermediatePath = systemPrefix + intermediatePath; } try { Method method = userManager.getClass().getMethod("createSystemUser", String.class, String.class); User user = (User) method.invoke(userManager, userID, intermediatePath); return user; } catch (Throwable e) { if (e instanceof InvocationTargetException) { e = ((InvocationTargetException) e).getTargetException(); } status.addError("Could not create system user " + userID + ". e:" + e); } return null; } /** Validates the authorizables in 'membersOf' array of a given authorizable. Validation fails if an authorizable is a user If an * authorizable contained in membersOf array doesn't exist it gets created and the current authorizable gets added as a member * * @param out * @param userManager * @param authorizablelID the ID of authorizable to validate * @param memberOf String array that contains the groups which the authorizable should be a member of * @return Set of authorizables which the current authorizable is a member of * @throws RepositoryException * @throws AuthorizableCreatorException if one of the authorizables contained in membersOf array is a user */ private Set<Authorizable> validateAssignedGroups( final UserManager userManager, final String authorizablelID, final String[] memberOf) throws RepositoryException, AuthorizableCreatorException { Set<Authorizable> authorizableSet = new HashSet<Authorizable>(); for (String principal : memberOf) { Authorizable authorizable = userManager.getAuthorizable(principal); // validation // if authorizable is existing in system if (authorizable != null) { // check if authorizable is a group if (authorizable.isGroup()) { authorizableSet.add(authorizable); } else { String message = "Failed to add authorizable " + authorizablelID + "to autorizable " + principal + "! Authorizable is not a group"; LOG.warn(message); throw new AuthorizableCreatorException( "Failed to add authorizable " + authorizablelID + "to autorizable " + principal + "! Authorizable is not a group"); } // if authorizable doesn't exist yet, it gets created and the // current authorizable gets added as a member } else { // check if authorizable is contained in any of the // configurations if (principalMapFromConfig.keySet().contains(principal)) { // get authorizable intermediatePath LinkedHashSet<AuthorizableConfigBean> authorizableConfigSet = principalMapFromConfig .get(principal); Iterator<AuthorizableConfigBean> it = authorizableConfigSet .iterator(); AuthorizableConfigBean authorizableConfigBean = null; while (it.hasNext()) { authorizableConfigBean = it.next(); } // create authorizable // if authorizableConfigBean.getPath() returns an empty // string (no path defined in configuration) the standard // path gets used Authorizable newGroup = userManager.createGroup( new PrincipalImpl(principal), authorizableConfigBean.getPath()); authorizableSet.add(newGroup); authorizableInstallationHistory .addNewCreatedAuthorizabe(newGroup.getID()); LOG.warn( "Failed to add group: {} to authorizable: {}. Didn't find this authorizable under /home! Created group", authorizablelID, principal); } else { String message = "Failed to add group: " + authorizablelID + " as member to authorizable: " + principal + ". Neither found this authorizable (" + principal + ") in any of the configurations nor installed in the system!"; LOG.error(message); throw new AuthorizableCreatorException(message); } } } return authorizableSet; } @Override public void performRollback(SlingRepository repository, AuthorizableInstallationHistory authorizableInstallationHistory, AcInstallationHistoryPojo history) throws RepositoryException { Session session = repository.loginAdministrative(null); ValueFactory vf = session.getValueFactory(); try { JackrabbitSession js = (JackrabbitSession) session; UserManager userManager = js.getUserManager(); // if groups was newly created delete it Set<String> newCreatedAuthorizables = authorizableInstallationHistory .getNewCreatedAuthorizables(); String message = "starting rollback of authorizables..."; history.addWarning(message); if (!newCreatedAuthorizables.isEmpty()) { history.addWarning("performing Groups rollback!"); for (String authorizableName : newCreatedAuthorizables) { userManager.getAuthorizable(authorizableName).remove(); message = "removed authorizable " + authorizableName + " from the system!"; LOG.info(message); history.addWarning(message); } } // if not compare the changes and reset them to the prevoius state Set<AuthorizableBean> authorizableBeans = authorizableInstallationHistory .getAuthorizableBeans(); for (AuthorizableBean snapshotBean : authorizableBeans) { Authorizable authorizable = userManager .getAuthorizable(snapshotBean.getName()); if (authorizable != null) { history.addMessage("found changed authorizable:" + authorizable.getID()); // check memberOf groups Iterator<Group> it = authorizable.memberOf(); Set<String> memberOfGroups = new HashSet<String>(); while (it.hasNext()) { memberOfGroups.add(it.next().getID()); } if (snapshotBean.getAuthorizablesSnapshot().equals( memberOfGroups)) { history.addMessage("No change found in memberOfGroups of authorizable: " + authorizable.getID()); } else { history.addMessage("changes found in memberOfGroups of authorizable: " + authorizable.getID()); // delete membership of currently set memberOf groups Iterator<Group> it2 = authorizable.memberOf(); while (it2.hasNext()) { Group group = it2.next(); group.removeMember(authorizable); history.addWarning("removed authorizable: " + authorizable.getID() + " from members of group: " + group.getID()); } // reset the state from snapshot bean for (String group : snapshotBean .getAuthorizablesSnapshot()) { Authorizable groupFromSnapshot = userManager .getAuthorizable(group); if (groupFromSnapshot != null) { ((Group) groupFromSnapshot) .addMember(authorizable); history.addWarning("add authorizable: " + authorizable.getID() + " to members of group: " + groupFromSnapshot.getID() + " again"); } } } String authorizableName = ""; if (authorizable.hasProperty("profile/givenName")) { authorizableName = authorizable .getProperty("profile/givenName")[0] .getString(); } if (snapshotBean.getName().equals(authorizableName)) { history.addMessage("No change found in name of authorizable: " + authorizable.getID()); } else { history.addMessage("change found in name of authorizable: " + authorizable.getID()); authorizable.setProperty("profile/givenName", vf.createValue(snapshotBean.getName())); history.addMessage("changed name of authorizable from: " + authorizableName + " back to: " + snapshotBean.getName()); } // TODO: compare other properties as well (name, path,...) } } } finally { if (session != null) { session.save(); session.logout(); } } } }
package lua.addon.compile; import java.io.DataOutputStream; import java.io.IOException; import java.io.OutputStream; import lua.Lua; import lua.io.Proto; import lua.value.LBoolean; import lua.value.LNil; import lua.value.LNumber; import lua.value.LString; import lua.value.LValue; public class DumpState { /** mark for precompiled code (`<esc>Lua') */ public static final String LUA_SIGNATURE = "\033Lua"; /** for header of binary files -- this is Lua 5.1 */ public static final int LUAC_VERSION = 0x51; /** for header of binary files -- this is the official format */ public static final int LUAC_FORMAT = 0; /** size of header of binary files */ public static final int LUAC_HEADERSIZE = 12; /** expected lua header bytes */ private static final byte[] LUAC_HEADER_SIGNATURE = { '\033', 'L', 'u', 'a' }; // header fields private boolean IS_LITTLE_ENDIAN = false; private boolean IS_NUMBER_INTEGRAL = false; private int SIZEOF_LUA_NUMBER = 8; private static final int SIZEOF_INT = 4; private static final int SIZEOF_SIZET = 4; private static final int SIZEOF_INSTRUCTION = 4; DataOutputStream writer; boolean strip; int status; public DumpState(OutputStream w, boolean strip) { this.writer = new DataOutputStream( w ); this.strip = strip; this.status = 0; } void dumpBlock(final byte[] b, int size) throws IOException { writer.write(b, 0, size); } void dumpChar(int b) throws IOException { writer.write( b ); } void dumpInt(int x) throws IOException { if ( IS_LITTLE_ENDIAN ) { writer.writeByte(x&0xff); writer.writeByte((x>>8)&0xff); writer.writeByte((x>>16)&0xff); writer.writeByte((x>>24)&0xff); } else { writer.writeInt(x); } } void dumpString(LString s) throws IOException { final int len = s.length(); dumpInt( len+1 ); s.write( writer, 0, len ); writer.write( 0 ); } void dumpNumber(double d) throws IOException { if ( IS_NUMBER_INTEGRAL ) { int i = (int) d; if ( i != d ) throw new java.lang.IllegalArgumentException("not an integer: "+d); dumpInt( i ); } else { long l = Double.doubleToLongBits(d); writer.writeLong(l); } } void dumpCode( final Proto f ) throws IOException { int n = f.code.length; dumpInt( n ); for ( int i=0; i<n; i++ ) dumpInt( f.code[i] ); } void dumpConstants(final Proto f) throws IOException { int i, n = f.k.length; dumpInt(n); for (i = 0; i < n; i++) { final LValue o = f.k[i]; if (o == LNil.NIL) { writer.write(Lua.LUA_TNIL); // do nothing more } else if (o instanceof LBoolean) { writer.write(Lua.LUA_TBOOLEAN); dumpChar(o.toJavaBoolean() ? 1 : 0); } else if (o instanceof LNumber) { writer.write(Lua.LUA_TNUMBER); dumpNumber(o.toJavaDouble()); } else if (o instanceof LString) { writer.write(Lua.LUA_TSTRING); dumpString((LString) o); } else { throw new IllegalArgumentException("bad type for " + o); } } n = f.p.length; dumpInt(n); for (i = 0; i < n; i++) dumpFunction(f.p[i], f.source); } void dumpDebug(final Proto f) throws IOException { int i, n; n = (strip) ? 0 : f.lineinfo.length; dumpInt(n); for (i = 0; i < n; i++) dumpInt(f.lineinfo[i]); n = (strip) ? 0 : f.locvars.length; dumpInt(n); for (i = 0; i < n; i++) { dumpString(f.locvars[i].varname); dumpInt(f.locvars[i].startpc); dumpInt(f.locvars[i].endpc); } n = (strip) ? 0 : f.upvalues.length; dumpInt(n); for (i = 0; i < n; i++) dumpString(f.upvalues[i]); } void dumpFunction(final Proto f, final LString string) throws IOException { if ( f.source == null || f.source.equals(string) || strip ) dumpInt(0); else dumpString(f.source); dumpInt(f.linedefined); dumpInt(f.lastlinedefined); dumpChar(f.nups); dumpChar(f.numparams); dumpChar(f.is_vararg? 1: 0); dumpChar(f.maxstacksize); dumpCode(f); dumpConstants(f); dumpDebug(f); } void dumpHeader() throws IOException { writer.write( LUAC_HEADER_SIGNATURE ); writer.write( LUAC_VERSION ); writer.write( LUAC_FORMAT ); writer.write( IS_LITTLE_ENDIAN? 1: 0 ); writer.write( SIZEOF_INT ); writer.write( SIZEOF_SIZET ); writer.write( SIZEOF_INSTRUCTION ); writer.write( SIZEOF_LUA_NUMBER ); writer.write( IS_NUMBER_INTEGRAL? 1: 0 ); } /* ** dump Lua function as precompiled chunk */ public static int dump( Proto f, OutputStream w, boolean strip ) throws IOException { DumpState D = new DumpState(w,strip); D.dumpHeader(); D.dumpFunction(f,null); return D.status; } public static int dump(Proto f, OutputStream w, boolean strip, boolean intonly, boolean littleendian) throws IOException { DumpState D = new DumpState(w,strip); D.IS_LITTLE_ENDIAN = littleendian; D.IS_NUMBER_INTEGRAL = intonly; D.SIZEOF_LUA_NUMBER = (intonly? 4: 8); D.dumpHeader(); D.dumpFunction(f,null); return D.status; } }
package etomica.dielectric; import java.awt.Color; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Calendar; import etomica.action.BoxImposePbc; import etomica.action.activity.ActivityIntegrate; import etomica.action.activity.Controller; import etomica.api.IAtom; import etomica.api.IAtomList; import etomica.api.IBox; import etomica.api.IMolecule; import etomica.api.IPotentialMaster; import etomica.api.ISpecies; import etomica.api.IVector; import etomica.api.IVectorMutable; import etomica.atom.AtomPositionCOM; import etomica.atom.DiameterHashByType; import etomica.atom.DipoleSource; import etomica.atom.IAtomPositionDefinition; import etomica.box.Box; import etomica.chem.elements.Hydrogen; import etomica.chem.elements.Oxygen; import etomica.config.ConfigurationLattice; import etomica.data.AccumulatorAverage; import etomica.data.AccumulatorAverageCovariance; import etomica.data.AccumulatorAverageFixed; import etomica.data.DataPump; import etomica.data.meter.MeterDipoleSumSquaredMappedAverage; import etomica.data.meter.MeterDipoleSumSquaredTIP4PWater; import etomica.data.types.DataDouble; import etomica.data.types.DataGroup; import etomica.graphics.ColorSchemeByType; import etomica.graphics.DisplayBox; import etomica.graphics.SimulationGraphic; import etomica.integrator.IntegratorMC; import etomica.integrator.mcmove.MCMoveMolecule; import etomica.integrator.mcmove.MCMoveRotateMolecule3D; import etomica.lattice.LatticeCubicFcc; import etomica.listener.IntegratorListenerAction; import etomica.models.water.P2WaterTIP4PSoft; import etomica.models.water.SpeciesWater4P; import etomica.potential.P2ReactionFieldDipole; import etomica.potential.PotentialMaster; import etomica.simulation.Simulation; import etomica.space.ISpace; import etomica.space.Space; import etomica.space3d.Space3D; import etomica.units.Electron; import etomica.units.Kelvin; import etomica.units.Pixel; import etomica.util.Constants; import etomica.util.ParameterBase; import etomica.util.ParseArgs; import etomica.util.RandomNumberGenerator; /** * Canonical ensemble Monte Carlo simulation (NVT) * dielectric constant (epsilon) * TIP4P water * @author shu and Weisong */ public class TIP4P_NVT extends Simulation { private static final long serialVersionUID = 1L; protected final IPotentialMaster potentialMaster; protected final IntegratorMC integrator; protected final MCMoveMolecule moveMolecule;//translation protected final MCMoveRotateMolecule3D rotateMolecule;//rotation protected final IBox box; protected SpeciesWater4P species; protected P2WaterTIP4PSoft pWater; private final static String APP_NAME = "TIP4P water"; private static final int PIXEL_SIZE = 15; public final ActivityIntegrate activityIntegrate; public Controller controller; protected double sigmaLJ, epsilonLJ; protected double chargeM, chargeH; // public static class DipoleSourceTIP4PWater implements DipoleSource{//for potential reaction field protected final IVectorMutable dipole; public DipoleSourceTIP4PWater(ISpace space){ dipole=space.makeVector(); } public IVector getDipole(IMolecule molecule) {// dipole = sum of position * charge on the site IAtomList childList = molecule.getChildList(); IAtom atomH1 = childList.getAtom(0); IAtom atomH2 = childList.getAtom(1); IAtom atomO = childList.getAtom(2); IAtom atomM = childList.getAtom(3); double chargeH = Electron.UNIT.toSim(+0.52); double chargeM = Electron.UNIT.toSim(-1.04); dipole.Ea1Tv1(chargeH, atomH1.getPosition()); dipole.PEa1Tv1(chargeH, atomH2.getPosition()); dipole.PEa1Tv1(chargeM, atomM.getPosition()); return dipole; } } // public TIP4P_NVT(Space space, int numberMolecules, double dielectricOutside, double boxSize, double temperature,double truncation){ super(space); // setRandom(new RandomNumberGenerator(1)); // debug only species = new SpeciesWater4P(space); addSpecies(species); box = new Box(space); addBox(box); box.setNMolecules(species, numberMolecules); box.getBoundary().setBoxSize(space.makeVector(new double[]{boxSize,boxSize,boxSize})); // double mu=168.96979945736229;//in simulation unit //for potential truncated IAtomPositionDefinition positionDefinition = new AtomPositionCOM(space) ; pWater = new P2WaterTIP4PSoft(space,truncation,positionDefinition); sigmaLJ= pWater.getSigma(); epsilonLJ=pWater.getEpsilon(); chargeM=pWater.getChargeM(); chargeH=pWater.getChargeH(); // System.out.println("sigma = " +sigmaLJ); // System.out.println("epsilon = " + epsilonLJ); // System.exit(2); // add reaction field potential DipoleSourceTIP4PWater dipoleSourceTIP4PWater = new DipoleSourceTIP4PWater(space); P2ReactionFieldDipole pRF = new P2ReactionFieldDipole(space,positionDefinition); pRF.setDipoleSource(dipoleSourceTIP4PWater); pRF.setRange(truncation); pRF.setDielectric(dielectricOutside); potentialMaster = new PotentialMaster(); potentialMaster.addPotential(pRF, new ISpecies[]{species, species}); potentialMaster.addPotential(pWater, new ISpecies[]{species, species}); potentialMaster.lrcMaster().addPotential(pRF.makeP0()); //add external field potential // P1ExternalField p1ExternalField = new P1ExternalField(space); // IVectorMutable dr = space.makeVector(); // p1ExternalField.setExternalField(dr); // p1ExternalField.setDipoleSource(dipoleSourceTIP4PWater);// // potentialMaster.addPotential(p1ExternalField, new ISpecies[] {species});//External field // integrator from potential master integrator = new IntegratorMC(this, potentialMaster); // add mc move moveMolecule = new MCMoveMolecule(this, potentialMaster, space);//stepSize:1.0, stepSizeMax:15.0 rotateMolecule = new MCMoveRotateMolecule3D(potentialMaster,random,space); activityIntegrate = new ActivityIntegrate(integrator); getController().addAction(activityIntegrate); public static class Param extends ParameterBase { public boolean isGraphic = false; public boolean mSquare = true; public boolean aEE = true; public double temperatureK = 1000; public int numberMolecules = 2; public double density = 0.001;//g/cm^3 public double dielectricOutside = 1.0E11; public int steps = 1000000; } }
package kata; import static kata.Printer.*; import java.util.*; public class FirstAndLastPositionOfElementInSortedArray { static int[] firstAndLastPositionOfElementInSortedArray(int[] nums, int target) { int[] targetRange = {-1, -1}; int leftIdx = extremeInsertionIndex2(nums, target, true); // assert that `leftIdx` is within the array bounds and that `target` // is actually in `nums`. if (leftIdx == nums.length || leftIdx == - 1 || nums[leftIdx] != target) { return targetRange; } targetRange[0] = leftIdx; targetRange[1] = extremeInsertionIndex2(nums, target, false); // or targetRange[1] = extremeInsertionIndex(nums, target, false) - 1; return targetRange; } // returns leftmost (or rightmost) index at which `target` should be // inserted in sorted array `nums` via binary search. private static int extremeInsertionIndex(int[] nums, int target, boolean left) { int lo = 0; int hi = nums.length; while (lo < hi) { int mid = (lo + hi) / 2; if (nums[mid] > target || (left && target == nums[mid])) { hi = mid; } else { lo = mid+1; } } return lo; } // Easier to understand, in my opinion. private static int extremeInsertionIndex2(int[] nums, int target, boolean left) { int lo = 0; int hi = nums.length; int ans = -1; while (lo <= hi) { int mid = (lo + hi) / 2; if (nums[mid] > target) { hi = mid - 1; } else if (nums[mid] < target) { lo = mid + 1; } else { // nums[mid] == target ans = mid; if (left) { hi = mid - 1; } else { lo = mid + 1; } } } return ans; } public static void main(String args[]) { runSample(new int[]{5,7,7,8,8,10}, 8, new int[]{3, 4}); runSample(new int[]{5,7,7,8,8,10}, 6, new int[]{-1, -1}); } static void runSample(int[] nums, int target, int[] ans) { System.out.printf( "%s,%s = %s(%s)\n", Arrays.toString(nums), target, Arrays.toString(firstAndLastPositionOfElementInSortedArray(nums, target)), Arrays.toString(ans)); } }
package com.github.onsdigital.index; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.nio.file.NoSuchFileException; import java.nio.file.Paths; import java.util.List; import java.util.Map; import org.junit.Test; import com.google.gson.JsonIOException; import com.google.gson.JsonSyntaxException; public class LoadIndexHelperTest { private final static String FILE_NAME = "index"; private final static String FILE_EXTENSION = ".html"; private final static String DATA_JSON_FILE_NAME = "data.json"; private final static String CONTENT_TYPE = "bulletins"; private final static String DELIMITTER = "/"; private final static String RESOURCE_FILE_PATH = "target/classes/files/home"; private final static String TAXONOMY_PATH = "/sample-taxonomy/"; private final static String PRE_BULLETINS_PATH = RESOURCE_FILE_PATH + TAXONOMY_PATH; private final static String CONTENT_TYPE_TEST_FILE = PRE_BULLETINS_PATH + CONTENT_TYPE + DELIMITTER + FILE_NAME + FILE_EXTENSION; private final static String HOME_PAGE_TEST_FILE = Paths.get(PRE_BULLETINS_PATH + DATA_JSON_FILE_NAME).toAbsolutePath().toString(); private final static String CONTENT_TYPE_URL = TAXONOMY_PATH + CONTENT_TYPE + DELIMITTER + FILE_NAME + FILE_EXTENSION; private final static String HOME_PAGE_URL = TAXONOMY_PATH; @Test public void testGetFileNames() throws IOException { List<String> fileNames = LoadIndexHelper.getAbsoluteFilePaths(RESOURCE_FILE_PATH); System.out.println("Tut siise is: " + fileNames.size()); assertFalse("Lookup should return some files", fileNames.isEmpty()); } @Test(expected = NoSuchFileException.class) public void testWrongPath() throws IOException { List<String> fileNames = LoadIndexHelper.getAbsoluteFilePaths("thepath/thesubpath"); System.out.println("Tut siise is: " + fileNames.size()); assertFalse("Lookup should return some files", fileNames.isEmpty()); } public void testGetDocumentMapForContentType() throws JsonIOException, JsonSyntaxException, IOException { Map<String, String> documentMap = LoadIndexHelper.getDocumentMap(CONTENT_TYPE_TEST_FILE); assertEquals("url should math file structure", documentMap.get("url"), CONTENT_TYPE_URL); assertEquals("type should be bulletins", documentMap.get("type"), "bulletins"); assertEquals("title should be data.json", documentMap.get("title"), "index.html"); assertTrue("tags should contain subdirs", documentMap.get("tags").contains("sample-taxonomy")); } public void testGetDocumentMapForHomePage() throws JsonIOException, JsonSyntaxException, IOException { Map<String, String> documentMap = LoadIndexHelper.getDocumentMap(HOME_PAGE_TEST_FILE); assertEquals("url should math file structure", documentMap.get("url"), HOME_PAGE_URL); assertEquals("type should be bulletins", documentMap.get("type"), "home"); assertEquals("title should be uksectoraccounts", documentMap.get("title"), "Government, Public Sector and Taxes"); assertFalse("tags should not contain content type subdir", documentMap.get("tags").contains("CONTENT_TYPE")); } }
package com.martensigwart.fakeload; import com.martensigwart.fakeload.internal.util.MoreAsserts; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.concurrent.TimeUnit; import static org.junit.Assert.*; public abstract class AbstractFakeLoadTest { private final Class<? extends FakeLoad> classUnderTest; private FakeLoad fakeload = null; AbstractFakeLoadTest(Class<? extends FakeLoad> classUnderTest) { this.classUnderTest = classUnderTest; } @Before public void setup() { try { fakeload = classUnderTest.newInstance(); } catch (InstantiationException | IllegalAccessException e) { e.printStackTrace(); } } @Test public void testLastingMethod1() { fakeload = fakeload.lasting(10, TimeUnit.SECONDS); assertDuration(10L, TimeUnit.SECONDS, fakeload); } @Test(expected = IllegalArgumentException.class) public void testLastingMethod2() { fakeload = fakeload.lasting(-10, TimeUnit.SECONDS); } @Test(expected = NullPointerException.class) public void testLastingMethod3(){ fakeload = fakeload.lasting(10, null); } @Test public void testRepeatMethod1() { fakeload = fakeload.repeat(20); assertRepetitions(20, fakeload); } @Test(expected = IllegalArgumentException.class) public void testRepeatMethod2() { fakeload = fakeload.repeat(-20); } @Test public void testCpuLoadMethod1() { fakeload = fakeload.withCpuLoad(20); assertCpuLoad(20, fakeload); } @Test(expected = IllegalArgumentException.class) public void testCpuLoadMethod2() { fakeload = fakeload.withCpuLoad(-20); } @Test(expected = IllegalArgumentException.class) public void testCpuLoadMethod3() { fakeload = fakeload.withCpuLoad(120); } @Test public void testMemoryLoadMethod1() { // Bytes fakeload = fakeload.withMemoryLoad(1024, MemoryUnit.BYTES); assertMemoryLoad(1024L, fakeload); fakeload = fakeload.withMemoryLoad(300, MemoryUnit.KB); assertMemoryLoad(300L*1024, fakeload); fakeload = fakeload.withMemoryLoad(300, MemoryUnit.MB); assertMemoryLoad(300L*1024*1024, fakeload); fakeload = fakeload.withMemoryLoad(2, MemoryUnit.GB); assertMemoryLoad(2L*1024*1024*1024, fakeload); } @Test(expected = IllegalArgumentException.class) public void testMemoryLoadMethod2() { fakeload = fakeload.withMemoryLoad(-20, MemoryUnit.MB); } @Test(expected = NullPointerException.class) public void testMemoryLoadMethod3() { fakeload = fakeload.withMemoryLoad(20, null); } @Test public void testAddLoadMethod() { FakeLoad child1 = fakeload.lasting(100, TimeUnit.MILLISECONDS).withCpuLoad(20); FakeLoad child2 = fakeload.lasting(10, TimeUnit.SECONDS).withMemoryLoad(100, MemoryUnit.MB); assertEquals(0, fakeload.getInnerLoads().size()); fakeload = fakeload.addLoad(child1) .addLoad(child2); assertEquals(2, fakeload.getInnerLoads().size()); } @Test public void testAddLoadsMethod() { FakeLoad child1 = fakeload.lasting(100, TimeUnit.MILLISECONDS).withCpuLoad(20); FakeLoad child2 = fakeload.lasting(10, TimeUnit.SECONDS).withMemoryLoad(100, MemoryUnit.MB); FakeLoad child3 = fakeload.lasting(10, TimeUnit.SECONDS).withMemoryLoad(300, MemoryUnit.MB); List<FakeLoad> children = new ArrayList<>(); children.add(child2); children.add(child3); fakeload = fakeload.addLoad(child1); assertEquals(1, fakeload.getInnerLoads().size()); fakeload = fakeload.addLoads(children); assertEquals(3, fakeload.getInnerLoads().size()); } // TEST OTHER METHODS @Test public void testEqualsMethodReflexivity() { FakeLoad child1 = new SimpleFakeLoad(5, TimeUnit.SECONDS); FakeLoad child2 = new SimpleFakeLoad(500, TimeUnit.MILLISECONDS); FakeLoad child3 = new SimpleFakeLoad(1, TimeUnit.MINUTES); // test reflexivity assertEqualsReflexivity(fakeload); fakeload = fakeload.lasting(300, TimeUnit.MILLISECONDS).repeat(3) .withCpuLoad(50) .withMemoryLoad(300, MemoryUnit.MB) .withNetIOLoad(2000) .withDiskIOLoad(5000); assertEqualsReflexivity(fakeload); fakeload = fakeload.lasting(30, TimeUnit.SECONDS).repeat(6) .withCpuLoad(80) .withMemoryLoad(300, MemoryUnit.KB) .withNetIOLoad(20) .withDiskIOLoad(51200) .addLoad(child1).addLoad(child2).addLoad(child3); assertEqualsReflexivity(fakeload); } @Test public void testEqualsMethodSymmetry() { FakeLoad parent1, parent2; FakeLoad child1 = new SimpleFakeLoad(5, TimeUnit.SECONDS); FakeLoad child2 = new SimpleFakeLoad(500, TimeUnit.MILLISECONDS); FakeLoad child3 = new SimpleFakeLoad(1, TimeUnit.MINUTES); FakeLoad child1Copy = new SimpleFakeLoad(5, TimeUnit.SECONDS); FakeLoad child2Copy = new SimpleFakeLoad(500, TimeUnit.MILLISECONDS); // parent load identical, children identical parent1 = fakeload.lasting(20, TimeUnit.SECONDS).withCpuLoad(30) .addLoad(child1) .addLoad(child2); parent2 = fakeload.lasting(20, TimeUnit.SECONDS).withCpuLoad(30) .addLoad(child1) .addLoad(child2); assertEquals(parent1, parent2); assertEqualsSymmetry(parent1, parent2); // parent load identical, children logically equal parent2 = fakeload.lasting(20, TimeUnit.SECONDS).withCpuLoad(30) .addLoad(child1Copy) .addLoad(child2Copy); assertEquals(parent1, parent2); assertEqualsSymmetry(parent1, parent2); // parent load identical, children different parent2 = new SimpleFakeLoad().lasting(20, TimeUnit.SECONDS).withCpuLoad(30) .addLoad(child1).addLoad(child3); assertNotEquals(parent1, parent2); assertEqualsSymmetry(parent1, parent2); // parent load different, children identical parent1 = fakeload.lasting(10, TimeUnit.SECONDS).withCpuLoad(20) .addLoad(child1) .addLoad(child2); parent2 = fakeload.lasting(20, TimeUnit.SECONDS).withCpuLoad(30) .addLoad(child1) .addLoad(child2); assertNotEquals(parent1, parent2); assertEqualsSymmetry(parent1, parent2); // parent load different, children logically equal parent1 = fakeload.lasting(10, TimeUnit.SECONDS).withCpuLoad(20) .addLoad(child1) .addLoad(child2); parent2 = fakeload.lasting(20, TimeUnit.SECONDS).withCpuLoad(30) .addLoad(child1Copy) .addLoad(child2Copy); assertNotEquals(parent1, parent2); assertEqualsSymmetry(parent1, parent2); // parent load different, children different parent1 = fakeload.lasting(10, TimeUnit.SECONDS).withCpuLoad(20) .addLoad(child1) .addLoad(child2); parent2 = fakeload.lasting(20, TimeUnit.SECONDS).withCpuLoad(30) .addLoad(child1) .addLoad(child3); assertNotEquals(parent1, parent2); assertEqualsSymmetry(parent1, parent2); } @Test public void testEqualsMethodTransitivity() { FakeLoad parent1, parent2, parent3; FakeLoad child1 = new SimpleFakeLoad(5, TimeUnit.SECONDS); FakeLoad child2 = new SimpleFakeLoad(500, TimeUnit.MILLISECONDS); FakeLoad child1Copy = new SimpleFakeLoad(5, TimeUnit.SECONDS); FakeLoad child2Copy = new SimpleFakeLoad(500, TimeUnit.MILLISECONDS); FakeLoad child1Copy2 = new SimpleFakeLoad(5, TimeUnit.SECONDS); FakeLoad child2Copy2 = new SimpleFakeLoad(500, TimeUnit.MILLISECONDS); parent1 = fakeload.lasting(10, TimeUnit.SECONDS) .addLoad(child1).addLoad(child2); parent2 = fakeload.lasting(10, TimeUnit.SECONDS) .addLoad(child1Copy).addLoad(child2Copy); parent3 = fakeload.lasting(10, TimeUnit.SECONDS) .addLoad(child1Copy2).addLoad(child2Copy2); assertEqualsTransitivity(parent1, parent2, parent3); } @Test public void testHashCode() { FakeLoad child1 = new SimpleFakeLoad(5, TimeUnit.SECONDS); FakeLoad child2 = new SimpleFakeLoad(500, TimeUnit.MILLISECONDS); FakeLoad f1 = fakeload.addLoad(child1).addLoad(child2); FakeLoad f2 = fakeload.addLoad(child1).addLoad(child2); assertEquals(f1.hashCode(), f2.hashCode()); f1 = fakeload.addLoad(child1).addLoad(child2); f2 = fakeload.addLoad(child2).addLoad(child1); assertNotEquals(f1.hashCode(), f2.hashCode()); } @Test public void testContainsMethod1() { FakeLoad twin1 = fakeload.lasting(5, TimeUnit.SECONDS); FakeLoad twin2 = fakeload.lasting(5, TimeUnit.SECONDS); FakeLoad other = fakeload.lasting(3, TimeUnit.SECONDS); assertTrue(twin1.contains(twin2)); assertTrue(twin2.contains(twin1)); assertFalse(twin1.contains(other)); assertFalse(twin2.contains(other)); } @Test public void testContainsMethod2() { FakeLoad child1 = fakeload.lasting(5, TimeUnit.SECONDS); FakeLoad child2 = fakeload.lasting(500, TimeUnit.MILLISECONDS); FakeLoad sameAsChild1 = fakeload.lasting(5, TimeUnit.SECONDS); FakeLoad other = fakeload.lasting(3, TimeUnit.SECONDS); // adding loads creates a new CompositeFakeLoad FakeLoad parent = fakeload.lasting(10, TimeUnit.SECONDS) .addLoad(child1) .addLoad(child2); assertTrue(parent.contains(child1)); assertTrue(parent.contains(child2)); assertTrue(parent.contains(sameAsChild1)); assertFalse(parent.contains(other)); } @Test(expected = NoSuchElementException.class) public void testIteratorMethod1() { FakeLoad simple = new SimpleFakeLoad().lasting(12, TimeUnit.SECONDS) .withCpuLoad(80) .withMemoryLoad(300, MemoryUnit.KB); Iterator<FakeLoad> iterator = simple.iterator(); assertTrue(iterator.hasNext()); FakeLoad next = iterator.next(); assertEquals(simple, next); assertFalse(iterator.hasNext()); // now throws an exception iterator.next(); } @Test(expected = NoSuchElementException.class) public void testIteratorMethod2() { FakeLoad simple = new SimpleFakeLoad().lasting(1111, TimeUnit.MILLISECONDS) .withCpuLoad(99) .withMemoryLoad(9999, MemoryUnit.BYTES); FakeLoad parent = simple; List<FakeLoad> children = new ArrayList<>(); int noOfChildren = 10; long startDuration = 1; long startCPU = 10; long startMemory = 100; for (int i=0; i<noOfChildren; i++) { FakeLoad child = new SimpleFakeLoad().lasting(startDuration*i, TimeUnit.SECONDS) .withCpuLoad(startCPU*i) .withMemoryLoad(startMemory*i, MemoryUnit.KB); children.add(child); parent = parent.addLoad(child); } // check that for loop is correct assertEquals(noOfChildren, children.size()); // now test iterator Iterator<FakeLoad> iterator = parent.iterator(); assertTrue(iterator.hasNext()); FakeLoad next = iterator.next(); assertEquals(simple, next); for (int i=0; i<noOfChildren; i++) { assertTrue(iterator.hasNext()); next = iterator.next(); assertEquals(children.get(i), next); } assertFalse(iterator.hasNext()); // now throws an exception iterator.next(); } @Test(expected = NoSuchElementException.class) public void testIteratorMethod3() { FakeLoad simple = new SimpleFakeLoad().lasting(9999, TimeUnit.MILLISECONDS) .withCpuLoad(99) .withMemoryLoad(9999, MemoryUnit.BYTES); int noOfChildren = 10; int noOfGrandChildrenPerChild = 9; FakeLoad parent = simple; List<FakeLoad> children = new ArrayList<>(); List<FakeLoad> grandChildren = new ArrayList<>(); long startDuration = 10; long startCPU = 1; long startMemory = 1000; // create children for (int i=0; i<noOfChildren; i++) { FakeLoad child = new SimpleFakeLoad().lasting(startDuration*i, TimeUnit.SECONDS) .withCpuLoad(startCPU*i) .withMemoryLoad(startMemory*i, MemoryUnit.KB); children.add(i, child); // create grand children for (int j=0; j<noOfGrandChildrenPerChild; j++) { FakeLoad grandChild = new SimpleFakeLoad().lasting(startDuration*i+j, TimeUnit.SECONDS) .withCpuLoad(startCPU+j) .withMemoryLoad(startMemory*i+j, MemoryUnit.KB); grandChildren.add(i*noOfGrandChildrenPerChild+j, grandChild); child = child.addLoad(grandChild); } parent = parent.addLoad(child); } // Check that for-loops are correct assertEquals(noOfChildren, children.size()); assertEquals(noOfGrandChildrenPerChild*noOfChildren, grandChildren.size()); // Now test iterator Iterator<FakeLoad> iterator = parent.iterator(); assertTrue(iterator.hasNext()); FakeLoad next = iterator.next(); assertEquals(simple, next); for (int i=0; i<noOfChildren; i++) { assertTrue(iterator.hasNext()); next = iterator.next(); assertEquals(children.get(i), next); for (int j=0; j<noOfGrandChildrenPerChild; j++) { assertTrue(iterator.hasNext()); next = iterator.next(); assertEquals(grandChildren.get(i*noOfGrandChildrenPerChild+j), next); } } assertFalse(iterator.hasNext()); // now throws an exception iterator.next(); } // HELPER METHODS void assertDefault(FakeLoad actual) { assertEquals(0, actual.getRepetitions()); assertEquals(0L, actual.getDuration()); assertEquals(TimeUnit.MILLISECONDS, actual.getTimeUnit()); assertEquals(0, actual.getCpuLoad()); assertEquals(0L, actual.getMemoryLoad()); assertEquals(0L, actual.getDiskIOLoad()); assertEquals(0L, actual.getNetIOLoad()); assertEquals(0, actual.getInnerLoads().size()); } void assertDuration(long expectedDuration, TimeUnit expectedUnit, FakeLoad actual) { assertEquals(0, actual.getRepetitions()); assertEquals(expectedDuration, actual.getDuration()); assertEquals(expectedUnit, actual.getTimeUnit()); assertEquals(0, actual.getCpuLoad()); assertEquals(0L, actual.getMemoryLoad()); assertEquals(0L, actual.getDiskIOLoad()); assertEquals(0L, actual.getNetIOLoad()); assertEquals(0, actual.getInnerLoads().size()); } void assertInnerLoadsSize(int expectedSize, FakeLoad actual) { assertEquals(0, actual.getRepetitions()); assertEquals(0L, actual.getDuration()); assertEquals(TimeUnit.MILLISECONDS, actual.getTimeUnit()); assertEquals(0, actual.getCpuLoad()); assertEquals(0L, actual.getMemoryLoad()); assertEquals(0L, actual.getDiskIOLoad()); assertEquals(0L, actual.getNetIOLoad()); assertEquals(expectedSize, actual.getInnerLoads().size()); } void assertRepetitions(int expectedRepetitions, FakeLoad actual) { assertEquals(expectedRepetitions, actual.getRepetitions()); assertEquals(0L, actual.getDuration()); assertEquals(TimeUnit.MILLISECONDS, actual.getTimeUnit()); assertEquals(0, actual.getCpuLoad()); assertEquals(0L, actual.getMemoryLoad()); assertEquals(0L, actual.getDiskIOLoad()); assertEquals(0L, actual.getNetIOLoad()); assertEquals(0, actual.getInnerLoads().size()); } private void assertCpuLoad(int expectedCpu, FakeLoad actual) { assertEquals(0, actual.getRepetitions()); assertEquals(0L, actual.getDuration()); assertEquals(TimeUnit.MILLISECONDS, actual.getTimeUnit()); assertEquals(expectedCpu, actual.getCpuLoad()); assertEquals(0L, actual.getMemoryLoad()); assertEquals(0L, actual.getDiskIOLoad()); assertEquals(0L, actual.getNetIOLoad()); assertEquals(0, actual.getInnerLoads().size()); } private void assertMemoryLoad(long expectedMemory, FakeLoad actual) { assertEquals(0, actual.getRepetitions()); assertEquals(0L, actual.getDuration()); assertEquals(TimeUnit.MILLISECONDS, actual.getTimeUnit()); assertEquals(0, actual.getCpuLoad()); assertEquals(expectedMemory, actual.getMemoryLoad()); assertEquals(0L, actual.getDiskIOLoad()); assertEquals(0L, actual.getNetIOLoad()); assertEquals(0, actual.getInnerLoads().size()); } private void assertDiskIOLoad(long expectedDiskIO, FakeLoad actual) { // TODO } private void assertNetIOLoad(long expectedNetIO, FakeLoad actual) { // TODO } public void assertEqualsReflexivity(FakeLoad load) { assertEquals(load, load); assertNotEquals(load, null); assertNotEquals(null, load); } public void assertEqualsSymmetry(FakeLoad f1, FakeLoad f2) { if (f1.equals(f2)) { assertEquals(f1, f2); assertEquals(f2, f1); } else { assertNotEquals(f1, f2); assertNotEquals(f2, f1); } } public void assertEqualsTransitivity(FakeLoad f1, FakeLoad f2, FakeLoad f3) { MoreAsserts.assertEqualsTransitivity(f1, f2, f3); MoreAsserts.assertEqualsTransitivity(f1, f3, f2); MoreAsserts.assertEqualsTransitivity(f3, f1, f2); MoreAsserts.assertEqualsTransitivity(f3, f2, f1); MoreAsserts.assertEqualsTransitivity(f2, f3, f1); MoreAsserts.assertEqualsTransitivity(f2, f1, f2); } }
package com.moosemorals.weather.xml; import com.moosemorals.weather.types.Astronomy; import com.moosemorals.weather.types.Current; import com.moosemorals.weather.types.Forecast; import com.moosemorals.weather.types.Hour; import com.moosemorals.weather.types.Location; import com.moosemorals.weather.types.WeatherReport; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.io.UnsupportedEncodingException; import javax.xml.stream.XMLInputFactory; import javax.xml.stream.XMLStreamReader; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import org.joda.time.LocalDate; import org.joda.time.LocalTime; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.testng.Assert.assertEquals; import static org.testng.Assert.assertNotEquals; import static org.testng.Assert.assertNotNull; import org.testng.annotations.Test; /** * * @author osric */ public class WeatherParserNGTest { private final Logger log = LoggerFactory.getLogger(WeatherParserNGTest.class); public WeatherParserNGTest() { } @Test public void basics() throws Exception { WeatherReport report = new WeatherParser().parse(getClass().getResourceAsStream("/sample-utc.xml")); assertNotNull(report); assertNotNull(report.getCurrent()); assertNotEquals(report.getForecasts().size(), 3); DateTime when = new DateTime(2015, 7, 25, 11, 01, 0, DateTimeZone.forOffsetHours(1)); assertEquals(report.getLocalTime(), when); } @Test public void location() throws Exception { WeatherReport report = new WeatherParser().parse(getClass().getResourceAsStream("/sample-utc.xml")); Location location = report.getLocation(); assertNotNull(location); assertEquals(location.getType(), "UK Postcode"); assertEquals(location.getName(), "NE6"); } @Test public void current() throws Exception { WeatherReport report = new WeatherParser().parse(getClass().getResourceAsStream("/sample-utc.xml")); Current current = report.getCurrent(); assertEquals(current.getObservationTime(), new LocalTime(10, 01)); assertEquals(current.getTempC(), 14); assertEquals(current.getWeatherCode(), 116); assertEquals(current.getWeatherIconUrl(), "http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0002_sunny_intervals.png"); assertEquals(current.getWeatherDesc(), "Partly Cloudy"); assertEquals(current.getWindspeedMPH(), 12); assertEquals(current.getWinddirDegree(), 340); assertEquals(current.getWinddirName(), "NNW"); assertEquals(current.getPrecipMM(), 0.0, 0.001); assertEquals(current.getVisibilityKm(), 10); assertEquals(current.getPressureMb(), 1012); assertEquals(current.getCloudcover(), 50); } @Test public void forecasts() throws Exception { WeatherReport report = new WeatherParser().parse(getClass().getResourceAsStream("/sample-utc.xml")); Forecast forecast = report.getForecasts().get(0); assertEquals(forecast.getDate(), new LocalDate(2015, 7, 25)); assertEquals(forecast.getMaxTempC(), 18); assertEquals(forecast.getMaxTempF(), 64); assertEquals(forecast.getMinTempC(), 9); assertEquals(forecast.getMinTempF(), 48); assertEquals(forecast.getUvIndex(), 5); } @Test public void astronomy() throws Exception { WeatherReport report = new WeatherParser().parse(getClass().getResourceAsStream("/sample-utc.xml")); Forecast forecast = report.getForecasts().get(0); Astronomy astronomy = forecast.getAstronomy(); assertNotNull(astronomy); assertEquals(astronomy.getSunrise(), new LocalTime(5, 2)); assertEquals(astronomy.getSunset(), new LocalTime(21, 22)); assertEquals(astronomy.getMoonrise(), new LocalTime(15, 26)); assertEquals(astronomy.getMoonset(), new LocalTime(0, 22)); } @Test public void hourly() throws Exception { WeatherReport report = new WeatherParser().parse(getClass().getResourceAsStream("/sample-utc.xml")); Forecast forecast = report.getForecasts().get(0); assertEquals(forecast.getHourly().size(), 8); Hour hour = forecast.getHourly().get(0); assertEquals(hour.getTime(), new DateTime(2015, 7, 25, 0, 0, 0, DateTimeZone.UTC)); assertEquals(hour.getTempC(), 11); assertEquals(hour.getTempF(), 52); assertEquals(hour.getWindspeedMiles(), 6); assertEquals(hour.getWinddirDegree(), 347); assertEquals(hour.getWeatherCode(), 113); assertEquals(hour.getWeatherIconUrl(), "http://cdn.worldweatheronline.net/images/wsymbols01_png_64/wsymbol_0008_clear_sky_night.png"); assertEquals(hour.getWeatherDesc(), "Clear"); assertEquals(hour.getPrecipMM(), 0.0, 0.001); assertEquals(hour.getHumidity(), 84); assertEquals(hour.getVisibility(), 10); assertEquals(hour.getPressureMb(), 1011); assertEquals(hour.getCloudcover(), 21); assertEquals(hour.getHeatIndexC(), 11); assertEquals(hour.getHeatIndexF(), 52); assertEquals(hour.getDewPointC(), 9); assertEquals(hour.getDewPointF(), 47); assertEquals(hour.getWindChillC(), 10); assertEquals(hour.getWindChillF(), 50); assertEquals(hour.getWindGustMiles(), 11); assertEquals(hour.getWindGustKmph(), 17); assertEquals(hour.getFeelsLikeC(), 10); assertEquals(hour.getFeelsLikeF(), 50); } @Test public void parse_sample_from_fetcher() throws Exception { WeatherReport report = new WeatherParser().parse(getClass().getResourceAsStream("/sample-from-fetcher.xml")); assertEquals(report.getForecasts().size(), 3); for (Forecast f : report.getForecasts()) { assertEquals(f.getHourly().size(), 8); } } @Test public void parse_error() throws Exception { WeatherReport report = new WeatherParser().parse(getClass().getResourceAsStream("/error-bad-location.xml")); assertEquals(report.isSuccess(), false, "Report is not a success"); assertNotNull(report.getError(), "ErrorReport should not be null"); assertEquals(report.getError().getMessage(), "Unable to find any matching weather location to the query submitted!", "Unexpected error message"); } @Test public void readTimeZonePlus1() throws Exception { InputStream in = getInput("<?xml version=\"1.0\"?><time_zone>\n" + " <localtime>2015-07-24 07:26</localtime>\n" + " <utcOffset>1.0</utcOffset>\n" + " </time_zone>"); XMLStreamReader reader = XMLInputFactory.newFactory().createXMLStreamReader(in, "UTF-8"); reader.nextTag(); WeatherParser parser = new WeatherParser(); DateTime result = parser.readTimeZone(reader); DateTime expected = new DateTime(2015, 7, 24, 7, 26, 0, DateTimeZone.forOffsetHours(1)); assertEquals(expected, result); } @Test public void readTimeZoneMinus1() throws Exception { InputStream in = getInput("<?xml version=\"1.0\"?><time_zone>\n" + " <localtime>2015-07-24 07:26</localtime>\n" + " <utcOffset>-1.0</utcOffset>\n" + " </time_zone>"); XMLStreamReader reader = XMLInputFactory.newFactory().createXMLStreamReader(in, "UTF-8"); reader.nextTag(); WeatherParser parser = new WeatherParser(); DateTime result = parser.readTimeZone(reader); DateTime expected = new DateTime(2015, 7, 24, 7, 26, 0, DateTimeZone.forOffsetHours(-1)); assertEquals(expected, result); } @Test public void readTimeZonePlusHalf() throws Exception { InputStream in = getInput("<?xml version=\"1.0\"?><time_zone>\n" + " <localtime>2015-07-24 07:26</localtime>\n" + " <utcOffset>0.5</utcOffset>\n" + " </time_zone>"); XMLStreamReader reader = XMLInputFactory.newFactory().createXMLStreamReader(in, "UTF-8"); reader.nextTag(); WeatherParser parser = new WeatherParser(); DateTime result = parser.readTimeZone(reader); DateTime expected = new DateTime(2015, 7, 24, 7, 26, 0, DateTimeZone.forOffsetHoursMinutes(0, 30)); assertEquals(expected, result); } @Test public void readTimeZoneMinusHalf() throws Exception { InputStream in = getInput("<?xml version=\"1.0\"?><time_zone>\n" + " <localtime>2015-07-24 07:26</localtime>\n" + " <utcOffset>-0.5</utcOffset>\n" + " </time_zone>"); XMLStreamReader reader = XMLInputFactory.newFactory().createXMLStreamReader(in, "UTF-8"); reader.nextTag(); WeatherParser parser = new WeatherParser(); DateTime result = parser.readTimeZone(reader); DateTime expected = new DateTime(2015, 7, 24, 7, 26, 0, DateTimeZone.forOffsetHoursMinutes(0, -30)); assertEquals(expected, result); } private static InputStream getInput(String source) throws UnsupportedEncodingException { return new ByteArrayInputStream(source.getBytes("UTF-8")); } }
package org.broadinstitute.sting.utils; import cern.jet.math.Arithmetic; import cern.jet.random.Normal; import com.google.java.contract.Ensures; import com.google.java.contract.Requires; import org.apache.commons.math.MathException; import org.apache.commons.math.distribution.NormalDistribution; import org.apache.commons.math.distribution.NormalDistributionImpl; import org.broadinstitute.sting.gatk.GenomeAnalysisEngine; import org.broadinstitute.sting.utils.collections.Pair; import org.broadinstitute.sting.utils.exceptions.StingException; import java.util.Comparator; import java.util.TreeSet; public class MannWhitneyU { private static Normal STANDARD_NORMAL = new Normal(0.0,1.0,null); private static NormalDistribution APACHE_NORMAL = new NormalDistributionImpl(0.0,1.0,1e-2); private TreeSet<Pair<Number,USet>> observations; private int sizeSet1; private int sizeSet2; public MannWhitneyU() { observations = new TreeSet<Pair<Number,USet>>(new DitheringComparator()); sizeSet1 = 0; sizeSet2 = 0; } /** * Add an observation into the observation tree * @param n: the observation (a number) * @param set: whether the observation comes from set 1 or set 2 */ public void add(Number n, USet set) { observations.add(new Pair<Number,USet>(n,set)); if ( set == USet.SET1 ) { ++sizeSet1; } else { ++sizeSet2; } } public Pair<Long,Long> getR1R2() { long u1 = calculateOneSidedU(observations,MannWhitneyU.USet.SET1); long n1 = sizeSet1*(sizeSet1+1)/2; long r1 = u1 + n1; long n2 = sizeSet2*(sizeSet2+1)/2; long u2 = n1*n2-u1; long r2 = u2 + n2; return new Pair<Long,Long>(r1,r2); } /** * Runs the one-sided test under the hypothesis that the data in set "lessThanOther" stochastically * dominates the other set * @param lessThanOther - either Set1 or Set2 * @return - u-based z-approximation, and p-value associated with the test (p-value is exact for small n,m) */ @Requires({"validateObservations(observations)", "lessThanOther != null"}) @Ensures({"result != null", "! Double.isInfinite(result.getFirst())", "! Double.isInfinite(result.getSecond())"}) public Pair<Double,Double> runOneSidedTest(USet lessThanOther) { long u = calculateOneSidedU(observations, lessThanOther); int n = lessThanOther == USet.SET1 ? sizeSet1 : sizeSet2; int m = lessThanOther == USet.SET1 ? sizeSet2 : sizeSet1; if ( n == 0 || m == 0 ) { // test is uninformative as one or both sets have no observations return new Pair<Double,Double>(Double.NaN,Double.NaN); } return calculateP(n, m, u, false); } /** * Runs the standard two-sided test, * returns the u-based z-approximate and p values. * @return a pair holding the u and p-value. */ @Ensures({"result != null", "! Double.isInfinite(result.getFirst())", "! Double.isInfinite(result.getSecond())"}) @Requires({"validateObservations(observations)"}) public Pair<Double,Double> runTwoSidedTest() { Pair<Long,USet> uPair = calculateTwoSidedU(observations); long u = uPair.first; int n = uPair.second == USet.SET1 ? sizeSet1 : sizeSet2; int m = uPair.second == USet.SET1 ? sizeSet2 : sizeSet1; if ( n == 0 || m == 0 ) { // test is uninformative as one or both sets have no observations return new Pair<Double,Double>(Double.NaN,Double.NaN); } return calculateP(n, m, u, true); } /** * Given a u statistic, calculate the p-value associated with it, dispatching to approximations where appropriate * @param n - The number of entries in the stochastically smaller (dominant) set * @param m - The number of entries in the stochastically larger (dominated) set * @param u - the Mann-Whitney U value * @param twoSided - is the test twosided * @return the (possibly approximate) p-value associated with the MWU test, and the (possibly approximate) z-value associated with it * todo -- there must be an approximation for small m and large n */ @Requires({"m > 0","n > 0"}) @Ensures({"result != null", "! Double.isInfinite(result.getFirst())", "! Double.isInfinite(result.getSecond())"}) public static Pair<Double,Double> calculateP(int n, int m, long u, boolean twoSided) { Pair<Double,Double> zandP; if ( n > 8 && m > 8 ) { // large m and n - normal approx zandP = calculatePNormalApproximation(n,m,u, twoSided); } else if ( n > 5 && m > 7 ) { // large m, small n - sum uniform approx // todo -- find the appropriate regimes where this approximation is actually better enough to merit slowness // pval = calculatePUniformApproximation(n,m,u); zandP = calculatePNormalApproximation(n, m, u, twoSided); } else if ( n > 8 || m > 8 ) { zandP = calculatePFromTable(n, m, u, twoSided); } else { // small m and n - full approx zandP = calculatePRecursively(n,m,u, twoSided); } return zandP; } public static Pair<Double,Double> calculatePFromTable(int n, int m, long u, boolean twoSided) { // todo -- actually use a table for: // todo - n large, m small return calculatePNormalApproximation(n,m,u, twoSided); } /** * Uses a normal approximation to the U statistic in order to return a cdf p-value. See Mann, Whitney [1947] * @param n - The number of entries in the stochastically smaller (dominant) set * @param m - The number of entries in the stochastically larger (dominated) set * @param u - the Mann-Whitney U value * @param twoSided - whether the test should be two sided * @return p-value associated with the normal approximation */ @Requires({"m > 0","n > 0"}) @Ensures({"result != null", "! Double.isInfinite(result.getFirst())", "! Double.isInfinite(result.getSecond())"}) public static Pair<Double,Double> calculatePNormalApproximation(int n,int m,long u, boolean twoSided) { double z = getZApprox(n,m,u); if ( twoSided ) { return new Pair<Double,Double>(z,2.0*(z < 0 ? STANDARD_NORMAL.cdf(z) : 1.0-STANDARD_NORMAL.cdf(z))); } else { return new Pair<Double,Double>(z,STANDARD_NORMAL.cdf(z)); } } /** * Calculates the Z-score approximation of the u-statistic * @param n - The number of entries in the stochastically smaller (dominant) set * @param m - The number of entries in the stochastically larger (dominated) set * @param u - the Mann-Whitney U value * @return the asymptotic z-approximation corresponding to the MWU p-value for n < m */ @Requires({"m > 0","n > 0"}) @Ensures({"result != null", "! Double.isInfinite(result)"}) private static double getZApprox(int n, int m, long u) { double mean = ( ((long)m)*n+1.0)/2; double var = (((long) n)*m*(n+m+1.0))/12; double z = ( u - mean )/Math.sqrt(var); return z; } /** * Uses a sum-of-uniform-0-1 random variable approximation to the U statistic in order to return an approximate * p-value. See Buckle, Kraft, van Eeden [1969] (approx) and Billingsly [1995] or Stephens, MA [1966, biometrika] (sum of uniform CDF) * @param n - The number of entries in the stochastically smaller (dominant) set * @param m - The number of entries in the stochastically larger (dominated) set * @param u - mann-whitney u value * @return p-value according to sum of uniform approx * todo -- this is currently not called due to not having a good characterization of where it is significantly more accurate than the * todo -- normal approxmation (e.g. enough to merit the runtime hit) */ public static double calculatePUniformApproximation(int n, int m, long u) { long R = u + (n*(n+1))/2; double a = Math.sqrt(m*(n+m+1)); double b = (n/2.0)*(1-Math.sqrt((n+m+1)/m)); double z = b + ((double)R)/a; if ( z < 0 ) { return 1.0; } else if ( z > n ) { return 0.0; } else { if ( z > ((double) n) /2 ) { return 1.0-1/((double)Arithmetic.factorial(n))*uniformSumHelper(z, (int) Math.floor(z), n, 0); } else { return 1/((double)Arithmetic.factorial(n))*uniformSumHelper(z, (int) Math.floor(z), n, 0); } } } /** * Helper function for the sum of n uniform random variables * @param z - value at which to compute the (un-normalized) cdf * @param m - a cutoff integer (defined by m <= z < m + 1) * @param n - the number of uniform random variables * @param k - holder variable for the recursion (alternatively, the index of the term in the sequence) * @return the (un-normalized) cdf for the sum of n random variables */ private static double uniformSumHelper(double z, int m, int n, int k) { if ( k > m ) { return 0; } int coef = (k % 2 == 0) ? 1 : -1; return coef*Arithmetic.binomial(n,k)*Math.pow(z-k,n) + uniformSumHelper(z,m,n,k+1); } /** * Calculates the U-statistic associated with a two-sided test (e.g. the RV from which one set is drawn * stochastically dominates the RV from which the other set is drawn); two-sidedness is accounted for * later on simply by multiplying the p-value by 2. * * Recall: If X stochastically dominates Y, the test is for occurrences of Y before X, so the lower value of u is chosen * @param observed - the observed data * @return the minimum of the U counts (set1 dominates 2, set 2 dominates 1) */ @Requires({"observed != null", "observed.size() > 0", "validateObservations(observed)"}) @Ensures({"result != null","result.first > 0"}) public static Pair<Long,USet> calculateTwoSidedU(TreeSet<Pair<Number,USet>> observed) { int set1SeenSoFar = 0; int set2SeenSoFar = 0; long uSet1DomSet2 = 0; long uSet2DomSet1 = 0; USet previous = null; for ( Pair<Number,USet> dataPoint : observed ) { if ( dataPoint.second == USet.SET1 ) { ++set1SeenSoFar; } else { ++set2SeenSoFar; } if ( previous != null ) { if ( dataPoint.second == USet.SET1 ) { uSet2DomSet1 += set2SeenSoFar; } else { uSet1DomSet2 += set1SeenSoFar; } } previous = dataPoint.second; } return uSet1DomSet2 < uSet2DomSet1 ? new Pair<Long,USet>(uSet1DomSet2,USet.SET1) : new Pair<Long,USet>(uSet2DomSet1,USet.SET2); } /** * Calculates the U-statistic associated with the one-sided hypothesis that "dominator" stochastically dominates * the other U-set. Note that if S1 dominates S2, we want to count the occurrences of points in S2 coming before points in S1. * @param observed - the observed data points, tagged by each set * @param dominator - the set that is hypothesized to be stochastically dominating * @return the u-statistic associated with the hypothesis */ @Requires({"observed != null","dominator != null","observed.size() > 0","validateObservations(observed)"}) @Ensures({"return > 0"}) public static long calculateOneSidedU(TreeSet<Pair<Number,USet>> observed,USet dominator) { long otherBeforeDominator = 0l; int otherSeenSoFar = 0; for ( Pair<Number,USet> dataPoint : observed ) { if ( dataPoint.second != dominator ) { ++otherSeenSoFar; } else { otherBeforeDominator += otherSeenSoFar; } } return otherBeforeDominator; } /** * The Mann-Whitney U statistic follows a recursive equation (that enumerates the proportion of possible * binary strings of "n" zeros, and "m" ones, where a one precedes a zero "u" times). This accessor * calls into that recursive calculation. * @param n: number of set-one entries (hypothesis: set one is stochastically less than set two) * @param m: number of set-two entries * @param u: number of set-two entries that precede set-one entries (e.g. 0,1,0,1,0 -> 3 ) * @param twoSided: whether the test is two sided or not. The recursive formula is symmetric, multiply by two for two-sidedness. * @return the probability under the hypothesis that all sequences are equally likely of finding a set-two entry preceding a set-one entry "u" times. */ @Requires({"m > 0","n > 0","u > 0"}) @Ensures({"result != null","! Double.isInfinite(result.getFirst())", "! Double.isInfinite(result.getSecond())"}) public static Pair<Double,Double> calculatePRecursively(int n, int m, long u, boolean twoSided) { if ( m > 8 && n > 5 ) { throw new StingException(String.format("Please use the appropriate (normal or sum of uniform) approximation. Values n: %d, m: %d",n,m)); } double p = cpr(n,m,u); double z; try { z = APACHE_NORMAL.inverseCumulativeProbability(p); } catch (MathException me) { throw new StingException("A math exception occurred in inverting the probability",me); } return new Pair<Double,Double>(z,(twoSided ? 2.0*p : p)); } /** * Hook into CPR with sufficient warning (for testing purposes) * calls into that recursive calculation. * @param n: number of set-one entries (hypothesis: set one is stochastically less than set two) * @param m: number of set-two entries * @param u: number of set-two entries that precede set-one entries (e.g. 0,1,0,1,0 -> 3 ) * @return same as cpr * @deprecated - for testing only (really) */ @Deprecated public static double calculatePRecursivelyDoNotCheckValuesEvenThoughItIsSlow(int n, int m, long u) { return cpr(n,m,u); } /** * : just a shorter name for calculatePRecursively. See Mann, Whitney, [1947] * @param n: number of set-1 entries * @param m: number of set-2 entries * @param u: number of times a set-2 entry as preceded a set-1 entry * @return recursive p-value */ private static double cpr(int n, int m, long u) { if ( u < 0 || n == 0 && m == 0 ) { return 0.0; } if ( m == 0 || n == 0 ) { // there are entries in set 1 or set 2, so no set-2 entry can precede a set-1 entry; thus u must be zero. // note that this exists only for edification, as when we reach this point, the coefficient on this term is zero anyway return ( u == 0 ) ? 1.0 : 0.0; } return (((double)n)/(n+m))*cpr(n-1,m,u-m) + (((double)m)/(n+m))*cpr(n,m-1,u); } /** * hook into the data tree, for testing purposes only * @return observations * @deprecated - only for testing */ @Deprecated public TreeSet<Pair<Number,USet>> getObservations() { return observations; } /** * hook into the set sizes, for testing purposes only * @return size set 1, size set 2 * @deprecated - only for testing */ public Pair<Integer,Integer> getSetSizes() { return new Pair<Integer,Integer>(sizeSet1,sizeSet2); } protected static boolean validateObservations(TreeSet<Pair<Number,USet>> tree) { boolean seen1 = false; boolean seen2 = false; boolean seenInvalid = false; for ( Pair<Number,USet> p : tree) { if ( ! seen1 && p.getSecond() == USet.SET1 ) { seen1 = true; } if ( ! seen2 && p.getSecond() == USet.SET2 ) { seen2 = true; } if ( Double.isNaN(p.getFirst().doubleValue()) || Double.isInfinite(p.getFirst().doubleValue())) { seenInvalid = true; } } return ! seenInvalid && seen1 && seen2; } /** * A comparator class which uses dithering on tie-breaking to ensure that the internal treeset drops no values * and to ensure that rank ties are broken at random. */ private class DitheringComparator implements Comparator<Pair<Number,USet>> { public DitheringComparator() {} public boolean equals(Object other) { return false; } public int compare(Pair<Number,USet> left, Pair<Number,USet> right) { double comp = Double.compare(left.first.doubleValue(),right.first.doubleValue()); if ( comp > 0 ) { return 1; } if ( comp < 0 ) { return -1; } return GenomeAnalysisEngine.getRandomGenerator().nextBoolean() ? -1 : 1; } } public enum USet { SET1, SET2 } }
package com.ociweb.pronghorn.exampleStages; import java.util.concurrent.TimeUnit; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; import com.ociweb.pronghorn.pipe.FieldReferenceOffsetManager; import com.ociweb.pronghorn.pipe.Pipe; import com.ociweb.pronghorn.pipe.PipeConfig; import com.ociweb.pronghorn.pipe.schema.loader.TemplateHandler; import com.ociweb.pronghorn.stage.PronghornStage; import com.ociweb.pronghorn.stage.monitor.MonitorConsoleStage; import com.ociweb.pronghorn.stage.monitor.PipeMonitorSchema; import com.ociweb.pronghorn.stage.route.RoundRobinRouteStage; import com.ociweb.pronghorn.stage.scheduling.GraphManager; import com.ociweb.pronghorn.stage.scheduling.StageScheduler; import com.ociweb.pronghorn.stage.scheduling.ThreadPerStageScheduler; public class PipelineTest { static final long TIMEOUT_SECONDS = 1; static final long TEST_LENGTH_IN_SECONDS = 2; private static FieldReferenceOffsetManager from; public static final int messagesOnRing = 1<<16; public static final int monitorMessagesOnRing = 7; private static final int maxLengthVarField = 40; private final Long monitorRate = Long.valueOf(50000000); private static PipeConfig ringBufferConfig; private static PipeConfig ringBufferMonitorConfig; @BeforeClass public static void loadSchema() { //When doing development and testing be sure that assertions are on by adding -ea to the JVM arguments //This will enable a lot of helpful to catch configuration and setup errors earlier try { from = TemplateHandler.loadFrom("/exampleTemplate.xml"); ringBufferConfig = new PipeConfig(from, messagesOnRing, maxLengthVarField); ringBufferMonitorConfig = new PipeConfig(PipeMonitorSchema.buildFROM(), monitorMessagesOnRing, maxLengthVarField); } catch (Exception e) { throw new RuntimeException(e); } System.gc(); } @Test public void lowLevelInputStageTest() { final byte[] expected = new String("tcp://localhost:1883thingFortytworoot/colors/blue ").getBytes(); int j = 8; while (--j>=0) { expected[expected.length-(8-j)] = (byte)j; } //build the expected data that should be found on the byte ring. final int[] expectedInts = new int[]{0, 0, 20, 20, 13, 42, 33, 16, 49, 8, 0, 57}; final int expectedMsg = 0; CheckStageArguments checkArgs = new CheckStageArguments() { @Override public int expectedMessageIdx() { return expectedMsg; } @Override public byte[] expectedBytes() { return expected; } @Override public int[] expectedInts() { return expectedInts; } }; GraphManager gm = new GraphManager(); PronghornStage stage = buildSplitterTree(checkArgs, gm, ringBufferConfig, true); InputStageLowLevelExample producer = new InputStageLowLevelExample(gm, GraphManager.getInputPipe(gm, stage)); //If we can ask for stages by some id then we can look them up at the end as needed. addMonitorAndTest(gm, " low level "); } private void addMonitorAndTest(GraphManager gm, String label) { //Add monitoring MonitorConsoleStage.attach(gm, monitorRate, ringBufferMonitorConfig); //Enable batching GraphManager.enableBatching(gm); Pipe ringForByteCount = GraphManager.getInputPipe(gm, GraphManager.findStageByPath(gm, 1, 1), 1); CheckVarLengthValuesStage[] outputStages = collectAllTheOutputStages(gm); timeAndRunTestByArray(ringForByteCount, gm, label, TEST_LENGTH_IN_SECONDS, outputStages); } public CheckVarLengthValuesStage[] collectAllTheOutputStages(GraphManager gm) { int outputStagesCount = GraphManager.getOutputStageCount(gm); CheckVarLengthValuesStage outputStages[] = new CheckVarLengthValuesStage[outputStagesCount]; int i = outputStagesCount; while (--i>=0) { outputStages[i] = (CheckVarLengthValuesStage)GraphManager.getOutputStage(gm, 1+i); } return outputStages; } private static PronghornStage buildSplitterTree(CheckStageArguments checkArgs, GraphManager gm, PipeConfig config, boolean deepTest) { // CheckVarLengthValuesStage dumpStage11 = new CheckVarLengthValuesStage(gm, new RingBuffer(config), checkArgs, deepTest); // CheckVarLengthValuesStage dumpStage12 = new CheckVarLengthValuesStage(gm, new RingBuffer(config), checkArgs, deepTest); // CheckVarLengthValuesStage dumpStage21 = new CheckVarLengthValuesStage(gm, new RingBuffer(config), checkArgs, deepTest); // CheckVarLengthValuesStage dumpStage22 = new CheckVarLengthValuesStage(gm, new RingBuffer(config), checkArgs, deepTest); // RoundRobinRouteStage stage = new RoundRobinRouteStage(gm, // new RingBuffer(config.grow2x().grow2x()), // GraphManager.getInputPipe(gm, dumpStage11), // GraphManager.getInputPipe(gm, dumpStage12), // GraphManager.getInputPipe(gm, dumpStage21), // GraphManager.getInputPipe(gm, dumpStage22) CheckVarLengthValuesStage stage = new CheckVarLengthValuesStage(gm, new Pipe(config), checkArgs, deepTest); return stage; } @Test public void lowLevelInputStageSimple40Test() { PipeConfig config = new PipeConfig(FieldReferenceOffsetManager.RAW_BYTES, messagesOnRing, InputStageLowLevel40ByteBaselineExample.payload.length); Pipe ringBuffer1 = new Pipe(config); final byte[] expectedBytes = InputStageLowLevel40ByteBaselineExample.payload; CheckStageArguments checkArgs = new CheckStageArguments() { @Override public int expectedMessageIdx() { return 0; } @Override public byte[] expectedBytes() { return expectedBytes; } @Override public int[] expectedInts() { return new int[]{0,0,InputStageLowLevel40ByteBaselineExample.payload.length}; } }; GraphManager gm = new GraphManager(); InputStageLowLevel40ByteBaselineExample iso = new InputStageLowLevel40ByteBaselineExample(gm, ringBuffer1); CheckVarLengthValuesStage dumpStage22 = new CheckVarLengthValuesStage(gm, ringBuffer1, checkArgs, false); //NO DEEP CHECK GraphManager.enableBatching(gm); timeAndRunTest(ringBuffer1, gm, " Simple40LowLevel", TEST_LENGTH_IN_SECONDS, dumpStage22); } @Test public void lowLevel40InputStageTest() { PipeConfig config = new PipeConfig(FieldReferenceOffsetManager.RAW_BYTES, messagesOnRing, InputStageLowLevel40ByteBaselineExample.payload.length); final byte[] expectedBytes = InputStageLowLevel40ByteBaselineExample.payload; CheckStageArguments checkArgs = new CheckStageArguments() { @Override public int expectedMessageIdx() { return 0; } @Override public byte[] expectedBytes() { return expectedBytes; } @Override public int[] expectedInts() { return new int[]{0,0,InputStageLowLevel40ByteBaselineExample.payload.length}; } }; GraphManager gm = new GraphManager(); PronghornStage stage = buildSplitterTree(checkArgs, gm, config, false); InputStageLowLevel40ByteBaselineExample producer = new InputStageLowLevel40ByteBaselineExample(gm, GraphManager.getInputPipe(gm, stage, 1)); addMonitorAndTest(gm, " low level 40 "); } @Test public void highLevelInputStageTest() { //NOTE: because everything is relative offset from the start of the message all the field position values will remain constant. CheckStageArguments checkArgs = argumentChecker((InputStageHighLevelExample.testSymbol+InputStageHighLevelExample.testCompanyName).getBytes(), new int[] {8, 0, 3, 3, 31, 0, 0, 2, 0, 10250, 2, 0, 10250, 2, 0, 10250, 2, 0, 10250, 0, 10000000, 34}); //The 0 0 is 34 0 when using the visitor because of the order of the fields written GraphManager gm = new GraphManager(); PronghornStage stage = buildSplitterTree(checkArgs, gm, ringBufferConfig, true); InputStageHighLevelExample producer = new InputStageHighLevelExample(gm, GraphManager.getInputPipe(gm, stage, 1)); addMonitorAndTest(gm, " high level "); } @Test public void streamingVisitorInputStageTest() { // build the expected data that should be found on the byte ring. CheckStageArguments checkArgs = argumentChecker((InputStageHighLevelExample.testSymbol+InputStageHighLevelExample.testCompanyName).getBytes(), new int[] {8, 0, 3, 3, 31, 34, 0, 2, 0, 10250, 2, 0, 10250, 2, 0, 10250, 2, 0, 10250, 0, 10000000, 34}); GraphManager gm = new GraphManager(); PronghornStage stage = buildSplitterTree(checkArgs, gm, ringBufferConfig, true); PronghornStage producer = new InputStageStreamingVisitorExample(gm, GraphManager.getInputPipe(gm, stage, 1)); addMonitorAndTest(gm, " streaming visitor "); } private CheckStageArguments argumentChecker(final byte[] expected, final int[] expectedInts) { final int expectedMsg = from.messageStarts[1]; CheckStageArguments checkArgs = new CheckStageArguments() { @Override public int expectedMessageIdx() { return expectedMsg; } @Override public byte[] expectedBytes() { return expected; } @Override public int[] expectedInts() { return expectedInts; } }; return checkArgs; } @Test public void eventConsumerInputStageTest() { CheckStageArguments checkArgs = argumentChecker((InputStageEventConsumerExample.testSymbol+InputStageEventConsumerExample.testCompanyName).getBytes(), new int[] {8, 0, 3, 3, 31, 0, 0, 2, 0, 2343, 2, 0, 8000, 2, 0, 2000, 2, 0, 7230, 0, 10000000, 34} ); int expectedBytes = InputStageEventConsumerExample.testSymbol.length() + InputStageEventConsumerExample.testCompanyName.length(); GraphManager gm = new GraphManager(); PronghornStage stage = buildSplitterTree(checkArgs, gm, ringBufferConfig, true); InputStageEventConsumerExample producer = new InputStageEventConsumerExample(gm, GraphManager.getInputPipe(gm, stage, 1)); addMonitorAndTest(gm, " event consumer "); } private long timeAndRunTest(Pipe ringBuffer, GraphManager gm, String label, long testInSeconds, CheckVarLengthValuesStage ... countStages) { return timeAndRunTestByArray(ringBuffer,gm, label, testInSeconds, countStages); } private long timeAndRunTestByArray(Pipe ringBuffer, GraphManager gm, String label, long testInSeconds, CheckVarLengthValuesStage[] countStages) { StageScheduler scheduler = new ThreadPerStageScheduler(GraphManager.cloneAll(gm)); long startTime = System.currentTimeMillis(); scheduler.startup(); try { Thread.sleep(testInSeconds*1000); } catch (InterruptedException e) { } //NOTE: if the tested input stage is the sort of stage that calls shutdown on its own then // you do not need the above sleep // you do not need the below shutdown scheduler.shutdown(); boolean cleanExit = scheduler.awaitTermination(TIMEOUT_SECONDS, TimeUnit.SECONDS); long duration = System.currentTimeMillis()-startTime; int j = countStages.length; long messages=0; long bytes=0; while (--j>=0) { messages+=countStages[j].messageCount(); bytes+=countStages[j].totalBytes(); } if ((duration>0) && (messages>0)) { long bytesMoved = (4l*Pipe.headPosition(ringBuffer))+bytes; float mbMoved = (8f*bytesMoved)/(float)(1<<20); int bytesPerMessage = (int)(bytesMoved/messages); float fmsg = messages; float fdur = duration; System.out.println("TotalMessages:"+messages + " Msg/Ms:"+(fmsg/fdur) + " Mb/Ms:"+(mbMoved/fdur) + label +" B/Msg:"+bytesPerMessage +" cleanExit:"+cleanExit ); } else { System.out.println(label+" warning duration:"+duration+" messages:"+messages); } assertTrue("RingBuffer: "+ringBuffer, cleanExit); return messages; } interface CheckStageArguments { public int expectedMessageIdx(); public byte[] expectedBytes(); public int[] expectedInts(); } }
package de.mvitz.jprops.core.api; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.failBecauseExceptionWasNotThrown; import static org.mockito.BDDMockito.given; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class PropertiesInjectorTest { @Mock private PropertyProvider provider; @InjectMocks private PropertiesInjector injector; private UnknownType unknownType; @Test public void shouldThrowExceptionForUnknownType() throws Exception { given(provider.get("unknownType")).willReturn("foo"); try { injector.injectInto(this); failBecauseExceptionWasNotThrown(InvalidPropertiesException.class); } catch (final InvalidPropertiesException e) { assertThat(e).hasNoCause().hasMessage("No converter found for type: UnknownType"); assertThat(unknownType).isNull(); } } public interface UnknownType { } }
/* * generated by Xtext */ package javamm.serializer; import java.util.List; import org.eclipse.xtext.serializer.ISerializationContext; import org.eclipse.xtext.serializer.acceptor.SequenceFeeder; import org.eclipse.xtext.serializer.sequencer.ISemanticNodeProvider.INodesForEObjectProvider; import org.eclipse.xtext.xbase.XExpression; import com.google.inject.Inject; import javamm.javamm.JavammXMemberFeatureCall; import javamm.services.JavammGrammarAccess; import javamm.services.JavammGrammarAccess.XMemberFeatureCallElements; /** * Customized to deal with custom AST structure for member feature call with array access. * * @author Lorenzo Bettini * */ public class JavammSemanticSequencer extends AbstractJavammSemanticSequencer { @Inject private JavammGrammarAccess grammarAccess; @Override protected void sequence_XMemberFeatureCall(ISerializationContext context, JavammXMemberFeatureCall featureCall) { INodesForEObjectProvider nodes = createNodeProvider(featureCall); SequenceFeeder acceptor = createSequencerFeeder(context, featureCall, nodes); XMemberFeatureCallElements memberFeatureCallElements= grammarAccess.getXMemberFeatureCallAccess(); // we manually modify the structure of this element, so we must serialize that accordingly acceptor.accept(memberFeatureCallElements.getJavammXMemberFeatureCallMemberCallTargetAction_1_1_0_0_0(), featureCall.getArrayAccessExpression().getArray()); final List<XExpression> indexes = featureCall.getIndexes(); acceptor.accept(memberFeatureCallElements.getIndexesXExpressionParserRuleCall_1_1_0_0_2_0(), indexes.get(0), 0); for (int i = 1; i < indexes.size(); i++) { acceptor.accept(memberFeatureCallElements.getIndexesXExpressionParserRuleCall_1_1_0_0_4_1_0(), indexes.get(i), i); } acceptor.accept(memberFeatureCallElements.getFeatureJvmIdentifiableElementIdOrSuperParserRuleCall_1_1_1_0_1(), featureCall.getFeature()); if (featureCall.isExplicitOperationCall()) { acceptor.accept(memberFeatureCallElements.getExplicitOperationCallLeftParenthesisKeyword_1_1_2_0_0()); } List<XExpression> arguments = featureCall.getMemberCallArguments(); if (!arguments.isEmpty()) { acceptor.accept(memberFeatureCallElements.getMemberCallArgumentsXExpressionParserRuleCall_1_1_2_1_0_0(), arguments.get(0), 0); for (int i = 1; i < arguments.size(); i++) { acceptor.accept(memberFeatureCallElements.getMemberCallArgumentsXExpressionParserRuleCall_1_1_2_1_1_1_0(), arguments.get(i), i); } } acceptor.finish(); } }
package org.jeasy.batch.extensions.univocity; import com.univocity.parsers.common.AbstractParser; import com.univocity.parsers.common.CommonParserSettings; import com.univocity.parsers.common.processor.BeanListProcessor; import org.jeasy.batch.core.mapper.RecordMapper; import org.jeasy.batch.core.record.GenericRecord; import org.jeasy.batch.core.record.Record; import java.io.StringReader; abstract class AbstractUnivocityRecordMapper<T, S extends CommonParserSettings<?>> implements RecordMapper<String, T> { S settings; private AbstractParser<S> parser; private BeanListProcessor<T> beanListProcessor; AbstractUnivocityRecordMapper(Class<T> recordClass, S settings) { this.settings = settings; this.beanListProcessor = new BeanListProcessor<>(recordClass); this.settings.setProcessor(this.beanListProcessor); this.parser = getParser(); } @Override public Record<T> processRecord(Record<String> record) { String payload = record.getPayload(); parser.parse(new StringReader(payload)); T result = beanListProcessor.getBeans().get(0); return new GenericRecord<>(record.getHeader(), result); } protected abstract AbstractParser<S> getParser(); }
package edu.harvard.iq.dataverse.api; import com.jayway.restassured.RestAssured; import com.jayway.restassured.path.json.JsonPath; import com.jayway.restassured.response.Response; import edu.harvard.iq.dataverse.authorization.DataverseRole; import java.util.logging.Logger; import javax.json.Json; import javax.json.JsonObjectBuilder; import static javax.ws.rs.core.Response.Status.CREATED; import static javax.ws.rs.core.Response.Status.OK; import static javax.ws.rs.core.Response.Status.UNAUTHORIZED; import static org.hamcrest.CoreMatchers.equalTo; import org.junit.BeforeClass; import org.junit.Test; public class InReviewWorkflowIT { private static final Logger logger = Logger.getLogger(DatasetsIT.class.getCanonicalName()); @BeforeClass public static void setUpClass() { RestAssured.baseURI = UtilIT.getRestAssuredBaseUri(); } @Test public void testCuratorSendsCommentsToAuthor() { Response createCurator = UtilIT.createRandomUser(); createCurator.prettyPrint(); createCurator.then().assertThat() .statusCode(OK.getStatusCode()); String curatorUsername = UtilIT.getUsernameFromResponse(createCurator); String curatorApiToken = UtilIT.getApiTokenFromResponse(createCurator); Response createDataverseResponse = UtilIT.createRandomDataverse(curatorApiToken); createDataverseResponse.prettyPrint(); createDataverseResponse.then().assertThat() .statusCode(CREATED.getStatusCode()); String dataverseAlias = UtilIT.getAliasFromResponse(createDataverseResponse); Response createAuthor = UtilIT.createRandomUser(); createAuthor.prettyPrint(); createAuthor.then().assertThat() .statusCode(OK.getStatusCode()); String authorUsername = UtilIT.getUsernameFromResponse(createAuthor); String authorApiToken = UtilIT.getApiTokenFromResponse(createAuthor); Response noPermToCreateDataset = UtilIT.createRandomDatasetViaNativeApi(dataverseAlias, authorApiToken); noPermToCreateDataset.prettyPrint(); noPermToCreateDataset.then().assertThat() .body("message", equalTo("User @" + authorUsername + " is not permitted to perform requested action.")) .statusCode(UNAUTHORIZED.getStatusCode()); Response grantAuthorAddDataset = UtilIT.grantRoleOnDataverse(dataverseAlias, DataverseRole.DS_CONTRIBUTOR.toString(), "@" + authorUsername, curatorApiToken); grantAuthorAddDataset.prettyPrint(); grantAuthorAddDataset.then().assertThat() .body("data.assignee", equalTo("@" + authorUsername)) .body("data._roleAlias", equalTo("dsContributor")) .statusCode(OK.getStatusCode()); Response createDataset = UtilIT.createRandomDatasetViaNativeApi(dataverseAlias, authorApiToken); createDataset.prettyPrint(); createDataset.then().assertThat() .statusCode(CREATED.getStatusCode()); Integer datasetId = UtilIT.getDatasetIdFromResponse(createDataset); // FIXME: have the initial create return the DOI or Handle to obviate the need for this call. Response getDatasetJsonBeforePublishing = UtilIT.nativeGet(datasetId, authorApiToken); getDatasetJsonBeforePublishing.prettyPrint(); String protocol = JsonPath.from(getDatasetJsonBeforePublishing.getBody().asString()).getString("data.protocol"); String authority = JsonPath.from(getDatasetJsonBeforePublishing.getBody().asString()).getString("data.authority"); String identifier = JsonPath.from(getDatasetJsonBeforePublishing.getBody().asString()).getString("data.identifier"); String datasetPersistentId = protocol + ":" + authority + "/" + identifier; System.out.println("datasetPersistentId: " + datasetPersistentId); // Whoops, the author tries to publish but isn't allowed. The curator will take a look. Response noPermToPublish = UtilIT.publishDatasetViaNativeApi(datasetPersistentId, "major", authorApiToken); noPermToPublish.prettyPrint(); noPermToPublish.then().assertThat() .body("message", equalTo("User @" + authorUsername + " is not permitted to perform requested action.")) .statusCode(UNAUTHORIZED.getStatusCode()); Response submitForReview = UtilIT.submitDatasetForReview(datasetPersistentId, authorApiToken); submitForReview.prettyPrint(); submitForReview.then().assertThat() .body("data.inReview", equalTo(true)) .statusCode(OK.getStatusCode()); Response authorsChecksForCommentsPrematurely = UtilIT.getNotifications(authorApiToken); authorsChecksForCommentsPrematurely.prettyPrint(); authorsChecksForCommentsPrematurely.then().assertThat() .body("data.notifications[0].type", equalTo("CREATEACC")) // The author thinks, "What's taking the curator so long to review my data?!?" .body("data.notifications[1]", equalTo(null)) .statusCode(OK.getStatusCode()); String comments = "You forgot to upload any files."; JsonObjectBuilder jsonObjectBuilder = Json.createObjectBuilder(); jsonObjectBuilder.add("comments", comments); Response returnToAuthor = UtilIT.returnDatasetToAuthor(datasetPersistentId, jsonObjectBuilder.build(), curatorApiToken); returnToAuthor.prettyPrint(); returnToAuthor.then().assertThat() .body("data.inReview", equalTo(false)) .statusCode(OK.getStatusCode()); Response authorsChecksForCommentsAgain = UtilIT.getNotifications(authorApiToken); authorsChecksForCommentsAgain.prettyPrint(); authorsChecksForCommentsAgain.then().assertThat() .body("data.notifications[0].type", equalTo("RETURNEDDS")) // The author thinks, "This why we have curators!" .body("data.notifications[0].comments", equalTo("You forgot to upload any files.")) .body("data.notifications[1].type", equalTo("CREATEACC")) .body("data.notifications[1].comments", equalTo(null)) .statusCode(OK.getStatusCode()); // The author upload the file she forgot. String pathToFile = "src/main/webapp/resources/images/dataverseproject.png"; Response authorAddsFile = UtilIT.uploadFileViaNative(datasetId.toString(), pathToFile, authorApiToken); authorAddsFile.prettyPrint(); authorAddsFile.then().assertThat() .body("status", equalTo("OK")) .body("data.files[0].label", equalTo("dataverseproject.png")) .statusCode(OK.getStatusCode()); // The author re-submits. Response resubmitForReview = UtilIT.submitDatasetForReview(datasetPersistentId, authorApiToken); resubmitForReview.prettyPrint(); resubmitForReview.then().assertThat() .body("data.inReview", equalTo(true)) .statusCode(OK.getStatusCode()); // The author checks to see if the author has resubmitted yet. Response curatorChecksNotifications = UtilIT.getNotifications(curatorApiToken); curatorChecksNotifications.prettyPrint(); curatorChecksNotifications.then().assertThat() .body("data.notifications[0].type", equalTo("SUBMITTEDDS")) .body("data.notifications[0].comments", equalTo(null)) .body("data.notifications[1].type", equalTo("SUBMITTEDDS")) .body("data.notifications[1].comments", equalTo(null)) .body("data.notifications[2].type", equalTo("CREATEACC")) .body("data.notifications[2].comments", equalTo(null)) .statusCode(OK.getStatusCode()); // The curator publishes the dataverse. Response publishDataverse = UtilIT.publishDataverseViaNativeApi(dataverseAlias, curatorApiToken); publishDataverse.prettyPrint(); publishDataverse.then().assertThat() .statusCode(OK.getStatusCode()); // The curator publishes the dataset. Response publishDataset = UtilIT.publishDatasetViaNativeApi(datasetPersistentId, "major", curatorApiToken); publishDataset.prettyPrint(); publishDataset.then().assertThat() .statusCode(OK.getStatusCode()); // These println's are here in case you want to log into the GUI to see what notifications look like. System.out.println("Curator username/password: " + curatorUsername); System.out.println("Author username/password: " + authorUsername); } }
package com.jenjinstudios.io; import java.util.TreeMap; /** * The Message class is used for fast-and-loose serialization for efficient transport of data over socket. * * @author Caleb Brinkman */ public class Message { /** The name of this message. */ public final String name; /** The message type of this message. */ private final MessageType messageType; /** The arguments for this message by name. */ private final TreeMap<String, Object> argumentsByName; /** The ID of this message. */ private final short id; /** * Construct a new Message with the given ID and arguments. This is intended <b>only</b> for use in MessageInputStream. * You should <b>not</b> use this constructor in your code. If, for some reason, you decide to (and you really, really * shouldn't) the arguments you pass <b>must</b> fill every available argument and be passed in the order in which they * appear in the XML file. * * @param id The ID of the message type for this message. * @param args The arguments of this message. This <b>must</b> fill every available argument for the message. */ public Message(short id, Object... args) { this.id = id; messageType = MessageRegistry.getMessageType(id); name = messageType.name; argumentsByName = new TreeMap<>(); for (int i = 0; i < messageType.argumentTypes.length; i++) setArgument(messageType.argumentTypes[i].name, args[i]); if (isInvalid()) throw new IllegalStateException("Attempting to retrieve arguments while message is invalid. (Not all " + "arguments have been set.)"); } /** * Construct a new Message using the MessageType specified by the given name; every argument in this message must be * set using the {@code setArgument} method before it can be sent properly over socket. * * @param name The name of the MessageType being filled by this message. */ public Message(String name) { messageType = MessageRegistry.getMessageType(name); this.name = messageType.name; id = messageType.id; argumentsByName = new TreeMap<>(); } public void setArgument(String argumentName, Object argument) { ArgumentType argType = messageType.getArgumentType(argumentName); if (argType == null) throw new IllegalArgumentException("Invalid argument name for Message: " + argumentName + " (Message type: " + messageType.name + ")"); if (!argType.type.isInstance(argument)) throw new IllegalArgumentException("Invalid argument type for Message: " + argument + " (Expected " + argType.type + ", got " + argument.getClass() + ")"); argumentsByName.put(argumentName, argument); } /** * Get the argument with the given name. * * @param argumentName The name of the argument. * @return The argument with the specified name. */ public Object getArgument(String argumentName) { return argumentsByName.get(argumentName); } /** * Determine whether this message is valid, which is to say that all arguments have been correctly set. * * @return true if all arguments have been set, and correctly. */ public boolean isInvalid() { return argumentsByName.size() != messageType.argumentTypes.length; } public short getID() { return id; } /** * Get the arguments of this message, in the order in which they should be sent over socket, assuming this message has * been validly filled. * * @return An array of objects specifying the arguments of the message, in the order in which they should be sent over * socket. */ public final Object[] getArgs() { if (isInvalid()) throw new IllegalStateException("Attempting to retrieve arguments while message is invalid. (Not all " + "arguments have been set.)"); Object[] argsArray = new Object[messageType.argumentTypes.length]; for (int i = 0; i < messageType.argumentTypes.length; i++) { argsArray[i] = argumentsByName.get(messageType.argumentTypes[i].name); } return argsArray; } @Override public String toString() { return "Message" + id; } }
package info.freelibrary.solr; import static org.junit.Assert.fail; import static org.junit.Assert.assertEquals; import nu.xom.Nodes; import nu.xom.Document; import nu.xom.Builder; import org.junit.Test; public class ISO639SolrIntegrationTest { private static final String URL = "http://localhost:8983/solr/select/?q=*:*&facet=true&facet.field=iso639"; private static final String FACET_PATH = "//str[@name='facet.field']"; /** * Tests that the schema registers a iso639 field and that the needed jar * file has been successfully loaded into Solr. */ @Test public void test() { try { Document doc = new Builder().build(URL); Nodes nodes = doc.query(FACET_PATH); if (nodes.size() != 1) { fail("Didn't find the facet.field facet in the response XML"); } assertEquals("iso639", nodes.get(0).getValue().trim()); } catch (Exception details) { fail(details.getMessage()); } } }
package info.u_team.u_team_test.screen; import org.apache.logging.log4j.*; import com.mojang.blaze3d.matrix.MatrixStack; import info.u_team.u_team_core.gui.elements.*; import info.u_team.u_team_core.gui.renderer.*; import info.u_team.u_team_core.util.RGBA; import info.u_team.u_team_test.TestMod; import net.minecraft.client.gui.screen.Screen; import net.minecraft.util.ResourceLocation; import net.minecraft.util.text.*; public class ButtonTestScreen extends Screen { private static final Logger LOGGER = LogManager.getLogger(); private static final ResourceLocation TEXTURE1 = new ResourceLocation(TestMod.MODID, "textures/item/better_enderpearl.png"); private static final ResourceLocation TEXTURE2 = new ResourceLocation(TestMod.MODID, "textures/item/basicitem.png"); public ButtonTestScreen() { super(new StringTextComponent("test")); } private ScalingTextRenderer scalingRenderer; private ScrollingTextRenderer scrollingRenderer; @Override protected void init() { // U Button Test final UButton uButton = addButton(new UButton(10, 10, 200, 15, ITextComponent.getTextComponentOrEmpty("U Button"))); uButton.setPressable(() -> LOGGER.info("Pressed U Button")); uButton.setTooltip((button, matrixStack, mouseX, mouseY) -> { if (button.isHovered()) { renderTooltip(matrixStack, ITextComponent.getTextComponentOrEmpty("U Button Tooltip"), mouseX, mouseY); } }); // Scalable Button Test final ScalableButton scalableButton = addButton(new ScalableButton(10, 30, 200, 15, ITextComponent.getTextComponentOrEmpty("Scalable Button"), 0.75F)); scalableButton.setTextColor(new RGBA(0x00FFFF80)); scalableButton.setPressable(button -> LOGGER.info("Pressed Scalable Button")); scalableButton.setTooltip((button, matrixStack, mouseX, mouseY) -> { if (button.isHovered()) { renderTooltip(matrixStack, ITextComponent.getTextComponentOrEmpty("Scalable Button Tooltip"), mouseX, mouseY); } }); // Scalable Activatable Button Test final ScalableActivatableButton scalableActivatableButton = addButton(new ScalableActivatableButton(10, 50, 200, 15, ITextComponent.getTextComponentOrEmpty("Scalable Activatable Button"), 0.75F, false, new RGBA(0x006442FF))); scalableActivatableButton.setPressable(() -> { System.out.println("Pressed Scalable Activatable Button"); scalableActivatableButton.setActivated(!scalableActivatableButton.isActivated()); }); scalableActivatableButton.setTooltip((button, matrixStack, mouseX, mouseY) -> { if (button.isHovered()) { renderTooltip(matrixStack, ITextComponent.getTextComponentOrEmpty("Scalable Activatable Button Tooltip"), mouseX, mouseY); } }); // Image Button Test final ImageButton imageButton = addButton(new ImageButton(10, 70, 15, 15, TEXTURE1)); imageButton.setPressable(() -> { System.out.println("Pressed Image Button"); }); imageButton.setTooltip((button, matrixStack, mouseX, mouseY) -> { if (button.isHovered()) { renderTooltip(matrixStack, ITextComponent.getTextComponentOrEmpty("Image Button Tooltip"), mouseX, mouseY); } }); final ImageButton imageButton2 = addButton(new ImageButton(30, 70, 15, 15, TEXTURE1)); imageButton2.setButtonColor(new RGBA(0xFFFF2080)); imageButton2.setImageColor(new RGBA(0x00FFFF80)); imageButton2.setPressable(() -> { System.out.println("Pressed Image Button 2"); }); imageButton2.setTooltip((button, matrixStack, mouseX, mouseY) -> { if (button.isHovered()) { renderTooltip(matrixStack, ITextComponent.getTextComponentOrEmpty("Image Button 2 Tooltip"), mouseX, mouseY); } }); // Image Activatable Button Test final ImageActivatableButton imageActivatableButton = addButton(new ImageActivatableButton(10, 90, 15, 15, TEXTURE1, false, new RGBA(0x006442FF))); imageActivatableButton.setPressable(() -> { System.out.println("Pressed Image Activatable Button"); imageActivatableButton.setActivated(!imageActivatableButton.isActivated()); }); imageActivatableButton.setTooltip((button, matrixStack, mouseX, mouseY) -> { if (button.isHovered()) { renderTooltip(matrixStack, ITextComponent.getTextComponentOrEmpty("Image Activatable Button Tooltip"), mouseX, mouseY); } }); // Image Toggle Button Test final ImageToggleButton imageToggleButton = addButton(new ImageToggleButton(10, 110, 15, 15, TEXTURE1, TEXTURE2, false)); imageToggleButton.setPressable(() -> { System.out.println("Pressed Image Toggle Button"); }); imageToggleButton.setTooltip((button, matrixStack, mouseX, mouseY) -> { if (button.isHovered()) { renderTooltip(matrixStack, ITextComponent.getTextComponentOrEmpty("Image Toggle Button Tooltip"), mouseX, mouseY); } }); final ImageToggleButton imageToggleButton2 = addButton(new ImageToggleButton(30, 110, 15, 15, TEXTURE1, TEXTURE1, false)); imageToggleButton2.setImageColor(new RGBA(0x00FF00FF)); imageToggleButton2.setToggleImageColor(new RGBA(0xFF0000FF)); imageToggleButton2.setPressable(() -> { System.out.println("Pressed Image Toggle Button 2"); }); imageToggleButton2.setTooltip((button, matrixStack, mouseX, mouseY) -> { if (button.isHovered()) { renderTooltip(matrixStack, ITextComponent.getTextComponentOrEmpty("Image Toggle Button 2 Tooltip"), mouseX, mouseY); } }); // U Slider Test final USlider uSlider = addButton(new USlider(10, 130, 200, 20, ITextComponent.getTextComponentOrEmpty("U Slider: "), ITextComponent.getTextComponentOrEmpty("%"), 0, 100, 20, false, true)); uSlider.setSlider(() -> { System.out.println("Updated U Slider: " + uSlider.getValueInt()); }); uSlider.setTooltip((slider, matrixStack, mouseX, mouseY) -> { if (slider.isHovered()) { renderTooltip(matrixStack, ITextComponent.getTextComponentOrEmpty("U Slider Tooltip"), mouseX, mouseY); } }); // Scalable Slider Test final ScalableSlider scalableSlider = addButton(new ScalableSlider(10, 155, 200, 15, ITextComponent.getTextComponentOrEmpty("Scalable Slider: "), ITextComponent.getTextComponentOrEmpty("%"), 0, 100, 20, false, true, 0.5F)); scalableSlider.setSlider(() -> { System.out.println("Updated Scalable Slider: " + scalableSlider.getValueInt()); }); scalableSlider.setTooltip((slider, matrixStack, mouseX, mouseY) -> { if (slider.isHovered()) { renderTooltip(matrixStack, ITextComponent.getTextComponentOrEmpty("Scalable Slider Tooltip"), mouseX, mouseY); } }); final ScalableSlider scalableSlider2 = addButton(new ScalableSlider(10, 175, 200, 30, ITextComponent.getTextComponentOrEmpty("Scalable Slider 2: "), ITextComponent.getTextComponentOrEmpty("%"), 0, 100, 20, false, true, 1.5F)); scalableSlider2.setSlider(() -> { System.out.println("Updated Scalable Slider 2: " + scalableSlider2.getValueInt()); }); scalableSlider2.setTooltip((slider, matrixStack, mouseX, mouseY) -> { if (slider.isHovered()) { renderTooltip(matrixStack, ITextComponent.getTextComponentOrEmpty("Scalable Slider 2 Tooltip"), mouseX, mouseY); } }); scalingRenderer = new ScalingTextRenderer(() -> font, () -> "This is a test for the scaling text renderer"); scalingRenderer.setColor(0xFFFFFF); scalingRenderer.setScale(2); scrollingRenderer = new ScrollingTextRenderer(() -> font, () -> "This is a test for the scrolling text renderer that should be really long to test the scrolling"); scrollingRenderer.setColor(0xFFFFFF); scrollingRenderer.setWidth(200); scrollingRenderer.setScale(0.75F); } @Override public void render(MatrixStack matrixStack, int mouseX, int mouseY, float partialTicks) { renderBackground(matrixStack); super.render(matrixStack, mouseX, mouseY, partialTicks); // scalingRenderer.render(matrixStack, 10, 145); // scrollingRenderer.render(matrixStack, 10, 170); buttons.forEach(widget -> widget.renderToolTip(matrixStack, mouseX, mouseY)); } }
package org.safehaus.subutai.ui.commandrunner; import com.google.common.base.Strings; import com.vaadin.server.VaadinService; import com.vaadin.ui.Button; import com.vaadin.ui.JavaScript; import com.vaadin.ui.TextArea; import com.vaadin.ui.VerticalLayout; public class TerminalControl extends VerticalLayout { private TextArea commandPrompt; private Button sendButton; private String inputPrompt; private String username, currentPath, machineName; public TerminalControl() { username = (String) VaadinService.getCurrentRequest().getWrappedSession().getAttribute("username"); currentPath = "/"; machineName = ""; initSendButton(); initCommandPrompt(); addComponent(sendButton); addComponent(commandPrompt); this.setSizeFull(); } private void initSendButton() { sendButton = new Button(""); sendButton.setVisible(false); sendButton.addClickListener(new Button.ClickListener() { @Override public void buttonClick(Button.ClickEvent clickEvent) { getCommand(); } }); } private void initCommandPrompt() { commandPrompt = new TextArea(); commandPrompt.setId("terminal"); commandPrompt.setSizeFull(); commandPrompt.setImmediate(true); commandPrompt.addStyleName("terminal"); setInputPrompt(); JavaScript.getCurrent().execute("document.getElementById(\"terminal\").addEventListener(\"keydown\", function(ev){\n" + " if (ev.which == 13 || ev.keyCode == 13) {\n" + " //code to execute here\n" + " return false;\n" + " }\n" + " return true;" + "}, true);"); } public void setInputPrompt() { inputPrompt = String.format("%s@%s:%s#", username, machineName, currentPath); if (Strings.isNullOrEmpty(commandPrompt.getValue())) { commandPrompt.setValue(String.format("%s", inputPrompt)); } else { commandPrompt.setValue(String.format("%s\n%s", commandPrompt.getValue(), inputPrompt)); } } public void focusPrompt() { commandPrompt.setCursorPosition(commandPrompt.getValue().length()); } public String getCommand() { String value = commandPrompt.getValue(); System.out.println(value); if (Strings.isNullOrEmpty(value)) { String[] args = value.split(inputPrompt); value = args[args.length - 1]; } System.out.println(value); return value; } }
package name.valery1707.kazPersonId; import org.junit.Test; import static com.google.common.truth.Truth.assertThat; public class PrivatePersonIdTest { @Test public void testPublicIds() throws Exception { PrivatePersonId id; id = new PrivatePersonId("871008401427"); assertThat(id.isValid()).isTrue(); assertThat(id.getBirthDate().toString()).isEqualTo("1987-10-08"); assertThat(id.getSex()).isSameAs(Sex.FEMALE); id = new PrivatePersonId("760212350620"); assertThat(id.isValid()).isTrue(); assertThat(id.getBirthDate().toString()).isEqualTo("1976-02-12"); assertThat(id.getSex()).isSameAs(Sex.MALE); id = new PrivatePersonId("800416300257"); assertThat(id.isValid()).isTrue(); assertThat(id.getBirthDate().toString()).isEqualTo("1980-04-16"); assertThat(id.getSex()).isSameAs(Sex.MALE); id = new PrivatePersonId("680503450037"); assertThat(id.isValid()).isTrue(); assertThat(id.getBirthDate().toString()).isEqualTo("1968-05-03"); assertThat(id.getSex()).isSameAs(Sex.FEMALE); } @Test public void testCenturyBit() throws Exception { PrivatePersonId id; id = new PrivatePersonId("800416100254"); assertThat(id.isValid()).isTrue(); assertThat(id.getBirthDate().toString()).isEqualTo("1880-04-16"); assertThat(id.getSex()).isSameAs(Sex.MALE); id = new PrivatePersonId("680503250034"); assertThat(id.isValid()).isTrue(); assertThat(id.getBirthDate().toString()).isEqualTo("1868-05-03"); assertThat(id.getSex()).isSameAs(Sex.FEMALE); } }
package org.safehaus.kiskis.mgmt.impl.mongodb; import java.util.*; import org.safehaus.kiskis.mgmt.api.lxcmanager.*; import org.safehaus.kiskis.mgmt.api.mongodb.NodeType; import org.safehaus.kiskis.mgmt.shared.protocol.Agent; public class CustomPlacementStrategy extends LxcPlacementStrategy { private float hddPerNodeMb; private float hddReservedMb; private float ramPerNodeMb; private float ramReservedMb; private float cpuPerNodePercentage; private float cpuReservedPercentage; private final Map<NodeType, Integer> nodesCount; public CustomPlacementStrategy(int configServers, int routers, int dataNodes) { this.nodesCount = new EnumMap<>(NodeType.class); this.nodesCount.put(NodeType.CONFIG_NODE, configServers); this.nodesCount.put(NodeType.ROUTER_NODE, routers); this.nodesCount.put(NodeType.DATA_NODE, dataNodes); } public static Map<NodeType, Set<Agent>> getNodes(LxcManager lxcManager, int configServers, int routers, int dataNodes) throws LxcCreateException { LxcPlacementStrategy strategy = new CustomPlacementStrategy( configServers, routers, dataNodes); Map<String, Map<Agent, Set<Agent>>> nodes = lxcManager.createLxcsByStrategy(strategy); // collect nodes by types regardless of parent nodes Map<NodeType, Set<Agent>> res = new EnumMap<>(NodeType.class); for(NodeType type : NodeType.values()) { Map<Agent, Set<Agent>> map = nodes.get(type.toString()); if(map == null) continue; Set<Agent> all = new HashSet<>(); for(Set<Agent> children : map.values()) all.addAll(children); Set<Agent> set = res.get(type); if(set != null) set.addAll(all); else res.put(type, all); } return res; } @Override public Map<Agent, Integer> calculateSlots(Map<Agent, ServerMetric> metrics) { if(metrics == null || metrics.isEmpty()) return null; Map<Agent, Integer> slots = new HashMap<>(); for(Map.Entry<Agent, ServerMetric> e : metrics.entrySet()) { ServerMetric m = e.getValue(); int min = Integer.MAX_VALUE; int n = Math.round((m.getFreeRamMb() - ramReservedMb) / ramPerNodeMb); if((min = Math.min(n, min)) <= 0) continue; n = Math.round((m.getFreeHddMb() - hddReservedMb) / hddPerNodeMb); if((min = Math.min(n, min)) <= 0) continue; int unusedCpu = 100 - m.getCpuLoadPercent(); n = Math.round(unusedCpu - cpuReservedPercentage / cpuPerNodePercentage); if((min = Math.min(n, min)) <= 0) continue; slots.put(e.getKey(), min); } return slots; } @Override public void calculatePlacement(Map<Agent, ServerMetric> serverMetrics) throws LxcCreateException { for(NodeType type : NodeType.values()) { setCriteria(type); Map<Agent, Integer> serverSlots = calculateSlots(serverMetrics); if(serverSlots == null || serverSlots.isEmpty()) return; int available = 0; for(Integer i : serverSlots.values()) available += i.intValue(); if(available < nodesCount.get(type)) return; calculatePlacement(type, serverSlots); } } public void setCriteria(NodeType type) { switch(type) { case CONFIG_NODE: hddPerNodeMb = GB2MB(5); hddReservedMb = GB2MB(10); ramPerNodeMb = GB2MB(1); ramReservedMb = GB2MB(1); cpuPerNodePercentage = 10; cpuReservedPercentage = 10; break; case ROUTER_NODE: hddPerNodeMb = GB2MB(3); hddReservedMb = GB2MB(5); ramPerNodeMb = GB2MB(0.5f); ramReservedMb = GB2MB(1); cpuPerNodePercentage = 5; cpuReservedPercentage = 10; break; case DATA_NODE: hddPerNodeMb = GB2MB(50); hddReservedMb = GB2MB(20); ramPerNodeMb = GB2MB(1); ramReservedMb = GB2MB(1); cpuPerNodePercentage = 10; cpuReservedPercentage = 10; break; default: throw new AssertionError(type.name()); } } private void calculatePlacement(NodeType type, Map<Agent, Integer> serverSlots) throws LxcCreateException { for(int i = 0; i < nodesCount.get(type); i++) { Agent physicalNode = findBestServer(serverSlots); if(physicalNode == null) break; Integer slotsCount = serverSlots.get(physicalNode); serverSlots.put(physicalNode, slotsCount - 1); Map<String, Integer> info = getPlacementInfoMap().get(physicalNode); int cnt = 1; if(info != null && info.get(type.toString()) != null) cnt = info.get(type.toString()).intValue() + 1; addPlacementInfo(physicalNode, type.toString(), cnt); } } private Agent findBestServer(Map<Agent, Integer> map) { int max = 0; Agent best = null; for(Map.Entry<Agent, Integer> e : map.entrySet()) { if(e.getValue().intValue() > max) { best = e.getKey(); max = e.getValue().intValue(); } } return best; } private int GB2MB(float gb) { return Math.round(gb * 1024); } }
package org.opencps.dossiermgt.listenner; import java.util.List; import org.opencps.dossiermgt.model.DossierAction; import org.opencps.dossiermgt.model.DossierFile; import org.opencps.dossiermgt.model.DossierLog; import org.opencps.dossiermgt.model.ProcessAction; import org.opencps.dossiermgt.service.DossierFileLocalServiceUtil; import org.opencps.dossiermgt.service.DossierLogLocalServiceUtil; import org.opencps.dossiermgt.service.ProcessActionLocalServiceUtil; import org.opencps.usermgt.action.impl.EmployeeActions; import org.opencps.usermgt.action.impl.JobposActions; import org.opencps.usermgt.model.Employee; import org.opencps.usermgt.model.JobPos; import org.osgi.service.component.annotations.Component; import com.liferay.portal.kernel.dao.orm.QueryUtil; import com.liferay.portal.kernel.exception.ModelListenerException; import com.liferay.portal.kernel.exception.PortalException; import com.liferay.portal.kernel.exception.SystemException; import com.liferay.portal.kernel.json.JSONArray; import com.liferay.portal.kernel.json.JSONFactoryUtil; import com.liferay.portal.kernel.json.JSONObject; import com.liferay.portal.kernel.log.Log; import com.liferay.portal.kernel.log.LogFactoryUtil; import com.liferay.portal.kernel.model.BaseModelListener; import com.liferay.portal.kernel.model.ModelListener; import com.liferay.portal.kernel.service.ServiceContext; import com.liferay.portal.kernel.util.GetterUtil; import com.liferay.portal.kernel.util.StringPool; import com.liferay.portal.kernel.util.Validator; import backend.utils.APIDateTimeUtils; @Component(immediate = true, service = ModelListener.class) public class DossierActionListenner extends BaseModelListener<DossierAction> { @Override public void onAfterCreate(DossierAction model) throws ModelListenerException { if (true) { ServiceContext serviceContext = new ServiceContext(); EmployeeActions employeeActions = new EmployeeActions(); JobposActions jobposActions = new JobposActions(); try { long userId = model.getUserId(); Employee employee = employeeActions.getEmployeeByMappingUserId(model.getGroupId(), userId); long mainJobposId = employee != null ? employee.getMainJobPostId() : 0; long dossierId = model.getDossierId(); String jobPosName = StringPool.BLANK; if (mainJobposId > 0) { JobPos jobPos = jobposActions.getJobPos(mainJobposId); jobPosName = (jobPos != null && Validator.isNotNull(jobPos.getTitle())) ? jobPos.getTitle() : StringPool.BLANK; } String content = model.getActionNote(); JSONObject payload = JSONFactoryUtil.createJSONObject(); JSONArray files = JSONFactoryUtil.createJSONArray(); if (dossierId > 0) { List<DossierLog> dossierLogs = DossierLogLocalServiceUtil.getByDossierAndType(dossierId, DossierFileListenerMessageKeys.DOSSIER_LOG_CREATE_TYPE, QueryUtil.ALL_POS, QueryUtil.ALL_POS); for (DossierLog log : dossierLogs) { long dossierFileId = 0; try { JSONObject payloadFile = JSONFactoryUtil.createJSONObject(log.getPayload()); dossierFileId = GetterUtil.getLong(payloadFile.get("dossierFileId")); } catch (Exception e) { } if (dossierFileId != 0) { DossierFile dossierFile = DossierFileLocalServiceUtil.fetchDossierFile(dossierFileId); if (Validator.isNotNull(dossierFile)) { JSONObject file = JSONFactoryUtil.createJSONObject(); file.put("dossierFileId", dossierFile.getDossierFileId()); file.put("fileName", dossierFile.getDisplayName()); file.put("createDate", APIDateTimeUtils.convertDateToString(dossierFile.getCreateDate(), APIDateTimeUtils._TIMESTAMP)); files.put(file); } } DossierLogLocalServiceUtil.deleteDossierLog(log); } } payload.put("jobPosName", jobPosName); payload.put("stepName", model.getActionName()); payload.put("stepInstruction", model.getStepInstruction()); payload.put("files", files); serviceContext.setCompanyId(model.getCompanyId()); serviceContext.setUserId(userId); ProcessAction processAction = ProcessActionLocalServiceUtil .getByNameActionNo(model.getServiceProcessId(), model.getActionCode(), model.getActionName()); boolean ok = true; if (Validator.isNotNull(processAction)) { if ((processAction.getPreCondition().contains("cancelling") && processAction.getAutoEvent().contains("timmer")) || (processAction.getPreCondition().contains("correcting") && processAction.getAutoEvent().contains("timmer")) || (processAction.getPreCondition().contains("submitting")) && processAction.getAutoEvent().contains("timmer")) { ok = false; _log.info("CHECK CONDITION OK ********** ....." + ok); } } else { _log.info("CANT GET DOSSIER ACTION ********** ....."); } if (ok) { DossierLogLocalServiceUtil.addDossierLog(model.getGroupId(), model.getDossierId(), model.getActionUser(), content, "PROCESS_TYPE", payload.toString(), serviceContext); } } catch (SystemException | PortalException e) { _log.error(e); } } if (Validator.isNotNull(model.getSyncActionCode()) && model.getSyncActionCode().length() != 0) { String content = "On DossiserAction Created"; String notificationType = ""; String payload = ""; ServiceContext serviceContext = new ServiceContext(); serviceContext.setCompanyId(model.getCompanyId()); serviceContext.setUserId(model.getUserId()); try { DossierLogLocalServiceUtil.addDossierLog(model.getGroupId(), model.getDossierId(), model.getUserName(), content, notificationType, payload, serviceContext); } catch (SystemException | PortalException e) { _log.error(e); } } } private Log _log = LogFactoryUtil.getLog(DossierActionListenner.class.getName()); }
package org.openqa.selenium.chrome; import org.openqa.selenium.Platform; import org.openqa.selenium.Proxy; import org.openqa.selenium.WebDriverException; import org.openqa.selenium.Proxy.ProxyType; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class ChromeBinary { private static final int BACKOFF_INTERVAL = 2500; private static int linearBackoffCoefficient = 1; private final ChromeProfile profile; private final ChromeExtension extension; protected String chromeBinaryLocation = null; Process chromeProcess = null; /** * Creates a new instance for managing an instance of Chrome using the given * {@code profile} and {@code extension}. * * @param profile The Chrome profile to use. * @param extension The extension to launch Chrome with. */ public ChromeBinary(ChromeProfile profile, ChromeExtension extension) { this.profile = profile; this.extension = extension; } /** * Starts the Chrome process for WebDriver. * Assumes the passed directories exist. * @param serverUrl URL from which commands should be requested * @throws IOException wrapped in WebDriverException if process couldn't be * started. */ public void start(String serverUrl) throws IOException { try { List<String> commandline = getCommandline(serverUrl); chromeProcess = new ProcessBuilder(commandline) .start(); } catch (IOException e) { throw new WebDriverException(e); } try { Thread.sleep(BACKOFF_INTERVAL * linearBackoffCoefficient); } catch (InterruptedException e) { //Nothing sane to do here } } // Visible for testing. public List<String> getCommandline(String serverUrl) throws IOException { ArrayList<String> commandline = new ArrayList<String>(Arrays.asList( getChromeFile(), "--user-data-dir=" + profile.getDirectory().getAbsolutePath(), "--load-extension=" + extension.getDirectory().getAbsolutePath(), "--activate-on-launch", "--homepage=about:blank", "--no-first-run", "--disable-hang-monitor", "--disable-popup-blocking", "--disable-prompt-on-repost", "--no-default-browser-check" )); appendProxyArguments(commandline) .add(serverUrl); return commandline; } private ArrayList<String> appendProxyArguments(ArrayList<String> commandline) { Proxy proxy = profile.getProxy(); if (proxy == null) { return commandline; } if (proxy.getProxyAutoconfigUrl() != null) { commandline.add("--proxy-pac-url=" + proxy.getProxyAutoconfigUrl()); } else if (proxy.getHttpProxy() != null) { commandline.add("--proxy-server=" + proxy.getHttpProxy()); } else if (proxy.isAutodetect()) { commandline.add("--proxy-auto-detect"); } else if (proxy.getProxyType() == ProxyType.DIRECT) { commandline.add("--no-proxy-server"); } else if (proxy.getProxyType() != ProxyType.SYSTEM) { throw new IllegalStateException("Unsupported proxy setting"); } return commandline; } public void kill() { if (chromeProcess != null) { chromeProcess.destroy(); chromeProcess = null; } } public void incrementBackoffBy(int diff) { linearBackoffCoefficient += diff; } /** * Locates the Chrome executable on the current platform. * First looks in the webdriver.chrome.bin property, then searches * through the default expected locations. * @return chrome.exe * @throws IOException if file could not be found/accessed */ protected String getChromeFile() throws IOException { if (!isChromeBinaryLocationKnown()) { chromeBinaryLocation = System.getProperty("webdriver.chrome.bin"); if (chromeBinaryLocation == null) { if (Platform.getCurrent().is(Platform.WINDOWS)) { chromeBinaryLocation = getWindowsBinaryLocation(); } else if (Platform.getCurrent().is(Platform.UNIX)) { chromeBinaryLocation = "/usr/bin/google-chrome"; } else if (Platform.getCurrent().is(Platform.MAC)) { String[] paths = new String[] { "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", "/Users/" + System.getProperty("user.name") + "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"}; for (String path : paths) { File binary = new File(path); if (binary.exists()) { chromeBinaryLocation = binary.getCanonicalFile().getAbsoluteFile().toString(); break; } } } else { throw new WebDriverException("Unsupported operating system. " + "Could not locate Chrome. Set webdriver.chrome.bin"); } } if (!isChromeBinaryLocationKnown()) { throw new WebDriverException("Couldn't locate Chrome. " + "Set webdriver.chrome.bin"); } } return chromeBinaryLocation; } protected boolean isChromeBinaryLocationKnown() { return chromeBinaryLocation != null && new File(chromeBinaryLocation).exists(); } /** * Returns null if couldn't read value from registry */ protected static final String getWindowsBinaryLocation() { //TODO: Promote org.openqa.selenium.server.browserlaunchers.WindowsUtils //to common and reuse that to read the registry if (!Platform.WINDOWS.is(Platform.getCurrent())) { throw new UnsupportedOperationException("Cannot get registry value on non-Windows systems"); } try { Process process = Runtime.getRuntime().exec( "reg query \"HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\chrome.exe\" /v \"\""); BufferedReader reader = new BufferedReader(new InputStreamReader( process.getInputStream())); process.waitFor(); String line; while ((line = reader.readLine()) != null) { if (line.contains(" ")) { String[] tokens = line.split("REG_SZ"); return tokens[tokens.length - 1].trim(); } } } catch (IOException e) { //Drop through to return null } catch (InterruptedException e) { //Drop through to return null } return null; } }
package org.neo4j.kernel.ha; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.ReadableByteChannel; import org.jboss.netty.buffer.ChannelBuffer; public class BlockLogReader implements ReadableByteChannel { private final ChannelBuffer source; private final byte[] byteArray = new byte[BlockLogBuffer.MAX_SIZE]; private final ByteBuffer byteBuffer = ByteBuffer.wrap( byteArray ); private boolean moreBlocks; public BlockLogReader( ChannelBuffer source ) { this.source = source; readNextBlock(); } private void readNextBlock() { int maxReadableBytes = source.readableBytes(); if ( maxReadableBytes > 0 ) { byteBuffer.clear(); byteBuffer.limit( Math.min( byteBuffer.capacity(), maxReadableBytes ) ); source.readBytes( byteBuffer ); byteBuffer.flip(); moreBlocks = byteBuffer.get() == BlockLogBuffer.FULL_BLOCK_AND_MORE; } } public boolean isOpen() { return true; } public void close() throws IOException { } public int read( ByteBuffer dst ) throws IOException { int bytesWanted = dst.limit(); int bytesRead = 0; while ( bytesWanted > 0 ) { int bytesReadThisTime = readAsMuchAsPossible( dst, bytesWanted ); if ( bytesReadThisTime == 0 ) { break; } bytesRead += bytesReadThisTime; bytesWanted -= bytesReadThisTime; } return bytesRead; } private int readAsMuchAsPossible( ByteBuffer dst, int maxBytesWanted ) { if ( byteBuffer.remaining() == 0 && moreBlocks ) { readNextBlock(); } int bytesToRead = Math.min( maxBytesWanted, byteBuffer.remaining() ); dst.put( byteArray, byteBuffer.position(), bytesToRead ); byteBuffer.position( byteBuffer.position()+bytesToRead ); return bytesToRead; } }
package tw.wancw.curator.widget; import android.content.Context; import android.graphics.Bitmap; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.assist.SimpleImageLoadingListener; import java.util.ArrayList; import java.util.Collection; import java.util.List; import tw.wancw.curator.R; import tw.wancw.curator.api.MeiZiCard; public class MeiZiCardAdapter extends BaseAdapter { private final Context context; private final ImageLoader loader; private final List<MeiZiCard> cards; public MeiZiCardAdapter(Context context, ImageLoader loader) { this.context = context; this.loader = loader; this.cards = new ArrayList<MeiZiCard>(); } @Override public int getCount() { return cards.size(); } @Override public MeiZiCard getItem(int i) { return cards.get(i); } @Override public long getItemId(int i) { return i; } @Override public View getView(int i, View view, ViewGroup viewGroup) { MeiZiCardAdapter.ViewHolder holder; if (view == null) { LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); view = inflater.inflate(R.layout.view_meizicard, null); holder = new MeiZiCardAdapter.ViewHolder(); holder.cardImage = (ImageView) view.findViewById(R.id.card_image); holder.cardCaption = (TextView) view.findViewById(R.id.card_caption); view.setTag(holder); } else { holder = (MeiZiCardAdapter.ViewHolder) view.getTag(); } MeiZiCard card = getItem(i); holder.cardImage.setVisibility(View.INVISIBLE); loader.cancelDisplayTask(holder.cardImage); loader.displayImage(card.getThumbnail().getUrl(), holder.cardImage, new SimpleImageLoadingListener() { @Override public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { view.setVisibility(View.VISIBLE); } } ); holder.cardCaption.setText(card.getCaption()); return view; } public void add(Collection<MeiZiCard> cards) { this.cards.addAll(cards); notifyDataSetChanged(); } private class ViewHolder { ImageView cardImage; TextView cardCaption; } }
package com.thaiopensource.xml.dtd; import java.io.IOException; public class SchemaWriter implements TopLevelVisitor, ModelGroupVisitor, AttributeGroupVisitor, DatatypeVisitor, EnumGroupVisitor { private XmlWriter w; public SchemaWriter(XmlWriter writer) { this.w = writer; } public void writeDtd(Dtd dtd) throws IOException { w.startElement("doctype"); try { dtd.accept(this); } catch (RuntimeException e) { throw e; } catch (Exception e) { throw (IOException)e; } w.endElement(); } public void elementDecl(String name, ModelGroup modelGroup) throws Exception { w.startElement("element"); w.attribute("name", name); modelGroup.accept(this); w.endElement(); } public void attlistDecl(String name, AttributeGroup attributeGroup) throws Exception { w.startElement("attlist"); w.attribute("name", name); attributeGroup.accept(this); w.endElement(); } public void processingInstruction(String target, String value) throws Exception { w.startElement("processingInstruction"); w.attribute("target", target); w.characters(value); w.endElement(); } public void comment(String value) throws Exception { w.comment(value); } public void ignoredSection(String value) throws Exception { } public void modelGroupDef(String name, ModelGroup modelGroup) throws Exception { w.startElement("modelGroup"); w.attribute("name", name); modelGroup.accept(this); w.endElement(); } public void attributeGroupDef(String name, AttributeGroup attributeGroup) throws Exception { w.startElement("attributeGroup"); w.attribute("name", name); attributeGroup.accept(this); w.endElement(); } public void enumGroupDef(String name, EnumGroup enumGroup) throws Exception { w.startElement("enumGroup"); w.attribute("name", name); enumGroup.accept(this); w.endElement(); } public void datatypeDef(String name, Datatype datatype) throws Exception { w.startElement("datatype"); w.attribute("name", name); datatype.accept(this); w.endElement(); } public void choice(ModelGroup[] members) throws Exception { w.startElement("choice"); for (int i = 0; i < members.length; i++) members[i].accept(this); w.endElement(); } public void sequence(ModelGroup[] members) throws Exception { w.startElement("sequence"); for (int i = 0; i < members.length; i++) members[i].accept(this); w.endElement(); } public void oneOrMore(ModelGroup member) throws Exception { w.startElement("oneOrMore"); member.accept(this); w.endElement(); } public void zeroOrMore(ModelGroup member) throws Exception { w.startElement("zeroOrMore"); member.accept(this); w.endElement(); } public void optional(ModelGroup member) throws Exception { w.startElement("optional"); member.accept(this); w.endElement(); } public void modelGroupRef(String name, ModelGroup modelGroup) throws Exception { w.startElement("modelGroupRef"); w.attribute("name", name); w.endElement(); } public void elementRef(String name) throws Exception { w.startElement("elementRef"); w.attribute("name", name); w.endElement(); } public void pcdata() throws Exception { w.startElement("pcdata"); w.endElement(); } public void any() throws Exception { w.startElement("any"); w.endElement(); } public void attribute(String name, boolean optional, Datatype datatype, String defaultValue) throws Exception { w.startElement("attribute"); w.attribute("name", name); w.attribute("use", optional ? "optional" : "required"); if (defaultValue != null) w.attribute("default", defaultValue); datatype.accept(this); w.endElement(); } public void attributeGroupRef(String name, AttributeGroup attributeGroup) throws Exception { w.startElement("attributeGroupRef"); w.attribute("name", name); w.endElement(); } public void enumValue(String value) throws Exception { w.startElement("enum"); w.characters(value); w.endElement(); } public void enumGroupRef(String name, EnumGroup enumGroup) throws Exception { w.startElement("enumGroupRef"); w.attribute("name", name); w.endElement(); } public void basicDatatype(String typeName) throws IOException { w.startElement("basic"); w.attribute("name", typeName); w.endElement(); } public void enumDatatype(EnumGroup enumGroup) throws Exception { w.startElement("enumChoice"); enumGroup.accept(this); w.endElement(); } public void notationDatatype(EnumGroup enumGroup) throws Exception { w.startElement("notation"); enumGroup.accept(this); w.endElement(); } public void datatypeRef(String name, Datatype datatype) throws IOException { w.startElement("datatypeRef"); w.attribute("name", name); w.endElement(); } }
package org.fxmisc.richtext; import javafx.beans.binding.Binding; import javafx.beans.value.ObservableValue; import javafx.geometry.Bounds; import org.fxmisc.richtext.model.TwoDimensional; import org.reactfx.EventStream; import org.reactfx.EventStreams; import org.reactfx.StateMachine; import org.reactfx.Subscription; import org.reactfx.Suspendable; import org.reactfx.SuspendableNo; import org.reactfx.value.SuspendableVal; import org.reactfx.value.Val; import org.reactfx.value.Var; import java.time.Duration; import java.util.Optional; import java.util.OptionalInt; import java.util.function.Consumer; import static javafx.util.Duration.ZERO; import static org.fxmisc.richtext.model.TwoDimensional.Bias.Forward; import static org.reactfx.EventStreams.invalidationsOf; import static org.reactfx.EventStreams.merge; final class CaretImpl implements Caret { private final Var<Integer> internalTextPosition; private final SuspendableVal<Integer> position; @Override public final int getPosition() { return position.getValue(); } @Override public final ObservableValue<Integer> positionProperty() { return position; } private final SuspendableVal<Integer> paragraphIndex; @Override public final int getParagraphIndex() { return paragraphIndex.getValue(); } @Override public final ObservableValue<Integer> paragraphIndexProperty() { return paragraphIndex; } private final SuspendableVal<OptionalInt> lineIndex; @Override public final OptionalInt getLineIndex() { return lineIndex.getValue(); } @Override public final ObservableValue<OptionalInt> lineIndexProperty() { return lineIndex; } private final SuspendableVal<Integer> columnPosition; @Override public final int getColumnPosition() { return columnPosition.getValue(); } @Override public final ObservableValue<Integer> columnPositionProperty() { return columnPosition; } private final Var<CaretVisibility> showCaret = Var.newSimpleVar(CaretVisibility.AUTO); @Override public final CaretVisibility getShowCaret() { return showCaret.getValue(); } @Override public final void setShowCaret(CaretVisibility value) { showCaret.setValue(value); } @Override public final Var<CaretVisibility> showCaretProperty() { return showCaret; } private final Binding<Boolean> visible; @Override public final boolean isVisible() { return visible.getValue(); } @Override public final ObservableValue<Boolean> visibleProperty() { return visible; } private final Val<Optional<Bounds>> bounds; @Override public final Optional<Bounds> getBounds() { return bounds.getValue(); } @Override public final ObservableValue<Optional<Bounds>> boundsProperty() { return bounds; } private Optional<ParagraphBox.CaretOffsetX> targetOffset = Optional.empty(); @Override public final void clearTargetOffset() { targetOffset = Optional.empty(); } @Override public final ParagraphBox.CaretOffsetX getTargetOffset() { if (!targetOffset.isPresent()) { targetOffset = Optional.of(area.getCaretOffsetX(getParagraphIndex())); } return targetOffset.get(); } private final EventStream<?> dirty; @Override public final EventStream<?> dirtyEvents() { return dirty; } private final SuspendableNo beingUpdated = new SuspendableNo(); @Override public final boolean isBeingUpdated() { return beingUpdated.get(); } @Override public final ObservableValue<Boolean> beingUpdatedProperty() { return beingUpdated; } private final GenericStyledArea<?, ?, ?> area; private final SuspendableNo dependentBeingUpdated; private Subscription subscriptions = () -> {}; CaretImpl(GenericStyledArea<?, ?, ?> area) { this(area, 0); } CaretImpl(GenericStyledArea<?, ?, ?> area, int startingPosition) { this(area, area.beingUpdatedProperty(), startingPosition); } CaretImpl(GenericStyledArea<?, ?, ?> area, SuspendableNo dependentBeingUpdated, int startingPosition) { this.area = area; this.dependentBeingUpdated = dependentBeingUpdated; internalTextPosition = Var.newSimpleVar(startingPosition); position = internalTextPosition.suspendable(); Val<TwoDimensional.Position> caretPosition2D = Val.create( () -> area.offsetToPosition(internalTextPosition.getValue(), Forward), internalTextPosition, area.getParagraphs() ); paragraphIndex = caretPosition2D.map(TwoDimensional.Position::getMajor).suspendable(); columnPosition = caretPosition2D.map(TwoDimensional.Position::getMinor).suspendable(); // when content is updated by an area, update the caret of all the other // clones that also display the same document manageSubscription(area.plainTextChanges(), (plainTextChange -> { int changeLength = plainTextChange.getInserted().length() - plainTextChange.getRemoved().length(); if (changeLength != 0) { int indexOfChange = plainTextChange.getPosition(); // in case of a replacement: "hello there" -> "hi." int endOfChange = indexOfChange + Math.abs(changeLength); int caretPosition = getPosition(); if (indexOfChange < caretPosition) { // if caret is within the changed content, move it to indexOfChange // otherwise offset it by changeLength moveTo( caretPosition < endOfChange ? indexOfChange : caretPosition + changeLength ); } } })); // whether or not to display the caret EventStream<Boolean> blinkCaret = showCaret.values() .flatMap(mode -> { switch (mode) { case ON: return Val.constant(true).values(); case OFF: return Val.constant(false).values(); default: case AUTO: return area.autoCaretBlink(); } }); dirty = merge( invalidationsOf(positionProperty()), invalidationsOf(area.getParagraphs()) ); // The caret is visible in periodic intervals, // but only when blinkCaret is true. visible = EventStreams.combine(blinkCaret, area.caretBlinkRateEvents()) .flatMap(tuple -> { Boolean blink = tuple.get1(); javafx.util.Duration rate = tuple.get2(); if(blink) { return rate.lessThanOrEqualTo(ZERO) ? Val.constant(true).values() : booleanPulse(rate, dirty); } else { return Val.constant(false).values(); } }) .toBinding(false); manageBinding(visible); bounds = Val.create( () -> area.getCaretBoundsOnScreen(getParagraphIndex()), area.boundsDirtyFor(dirty) ); lineIndex = Val.create( () -> OptionalInt.of(area.lineIndex(getParagraphIndex(), getColumnPosition())), dirty ).suspendable(); Suspendable omniSuspendable = Suspendable.combine( beingUpdated, paragraphIndex, columnPosition, position ); manageSubscription(omniSuspendable.suspendWhen(dependentBeingUpdated)); } public void moveTo(int paragraphIndex, int columnPosition) { moveTo(textPosition(paragraphIndex, columnPosition)); } public void moveTo(int position) { dependentBeingUpdated.suspendWhile(() -> internalTextPosition.setValue(position)); } public void dispose() { subscriptions.unsubscribe(); } private int textPosition(int row, int col) { return area.position(row, col).toOffset(); } private <T> void manageSubscription(EventStream<T> stream, Consumer<T> subscriber) { manageSubscription(stream.subscribe(subscriber)); } private void manageBinding(Binding<?> binding) { manageSubscription(binding::dispose); } private void manageSubscription(Subscription s) { subscriptions = subscriptions.and(s); } private static EventStream<Boolean> booleanPulse(javafx.util.Duration javafxDuration, EventStream<?> restartImpulse) { Duration duration = Duration.ofMillis(Math.round(javafxDuration.toMillis())); EventStream<?> ticks = EventStreams.restartableTicks(duration, restartImpulse); return StateMachine.init(false) .on(restartImpulse.withDefaultEvent(null)).transition((state, impulse) -> true) .on(ticks).transition((state, tick) -> !state) .toStateStream(); } }
package org.labcrypto.wideroid; import android.graphics.PointF; import android.view.MotionEvent; import android.view.View; import java.util.Date; /** * @author Kamran Amini <[email protected]> * @author Mohammad Ghorbani <???> */ public class TouchHelper { /** * Static method for creating a new TouchHelper instance. */ public static TouchHelper createTouchHelper() { return new TouchHelper(); } /** * Listener for events caused by touches from up to down. */ public interface UpToDownTouchListener { void handle(TouchEvent touchEvent); } /** * Listener for events caused by touches from down to up. */ public interface DownToUpTouchListener { void handle(TouchEvent touchEvent); } /** * Listener for events caused by touches from left to right. */ public interface LeftToRightTouchListener { void handle(TouchEvent touchEvent); } /** * Listener for events caused by touches from right to left. */ public interface RightToLeftTouchListener { void handle(TouchEvent touchEvent); } /** * Listener for events caused by touches with unknown directional pattern. */ public interface UnknownDirectionTouchListener { void handle(TouchEvent touchEvent); } /** * Event object propagated when a touch happens. */ public class TouchEvent { public float dx; public float dy; public float dt; public float r; } /** * Target view which should be monitored for touch events. */ protected View view; /** * Listener reference for up to down touch events. */ protected UpToDownTouchListener upToDownTouchListener; /** * Listener reference for down to up touch events. */ protected DownToUpTouchListener downToUpTouchListener; /** * Listener reference for left to right touch events. */ protected LeftToRightTouchListener leftToRightTouchListener; /** * Listener reference for right to left touch events. */ protected RightToLeftTouchListener rightToLeftTouchListener; /** * Listener reference for unknown touch events. */ protected UnknownDirectionTouchListener unknownDirectionTouchListener; /** * Returns target view. */ public View getView() { return view; } /** * Sets target view. * * @return Reference to this touch helper object. */ public TouchHelper setView(View view) { this.view = view; return this; } /** * Returns up to down listener. */ public UpToDownTouchListener getUpToDownTouchListener() { return upToDownTouchListener; } /** * Sets up to down listener. * * @return Reference to this touch helper object. */ public TouchHelper setUpToDownTouchListener(UpToDownTouchListener upToDownTouchListener) { this.upToDownTouchListener = upToDownTouchListener; return this; } /** * Returns down to up listener. */ public DownToUpTouchListener getDownToUpTouchListener() { return downToUpTouchListener; } /** * Sets down to up listener. * * @return Reference to this touch helper object. */ public TouchHelper setDownToUpTouchListener(DownToUpTouchListener downToUpTouchListener) { this.downToUpTouchListener = downToUpTouchListener; return this; } /** * Returns left to right listener. */ public LeftToRightTouchListener getLeftToRightTouchListener() { return leftToRightTouchListener; } /** * Sets left to right listener. * * @return Reference to this touch helper object. */ public TouchHelper setLeftToRightTouchListener(LeftToRightTouchListener leftToRightTouchListener) { this.leftToRightTouchListener = leftToRightTouchListener; return this; } /** * Returns right to left listener. */ public RightToLeftTouchListener getRightToLeftTouchListener() { return rightToLeftTouchListener; } /** * Sets right to left listener. * * @return Reference to this touch helper object. */ public TouchHelper setRightToLeftTouchListener(RightToLeftTouchListener rightToLeftTouchListener) { this.rightToLeftTouchListener = rightToLeftTouchListener; return this; } /** * Returns unknown touch listener. */ public UnknownDirectionTouchListener getUnknownDirectionTouchListener() { return unknownDirectionTouchListener; } /** * Sets unknown touch listener. * * @return Reference to this touch helper object. */ public TouchHelper setUnknownDirectionTouchListener(UnknownDirectionTouchListener unknownDirectionTouchListener) { this.unknownDirectionTouchListener = unknownDirectionTouchListener; return this; } /** * Attaches to target view for monitoring touch events and assigns the listeners. * This method should be called at last in the method call chains. */ public void assign() { view.setOnTouchListener(new View.OnTouchListener() { private long downTime; private PointF downPoint; @Override public boolean onTouch(View v, MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: downTime = new Date().getTime(); downPoint = new PointF(event.getX(), event.getY()); break; case MotionEvent.ACTION_MOVE: break; case MotionEvent.ACTION_UP: if (downPoint != null) { TouchEvent touchEvent = new TouchEvent(); touchEvent.dx = event.getX() - downPoint.x; touchEvent.dy = event.getY() - downPoint.y; touchEvent.dt = new Date().getTime() - downTime; touchEvent.r = Math.abs(touchEvent.dy / touchEvent.dx); downPoint = null; if (touchEvent.r < 0.4) { if (touchEvent.dx > 0) { if (leftToRightTouchListener != null) { leftToRightTouchListener.handle(touchEvent); } } else { if (rightToLeftTouchListener != null) { rightToLeftTouchListener.handle(touchEvent); } } } else if (touchEvent.r > 3.0) { if (touchEvent.dy > 0) { if (upToDownTouchListener != null) { upToDownTouchListener.handle(touchEvent); } } else { if (downToUpTouchListener != null) { downToUpTouchListener.handle(touchEvent); } } } else { if (unknownDirectionTouchListener != null) { unknownDirectionTouchListener.handle(touchEvent); } } } break; } return true; } }); } }
package org.neo4j.server; import java.io.File; import java.util.HashSet; import org.apache.commons.configuration.Configuration; import org.neo4j.graphdb.GraphDatabaseService; import org.neo4j.server.configuration.Configurator; import org.neo4j.server.database.Database; import org.neo4j.server.logging.Logger; import org.neo4j.server.web.JettyWebServer; import org.neo4j.server.web.WebServer; /** * Application entry point for the Neo4j Server. */ public class NeoServer { public static final Logger log = Logger.getLogger(NeoServer.class); private static final String NEO_CONFIGDIR_PROPERTY = "org.neo4j.server.properties"; private static final String DEFAULT_NEO_CONFIGDIR = File.separator + "etc" + File.separator + "neo"; private Configurator configurator; private Database database; private WebServer webServer; public NeoServer(Configurator configurator, Database db, WebServer ws) { this.configurator = configurator; this.database = db; this.webServer = ws; } public static void main(String[] args) { Configurator conf = new Configurator(getConfigFile()); JettyWebServer ws = new JettyWebServer(); HashSet<String> packages = new HashSet<String>(); packages.add("org.neo4j.server.web"); ws.addPackages(packages); NeoServer theServer = new NeoServer(conf, new Database(conf.configuration().getString("database.location")), ws); theServer.start(); } private static File getConfigFile() { return new File(System.getProperty(NEO_CONFIGDIR_PROPERTY, DEFAULT_NEO_CONFIGDIR)); } public void start() { log.info("Starting Neo Server on port [%s]", webServer.getPort()); try { webServer.start(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { log.info("Neo Server shutdown initiated by kill signal"); shutdown(); } }); } catch (Exception e) { throw new RuntimeException(e); } } public void shutdown() { int portNo = -1; String location = "unknown"; try { if(database != null) { location = database.getLocation(); database.shutdown(); database = null; } if (webServer != null) { portNo = webServer.getPort(); webServer.shutdown(); webServer = null; } configurator = null; log.info("Successfully shutdown Neo Server on port [%d], database [%s]", portNo, location); } catch (Exception e) { log.error("Failed to cleanly shutdown Neo Server on port [%d], database [%s]", portNo, location); throw new RuntimeException(e); } } public GraphDatabaseService database() { return database.db; } public WebServer webServer() { return webServer; } public Configuration configuration() { return configurator.configuration(); } }
package com.braintreepayments.demo; import android.app.ActionBar; import android.app.ActionBar.OnNavigationListener; import android.app.Activity; import android.app.AlertDialog; import android.app.Fragment; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.content.pm.PackageManager; import android.os.Bundle; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.text.TextUtils; import android.view.Menu; import android.view.MenuItem; import android.widget.ArrayAdapter; import com.braintreepayments.api.BraintreeFragment; import com.braintreepayments.api.PaymentButton; import com.braintreepayments.api.interfaces.BraintreeCancelListener; import com.braintreepayments.api.interfaces.BraintreeErrorListener; import com.braintreepayments.api.interfaces.PaymentMethodNonceCreatedListener; import com.braintreepayments.api.internal.SignatureVerificationOverrides; import com.braintreepayments.api.models.PaymentMethodNonce; import com.braintreepayments.demo.internal.LogReporting; import com.braintreepayments.demo.models.ClientToken; import com.paypal.android.sdk.onetouch.core.PayPalOneTouchCore; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import retrofit.Callback; import retrofit.RetrofitError; import retrofit.client.Response; import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; @SuppressWarnings("deprecation") public abstract class BaseActivity extends Activity implements ActivityCompat.OnRequestPermissionsResultCallback, PaymentMethodNonceCreatedListener, BraintreeCancelListener, BraintreeErrorListener, OnNavigationListener { private static final String KEY_AUTHORIZATION = "com.braintreepayments.demo.KEY_AUTHORIZATION"; protected String mAuthorization; protected String mCustomerId; protected BraintreeFragment mBraintreeFragment; protected Logger mLogger; private boolean mActionBarSetup; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mLogger = LoggerFactory.getLogger(getClass().getSimpleName()); if (savedInstanceState != null && savedInstanceState.containsKey(KEY_AUTHORIZATION)) { mAuthorization = savedInstanceState.getString(KEY_AUTHORIZATION); } } @Override protected void onResume() { super.onResume(); if (!mActionBarSetup) { setupActionBar(); mActionBarSetup = true; } SignatureVerificationOverrides.disableAppSwitchSignatureVerification( Settings.isPayPalSignatureVerificationDisabled(this)); PayPalOneTouchCore.useHardcodedConfig(this, Settings.useHardcodedPayPalConfiguration(this)); if (BuildConfig.DEBUG && ContextCompat.checkSelfPermission(this, WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { ActivityCompat.requestPermissions(this, new String[]{ WRITE_EXTERNAL_STORAGE }, 1); } else { handleAuthorizationState(); } } @Override public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) { super.onRequestPermissionsResult(requestCode, permissions, grantResults); handleAuthorizationState(); } private void handleAuthorizationState() { if (mAuthorization == null || (Settings.useTokenizationKey(this) && !mAuthorization.equals(Settings.getEnvironmentTokenizationKey(this))) || !TextUtils.equals(mCustomerId, Settings.getCustomerId(this))) { performReset(); } else { onAuthorizationFetched(); } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mAuthorization != null) { outState.putString(KEY_AUTHORIZATION, mAuthorization); } } @Override public void onPaymentMethodNonceCreated(PaymentMethodNonce paymentMethodNonce) { mLogger.debug("Payment Method Nonce received: " + paymentMethodNonce.getTypeLabel()); } @Override public void onCancel(int requestCode) { mLogger.debug("Cancel received: " + requestCode); } @Override public void onError(Exception error) { mLogger.debug("Error received (" + error.getClass() + "): " + error.getMessage()); mLogger.debug(error.toString()); showDialog("An error occurred (" + error.getClass() + "): " + error.getMessage()); } private void performReset() { mAuthorization = null; mCustomerId = Settings.getCustomerId(this); Fragment paymentButton = getFragmentManager().findFragmentByTag(PaymentButton.TAG); if (paymentButton != null) { getFragmentManager().beginTransaction().remove(paymentButton).commit(); } if (mBraintreeFragment != null) { getFragmentManager().beginTransaction().remove(mBraintreeFragment).commit(); mBraintreeFragment = null; } reset(); fetchAuthorization(); } protected abstract void reset(); protected abstract void onAuthorizationFetched(); protected void fetchAuthorization() { if (mAuthorization != null) { onAuthorizationFetched(); } else if (Settings.useTokenizationKey(this)) { mAuthorization = Settings.getEnvironmentTokenizationKey(this); onAuthorizationFetched(); } else { DemoApplication.getApiClient(this).getClientToken(Settings.getCustomerId(this), Settings.getThreeDSecureMerchantAccountId(this), new Callback<ClientToken>() { @Override public void success(ClientToken clientToken, Response response) { if (TextUtils.isEmpty(clientToken.getClientToken())) { showDialog("Client token was empty"); } else { mAuthorization = clientToken.getClientToken(); onAuthorizationFetched(); } } @Override public void failure(RetrofitError error) { showDialog("Unable to get a client token. Response Code: " + error.getResponse().getStatus() + " Response body: " + error.getResponse().getBody()); } }); } } protected void showDialog(String message) { new AlertDialog.Builder(this) .setMessage(message) .setPositiveButton(android.R.string.ok, new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }) .show(); } protected void setUpAsBack() { if (getActionBar() != null) { getActionBar().setDisplayHomeAsUpEnabled(true); } } @SuppressWarnings("ConstantConditions") private void setupActionBar() { ActionBar actionBar = getActionBar(); actionBar.setDisplayShowTitleEnabled(false); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST); ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.environments, android.R.layout.simple_spinner_dropdown_item); actionBar.setListNavigationCallbacks(adapter, this); actionBar.setSelectedNavigationItem(Settings.getEnvironment(this)); } @Override public boolean onNavigationItemSelected(int itemPosition, long itemId) { if (Settings.getEnvironment(this) != itemPosition) { Settings.setEnvironment(this, itemPosition); performReset(); } return true; } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); return true; case R.id.reset: performReset(); return true; case R.id.settings: startActivity(new Intent(this, SettingsActivity.class)); return true; case R.id.feedback: new LogReporting(this).collectAndSendLogs(); default: return false; } } }
package com.braintreepayments.demo; import android.content.Intent; import android.os.Bundle; import android.os.Parcelable; import android.view.View; import android.widget.Button; import android.widget.ImageView; import android.widget.TextView; import com.braintreepayments.api.PayPal; import com.braintreepayments.api.dropin.DropInActivity; import com.braintreepayments.api.dropin.DropInRequest; import com.braintreepayments.api.dropin.DropInResult; import com.braintreepayments.api.dropin.utils.PaymentMethodType; import com.braintreepayments.api.models.CardNonce; import com.braintreepayments.api.models.GooglePaymentCardNonce; import com.braintreepayments.api.models.GooglePaymentRequest; import com.braintreepayments.api.models.LocalPaymentResult; import com.braintreepayments.api.models.PayPalAccountNonce; import com.braintreepayments.api.models.PaymentMethodNonce; import com.braintreepayments.api.models.VenmoAccountNonce; import com.braintreepayments.api.models.VisaCheckoutNonce; import com.google.android.gms.wallet.ShippingAddressRequirements; import com.google.android.gms.wallet.TransactionInfo; import com.google.android.gms.wallet.WalletConstants; import java.util.Collections; import static android.view.View.GONE; import static android.view.View.VISIBLE; public class MainActivity extends BaseActivity { static final String EXTRA_PAYMENT_RESULT = "payment_result"; static final String EXTRA_DEVICE_DATA = "device_data"; static final String EXTRA_COLLECT_DEVICE_DATA = "collect_device_data"; private static final int DROP_IN_REQUEST = 1; private static final int GOOGLE_PAYMENT_REQUEST = 2; private static final int CARDS_REQUEST = 3; private static final int PAYPAL_REQUEST = 4; private static final int VENMO_REQUEST = 5; private static final int VISA_CHECKOUT_REQUEST = 6; private static final String KEY_NONCE = "nonce"; private PaymentMethodNonce mNonce; private ImageView mNonceIcon; private TextView mNonceString; private TextView mNonceDetails; private TextView mDeviceData; private Button mDropInButton; private Button mGooglePaymentButton; private Button mCardsButton; private Button mPayPalButton; private Button mVenmoButton; private Button mVisaCheckoutButton; private Button mCreateTransactionButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_activity); mNonceIcon = findViewById(R.id.nonce_icon); mNonceString = findViewById(R.id.nonce); mNonceDetails = findViewById(R.id.nonce_details); mDeviceData = findViewById(R.id.device_data); mDropInButton = findViewById(R.id.drop_in); mGooglePaymentButton = findViewById(R.id.google_payment); mCardsButton = findViewById(R.id.card); mPayPalButton = findViewById(R.id.paypal); mVenmoButton = findViewById(R.id.venmo); mVisaCheckoutButton = findViewById(R.id.visa_checkout); mCreateTransactionButton = findViewById(R.id.create_transaction); if (savedInstanceState != null) { if (savedInstanceState.containsKey(KEY_NONCE)) { mNonce = savedInstanceState.getParcelable(KEY_NONCE); } } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mNonce != null) { outState.putParcelable(KEY_NONCE, mNonce); } } public void launchDropIn(View v) { startActivityForResult(getDropInRequest().getIntent(this), DROP_IN_REQUEST); } public void launchGooglePayment(View v) { Intent intent = new Intent(this, GooglePaymentActivity.class); startActivityForResult(intent, GOOGLE_PAYMENT_REQUEST); } public void launchCards(View v) { Intent intent = new Intent(this, CardActivity.class) .putExtra(EXTRA_COLLECT_DEVICE_DATA, Settings.shouldCollectDeviceData(this)); startActivityForResult(intent, CARDS_REQUEST); } public void launchPayPal(View v) { Intent intent = new Intent(this, PayPalActivity.class) .putExtra(EXTRA_COLLECT_DEVICE_DATA, Settings.shouldCollectDeviceData(this)); startActivityForResult(intent, PAYPAL_REQUEST); } public void launchVenmo(View v) { Intent intent = new Intent(this, VenmoActivity.class); startActivityForResult(intent, VENMO_REQUEST); } public void launchVisaCheckout(View v) { Intent intent = new Intent(this, VisaCheckoutActivity.class); startActivityForResult(intent, VISA_CHECKOUT_REQUEST); } private DropInRequest getDropInRequest() { GooglePaymentRequest googlePaymentRequest = new GooglePaymentRequest() .transactionInfo(TransactionInfo.newBuilder() .setCurrencyCode(Settings.getGooglePaymentCurrency(this)) .setTotalPrice("1.00") .setTotalPriceStatus(WalletConstants.TOTAL_PRICE_STATUS_FINAL) .build()) .allowPrepaidCards(Settings.areGooglePaymentPrepaidCardsAllowed(this)) .billingAddressFormat(WalletConstants.BILLING_ADDRESS_FORMAT_FULL) .billingAddressRequired(Settings.isGooglePaymentBillingAddressRequired(this)) .emailRequired(Settings.isGooglePaymentEmailRequired(this)) .phoneNumberRequired(Settings.isGooglePaymentPhoneNumberRequired(this)) .shippingAddressRequired(Settings.isGooglePaymentShippingAddressRequired(this)) .shippingAddressRequirements(ShippingAddressRequirements.newBuilder() .addAllowedCountryCodes(Settings.getGooglePaymentAllowedCountriesForShipping(this)) .build()) .googleMerchantId(Settings.getGooglePaymentMerchantId(this)); return new DropInRequest() .amount("1.00") .clientToken(mAuthorization) .collectDeviceData(Settings.shouldCollectDeviceData(this)) .requestThreeDSecureVerification(Settings.isThreeDSecureEnabled(this)) .googlePaymentRequest(googlePaymentRequest); } public void createTransaction(View v) { Intent intent = new Intent(this, CreateTransactionActivity.class) .putExtra(CreateTransactionActivity.EXTRA_PAYMENT_METHOD_NONCE, mNonce); startActivity(intent); mCreateTransactionButton.setEnabled(false); clearNonce(); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { if (requestCode == DROP_IN_REQUEST) { DropInResult result = data.getParcelableExtra(DropInResult.EXTRA_DROP_IN_RESULT); displayNonce(result.getPaymentMethodNonce(), result.getDeviceData()); } else { Parcelable returnedData = data.getParcelableExtra(EXTRA_PAYMENT_RESULT); String deviceData = data.getStringExtra(EXTRA_DEVICE_DATA); if (returnedData instanceof PaymentMethodNonce) { displayNonce((PaymentMethodNonce) returnedData, deviceData); } mCreateTransactionButton.setEnabled(true); } } else if (resultCode != RESULT_CANCELED) { showDialog(((Exception) data.getSerializableExtra(DropInActivity.EXTRA_ERROR)).getMessage()); } } @Override protected void reset() { enableButtons(false); mCreateTransactionButton.setEnabled(false); clearNonce(); } @Override protected void onAuthorizationFetched() { enableButtons(true); } private void displayNonce(PaymentMethodNonce paymentMethodNonce, String deviceData) { mNonce = paymentMethodNonce; mNonceIcon.setImageResource(PaymentMethodType.forType(mNonce).getDrawable()); mNonceIcon.setVisibility(VISIBLE); mNonceString.setText(getString(R.string.nonce_placeholder, mNonce.getNonce())); mNonceString.setVisibility(VISIBLE); String details = ""; if (mNonce instanceof CardNonce) { details = CardActivity.getDisplayString((CardNonce) mNonce); } else if (mNonce instanceof PayPalAccountNonce) { details = PayPalActivity.getDisplayString((PayPalAccountNonce) mNonce); } else if (mNonce instanceof GooglePaymentCardNonce) { details = GooglePaymentActivity.getDisplayString((GooglePaymentCardNonce) mNonce); } else if (mNonce instanceof VisaCheckoutNonce) { details = VisaCheckoutActivity.getDisplayString((VisaCheckoutNonce) mNonce); } else if (mNonce instanceof VenmoAccountNonce) { details = VenmoActivity.getDisplayString((VenmoAccountNonce) mNonce); } else if (mNonce instanceof LocalPaymentResult) { details = LocalPaymentsActivity.getDisplayString((LocalPaymentResult) mNonce); } mNonceDetails.setText(details); mNonceDetails.setVisibility(VISIBLE); mDeviceData.setText(getString(R.string.device_data_placeholder, deviceData)); mDeviceData.setVisibility(VISIBLE); mCreateTransactionButton.setEnabled(true); } private void clearNonce() { mNonceIcon.setVisibility(GONE); mNonceString.setVisibility(GONE); mNonceDetails.setVisibility(GONE); mDeviceData.setVisibility(GONE); mCreateTransactionButton.setEnabled(false); } private void enableButtons(boolean enable) { mDropInButton.setEnabled(enable); mGooglePaymentButton.setEnabled(enable); mCardsButton.setEnabled(enable); mPayPalButton.setEnabled(enable); mVenmoButton.setEnabled(enable); mVisaCheckoutButton.setEnabled(enable); } }
package nl.us2.cloudpelican.stormprocessor; import com.google.gson.JsonObject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Date; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Filter { private final JsonObject obj; private final String id; private final String name; private Pattern pattern; private Matcher matcher; private boolean useIndexOf = false; private final String regexStr; private static final Logger LOG = LoggerFactory.getLogger(Filter.class); public Filter(JsonObject obj) { this.obj = obj; id = obj.get("id").getAsString(); name = obj.get("name").getAsString(); regexStr = obj.get("regex").getAsString(); } public void compileRegex() { // Is this just a word or so to match? if (Pattern.compile("^[A-z0-9_-]+$").matcher(regexStr).matches()) { LOG.debug("Matching with indexOf() enabled for " + regexStr); useIndexOf = true; } // Compile pattern pattern = Pattern.compile(regexStr); } public String Id() { return id; } public boolean isValid() { // ID must be hex UUID (e.g. 1cb4978b-b2e1-44c3-a007-8c0c7fb57e82) if (Id().length() != 36) { return false; } // Is this a temp filter which is old? if (name.startsWith("__tmp__")) { String tsStr = name.substring(7); long ts = Long.parseLong(tsStr); long tsNow = new Date().getTime() / 1000L; int maxHours = 1; long tsMin = tsNow - (maxHours*3600); // after X hours auto deleted if (ts < tsMin) { LOG.info("Filter " + id + " was temporary and is declared invalid after " + maxHours + " hour(s)"); return false; } } return true; } public Matcher Matcher(String msg) { if (matcher == null) { matcher = pattern.matcher(msg); return matcher; } return matcher.reset(msg); } public boolean matches(String msg) { if (useIndexOf) { // Use faster matching (2-30x) first if (!msg.contains(regexStr)) { return false; } } // Regex matching Matcher m = Matcher(msg); boolean b = m.find(); return b; } }
package io.spacedog.model; import java.util.Iterator; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ObjectNode; import io.spacedog.http.SpaceFields; import io.spacedog.utils.Exceptions; import io.spacedog.utils.Json; import io.spacedog.utils.JsonBuilder; public class SchemaTranslator implements SpaceFields, SchemaDirectives, MappingDirectives { private static final ObjectNode STASH = Json.object(m_type, m_object, m_enabled, false); private static final ObjectNode KEYWORD = Json.object(m_type, m_keyword); private static final ObjectNode TIMESTAMP = Json.object(m_type, m_date, m_format, "date_time"); private static final ObjectNode DATE = Json.object(m_type, m_date, m_format, "date"); private static final ObjectNode TIME = Json.object(m_type, m_date, m_format, "hour_minute_second"); private static final ObjectNode BOOLEAN = Json.object(m_type, m_boolean); private static final ObjectNode INTEGER = Json.object(m_type, m_integer, m_coerce, false); private static final ObjectNode LONG = Json.object(m_type, m_long, m_coerce, false); private static final ObjectNode FLOAT = Json.object(m_type, m_float, m_coerce, false); private static final ObjectNode DOUBLE = Json.object(m_type, m_double, m_coerce, false); private static final ObjectNode GEOPOINT = Json.object(m_type, "geo_point"); public static ObjectNode translate(String type, JsonNode schema) { ObjectNode subMapping = toElasticMapping(schema.get(type)); subMapping.set("_meta", schema); return Json.builder().object().add(type, subMapping).build(); } private static ObjectNode toElasticMapping(JsonNode schema) { String type = schema.path(s_type).asText(m_object); String defaultLanguage = language(schema, m_french); ObjectNode propertiesNode = toElasticProperties(schema, defaultLanguage); addMetadataFields(propertiesNode); if (m_object.equals(type)) return Json.builder().object() .add(m_dynamic, m_strict) .add(m_date_detection, false) .add(m_properties, propertiesNode) .object(m_all) .add(m_analyzer, defaultLanguage) .build(); throw Exceptions.illegalArgument("invalid schema root type [%s]", type); } private static void addMetadataFields(ObjectNode propertiesNode) { propertiesNode.set(OWNER_FIELD, KEYWORD); propertiesNode.set(GROUP_FIELD, KEYWORD); propertiesNode.set(CREATED_AT_FIELD, TIMESTAMP); propertiesNode.set(UPDATED_AT_FIELD, TIMESTAMP); } private static ObjectNode toElasticProperties(JsonNode schema, String defaultLanguage) { JsonBuilder<ObjectNode> builder = Json.builder().object(); Iterator<String> fieldNames = schema.fieldNames(); while (fieldNames.hasNext()) { String fieldName = fieldNames.next(); if (fieldName.charAt(0) != '_') { builder.add(fieldName, toElasticProperty( fieldName, schema.get(fieldName), defaultLanguage)); } } return builder.build(); } private static String language(JsonNode schema, String defaultLanguage) { return schema.path(s_language).asText(defaultLanguage); } private static ObjectNode toElasticProperty(String key, JsonNode schema, String defaultLanguage) { String type = schema.path(s_type).asText(m_object); if (s_text.equals(type)) return Json.object(m_type, m_text, m_index, true, m_analyzer, language(schema, defaultLanguage)); else if (s_string.equals(type)) return KEYWORD; else if (s_boolean.equals(type)) return BOOLEAN; else if (s_integer.equals(type)) return INTEGER; else if (s_long.equals(type)) return LONG; else if (s_float.equals(type)) return FLOAT; else if (s_double.equals(type)) return DOUBLE; else if (s_date.equals(type)) return DATE; else if (s_time.equals(type)) return TIME; else if (s_timestamp.equals(type)) return TIMESTAMP; else if (s_enum.equals(type)) return KEYWORD; else if (s_geopoint.equals(type)) return GEOPOINT; else if (m_object.equals(type)) return Json.object(m_type, m_object, m_properties, toElasticProperties(schema, language(schema, defaultLanguage))); else if (s_stash.equals(type)) return STASH; throw Exceptions.illegalArgument("invalid type [%s] for property [%s]", type, key); } }
package com.stripe.android.net; /** * Container class for polling parameters. */ class PollingParameters { private static final long DEFAULT_TIMEOUT_MS = 10000L; private static final long INITIAL_DELAY_MS = 1000; private static final long MAX_DELAY_MS = 15000; private static final int MAX_RETRY_COUNT = 5; private static final long MAX_TIMEOUT_MS = 5L * 60L * 1000L; // five minutes private static final int POLLING_MULTIPLIER = 2; private final long mDefaultTimeoutMs; private final long mInitialDelayMs; private final long mMaxDelayMs; private final int mMaxRetryCount; private final long mMaxTimeoutMs; private final int mPollingMultiplier; PollingParameters( long defaultTimeoutMs, long initialDelayMs, long maxDelayMs, int maxRetryCount, long maxTimeoutMs, int pollingMultiplier) { mDefaultTimeoutMs = defaultTimeoutMs; mInitialDelayMs = initialDelayMs; mMaxDelayMs = maxDelayMs; mMaxRetryCount = maxRetryCount; mMaxTimeoutMs = maxTimeoutMs; mPollingMultiplier = pollingMultiplier; } long getDefaultTimeoutMs() { return mDefaultTimeoutMs; } long getInitialDelayMs() { return mInitialDelayMs; } int getInitialDelayMsInt() { return (int) mInitialDelayMs; } long getMaxDelayMs() { return mMaxDelayMs; } int getMaxRetryCount() { return mMaxRetryCount; } long getMaxTimeoutMs() { return mMaxTimeoutMs; } int getPollingMultiplier() { return mPollingMultiplier; } static PollingParameters generateDefaultParameters() { return new PollingParameters( DEFAULT_TIMEOUT_MS, INITIAL_DELAY_MS, MAX_DELAY_MS, MAX_RETRY_COUNT, MAX_TIMEOUT_MS, POLLING_MULTIPLIER); } }
package cn.cerc.mis.excel.output; import cn.cerc.core.DataSet; import cn.cerc.db.core.LocalConfig; import jxl.Workbook; import jxl.write.WritableSheet; import jxl.write.WritableWorkbook; import jxl.write.WriteException; import org.springframework.context.ApplicationContext; import org.springframework.context.support.FileSystemXmlApplicationContext; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.net.URLEncoder; public class ExportExcel { private static ApplicationContext app; private final static String xmlFile = "classpath:export-excel.xml"; private HttpServletResponse response; private String templateId; private ExcelTemplate template; private Object handle; // false private boolean saveLocal = false; public ExportExcel() { } public ExportExcel(HttpServletResponse response) { this.response = response; } public void export() throws IOException, WriteException, AccreditException { if (this.handle == null) { throw new RuntimeException("handle is null"); } template = this.getTemplate(); IAccreditManager manager = template.getAccreditManager(); if (manager != null) { if (!manager.isPass(this.handle)) { throw new AccreditException(String.format("[%s]", manager.getDescribe())); } } HistoryWriter writer = template.getHistoryWriter(); if (writer != null) { writer.start(this.handle, template); exportDataSet(); writer.finish(this.handle, template); } else { exportDataSet(); } } private void exportDataSet() throws IOException, WriteException { template = this.getTemplate(); WritableWorkbook workbook; OutputStream os = null; if (!saveLocal) { os = response.getOutputStream(); response.reset(); response.setCharacterEncoding("UTF-8"); String fname = URLEncoder.encode(template.getFileName(), "UTF-8"); response.setHeader("Content-Disposition", "attachment;filename=" + fname + ".xls"); response.setContentType("application/msexcel"); workbook = Workbook.createWorkbook(os); } else { String path = LocalConfig.path + "\\" + URLEncoder.encode(template.getFileName(), "UTF-8") + ".xls"; workbook = Workbook.createWorkbook(new File(path)); } WritableSheet sheet = workbook.createSheet("Sheet1", 0); template.output(sheet); workbook.write(); workbook.close(); if (os != null) { os.close(); } } public void export(String message) throws WriteException, IOException { this.setTemplateId("ExportMessage"); DataSet ds = new DataSet(); ds.append(); ds.setField("message_", message); this.getTemplate().setDataSet(ds); exportDataSet(); } public HttpServletResponse getResponse() { return response; } public void setResponse(HttpServletResponse response) { this.response = response; } public ExcelTemplate getTemplate() { if (template == null) { if (getTemplateId() == null) { throw new RuntimeException("templateId is null"); } if (app == null) { app = new FileSystemXmlApplicationContext(xmlFile); } template = app.getBean(getTemplateId(), ExcelTemplate.class); } return template; } public void setTemplate(ExcelTemplate template) { this.template = template; } public String getTemplateId() { return templateId; } public void setTemplateId(String templateId) { this.templateId = templateId; } public Object getHandle() { return handle; } public void setHandle(Object handle) { this.handle = handle; } public void setSaveLocal(boolean saveLocal) { this.saveLocal = saveLocal; } }
package jenkins.security; import hudson.Launcher; import hudson.model.AbstractBuild; import hudson.model.BuildListener; import hudson.model.FreeStyleProject; import hudson.model.JobProperty; import hudson.model.JobPropertyDescriptor; import hudson.slaves.DumbSlave; import org.apache.commons.lang.StringUtils; import org.junit.Rule; import org.junit.Test; import org.junit.runners.model.Statement; import org.jvnet.hudson.test.Issue; import org.jvnet.hudson.test.RestartableJenkinsRule; import org.jvnet.hudson.test.TestExtension; import java.io.IOException; import java.lang.reflect.Field; import java.net.URL; import java.net.URLStreamHandler; import java.util.HashSet; import java.util.Set; import static org.hamcrest.CoreMatchers.containsString; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.not; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertThat; import org.junit.Ignore; public class Security637Test { @Rule public RestartableJenkinsRule rr = new RestartableJenkinsRule(); @Test @Issue("SECURITY-637") public void urlSafeDeserialization_handler_inSameJVMRemotingContext() { rr.addStep(new Statement() { @Override public void evaluate() throws Exception { DumbSlave slave = rr.j.createOnlineSlave(); String unsafeHandlerClassName = slave.getChannel().call(new URLHandlerCallable(new URL("https: assertThat(unsafeHandlerClassName, containsString("SafeURLStreamHandler")); String safeHandlerClassName = slave.getChannel().call(new URLHandlerCallable(new URL("file", null, -1, "", null))); assertThat(safeHandlerClassName, not(containsString("SafeURLStreamHandler"))); } }); } private static class URLHandlerCallable extends MasterToSlaveCallable<String, Exception> { private URL url; public URLHandlerCallable(URL url) { this.url = url; } @Override public String call() throws Exception { Field handlerField = URL.class.getDeclaredField("handler"); handlerField.setAccessible(true); URLStreamHandler handler = (URLStreamHandler) handlerField.get(url); return handler.getClass().getName(); } } @Ignore("TODO these map to different IPs now") @Test @Issue("SECURITY-637") public void urlDnsEquivalence() { rr.addStep(new Statement() { @Override public void evaluate() throws Exception { // due to the DNS resolution they are equal assertEquals( new URL("https://jenkins.io"), new URL("https: ); } }); } @Ignore("TODO these map to different IPs now") @Test @Issue("SECURITY-637") public void urlSafeDeserialization_urlBuiltInAgent_inSameJVMRemotingContext() { rr.addStep(new Statement() { @Override public void evaluate() throws Exception { DumbSlave slave = rr.j.createOnlineSlave(); // we bypass the standard equals method that resolve the hostname assertThat( slave.getChannel().call(new URLBuilderCallable("https://jenkins.io")), not(equalTo( slave.getChannel().call(new URLBuilderCallable("https: )) ); } }); } private static class URLBuilderCallable extends MasterToSlaveCallable<URL, Exception> { private String url; public URLBuilderCallable(String url) { this.url = url; } @Override public URL call() throws Exception { return new URL(url); } } @Ignore("TODO these map to different IPs now") @Test @Issue("SECURITY-637") public void urlSafeDeserialization_urlBuiltInMaster_inSameJVMRemotingContext() { rr.addStep(new Statement() { @Override public void evaluate() throws Exception { DumbSlave slave = rr.j.createOnlineSlave(); // we bypass the standard equals method that resolve the hostname assertThat( slave.getChannel().call(new URLTransferCallable(new URL("https://jenkins.io"))), not(equalTo( slave.getChannel().call(new URLTransferCallable(new URL("https: )) ); // due to the DNS resolution they are equal assertEquals( new URL("https://jenkins.io"), new URL("https: ); } }); } // the URL is serialized / deserialized twice, master => agent and then agent => master private static class URLTransferCallable extends MasterToSlaveCallable<URL, Exception> { private URL url; public URLTransferCallable(URL url) { this.url = url; } @Override public URL call() throws Exception { return url; } } @Test @Issue("SECURITY-637") public void urlSafeDeserialization_inXStreamContext() { rr.addStep(new Statement() { @Override public void evaluate() throws Exception { FreeStyleProject project = rr.j.createFreeStyleProject("project-with-url"); URLJobProperty URLJobProperty = new URLJobProperty( // url to be wrapped new URL("https: // safe url, not required to be wrapped new URL("https", null, -1, "", null) ); project.addProperty(URLJobProperty); project.save(); } }); rr.addStep(new Statement() { @Override public void evaluate() throws Exception { FreeStyleProject project = rr.j.jenkins.getItemByFullName("project-with-url", FreeStyleProject.class); assertNotNull(project); Field handlerField = URL.class.getDeclaredField("handler"); handlerField.setAccessible(true); URLJobProperty urlJobProperty = project.getProperty(URLJobProperty.class); for (URL url : urlJobProperty.urlSet) { URLStreamHandler handler = (URLStreamHandler) handlerField.get(url); if (StringUtils.isEmpty(url.getHost())) { assertThat(handler.getClass().getName(), not(containsString("SafeURLStreamHandler"))); } else { assertThat(handler.getClass().getName(), containsString("SafeURLStreamHandler")); } } } }); } public static class URLJobProperty extends JobProperty<FreeStyleProject> { private Set<URL> urlSet; public URLJobProperty(URL... urls) throws Exception { this.urlSet = new HashSet<>(); for (URL url : urls) { urlSet.add(url); } } @Override public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException { return true; } @TestExtension("urlSafeDeserialization_inXStreamContext") public static class DescriptorImpl extends JobPropertyDescriptor {} } }
package org.jetel.ctl; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.math.BigDecimal; import java.math.BigInteger; import java.math.MathContext; import java.math.RoundingMode; import java.net.URL; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.GregorianCalendar; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Properties; import java.util.Set; import java.util.TimeZone; import junit.framework.AssertionFailedError; import org.jetel.component.CTLRecordTransform; import org.jetel.component.RecordTransform; import org.jetel.data.DataField; import org.jetel.data.DataRecord; import org.jetel.data.DataRecordFactory; import org.jetel.data.SetVal; import org.jetel.data.lookup.LookupTable; import org.jetel.data.lookup.LookupTableFactory; import org.jetel.data.primitive.Decimal; import org.jetel.data.sequence.Sequence; import org.jetel.data.sequence.SequenceFactory; import org.jetel.exception.ComponentNotReadyException; import org.jetel.exception.ConfigurationStatus; import org.jetel.exception.TransformException; import org.jetel.graph.ContextProvider; import org.jetel.graph.ContextProvider.Context; import org.jetel.graph.TransformationGraph; import org.jetel.metadata.DataFieldContainerType; import org.jetel.metadata.DataFieldMetadata; import org.jetel.metadata.DataFieldType; import org.jetel.metadata.DataRecordMetadata; import org.jetel.test.CloverTestCase; import org.jetel.util.MiscUtils; import org.jetel.util.bytes.PackedDecimal; import org.jetel.util.crypto.Base64; import org.jetel.util.crypto.Digest; import org.jetel.util.crypto.Digest.DigestType; import org.jetel.util.primitive.TypedProperties; import org.jetel.util.string.StringUtils; import org.joda.time.DateTime; import org.joda.time.Years; public abstract class CompilerTestCase extends CloverTestCase { protected static final String INPUT_1 = "firstInput"; protected static final String INPUT_2 = "secondInput"; protected static final String INPUT_3 = "thirdInput"; protected static final String INPUT_4 = "multivalueInput"; protected static final String OUTPUT_1 = "firstOutput"; protected static final String OUTPUT_2 = "secondOutput"; protected static final String OUTPUT_3 = "thirdOutput"; protected static final String OUTPUT_4 = "fourthOutput"; protected static final String OUTPUT_5 = "firstMultivalueOutput"; protected static final String OUTPUT_6 = "secondMultivalueOutput"; protected static final String OUTPUT_7 = "thirdMultivalueOutput"; protected static final String LOOKUP = "lookupMetadata"; protected static final String NAME_VALUE = " HELLO "; protected static final Double AGE_VALUE = 20.25; protected static final String CITY_VALUE = "Chong'La"; protected static final Date BORN_VALUE; protected static final Long BORN_MILLISEC_VALUE; static { Calendar c = Calendar.getInstance(); c.set(2008, 12, 25, 13, 25, 55); c.set(Calendar.MILLISECOND, 333); BORN_VALUE = c.getTime(); BORN_MILLISEC_VALUE = c.getTimeInMillis(); } protected static final Integer VALUE_VALUE = Integer.MAX_VALUE - 10; protected static final Boolean FLAG_VALUE = true; protected static final byte[] BYTEARRAY_VALUE = "Abeceda zedla deda".getBytes(); protected static final BigDecimal CURRENCY_VALUE = new BigDecimal("133.525"); protected static final int DECIMAL_PRECISION = 7; protected static final int DECIMAL_SCALE = 3; protected static final int NORMALIZE_RETURN_OK = 0; public static final int DECIMAL_MAX_PRECISION = 32; public static final MathContext MAX_PRECISION = new MathContext(DECIMAL_MAX_PRECISION,RoundingMode.DOWN); /** Flag to trigger Java compilation */ private boolean compileToJava; protected DataRecord[] inputRecords; protected DataRecord[] outputRecords; protected TransformationGraph graph; public CompilerTestCase(boolean compileToJava) { this.compileToJava = compileToJava; } /** * Method to execute tested CTL code in a way specific to testing scenario. * * Assumes that * {@link #graph}, {@link #inputRecords} and {@link #outputRecords} * have already been set. * * @param compiler */ public abstract void executeCode(ITLCompiler compiler); /** * Method which provides access to specified global variable * * @param varName * global variable to be accessed * @return * */ protected abstract Object getVariable(String varName); protected void check(String varName, Object expectedResult) { assertEquals(varName, expectedResult, getVariable(varName)); } protected void checkEquals(String varName1, String varName2) { assertEquals("Comparing " + varName1 + " and " + varName2 + " : ", getVariable(varName1), getVariable(varName2)); } protected void checkNull(String varName) { assertNull(getVariable(varName)); } private void checkArray(String varName, byte[] expected) { byte[] actual = (byte[]) getVariable(varName); assertTrue("Arrays do not match; expected: " + byteArrayAsString(expected) + " but was " + byteArrayAsString(actual), Arrays.equals(actual, expected)); } private static String byteArrayAsString(byte[] array) { final StringBuilder sb = new StringBuilder("["); for (final byte b : array) { sb.append(b); sb.append(", "); } sb.delete(sb.length() - 2, sb.length()); sb.append(']'); return sb.toString(); } @Override protected void setUp() { // set default locale to English to prevent various parsing errors Locale.setDefault(Locale.ENGLISH); initEngine(); } @Override protected void tearDown() throws Exception { super.tearDown(); inputRecords = null; outputRecords = null; graph = null; } protected TransformationGraph createEmptyGraph() { return new TransformationGraph(); } protected TransformationGraph createDefaultGraph() { TransformationGraph g = createEmptyGraph(); // set the context URL, so that imports can be used g.getRuntimeContext().setContextURL(CompilerTestCase.class.getResource(".")); final HashMap<String, DataRecordMetadata> metadataMap = new HashMap<String, DataRecordMetadata>(); metadataMap.put(INPUT_1, createDefaultMetadata(INPUT_1)); metadataMap.put(INPUT_2, createDefaultMetadata(INPUT_2)); metadataMap.put(INPUT_3, createDefaultMetadata(INPUT_3)); metadataMap.put(INPUT_4, createDefaultMultivalueMetadata(INPUT_4)); metadataMap.put(OUTPUT_1, createDefaultMetadata(OUTPUT_1)); metadataMap.put(OUTPUT_2, createDefaultMetadata(OUTPUT_2)); metadataMap.put(OUTPUT_3, createDefaultMetadata(OUTPUT_3)); metadataMap.put(OUTPUT_4, createDefault1Metadata(OUTPUT_4)); metadataMap.put(OUTPUT_5, createDefaultMultivalueMetadata(OUTPUT_5)); metadataMap.put(OUTPUT_6, createDefaultMultivalueMetadata(OUTPUT_6)); metadataMap.put(OUTPUT_7, createDefaultMultivalueMetadata(OUTPUT_7)); metadataMap.put(LOOKUP, createDefaultMetadata(LOOKUP)); g.addDataRecordMetadata(metadataMap); g.addSequence(createDefaultSequence(g, "TestSequence")); g.addLookupTable(createDefaultLookup(g, "TestLookup")); Properties properties = new Properties(); properties.put("PROJECT", "."); properties.put("DATAIN_DIR", "${PROJECT}/data-in"); properties.put("COUNT", "`1+2`"); properties.put("NEWLINE", "\\n"); g.getGraphParameters().setProperties(properties); initDefaultDictionary(g); return g; } private void initDefaultDictionary(TransformationGraph g) { try { g.getDictionary().init(); g.getDictionary().setValue("s", "string", null); g.getDictionary().setValue("i", "integer", null); g.getDictionary().setValue("l", "long", null); g.getDictionary().setValue("d", "decimal", null); g.getDictionary().setValue("n", "number", null); g.getDictionary().setValue("a", "date", null); g.getDictionary().setValue("b", "boolean", null); g.getDictionary().setValue("y", "byte", null); g.getDictionary().setValue("i211", "integer", new Integer(211)); g.getDictionary().setValue("sVerdon", "string", "Verdon"); g.getDictionary().setValue("l452", "long", new Long(452)); g.getDictionary().setValue("d621", "decimal", new BigDecimal(621)); g.getDictionary().setValue("n9342", "number", new Double(934.2)); g.getDictionary().setValue("a1992", "date", new GregorianCalendar(1992, GregorianCalendar.AUGUST, 1).getTime()); g.getDictionary().setValue("bTrue", "boolean", Boolean.TRUE); g.getDictionary().setValue("yFib", "byte", new byte[]{1,2,3,5,8,13,21,34,55,89} ); g.getDictionary().setValue("stringList", "list", Arrays.asList("aa", "bb", null, "cc")); g.getDictionary().setContentType("stringList", "string"); g.getDictionary().setValue("dateList", "list", Arrays.asList(new Date(12000), new Date(34000), null, new Date(56000))); g.getDictionary().setContentType("dateList", "date"); g.getDictionary().setValue("byteList", "list", Arrays.asList(new byte[] {0x12}, new byte[] {0x34, 0x56}, null, new byte[] {0x78})); g.getDictionary().setContentType("byteList", "byte"); } catch (ComponentNotReadyException e) { throw new RuntimeException("Error init default dictionary", e); } } protected Sequence createDefaultSequence(TransformationGraph graph, String name) { Sequence seq = SequenceFactory.createSequence(graph, "PRIMITIVE_SEQUENCE", new Object[] { "Sequence0", graph, name }, new Class[] { String.class, TransformationGraph.class, String.class }); try { seq.checkConfig(new ConfigurationStatus()); seq.init(); } catch (ComponentNotReadyException e) { throw new RuntimeException(e); } return seq; } /** * Creates default lookup table of type SimpleLookupTable with 4 records using default metadata and a composite * lookup key Name+Value. Use field City for testing response. * * @param graph * @param name * @return */ protected LookupTable createDefaultLookup(TransformationGraph graph, String name) { final TypedProperties props = new TypedProperties(); props.setProperty("id", "LookupTable0"); props.setProperty("type", "simpleLookup"); props.setProperty("metadata", LOOKUP); props.setProperty("key", "Name;Value"); props.setProperty("name", name); props.setProperty("keyDuplicates", "true"); /* * The test lookup table is populated from file TestLookup.dat. Alternatively uncomment the populating code * below, however this will most probably break down test_lookup() because free() will wipe away all data and * noone will restore them */ URL dataFile = getClass().getSuperclass().getResource("TestLookup.dat"); if (dataFile == null) { throw new RuntimeException("Unable to populate testing lookup table. File 'TestLookup.dat' not found by classloader"); } props.setProperty("fileURL", dataFile.getFile()); LookupTableFactory.init(); LookupTable lkp = LookupTableFactory.createLookupTable(props); lkp.setGraph(graph); try { lkp.checkConfig(new ConfigurationStatus()); lkp.init(); lkp.preExecute(); } catch (ComponentNotReadyException ex) { throw new RuntimeException(ex); } /*DataRecord lkpRecord = createEmptyRecord(createDefaultMetadata("lookupResponse")); lkpRecord.getField("Name").setValue("Alpha"); lkpRecord.getField("Value").setValue(1); lkpRecord.getField("City").setValue("Andorra la Vella"); lkp.put(lkpRecord); lkpRecord.getField("Name").setValue("Bravo"); lkpRecord.getField("Value").setValue(2); lkpRecord.getField("City").setValue("Bruxelles"); lkp.put(lkpRecord); // duplicate entry lkpRecord.getField("Name").setValue("Charlie"); lkpRecord.getField("Value").setValue(3); lkpRecord.getField("City").setValue("Chamonix"); lkp.put(lkpRecord); lkpRecord.getField("Name").setValue("Charlie"); lkpRecord.getField("Value").setValue(3); lkpRecord.getField("City").setValue("Chomutov"); lkp.put(lkpRecord);*/ return lkp; } /** * Creates records with default structure * * @param name * name for the record to use * @return metadata with default structure */ protected DataRecordMetadata createDefaultMetadata(String name) { DataRecordMetadata ret = new DataRecordMetadata(name); ret.addField(new DataFieldMetadata("Name", DataFieldType.STRING, "|")); ret.addField(new DataFieldMetadata("Age", DataFieldType.NUMBER, "|")); ret.addField(new DataFieldMetadata("City", DataFieldType.STRING, "|")); DataFieldMetadata dateField = new DataFieldMetadata("Born", DataFieldType.DATE, "|"); dateField.setFormatStr("yyyy-MM-dd HH:mm:ss"); ret.addField(dateField); ret.addField(new DataFieldMetadata("BornMillisec", DataFieldType.LONG, "|")); ret.addField(new DataFieldMetadata("Value", DataFieldType.INTEGER, "|")); ret.addField(new DataFieldMetadata("Flag", DataFieldType.BOOLEAN, "|")); ret.addField(new DataFieldMetadata("ByteArray", DataFieldType.BYTE, "|")); DataFieldMetadata decimalField = new DataFieldMetadata("Currency", DataFieldType.DECIMAL, "\n"); decimalField.setProperty(DataFieldMetadata.LENGTH_ATTR, String.valueOf(DECIMAL_PRECISION)); decimalField.setProperty(DataFieldMetadata.SCALE_ATTR, String.valueOf(DECIMAL_SCALE)); ret.addField(decimalField); return ret; } /** * Creates records with default structure * * @param name * name for the record to use * @return metadata with default structure */ protected DataRecordMetadata createDefault1Metadata(String name) { DataRecordMetadata ret = new DataRecordMetadata(name); ret.addField(new DataFieldMetadata("Field1", DataFieldType.STRING, "|")); ret.addField(new DataFieldMetadata("Age", DataFieldType.NUMBER, "|")); ret.addField(new DataFieldMetadata("City", DataFieldType.STRING, "|")); return ret; } /** * Creates records with default structure * containing multivalue fields. * * @param name * name for the record to use * @return metadata with default structure */ protected DataRecordMetadata createDefaultMultivalueMetadata(String name) { DataRecordMetadata ret = new DataRecordMetadata(name); DataFieldMetadata stringListField = new DataFieldMetadata("stringListField", DataFieldType.STRING, "|"); stringListField.setContainerType(DataFieldContainerType.LIST); ret.addField(stringListField); DataFieldMetadata dateField = new DataFieldMetadata("dateField", DataFieldType.DATE, "|"); ret.addField(dateField); DataFieldMetadata byteField = new DataFieldMetadata("byteField", DataFieldType.BYTE, "|"); ret.addField(byteField); DataFieldMetadata dateListField = new DataFieldMetadata("dateListField", DataFieldType.DATE, "|"); dateListField.setContainerType(DataFieldContainerType.LIST); ret.addField(dateListField); DataFieldMetadata byteListField = new DataFieldMetadata("byteListField", DataFieldType.BYTE, "|"); byteListField.setContainerType(DataFieldContainerType.LIST); ret.addField(byteListField); DataFieldMetadata stringField = new DataFieldMetadata("stringField", DataFieldType.STRING, "|"); ret.addField(stringField); DataFieldMetadata integerMapField = new DataFieldMetadata("integerMapField", DataFieldType.INTEGER, "|"); integerMapField.setContainerType(DataFieldContainerType.MAP); ret.addField(integerMapField); DataFieldMetadata stringMapField = new DataFieldMetadata("stringMapField", DataFieldType.STRING, "|"); stringMapField.setContainerType(DataFieldContainerType.MAP); ret.addField(stringMapField); DataFieldMetadata dateMapField = new DataFieldMetadata("dateMapField", DataFieldType.DATE, "|"); dateMapField.setContainerType(DataFieldContainerType.MAP); ret.addField(dateMapField); DataFieldMetadata byteMapField = new DataFieldMetadata("byteMapField", DataFieldType.BYTE, "|"); byteMapField.setContainerType(DataFieldContainerType.MAP); ret.addField(byteMapField); DataFieldMetadata integerListField = new DataFieldMetadata("integerListField", DataFieldType.INTEGER, "|"); integerListField.setContainerType(DataFieldContainerType.LIST); ret.addField(integerListField); DataFieldMetadata decimalListField = new DataFieldMetadata("decimalListField", DataFieldType.DECIMAL, "|"); decimalListField.setContainerType(DataFieldContainerType.LIST); ret.addField(decimalListField); DataFieldMetadata decimalMapField = new DataFieldMetadata("decimalMapField", DataFieldType.DECIMAL, "|"); decimalMapField.setContainerType(DataFieldContainerType.MAP); ret.addField(decimalMapField); return ret; } protected DataRecord createDefaultMultivalueRecord(DataRecordMetadata dataRecordMetadata) { final DataRecord ret = DataRecordFactory.newRecord(dataRecordMetadata); ret.init(); for (int i = 0; i < ret.getNumFields(); i++) { DataField field = ret.getField(i); DataFieldMetadata fieldMetadata = field.getMetadata(); switch (fieldMetadata.getContainerType()) { case SINGLE: switch (fieldMetadata.getDataType()) { case STRING: field.setValue("John"); break; case DATE: field.setValue(new Date(10000)); break; case BYTE: field.setValue(new byte[] { 0x12, 0x34, 0x56, 0x78 } ); break; default: throw new UnsupportedOperationException("Not implemented."); } break; case LIST: { List<Object> value = new ArrayList<Object>(); switch (fieldMetadata.getDataType()) { case STRING: value.addAll(Arrays.asList("John", "Doe", "Jersey")); break; case INTEGER: value.addAll(Arrays.asList(123, 456, 789)); break; case DATE: value.addAll(Arrays.asList(new Date (12000), new Date(34000))); break; case BYTE: value.addAll(Arrays.asList(new byte[] {0x12, 0x34}, new byte[] {0x56, 0x78})); break; case DECIMAL: value.addAll(Arrays.asList(12.34, 56.78)); break; default: throw new UnsupportedOperationException("Not implemented."); } field.setValue(value); } break; case MAP: { Map<String, Object> value = new HashMap<String, Object>(); switch (fieldMetadata.getDataType()) { case STRING: value.put("firstName", "John"); value.put("lastName", "Doe"); value.put("address", "Jersey"); break; case INTEGER: value.put("count", 123); value.put("max", 456); value.put("sum", 789); break; case DATE: value.put("before", new Date (12000)); value.put("after", new Date(34000)); break; case BYTE: value.put("hash", new byte[] {0x12, 0x34}); value.put("checksum", new byte[] {0x56, 0x78}); break; case DECIMAL: value.put("asset", 12.34); value.put("liability", 56.78); break; default: throw new UnsupportedOperationException("Not implemented."); } field.setValue(value); } break; default: throw new IllegalArgumentException(fieldMetadata.getContainerType().toString()); } } return ret; } protected DataRecord createDefaultRecord(DataRecordMetadata dataRecordMetadata) { final DataRecord ret = DataRecordFactory.newRecord(dataRecordMetadata); ret.init(); SetVal.setString(ret, "Name", NAME_VALUE); SetVal.setDouble(ret, "Age", AGE_VALUE); SetVal.setString(ret, "City", CITY_VALUE); SetVal.setDate(ret, "Born", BORN_VALUE); SetVal.setLong(ret, "BornMillisec", BORN_MILLISEC_VALUE); SetVal.setInt(ret, "Value", VALUE_VALUE); SetVal.setValue(ret, "Flag", FLAG_VALUE); SetVal.setValue(ret, "ByteArray", BYTEARRAY_VALUE); SetVal.setValue(ret, "Currency", CURRENCY_VALUE); return ret; } /** * Allocates new records with structure prescribed by metadata and sets all its fields to <code>null</code> * * @param metadata * structure to use * @return empty record */ protected DataRecord createEmptyRecord(DataRecordMetadata metadata) { DataRecord ret = DataRecordFactory.newRecord(metadata); ret.init(); for (int i = 0; i < ret.getNumFields(); i++) { SetVal.setNull(ret, i); } return ret; } /** * Executes the code using the default graph and records. */ protected void doCompile(String expStr, String testIdentifier) { TransformationGraph graph = createDefaultGraph(); DataRecord[] inRecords = new DataRecord[] { createDefaultRecord(graph.getDataRecordMetadata(INPUT_1)), createDefaultRecord(graph.getDataRecordMetadata(INPUT_2)), createEmptyRecord(graph.getDataRecordMetadata(INPUT_3)), createDefaultMultivalueRecord(graph.getDataRecordMetadata(INPUT_4)) }; DataRecord[] outRecords = new DataRecord[] { createEmptyRecord(graph.getDataRecordMetadata(OUTPUT_1)), createEmptyRecord(graph.getDataRecordMetadata(OUTPUT_2)), createEmptyRecord(graph.getDataRecordMetadata(OUTPUT_3)), createEmptyRecord(graph.getDataRecordMetadata(OUTPUT_4)), createEmptyRecord(graph.getDataRecordMetadata(OUTPUT_5)), createEmptyRecord(graph.getDataRecordMetadata(OUTPUT_6)), createEmptyRecord(graph.getDataRecordMetadata(OUTPUT_7)) }; doCompile(expStr, testIdentifier, graph, inRecords, outRecords); } /** * This method should be used to execute a test with a custom graph and custom input and output records. * * To execute a test with the default graph, * use {@link #doCompile(String)} * or {@link #doCompile(String, String)} instead. * * @param expStr * @param testIdentifier * @param graph * @param inRecords * @param outRecords */ protected void doCompile(String expStr, String testIdentifier, TransformationGraph graph, DataRecord[] inRecords, DataRecord[] outRecords) { this.graph = graph; this.inputRecords = inRecords; this.outputRecords = outRecords; // prepend the compilation mode prefix if (compileToJava) { expStr = "//#CTL2:COMPILE\n" + expStr; } print_code(expStr); DataRecordMetadata[] inMetadata = new DataRecordMetadata[inRecords.length]; for (int i = 0; i < inRecords.length; i++) { inMetadata[i] = inRecords[i].getMetadata(); } DataRecordMetadata[] outMetadata = new DataRecordMetadata[outRecords.length]; for (int i = 0; i < outRecords.length; i++) { outMetadata[i] = outRecords[i].getMetadata(); } ITLCompiler compiler = TLCompilerFactory.createCompiler(graph, inMetadata, outMetadata, "UTF-8"); // try { // System.out.println(compiler.convertToJava(expStr, CTLRecordTransform.class, testIdentifier)); // } catch (ErrorMessageException e) { // System.out.println("Error parsing CTL code. Unable to output Java translation."); List<ErrorMessage> messages = compiler.compile(expStr, CTLRecordTransform.class, testIdentifier); printMessages(messages); if (compiler.errorCount() > 0) { throw new AssertionFailedError("Error in execution. Check standard output for details."); } // CLVFStart parseTree = compiler.getStart(); // parseTree.dump(""); executeCode(compiler); } protected void doCompileExpectError(String expStr, String testIdentifier, List<String> errCodes) { graph = createDefaultGraph(); DataRecordMetadata[] inMetadata = new DataRecordMetadata[] { graph.getDataRecordMetadata(INPUT_1), graph.getDataRecordMetadata(INPUT_2), graph.getDataRecordMetadata(INPUT_3) }; DataRecordMetadata[] outMetadata = new DataRecordMetadata[] { graph.getDataRecordMetadata(OUTPUT_1), graph.getDataRecordMetadata(OUTPUT_2), graph.getDataRecordMetadata(OUTPUT_3), graph.getDataRecordMetadata(OUTPUT_4) }; // prepend the compilation mode prefix if (compileToJava) { expStr = "//#CTL2:COMPILE\n" + expStr; } print_code(expStr); ITLCompiler compiler = TLCompilerFactory.createCompiler(graph, inMetadata, outMetadata, "UTF-8"); List<ErrorMessage> messages = compiler.compile(expStr, CTLRecordTransform.class, testIdentifier); printMessages(messages); if (compiler.errorCount() == 0) { throw new AssertionFailedError("No errors in parsing. Expected " + errCodes.size() + " errors."); } if (compiler.errorCount() != errCodes.size()) { throw new AssertionFailedError(compiler.errorCount() + " errors in code, but expected " + errCodes.size() + " errors."); } Iterator<String> it = errCodes.iterator(); for (ErrorMessage errorMessage : compiler.getDiagnosticMessages()) { String expectedError = it.next(); if (!expectedError.equals(errorMessage.getErrorMessage())) { throw new AssertionFailedError("Error : \'" + compiler.getDiagnosticMessages().get(0).getErrorMessage() + "\', but expected: \'" + expectedError + "\'"); } } // CLVFStart parseTree = compiler.getStart(); // parseTree.dump(""); // executeCode(compiler); } protected void doCompileExpectError(String testIdentifier, String errCode) { doCompileExpectErrors(testIdentifier, Arrays.asList(errCode)); } protected void doCompileExpectErrors(String testIdentifier, List<String> errCodes) { URL importLoc = CompilerTestCase.class.getResource(testIdentifier + ".ctl"); if (importLoc == null) { throw new RuntimeException("Test case '" + testIdentifier + ".ctl" + "' not found"); } final StringBuilder sourceCode = new StringBuilder(); String line = null; try { BufferedReader rd = new BufferedReader(new InputStreamReader(importLoc.openStream())); while ((line = rd.readLine()) != null) { sourceCode.append(line).append("\n"); } rd.close(); } catch (IOException e) { throw new RuntimeException("I/O error occured when reading source file", e); } doCompileExpectError(sourceCode.toString(), testIdentifier, errCodes); } /** * Method loads tested CTL code from a file with the name <code>testIdentifier.ctl</code> The CTL code files should * be stored in the same directory as this class. * * @param Test * identifier defining CTL file to load code from */ protected String loadSourceCode(String testIdentifier) { URL importLoc = CompilerTestCase.class.getResource(testIdentifier + ".ctl"); if (importLoc == null) { throw new RuntimeException("Test case '" + testIdentifier + ".ctl" + "' not found"); } final StringBuilder sourceCode = new StringBuilder(); String line = null; try { BufferedReader rd = new BufferedReader(new InputStreamReader(importLoc.openStream())); while ((line = rd.readLine()) != null) { sourceCode.append(line).append("\n"); } rd.close(); } catch (IOException e) { throw new RuntimeException("I/O error occured when reading source file", e); } return sourceCode.toString(); } /** * Method loads and compiles tested CTL code from a file with the name <code>testIdentifier.ctl</code> The CTL code files should * be stored in the same directory as this class. * * The default graph and records are used for the execution. * * @param Test * identifier defining CTL file to load code from */ protected void doCompile(String testIdentifier) { String sourceCode = loadSourceCode(testIdentifier); doCompile(sourceCode, testIdentifier); } protected void printMessages(List<ErrorMessage> diagnosticMessages) { for (ErrorMessage e : diagnosticMessages) { System.out.println(e); } } /** * Compares two records if they have the same number of fields and identical values in their fields. Does not * consider (or examine) metadata. * * @param lhs * @param rhs * @return true if records have the same number of fields and the same values in them */ protected static boolean recordEquals(DataRecord lhs, DataRecord rhs) { if (lhs == rhs) return true; if (rhs == null) return false; if (lhs == null) { return false; } if (lhs.getNumFields() != rhs.getNumFields()) { return false; } for (int i = 0; i < lhs.getNumFields(); i++) { if (lhs.getField(i).isNull()) { if (!rhs.getField(i).isNull()) { return false; } } else if (!lhs.getField(i).equals(rhs.getField(i))) { return false; } } return true; } public void print_code(String text) { String[] lines = text.split("\n"); System.out.println("\t: 1 2 3 4 5 "); System.out.println("\t:12345678901234567890123456789012345678901234567890123456789"); for (int i = 0; i < lines.length; i++) { System.out.println((i + 1) + "\t:" + lines[i]); } } @SuppressWarnings("unchecked") public void test_operators_unary_record_allowed() { doCompile("test_operators_unary_record_allowed"); check("value", Arrays.asList(14, 16, 16, 65, 63, 63)); check("bornMillisec", Arrays.asList(14L, 16L, 16L, 65L, 63L, 63L)); List<Double> actualAge = (List<Double>) getVariable("age"); double[] expectedAge = {14.123, 16.123, 16.123, 65.789, 63.789, 63.789}; for (int i = 0; i < actualAge.size(); i++) { assertEquals("age[" + i + "]", expectedAge[i], actualAge.get(i), 0.0001); } check("currency", Arrays.asList( new BigDecimal(BigInteger.valueOf(12500), 3), new BigDecimal(BigInteger.valueOf(14500), 3), new BigDecimal(BigInteger.valueOf(14500), 3), new BigDecimal(BigInteger.valueOf(65432), 3), new BigDecimal(BigInteger.valueOf(63432), 3), new BigDecimal(BigInteger.valueOf(63432), 3) )); } @SuppressWarnings("unchecked") public void test_dynamiclib_compare() { doCompile("test_dynamic_compare"); String varName = "compare"; List<Integer> compareResult = (List<Integer>) getVariable(varName); for (int i = 0; i < compareResult.size(); i++) { if ((i % 3) == 0) { assertTrue(varName + "[" + i + "]", compareResult.get(i) > 0); } else if ((i % 3) == 1) { assertEquals(varName + "[" + i + "]", Integer.valueOf(0), compareResult.get(i)); } else if ((i % 3) == 2) { assertTrue(varName + "[" + i + "]", compareResult.get(i) < 0); } } varName = "compareBooleans"; compareResult = (List<Integer>) getVariable(varName); assertEquals(varName + "[0]", Integer.valueOf(0), compareResult.get(0)); assertTrue(varName + "[1]", compareResult.get(1) > 0); assertTrue(varName + "[2]", compareResult.get(2) < 0); assertEquals(varName + "[3]", Integer.valueOf(0), compareResult.get(3)); } public void test_dynamiclib_compare_expect_error(){ try { doCompile("function integer transform(){" + "firstInput myRec; myRec = $out.0; " + "firstOutput myRec2; myRec2 = $out.1;" + "integer i = compare(myRec, 'Flagxx', myRec2, 'Flag'); return 0;}","test_dynamiclib_compare_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "firstInput myRec; myRec = $out.0; " + "firstOutput myRec2; myRec2 = $out.1;" + "integer i = compare(myRec, 'Flag', myRec2, 'Flagxx'); return 0;}","test_dynamiclib_compare_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "firstInput myRec; myRec = null; " + "firstOutput myRec2; myRec2 = $out.1;" + "integer i = compare(myRec, 'Flag', myRec2, 'Flag'); return 0;}","test_dynamiclib_compare_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "firstInput myRec; myRec = null; " + "firstOutput myRec2; myRec2 = null;" + "integer i = compare(myRec, 'Flag', myRec2, 'Flag'); return 0;}","test_dynamiclib_compare_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "firstInput myRec; myRec = $out.1; " + "firstOutput myRec2; myRec2 = null;" + "integer i = compare(myRec, 'Flag', myRec2, 'Flag'); return 0;}","test_dynamiclib_compare_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "$out.0.Flag = true; " + "$out.1.Age = 11;" + "integer i = compare($out.0, 'Flag', $out.1, 'Age'); return 0;}","test_dynamiclib_compare_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "firstInput myRec; myRec = $out.0; " + "firstOutput myRec2; myRec2 = $out.1;" + "integer i = compare(myRec, -1, myRec2, -1 ); return 0;}","test_dynamiclib_compare_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "firstInput myRec; myRec = $out.0; " + "firstOutput myRec2; myRec2 = $out.1;" + "integer i = compare(myRec, 2, myRec2, 2 ); return 0;}","test_dynamiclib_compare_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "$out.0.8 = 12.4d; " + "$out.1.8 = 12.5d;" + "integer i = compare($out.0, 9, $out.1, 9 ); return 0;}","test_dynamiclib_compare_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "$out.0.0 = null; " + "$out.1.0 = null;" + "integer i = compare($out.0, 0, $out.1, 0 ); return 0;}","test_dynamiclib_compare_expect_error"); fail(); } catch (Exception e) { // do nothing } } private void test_dynamic_get_set_loop(String testIdentifier) { doCompile(testIdentifier); check("recordLength", 9); check("value", Arrays.asList(654321, 777777, 654321, 654323, 123456, 112567, 112233)); check("type", Arrays.asList("string", "number", "string", "date", "long", "integer", "boolean", "byte", "decimal")); check("asString", Arrays.asList("1000", "1001.0", "1002", "Thu Jan 01 01:00:01 CET 1970", "1004", "1005", "true", null, "1008.000")); check("isNull", Arrays.asList(false, false, false, false, false, false, false, true, false)); check("fieldName", Arrays.asList("Name", "Age", "City", "Born", "BornMillisec", "Value", "Flag", "ByteArray", "Currency")); Integer[] indices = new Integer[9]; for (int i = 0; i < indices.length; i++) { indices[i] = i; } check("fieldIndex", Arrays.asList(indices)); // check dynamic write and read with all data types check("booleanVar", true); assertTrue("byteVar", Arrays.equals(new BigInteger("1234567890abcdef", 16).toByteArray(), (byte[]) getVariable("byteVar"))); check("decimalVar", new BigDecimal(BigInteger.valueOf(1000125), 3)); check("integerVar", 1000); check("longVar", 1000000000000L); check("numberVar", 1000.5); check("stringVar", "hello"); check("dateVar", new Date(5000)); // null value Boolean[] someValue = new Boolean[graph.getDataRecordMetadata(INPUT_1).getNumFields()]; Arrays.fill(someValue, Boolean.FALSE); check("someValue", Arrays.asList(someValue)); Boolean[] nullValue = new Boolean[graph.getDataRecordMetadata(INPUT_1).getNumFields()]; Arrays.fill(nullValue, Boolean.TRUE); check("nullValue", Arrays.asList(nullValue)); String[] asString2 = new String[graph.getDataRecordMetadata(INPUT_1).getNumFields()]; check("asString2", Arrays.asList(asString2)); Boolean[] isNull2 = new Boolean[graph.getDataRecordMetadata(INPUT_1).getNumFields()]; Arrays.fill(isNull2, Boolean.TRUE); check("isNull2", Arrays.asList(isNull2)); } public void test_dynamic_get_set_loop() { test_dynamic_get_set_loop("test_dynamic_get_set_loop"); } public void test_dynamic_get_set_loop_alternative() { test_dynamic_get_set_loop("test_dynamic_get_set_loop_alternative"); } public void test_dynamic_invalid() { doCompileExpectErrors("test_dynamic_invalid", Arrays.asList( "Input record cannot be assigned to", "Input record cannot be assigned to" )); } public void test_dynamiclib_getBoolValue(){ doCompile("test_dynamiclib_getBoolValue"); check("ret1", true); check("ret2", true); check("ret3", false); check("ret4", false); check("ret5", null); check("ret6", null); } public void test_dynamiclib_getBoolValue_expect_error(){ try { doCompile("function integer transform(){boolean b = getBoolValue($in.0, 2);return 0;}","test_dynamiclib_getBoolValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){boolean b = getBoolValue($in.0, 'Age');return 0;}","test_dynamiclib_getBoolValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){firstInput fi; fi = null; boolean b = getBoolValue(fi, 6); return 0;}","test_dynamiclib_getBoolValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){firstInput fi; fi = null; boolean b = getBoolValue(fi, 'Flag'); return 0;}","test_dynamiclib_getBoolValue_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_getByteValue(){ doCompile("test_dynamiclib_getByteValue"); checkArray("ret1",CompilerTestCase.BYTEARRAY_VALUE); checkArray("ret2",CompilerTestCase.BYTEARRAY_VALUE); check("ret3", null); check("ret4", null); } public void test_dynamiclib_getByteValue_expect_error(){ try { doCompile("function integer transform(){firstInput fi = null; byte b = getByteValue(fi,7); return 0;}","test_dynamiclib_getByteValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){firstInput fi = null; byte b = fi.getByteValue('ByteArray'); return 0;}","test_dynamiclib_getByteValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){byte b = $in.0.getByteValue('Age'); return 0;}","test_dynamiclib_getByteValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){byte b = getByteValue($in.0, 0); return 0;}","test_dynamiclib_getByteValue_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_getDateValue(){ doCompile("test_dynamiclib_getDateValue"); check("ret1", CompilerTestCase.BORN_VALUE); check("ret2", CompilerTestCase.BORN_VALUE); check("ret3", null); check("ret4", null); } public void test_dynamiclib_getDateValue_expect_error(){ try { doCompile("function integer transform(){date d = getDateValue($in.0,1); return 0;}","test_dynamiclib_getDateValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){date d = getDateValue($in.0,'Age'); return 0;}","test_dynamiclib_getDateValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){firstInput fi = null; date d = getDateValue(null,'Born'); return 0;}","test_dynamiclib_getDateValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){firstInput fi = null; date d = getDateValue(null,3); return 0;}","test_dynamiclib_getDateValue_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_getDecimalValue(){ doCompile("test_dynamiclib_getDecimalValue"); check("ret1", CompilerTestCase.CURRENCY_VALUE); check("ret2", CompilerTestCase.CURRENCY_VALUE); check("ret3", null); check("ret4", null); } public void test_dynamiclib_getDecimalValue_expect_error(){ try { doCompile("function integer transform(){decimal d = getDecimalValue($in.0, 1); return 0;}","test_dynamiclib_getDecimalValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){decimal d = getDecimalValue($in.0, 'Age'); return 0;}","test_dynamiclib_getDecimalValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){firstInput fi = null; decimal d = getDecimalValue(fi,8); return 0;}","test_dynamiclib_getDecimalValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){firstInput fi = null; decimal d = getDecimalValue(fi,'Currency'); return 0;}","test_dynamiclib_getDecimalValue_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_getFieldIndex(){ doCompile("test_dynamiclib_getFieldIndex"); check("ret1", 1); check("ret2", 1); check("ret3", -1); } public void test_dynamiclib_getFieldIndex_expect_error(){ try { doCompile("function integer transform(){firstInput fi = null; integer int = fi.getFieldIndex('Age'); return 0;}","test_dynamiclib_getFieldIndex_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_getFieldLabel(){ doCompile("test_dynamiclib_getFieldLabel"); check("ret1", "Age"); check("ret2", "Name"); check("ret3", "Age"); check("ret4", "Value"); } public void test_dynamiclib_getFieldLabel_expect_error(){ try { doCompile("function integer transform(){string name = getFieldLabel($in.0, -5);return 0;}","test_dynamiclib_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string name = getFieldLabel($in.0, 12);return 0;}","test_dynamiclib_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){firstInput fi = null; string name = fi.getFieldLabel(2);return 0;}","test_dynamiclib_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){firstInput fi = null; string name = fi.getFieldLabel('Age');return 0;}","test_dynamiclib_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){firstInput fi = null; string name = fi.getFieldLabel('');return 0;}","test_dynamiclib_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string s = null; firstInput fi = null; string name = fi.getFieldLabel(s);return 0;}","test_dynamiclib_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer s = null; firstInput fi = null; string name = fi.getFieldLabel(s);return 0;}","test_dynamiclib_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string name = getFieldLabel($in.0, 'Tristana');return 0;}","test_dynamiclib_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string s = null; string name = getFieldLabel($in.0, s);return 0;}","test_dynamiclib_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer s = null; string name = getFieldLabel($in.0, s);return 0;}","test_dynamiclib_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string name = getFieldLabel($in.0, '');return 0;}","test_dynamiclib_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_getFieldName(){ doCompile("test_dynamiclib_getFieldName"); check("ret1", "Age"); check("ret2", "Name"); } public void test_dynamiclib_getFieldName_expect_error(){ try { doCompile("function integer transform(){string str = getFieldName($in.0, -5); return 0;}","test_dynamiclib_getFieldName_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string str = getFieldName($in.0, 15); return 0;}","test_dynamiclib_getFieldName_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){firstInput fi = null; string str = fi.getFieldName(2); return 0;}","test_dynamiclib_getFieldName_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_getFieldType(){ doCompile("test_dynamiclib_getFieldType"); check("ret1", "string"); check("ret2", "number"); } public void test_dynamiclib_getFieldType_expect_error(){ try { doCompile("function integer transform(){string str = getFieldType($in.0, -5); return 0;}","test_dynamiclib_getFieldType_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string str = getFieldType($in.0, 12); return 0;}","test_dynamiclib_getFieldType_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){firstInput fi = null; string str = fi.getFieldType(5); return 0;}","test_dynamiclib_getFieldType_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_getIntValue(){ doCompile("test_dynamiclib_getIntValue"); check("ret1", CompilerTestCase.VALUE_VALUE); check("ret2", CompilerTestCase.VALUE_VALUE); check("ret3", CompilerTestCase.VALUE_VALUE); check("ret4", CompilerTestCase.VALUE_VALUE); check("ret5", null); } public void test_dynamiclib_getIntValue_expect_error(){ try { doCompile("function integer transform(){firstInput fi = null; integer i = fi.getIntValue(5); return 0;}","test_dynamiclib_getIntValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer i = getIntValue($in.0, 1); return 0;}","test_dynamiclib_getIntValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer i = getIntValue($in.0, 'Born'); return 0;}","test_dynamiclib_getIntValue_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_getLongValue(){ doCompile("test_dynamiclib_getLongValue"); check("ret1", CompilerTestCase.BORN_MILLISEC_VALUE); check("ret2", CompilerTestCase.BORN_MILLISEC_VALUE); check("ret3", null); } public void test_dynamiclib_getLongValue_expect_error(){ try { doCompile("function integer transform(){firstInput fi = null; long l = getLongValue(fi, 4);return 0;} ","test_dynamiclib_getLongValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long l = getLongValue($in.0, 7);return 0;} ","test_dynamiclib_getLongValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long l = getLongValue($in.0, 'Age');return 0;} ","test_dynamiclib_getLongValue_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_getNumValue(){ doCompile("test_dynamiclib_getNumValue"); check("ret1", CompilerTestCase.AGE_VALUE); check("ret2", CompilerTestCase.AGE_VALUE); check("ret3", null); } public void test_dynamiclib_getNumValue_expectValue(){ try { doCompile("function integer transform(){firstInput fi = null; number n = getNumValue(fi, 1); return 0;}","test_dynamiclib_getNumValue_expectValue"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){number n = getNumValue($in.0, 4); return 0;}","test_dynamiclib_getNumValue_expectValue"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){number n = $in.0.getNumValue('Name'); return 0;}","test_dynamiclib_getNumValue_expectValue"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_getStringValue(){ doCompile("test_dynamiclib_getStringValue"); check("ret1", CompilerTestCase.NAME_VALUE); check("ret2", CompilerTestCase.NAME_VALUE); check("ret3", null); } public void test_dynamiclib_getStringValue_expect_error(){ try { doCompile("function integer transform(){firstInput fi = null; string str = getStringValue(fi, 0); return 0;}","test_dynamiclib_getStringValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string str = getStringValue($in.0, 5); return 0;}","test_dynamiclib_getStringValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string str = $in.0.getStringValue('Age'); return 0;}","test_dynamiclib_getStringValue_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_getValueAsString(){ doCompile("test_dynamiclib_getValueAsString"); check("ret1", " HELLO "); check("ret2", "20.25"); check("ret3", "Chong'La"); check("ret4", "Sun Jan 25 13:25:55 CET 2009"); check("ret5", "1232886355333"); check("ret6", "2147483637"); check("ret7", "true"); check("ret8", "41626563656461207a65646c612064656461"); check("ret9", "133.525"); check("ret10", null); } public void test_dynamiclib_getValueAsString_expect_error(){ try { doCompile("function integer transform(){firstInput fi = null; string str = getValueAsString(fi, 1); return 0;}","test_dynamiclib_getValueAsString_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string str = getValueAsString($in.0, -1); return 0;}","test_dynamiclib_getValueAsString_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string str = $in.0.getValueAsString(10); return 0;}","test_dynamiclib_getValueAsString_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_isNull(){ doCompile("test_dynamiclib_isNull"); check("ret1", false); check("ret2", false); check("ret3", true); } public void test_dynamiclib_isNull_expect_error(){ try { doCompile("function integer transform(){firstInput fi = null; boolean b = fi.isNull(1); return 0;}","test_dynamiclib_isNull_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){boolean b = $in.0.isNull(-5); return 0;}","test_dynamiclib_isNull_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){boolean b = isNull($in.0,12); return 0;}","test_dynamiclib_isNull_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_setBoolValue(){ doCompile("test_dynamiclib_setBoolValue"); check("ret1", null); check("ret2", true); check("ret3", false); } public void test_dynamiclib_setBoolValue_expect_error(){ try { doCompile("function integer transform(){firstInput fi = null; setBoolValue(fi,6,true); return 0;}","test_dynamiclib_setBoolValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){setBoolValue($out.0,1,true); return 0;}","test_dynamiclib_setBoolValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){$out.0.setBoolValue(15,true); return 0;}","test_dynamiclib_setBoolValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){$out.0.setBoolValue(-1,true); return 0;}","test_dynamiclib_setBoolValue_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_setByteValue() throws UnsupportedEncodingException{ doCompile("test_dynamiclib_setByteValue"); checkArray("ret1", "Urgot".getBytes("UTF-8")); check("ret2", null); } public void test_dynamiclib_setByteValue_expect_error(){ try { doCompile("function integer transform(){firstInput fi =null; setByteValue(fi,7,str2byte('Sion', 'utf-8')); return 0;}","test_dynamiclib_setByteValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){setByteValue($out.0, 1, str2byte('Sion', 'utf-8')); return 0;}","test_dynamiclib_setByteValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){setByteValue($out.0, 12, str2byte('Sion', 'utf-8')); return 0;}","test_dynamiclib_setByteValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){$out.0.setByteValue(-2, str2byte('Sion', 'utf-8')); return 0;}","test_dynamiclib_setByteValue_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_setDateValue(){ doCompile("test_dynamiclib_setDateValue"); Calendar cal = Calendar.getInstance(); cal.set(2006,10,12,0,0,0); cal.set(Calendar.MILLISECOND, 0); check("ret1", cal.getTime()); check("ret2", null); } public void test_dynamiclib_setDateValue_expect_error(){ try { doCompile("function integer transform(){firstInput fi = null; setDateValue(fi,'Born', null);return 0;}","test_dynamiclib_setDateValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){setDateValue($out.0,1, null);return 0;}","test_dynamiclib_setDateValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){setDateValue($out.0,-2, null);return 0;}","test_dynamiclib_setDateValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){$out.0.setDateValue(12, null);return 0;}","test_dynamiclib_setDateValue_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_setDecimalValue(){ doCompile("test_dynamiclib_setDecimalValue"); check("ret1", new BigDecimal("12.300")); check("ret2", null); } public void test_dynamiclib_setDecimalValue_expect_error(){ try { doCompile("function integer transform(){firstInput fi = null; setDecimalValue(fi, 'Currency', 12.8d);return 0;}","test_dynamiclib_setDecimalValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){setDecimalValue($out.0, 'Name', 12.8d);return 0;}","test_dynamiclib_setDecimalValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){$out.0.setDecimalValue(-1, 12.8d);return 0;}","test_dynamiclib_setDecimalValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){$out.0.setDecimalValue(15, 12.8d);return 0;}","test_dynamiclib_setDecimalValue_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_setIntValue(){ doCompile("test_dynamiclib_setIntValue"); check("ret1", 90); check("ret2", null); } public void test_dynamiclib_setIntValue_expect_error(){ try { doCompile("function integer transform(){firstInput fi =null; setIntValue(fi,5,null);return 0;}","test_dynamiclib_setIntValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){setIntValue($out.0,4,90);return 0;}","test_dynamiclib_setIntValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){setIntValue($out.0,-2,90);return 0;}","test_dynamiclib_setIntValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){$out.0.setIntValue(15,90);return 0;}","test_dynamiclib_setIntValue_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_setLongValue(){ doCompile("test_dynamiclib_setLongValue"); check("ret1", 1565486L); check("ret2", null); } public void test_dynamiclib_setLongValue_expect_error(){ try { doCompile("function integer transform(){firstInput fi = null; setLongValue(fi, 4, 51231L); return 0;}","test_dynamiclib_setLongValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){setLongValue($out.0, 0, 51231L); return 0;}","test_dynamiclib_setLongValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){setLongValue($out.0, -1, 51231L); return 0;}","test_dynamiclib_setLongValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){$out.0.setLongValue(12, 51231L); return 0;}","test_dynamiclib_setLongValue_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_setNumValue(){ doCompile("test_dynamiclib_setNumValue"); check("ret1", 12.5d); check("ret2", null); } public void test_dynamiclib_setNumValue_expect_error(){ try { doCompile("function integer transform(){firstInput fi = null; setNumValue(fi, 'Age', 15.3); return 0;}","test_dynamiclib_setNumValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){setNumValue($out.0, 'Name', 15.3); return 0;}","test_dynamiclib_setNumValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){setNumValue($out.0, -1, 15.3); return 0;}","test_dynamiclib_setNumValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){$out.0.setNumValue(11, 15.3); return 0;}","test_dynamiclib_setNumValue_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_dynamiclib_setStringValue(){ doCompile("test_dynamiclib_setStringValue"); check("ret1", "Zac"); check("ret2", null); } public void test_dynamiclib_setStringValue_expect_error(){ try { doCompile("function integer transform(){firstInput fi = null; setStringValue(fi, 'Name', 'Draven'); return 0;}","test_dynamiclib_setStringValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){setStringValue($out.0, 'Age', 'Soraka'); return 0;}","test_dynamiclib_setStringValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){setStringValue($out.0, -1, 'Rengar'); return 0;}","test_dynamiclib_setStringValue_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){$out.0.setStringValue(11, 'Vaigar'); return 0;}","test_dynamiclib_setStringValue_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_return_constants() { // test case for issue 2257 System.out.println("Return constants test:"); doCompile("test_return_constants"); check("skip", RecordTransform.SKIP); check("all", RecordTransform.ALL); check("ok", NORMALIZE_RETURN_OK); check("stop", RecordTransform.STOP); } public void test_ambiguous() { // built-in toString function doCompileExpectError("test_ambiguous_toString", "Function 'toString' is ambiguous"); // built-in join function doCompileExpectError("test_ambiguous_join", "Function 'join' is ambiguous"); // locally defined functions doCompileExpectError("test_ambiguous_localFunctions", "Function 'local' is ambiguous"); // locally overloaded built-in getUrlPath() function doCompileExpectError("test_ambiguous_combined", "Function 'getUrlPath' is ambiguous"); // swapped arguments - non null ambiguity doCompileExpectError("test_ambiguous_swapped", "Function 'swapped' is ambiguous"); // primitive type widening; the test depends on specific values of the type distance function, can be removed doCompileExpectError("test_ambiguous_widening", "Function 'widening' is ambiguous"); } public void test_raise_error_terminal() { // test case for issue 2337 doCompile("test_raise_error_terminal"); } public void test_raise_error_nonliteral() { // test case for issue CL-2071 doCompile("test_raise_error_nonliteral"); } public void test_case_unique_check() { // test case for issue 2515 doCompileExpectErrors("test_case_unique_check", Arrays.asList("Duplicate case", "Duplicate case")); } public void test_case_unique_check2() { // test case for issue 2515 doCompileExpectErrors("test_case_unique_check2", Arrays.asList("Duplicate case", "Duplicate case")); } public void test_case_unique_check3() { doCompileExpectError("test_case_unique_check3", "Default case is already defined"); } public void test_rvalue_for_append() { // test case for issue 3956 doCompile("test_rvalue_for_append"); check("a", Arrays.asList("1", "2")); check("b", Arrays.asList("a", "b", "c")); check("c", Arrays.asList("1", "2", "a", "b", "c")); } public void test_rvalue_for_map_append() { // test case for issue 3960 doCompile("test_rvalue_for_map_append"); HashMap<Integer, String> map1instance = new HashMap<Integer, String>(); map1instance.put(1, "a"); map1instance.put(2, "b"); HashMap<Integer, String> map2instance = new HashMap<Integer, String>(); map2instance.put(3, "c"); map2instance.put(4, "d"); HashMap<Integer, String> map3instance = new HashMap<Integer, String>(); map3instance.put(1, "a"); map3instance.put(2, "b"); map3instance.put(3, "c"); map3instance.put(4, "d"); check("map1", map1instance); check("map2", map2instance); check("map3", map3instance); } public void test_global_field_access() { // test case for issue 3957 doCompileExpectError("test_global_field_access", "Unable to access record field in global scope"); } public void test_global_scope() { // test case for issue 5006 doCompile("test_global_scope"); check("len", "Kokon".length()); } //TODO Implement /*public void test_new() { doCompile("test_new"); }*/ public void test_parser() { System.out.println("\nParser test:"); doCompile("test_parser"); } public void test_ref_res_import() { System.out.println("\nSpecial character resolving (import) test:"); URL importLoc = getClass().getSuperclass().getResource("test_ref_res.ctl"); String expStr = "import '" + importLoc + "';\n"; doCompile(expStr, "test_ref_res_import"); } public void test_ref_res_noimport() { System.out.println("\nSpecial character resolving (no import) test:"); doCompile("test_ref_res"); } public void test_import() { System.out.println("\nImport test:"); URL importLoc = getClass().getSuperclass().getResource("import.ctl"); String expStr = "import '" + importLoc + "';\n"; importLoc = getClass().getSuperclass().getResource("other.ctl"); expStr += "import '" + importLoc + "';\n" + "integer sumInt;\n" + "function integer transform() {\n" + " if (a == 3) {\n" + " otherImportVar++;\n" + " }\n" + " sumInt = sum(a, otherImportVar);\n" + " return 0;\n" + "}\n"; doCompile(expStr, "test_import"); } public void test_scope() throws ComponentNotReadyException, TransformException { System.out.println("\nMapping test:"); // String expStr = // "function string computeSomething(int n) {\n" + // " string s = '';\n" + // " do {\n" + // " int i = n--;\n" + // " s = s + '-' + i;\n" + // " } while (n > 0)\n" + // " return s;" + // "function int transform() {\n" + // " printErr(computeSomething(10));\n" + // " return 0;\n" + URL importLoc = getClass().getSuperclass().getResource("samplecode.ctl"); String expStr = "import '" + importLoc + "';\n"; // "function int getIndexOfOffsetStart(string encodedDate) {\n" + // "int offsetStart;\n" + // "int actualLastMinus;\n" + // "int lastMinus = -1;\n" + // "if ( index_of(encodedDate, '+') != -1 )\n" + // " return index_of(encodedDate, '+');\n" + // "do {\n" + // " actualLastMinus = index_of(encodedDate, '-', lastMinus+1);\n" + // " if ( actualLastMinus != -1 )\n" + // " lastMinus = actualLastMinus;\n" + // "} while ( actualLastMinus != -1 )\n" + // "return lastMinus;\n" + // "function int transform() {\n" + // " getIndexOfOffsetStart('2009-04-24T08:00:00-05:00');\n" + // " return 0;\n" + doCompile(expStr, "test_scope"); } public void test_type_void() { doCompileExpectErrors("test_type_void", Arrays.asList("Syntax error on token 'void'", "Variable 'voidVar' is not declared", "Variable 'voidVar' is not declared", "Syntax error on token 'void'")); } public void test_type_integer() { doCompile("test_type_integer"); check("i", 0); check("j", -1); check("field", VALUE_VALUE); checkNull("nullValue"); check("varWithInitializer", 123); checkNull("varWithNullInitializer"); } public void test_type_integer_edge() { String testExpression = "integer minInt;\n"+ "integer maxInt;\n"+ "function integer transform() {\n" + "minInt=" + Integer.MIN_VALUE + ";\n" + "printErr(minInt, true);\n" + "maxInt=" + Integer.MAX_VALUE + ";\n" + "printErr(maxInt, true);\n" + "return 0;\n" + "}\n"; doCompile(testExpression, "test_int_edge"); check("minInt", Integer.MIN_VALUE); check("maxInt", Integer.MAX_VALUE); } public void test_type_long() { doCompile("test_type_long"); check("i", Long.valueOf(0)); check("j", Long.valueOf(-1)); check("field", BORN_MILLISEC_VALUE); check("def", Long.valueOf(0)); checkNull("nullValue"); check("varWithInitializer", 123L); checkNull("varWithNullInitializer"); } public void test_type_long_edge() { String expStr = "long minLong;\n"+ "long maxLong;\n"+ "function integer transform() {\n" + "minLong=" + (Long.MIN_VALUE) + "L;\n" + "printErr(minLong);\n" + "maxLong=" + (Long.MAX_VALUE) + "L;\n" + "printErr(maxLong);\n" + "return 0;\n" + "}\n"; doCompile(expStr,"test_long_edge"); check("minLong", Long.MIN_VALUE); check("maxLong", Long.MAX_VALUE); } public void test_type_decimal() { doCompile("test_type_decimal"); check("i", new BigDecimal(0, MAX_PRECISION)); check("j", new BigDecimal(-1, MAX_PRECISION)); check("field", CURRENCY_VALUE); check("def", new BigDecimal(0, MAX_PRECISION)); checkNull("nullValue"); check("varWithInitializer", new BigDecimal("123.35", MAX_PRECISION)); checkNull("varWithNullInitializer"); check("varWithInitializerNoDist", new BigDecimal(123.35, MAX_PRECISION)); } public void test_type_decimal_edge() { String testExpression = "decimal minLong;\n"+ "decimal maxLong;\n"+ "decimal minLongNoDist;\n"+ "decimal maxLongNoDist;\n"+ "decimal minDouble;\n"+ "decimal maxDouble;\n"+ "decimal minDoubleNoDist;\n"+ "decimal maxDoubleNoDist;\n"+ "function integer transform() {\n" + "minLong=" + String.valueOf(Long.MIN_VALUE) + "d;\n" + "printErr(minLong);\n" + "maxLong=" + String.valueOf(Long.MAX_VALUE) + "d;\n" + "printErr(maxLong);\n" + "minLongNoDist=" + String.valueOf(Long.MIN_VALUE) + "L;\n" + "printErr(minLongNoDist);\n" + "maxLongNoDist=" + String.valueOf(Long.MAX_VALUE) + "L;\n" + "printErr(maxLongNoDist);\n" + // distincter will cause the double-string be parsed into exact representation within BigDecimal "minDouble=" + String.valueOf(Double.MIN_VALUE) + "D;\n" + "printErr(minDouble);\n" + "maxDouble=" + String.valueOf(Double.MAX_VALUE) + "D;\n" + "printErr(maxDouble);\n" + // no distincter will cause the double-string to be parsed into inexact representation within double // then to be assigned into BigDecimal (which will extract only MAX_PRECISION digits) "minDoubleNoDist=" + String.valueOf(Double.MIN_VALUE) + ";\n" + "printErr(minDoubleNoDist);\n" + "maxDoubleNoDist=" + String.valueOf(Double.MAX_VALUE) + ";\n" + "printErr(maxDoubleNoDist);\n" + "return 0;\n" + "}\n"; doCompile(testExpression, "test_decimal_edge"); check("minLong", new BigDecimal(String.valueOf(Long.MIN_VALUE), MAX_PRECISION)); check("maxLong", new BigDecimal(String.valueOf(Long.MAX_VALUE), MAX_PRECISION)); check("minLongNoDist", new BigDecimal(String.valueOf(Long.MIN_VALUE), MAX_PRECISION)); check("maxLongNoDist", new BigDecimal(String.valueOf(Long.MAX_VALUE), MAX_PRECISION)); // distincter will cause the MIN_VALUE to be parsed into exact representation (i.e. 4.9E-324) check("minDouble", new BigDecimal(String.valueOf(Double.MIN_VALUE), MAX_PRECISION)); check("maxDouble", new BigDecimal(String.valueOf(Double.MAX_VALUE), MAX_PRECISION)); // no distincter will cause MIN_VALUE to be parsed into double inexact representation and extraction of // MAX_PRECISION digits (i.e. 4.94065.....E-324) check("minDoubleNoDist", new BigDecimal(Double.MIN_VALUE, MAX_PRECISION)); check("maxDoubleNoDist", new BigDecimal(Double.MAX_VALUE, MAX_PRECISION)); } public void test_type_number() { doCompile("test_type_number"); check("i", Double.valueOf(0)); check("j", Double.valueOf(-1)); check("field", AGE_VALUE); check("def", Double.valueOf(0)); checkNull("nullValue"); checkNull("varWithNullInitializer"); } public void test_type_number_edge() { String testExpression = "number minDouble;\n" + "number maxDouble;\n"+ "function integer transform() {\n" + "minDouble=" + Double.MIN_VALUE + ";\n" + "printErr(minDouble);\n" + "maxDouble=" + Double.MAX_VALUE + ";\n" + "printErr(maxDouble);\n" + "return 0;\n" + "}\n"; doCompile(testExpression, "test_number_edge"); check("minDouble", Double.valueOf(Double.MIN_VALUE)); check("maxDouble", Double.valueOf(Double.MAX_VALUE)); } public void test_type_string() { doCompile("test_type_string"); check("i","0"); check("helloEscaped", "hello\\nworld"); check("helloExpanded", "hello\nworld"); check("fieldName", NAME_VALUE); check("fieldCity", CITY_VALUE); check("escapeChars", "a\u0101\u0102A"); check("doubleEscapeChars", "a\\u0101\\u0102A"); check("specialChars", "špeciálne značky s mäkčeňom môžu byť"); check("dQescapeChars", "a\u0101\u0102A"); //TODO:Is next test correct? check("dQdoubleEscapeChars", "a\\u0101\\u0102A"); check("dQspecialChars", "špeciálne značky s mäkčeňom môžu byť"); check("empty", ""); check("def", ""); checkNull("varWithNullInitializer"); } public void test_type_string_long() { int length = 1000; StringBuilder tmp = new StringBuilder(length); for (int i = 0; i < length; i++) { tmp.append(i % 10); } String testExpression = "string longString;\n" + "function integer transform() {\n" + "longString=\"" + tmp + "\";\n" + "printErr(longString);\n" + "return 0;\n" + "}\n"; doCompile(testExpression, "test_string_long"); check("longString", String.valueOf(tmp)); } public void test_type_date() throws Exception { doCompile("test_type_date"); check("d3", new GregorianCalendar(2006, GregorianCalendar.AUGUST, 1).getTime()); check("d2", new GregorianCalendar(2006, GregorianCalendar.AUGUST, 2, 15, 15, 3).getTime()); check("d1", new GregorianCalendar(2006, GregorianCalendar.JANUARY, 1, 1, 2, 3).getTime()); check("field", BORN_VALUE); checkNull("nullValue"); check("minValue", new GregorianCalendar(1970, GregorianCalendar.JANUARY, 1, 1, 0, 0).getTime()); checkNull("varWithNullInitializer"); // test with a default time zone set on the GraphRuntimeContext Context context = null; try { tearDown(); setUp(); TransformationGraph graph = new TransformationGraph(); graph.getRuntimeContext().setTimeZone("GMT+8"); context = ContextProvider.registerGraph(graph); doCompile("test_type_date"); Calendar calendar = new GregorianCalendar(2006, GregorianCalendar.AUGUST, 2, 15, 15, 3); calendar.setTimeZone(TimeZone.getTimeZone("GMT+8")); check("d2", calendar.getTime()); calendar.set(2006, 0, 1, 1, 2, 3); check("d1", calendar.getTime()); } finally { ContextProvider.unregister(context); } } public void test_type_boolean() { doCompile("test_type_boolean"); check("b1", true); check("b2", false); check("b3", false); checkNull("nullValue"); checkNull("varWithNullInitializer"); } public void test_type_boolean_compare() { doCompileExpectErrors("test_type_boolean_compare", Arrays.asList( "Operator '>' is not defined for types 'boolean' and 'boolean'", "Operator '>=' is not defined for types 'boolean' and 'boolean'", "Operator '<' is not defined for types 'boolean' and 'boolean'", "Operator '<=' is not defined for types 'boolean' and 'boolean'", "Operator '<' is not defined for types 'boolean' and 'boolean'", "Operator '>' is not defined for types 'boolean' and 'boolean'", "Operator '>=' is not defined for types 'boolean' and 'boolean'", "Operator '<=' is not defined for types 'boolean' and 'boolean'")); } public void test_type_list() { doCompile("test_type_list"); check("intList", Arrays.asList(1, 2, 3, 4, 5, 6)); check("intList2", Arrays.asList(1, 2, 3)); check("stringList", Arrays.asList( "first", "replaced", "third", "fourth", "fifth", "sixth", "extra")); check("stringListCopy", Arrays.asList( "first", "second", "third", "fourth", "fifth", "seventh")); check("stringListCopy2", Arrays.asList( "first", "replaced", "third", "fourth", "fifth", "sixth", "extra")); assertTrue(getVariable("stringList") != getVariable("stringListCopy")); assertEquals(getVariable("stringList"), getVariable("stringListCopy2")); assertEquals(Arrays.asList(false, null, true), getVariable("booleanList")); assertDeepEquals(Arrays.asList(new byte[] {(byte) 0xAB}, null), getVariable("byteList")); assertDeepEquals(Arrays.asList(null, new byte[] {(byte) 0xCD}), getVariable("cbyteList")); assertEquals(Arrays.asList(new Date(12000), null, new Date(34000)), getVariable("dateList")); assertEquals(Arrays.asList(null, new BigDecimal(BigInteger.valueOf(1234), 2)), getVariable("decimalList")); assertEquals(Arrays.asList(12, null, 34), getVariable("intList3")); assertEquals(Arrays.asList(12l, null, 98l), getVariable("longList")); assertEquals(Arrays.asList(12.34, null, 56.78), getVariable("numberList")); assertEquals(Arrays.asList("aa", null, "bb"), getVariable("stringList2")); List<?> decimalList2 = (List<?>) getVariable("decimalList2"); for (Object o: decimalList2) { assertTrue(o instanceof BigDecimal); } List<?> intList4 = (List<?>) getVariable("intList4"); Set<Object> intList4Set = new HashSet<Object>(intList4); assertEquals(3, intList4Set.size()); } public void test_type_list_field() { doCompile("test_type_list_field"); check("copyByValueTest1", "2"); check("copyByValueTest2", "test"); } public void test_type_map_field() { doCompile("test_type_map_field"); Integer copyByValueTest1 = (Integer) getVariable("copyByValueTest1"); assertEquals(new Integer(2), copyByValueTest1); Integer copyByValueTest2 = (Integer) getVariable("copyByValueTest2"); assertEquals(new Integer(100), copyByValueTest2); } /** * The structure of the objects must be exactly the same! * * @param o1 * @param o2 */ private static void assertDeepCopy(Object o1, Object o2) { if (o1 instanceof DataRecord) { assertFalse(o1 == o2); DataRecord r1 = (DataRecord) o1; DataRecord r2 = (DataRecord) o2; for (int i = 0; i < r1.getNumFields(); i++) { assertDeepCopy(r1.getField(i).getValue(), r2.getField(i).getValue()); } } else if (o1 instanceof Map) { assertFalse(o1 == o2); Map<?, ?> m1 = (Map<?, ?>) o1; Map<?, ?> m2 = (Map<?, ?>) o2; for (Object key: m1.keySet()) { assertDeepCopy(m1.get(key), m2.get(key)); } } else if (o1 instanceof List) { assertFalse(o1 == o2); List<?> l1 = (List<?>) o1; List<?> l2 = (List<?>) o2; for (int i = 0; i < l1.size(); i++) { assertDeepCopy(l1.get(i), l2.get(i)); } } else if (o1 instanceof Date) { assertFalse(o1 == o2); // } else if (o1 instanceof byte[]) { // not required anymore // assertFalse(o1 == o2); } } /** * The structure of the objects must be exactly the same! * * @param o1 * @param o2 */ private static void assertDeepEquals(Object o1, Object o2) { if ((o1 == null) && (o2 == null)) { return; } assertTrue((o1 == null) == (o2 == null)); if (o1 instanceof DataRecord) { DataRecord r1 = (DataRecord) o1; DataRecord r2 = (DataRecord) o2; assertEquals(r1.getNumFields(), r2.getNumFields()); for (int i = 0; i < r1.getNumFields(); i++) { assertDeepEquals(r1.getField(i).getValue(), r2.getField(i).getValue()); } } else if (o1 instanceof Map) { Map<?, ?> m1 = (Map<?, ?>) o1; Map<?, ?> m2 = (Map<?, ?>) o2; assertTrue(m1.keySet().equals(m2.keySet())); for (Object key: m1.keySet()) { assertDeepEquals(m1.get(key), m2.get(key)); } } else if (o1 instanceof List) { List<?> l1 = (List<?>) o1; List<?> l2 = (List<?>) o2; assertEquals("size", l1.size(), l2.size()); for (int i = 0; i < l1.size(); i++) { assertDeepEquals(l1.get(i), l2.get(i)); } } else if (o1 instanceof byte[]) { byte[] b1 = (byte[]) o1; byte[] b2 = (byte[]) o2; if (b1 != b2) { if (b1 == null || b2 == null) { assertEquals(b1, b2); } assertEquals("length", b1.length, b2.length); for (int i = 0; i < b1.length; i++) { assertEquals(String.format("[%d]", i), b1[i], b2[i]); } } } else if (o1 instanceof CharSequence) { String s1 = ((CharSequence) o1).toString(); String s2 = ((CharSequence) o2).toString(); assertEquals(s1, s2); } else if ((o1 instanceof Decimal) || (o1 instanceof BigDecimal)) { BigDecimal d1 = o1 instanceof Decimal ? ((Decimal) o1).getBigDecimalOutput() : (BigDecimal) o1; BigDecimal d2 = o2 instanceof Decimal ? ((Decimal) o2).getBigDecimalOutput() : (BigDecimal) o2; assertEquals(d1, d2); } else { assertEquals(o1, o2); } } private void check_assignment_deepcopy_variable_declaration() { Date testVariableDeclarationDate1 = (Date) getVariable("testVariableDeclarationDate1"); Date testVariableDeclarationDate2 = (Date) getVariable("testVariableDeclarationDate2"); byte[] testVariableDeclarationByte1 = (byte[]) getVariable("testVariableDeclarationByte1"); byte[] testVariableDeclarationByte2 = (byte[]) getVariable("testVariableDeclarationByte2"); assertDeepEquals(testVariableDeclarationDate1, testVariableDeclarationDate2); assertDeepEquals(testVariableDeclarationByte1, testVariableDeclarationByte2); assertDeepCopy(testVariableDeclarationDate1, testVariableDeclarationDate2); assertDeepCopy(testVariableDeclarationByte1, testVariableDeclarationByte2); } @SuppressWarnings("unchecked") private void check_assignment_deepcopy_array_access_expression() { { // JJTARRAYACCESSEXPRESSION - List List<String> stringListField1 = (List<String>) getVariable("stringListField1"); DataRecord recordInList1 = (DataRecord) getVariable("recordInList1"); List<DataRecord> recordList1 = (List<DataRecord>) getVariable("recordList1"); List<DataRecord> recordList2 = (List<DataRecord>) getVariable("recordList2"); assertDeepEquals(stringListField1, recordInList1.getField("stringListField").getValue()); assertDeepEquals(recordInList1, recordList1.get(0)); assertDeepEquals(recordList1, recordList2); assertDeepCopy(stringListField1, recordInList1.getField("stringListField").getValue()); assertDeepCopy(recordInList1, recordList1.get(0)); assertDeepCopy(recordList1, recordList2); } { // map of records Date testDate1 = (Date) getVariable("testDate1"); Map<Integer, DataRecord> recordMap1 = (Map<Integer, DataRecord>) getVariable("recordMap1"); DataRecord recordInMap1 = (DataRecord) getVariable("recordInMap1"); DataRecord recordInMap2 = (DataRecord) getVariable("recordInMap2"); Map<Integer, DataRecord> recordMap2 = (Map<Integer, DataRecord>) getVariable("recordMap2"); assertDeepEquals(testDate1, recordInMap1.getField("dateField").getValue()); assertDeepEquals(recordInMap1, recordMap1.get(0)); assertDeepEquals(recordInMap2, recordMap1.get(0)); assertDeepEquals(recordMap1, recordMap2); assertDeepCopy(testDate1, recordInMap1.getField("dateField").getValue()); assertDeepCopy(recordInMap1, recordMap1.get(0)); assertDeepCopy(recordInMap2, recordMap1.get(0)); assertDeepCopy(recordMap1, recordMap2); } { // map of dates Map<Integer, Date> dateMap1 = (Map<Integer, Date>) getVariable("dateMap1"); Date date1 = (Date) getVariable("date1"); Date date2 = (Date) getVariable("date2"); assertDeepCopy(date1, dateMap1.get(0)); assertDeepCopy(date2, dateMap1.get(1)); } { // map of byte arrays Map<Integer, byte[]> byteMap1 = (Map<Integer, byte[]>) getVariable("byteMap1"); byte[] byte1 = (byte[]) getVariable("byte1"); byte[] byte2 = (byte[]) getVariable("byte2"); assertDeepCopy(byte1, byteMap1.get(0)); assertDeepCopy(byte2, byteMap1.get(1)); } { // JJTARRAYACCESSEXPRESSION - Function call List<String> testArrayAccessFunctionCallStringList = (List<String>) getVariable("testArrayAccessFunctionCallStringList"); DataRecord testArrayAccessFunctionCall = (DataRecord) getVariable("testArrayAccessFunctionCall"); Map<String, DataRecord> function_call_original_map = (Map<String, DataRecord>) getVariable("function_call_original_map"); Map<String, DataRecord> function_call_copied_map = (Map<String, DataRecord>) getVariable("function_call_copied_map"); List<DataRecord> function_call_original_list = (List<DataRecord>) getVariable("function_call_original_list"); List<DataRecord> function_call_copied_list = (List<DataRecord>) getVariable("function_call_copied_list"); assertDeepEquals(testArrayAccessFunctionCallStringList, testArrayAccessFunctionCall.getField("stringListField").getValue()); assertEquals(1, function_call_original_map.size()); assertEquals(2, function_call_copied_map.size()); assertDeepEquals(Arrays.asList(null, testArrayAccessFunctionCall), function_call_original_list); assertDeepEquals(Arrays.asList(null, testArrayAccessFunctionCall, testArrayAccessFunctionCall), function_call_copied_list); assertDeepEquals(testArrayAccessFunctionCall, function_call_original_map.get("1")); assertDeepEquals(testArrayAccessFunctionCall, function_call_copied_map.get("1")); assertDeepEquals(testArrayAccessFunctionCall, function_call_copied_map.get("2")); assertDeepEquals(testArrayAccessFunctionCall, function_call_original_list.get(1)); assertDeepEquals(testArrayAccessFunctionCall, function_call_copied_list.get(1)); assertDeepEquals(testArrayAccessFunctionCall, function_call_copied_list.get(2)); assertDeepCopy(testArrayAccessFunctionCall, function_call_original_map.get("1")); assertDeepCopy(testArrayAccessFunctionCall, function_call_copied_map.get("1")); assertDeepCopy(testArrayAccessFunctionCall, function_call_copied_map.get("2")); assertDeepCopy(testArrayAccessFunctionCall, function_call_original_list.get(1)); assertDeepCopy(testArrayAccessFunctionCall, function_call_copied_list.get(1)); assertDeepCopy(testArrayAccessFunctionCall, function_call_copied_list.get(2)); } // CLO-1210 { check("stringListNull", Arrays.asList((Object) null)); Map<String, String> stringMapNull = new HashMap<String, String>(); stringMapNull.put("a", null); check("stringMapNull", stringMapNull); } } @SuppressWarnings("unchecked") private void check_assignment_deepcopy_field_access_expression() { // field access Date testFieldAccessDate1 = (Date) getVariable("testFieldAccessDate1"); String testFieldAccessString1 = (String) getVariable("testFieldAccessString1"); List<Date> testFieldAccessDateList1 = (List<Date>) getVariable("testFieldAccessDateList1"); List<String> testFieldAccessStringList1 = (List<String>) getVariable("testFieldAccessStringList1"); Map<String, Date> testFieldAccessDateMap1 = (Map<String, Date>) getVariable("testFieldAccessDateMap1"); Map<String, String> testFieldAccessStringMap1 = (Map<String, String>) getVariable("testFieldAccessStringMap1"); DataRecord testFieldAccessRecord1 = (DataRecord) getVariable("testFieldAccessRecord1"); DataRecord firstMultivalueOutput = outputRecords[4]; DataRecord secondMultivalueOutput = outputRecords[5]; DataRecord thirdMultivalueOutput = outputRecords[6]; assertDeepEquals(testFieldAccessDate1, firstMultivalueOutput.getField("dateField").getValue()); assertDeepEquals(testFieldAccessDate1, ((List<?>) firstMultivalueOutput.getField("dateListField").getValue()).get(0)); assertDeepEquals(testFieldAccessString1, ((List<?>) firstMultivalueOutput.getField("stringListField").getValue()).get(0)); assertDeepEquals(testFieldAccessDate1, ((Map<?, ?>) firstMultivalueOutput.getField("dateMapField").getValue()).get("first")); assertDeepEquals(testFieldAccessString1, ((Map<?, ?>) firstMultivalueOutput.getField("stringMapField").getValue()).get("first")); assertDeepEquals(testFieldAccessDateList1, secondMultivalueOutput.getField("dateListField").getValue()); assertDeepEquals(testFieldAccessStringList1, secondMultivalueOutput.getField("stringListField").getValue()); assertDeepEquals(testFieldAccessDateMap1, secondMultivalueOutput.getField("dateMapField").getValue()); assertDeepEquals(testFieldAccessStringMap1, secondMultivalueOutput.getField("stringMapField").getValue()); assertDeepEquals(testFieldAccessRecord1, thirdMultivalueOutput); assertDeepCopy(testFieldAccessDate1, firstMultivalueOutput.getField("dateField").getValue()); assertDeepCopy(testFieldAccessDate1, ((List<?>) firstMultivalueOutput.getField("dateListField").getValue()).get(0)); assertDeepCopy(testFieldAccessString1, ((List<?>) firstMultivalueOutput.getField("stringListField").getValue()).get(0)); assertDeepCopy(testFieldAccessDate1, ((Map<?, ?>) firstMultivalueOutput.getField("dateMapField").getValue()).get("first")); assertDeepCopy(testFieldAccessString1, ((Map<?, ?>) firstMultivalueOutput.getField("stringMapField").getValue()).get("first")); assertDeepCopy(testFieldAccessDateList1, secondMultivalueOutput.getField("dateListField").getValue()); assertDeepCopy(testFieldAccessStringList1, secondMultivalueOutput.getField("stringListField").getValue()); assertDeepCopy(testFieldAccessDateMap1, secondMultivalueOutput.getField("dateMapField").getValue()); assertDeepCopy(testFieldAccessStringMap1, secondMultivalueOutput.getField("stringMapField").getValue()); assertDeepCopy(testFieldAccessRecord1, thirdMultivalueOutput); } @SuppressWarnings("unchecked") private void check_assignment_deepcopy_member_access_expression() { { // member access - record Date testMemberAccessDate1 = (Date) getVariable("testMemberAccessDate1"); byte[] testMemberAccessByte1 = (byte[]) getVariable("testMemberAccessByte1"); List<Date> testMemberAccessDateList1 = (List<Date>) getVariable("testMemberAccessDateList1"); List<byte[]> testMemberAccessByteList1 = (List<byte[]>) getVariable("testMemberAccessByteList1"); DataRecord testMemberAccessRecord1 = (DataRecord) getVariable("testMemberAccessRecord1"); DataRecord testMemberAccessRecord2 = (DataRecord) getVariable("testMemberAccessRecord2"); assertDeepEquals(testMemberAccessDate1, testMemberAccessRecord1.getField("dateField").getValue()); assertDeepEquals(testMemberAccessByte1, testMemberAccessRecord1.getField("byteField").getValue()); assertDeepEquals(testMemberAccessDate1, ((List<?>) testMemberAccessRecord1.getField("dateListField").getValue()).get(0)); assertDeepEquals(testMemberAccessByte1, ((List<?>) testMemberAccessRecord1.getField("byteListField").getValue()).get(0)); assertDeepEquals(testMemberAccessDateList1, testMemberAccessRecord2.getField("dateListField").getValue()); assertDeepEquals(testMemberAccessByteList1, testMemberAccessRecord2.getField("byteListField").getValue()); assertDeepCopy(testMemberAccessDate1, testMemberAccessRecord1.getField("dateField").getValue()); assertDeepCopy(testMemberAccessByte1, testMemberAccessRecord1.getField("byteField").getValue()); assertDeepCopy(testMemberAccessDate1, ((List<?>) testMemberAccessRecord1.getField("dateListField").getValue()).get(0)); assertDeepCopy(testMemberAccessByte1, ((List<?>) testMemberAccessRecord1.getField("byteListField").getValue()).get(0)); assertDeepCopy(testMemberAccessDateList1, testMemberAccessRecord2.getField("dateListField").getValue()); assertDeepCopy(testMemberAccessByteList1, testMemberAccessRecord2.getField("byteListField").getValue()); } { // member access - record Date testMemberAccessDate1 = (Date) getVariable("testMemberAccessDate1"); byte[] testMemberAccessByte1 = (byte[]) getVariable("testMemberAccessByte1"); List<Date> testMemberAccessDateList1 = (List<Date>) getVariable("testMemberAccessDateList1"); List<byte[]> testMemberAccessByteList1 = (List<byte[]>) getVariable("testMemberAccessByteList1"); DataRecord testMemberAccessRecord1 = (DataRecord) getVariable("testMemberAccessRecord1"); DataRecord testMemberAccessRecord2 = (DataRecord) getVariable("testMemberAccessRecord2"); DataRecord testMemberAccessRecord3 = (DataRecord) getVariable("testMemberAccessRecord3"); assertDeepEquals(testMemberAccessDate1, testMemberAccessRecord1.getField("dateField").getValue()); assertDeepEquals(testMemberAccessByte1, testMemberAccessRecord1.getField("byteField").getValue()); assertDeepEquals(testMemberAccessDate1, ((List<?>) testMemberAccessRecord1.getField("dateListField").getValue()).get(0)); assertDeepEquals(testMemberAccessByte1, ((List<?>) testMemberAccessRecord1.getField("byteListField").getValue()).get(0)); assertDeepEquals(testMemberAccessDateList1, testMemberAccessRecord2.getField("dateListField").getValue()); assertDeepEquals(testMemberAccessByteList1, testMemberAccessRecord2.getField("byteListField").getValue()); assertDeepEquals(testMemberAccessRecord3, testMemberAccessRecord2); assertDeepCopy(testMemberAccessDate1, testMemberAccessRecord1.getField("dateField").getValue()); assertDeepCopy(testMemberAccessByte1, testMemberAccessRecord1.getField("byteField").getValue()); assertDeepCopy(testMemberAccessDate1, ((List<?>) testMemberAccessRecord1.getField("dateListField").getValue()).get(0)); assertDeepCopy(testMemberAccessByte1, ((List<?>) testMemberAccessRecord1.getField("byteListField").getValue()).get(0)); assertDeepCopy(testMemberAccessDateList1, testMemberAccessRecord2.getField("dateListField").getValue()); assertDeepCopy(testMemberAccessByteList1, testMemberAccessRecord2.getField("byteListField").getValue()); assertDeepCopy(testMemberAccessRecord3, testMemberAccessRecord2); // dictionary Date dictionaryDate = (Date) graph.getDictionary().getEntry("a").getValue(); byte[] dictionaryByte = (byte[]) graph.getDictionary().getEntry("y").getValue(); List<String> testMemberAccessStringList1 = (List<String>) getVariable("testMemberAccessStringList1"); List<Date> testMemberAccessDateList2 = (List<Date>) getVariable("testMemberAccessDateList2"); List<byte[]> testMemberAccessByteList2 = (List<byte[]>) getVariable("testMemberAccessByteList2"); List<String> dictionaryStringList = (List<String>) graph.getDictionary().getValue("stringList"); List<Date> dictionaryDateList = (List<Date>) graph.getDictionary().getValue("dateList"); List<byte[]> dictionaryByteList = (List<byte[]>) graph.getDictionary().getValue("byteList"); assertDeepEquals(dictionaryDate, testMemberAccessDate1); assertDeepEquals(dictionaryByte, testMemberAccessByte1); assertDeepEquals(dictionaryStringList, testMemberAccessStringList1); assertDeepEquals(dictionaryDateList, testMemberAccessDateList2); assertDeepEquals(dictionaryByteList, testMemberAccessByteList2); assertDeepCopy(dictionaryDate, testMemberAccessDate1); assertDeepCopy(dictionaryByte, testMemberAccessByte1); assertDeepCopy(dictionaryStringList, testMemberAccessStringList1); assertDeepCopy(dictionaryDateList, testMemberAccessDateList2); assertDeepCopy(dictionaryByteList, testMemberAccessByteList2); // member access - array of records List<DataRecord> testMemberAccessRecordList1 = (List<DataRecord>) getVariable("testMemberAccessRecordList1"); assertDeepEquals(testMemberAccessDate1, testMemberAccessRecordList1.get(0).getField("dateField").getValue()); assertDeepEquals(testMemberAccessByte1, testMemberAccessRecordList1.get(0).getField("byteField").getValue()); assertDeepEquals(testMemberAccessDate1, ((List<Date>) testMemberAccessRecordList1.get(0).getField("dateListField").getValue()).get(0)); assertDeepEquals(testMemberAccessByte1, ((List<byte[]>) testMemberAccessRecordList1.get(0).getField("byteListField").getValue()).get(0)); assertDeepEquals(testMemberAccessDateList1, testMemberAccessRecordList1.get(1).getField("dateListField").getValue()); assertDeepEquals(testMemberAccessByteList1, testMemberAccessRecordList1.get(1).getField("byteListField").getValue()); assertDeepEquals(testMemberAccessRecordList1.get(1), testMemberAccessRecordList1.get(2)); assertDeepCopy(testMemberAccessDate1, testMemberAccessRecordList1.get(0).getField("dateField").getValue()); assertDeepCopy(testMemberAccessByte1, testMemberAccessRecordList1.get(0).getField("byteField").getValue()); assertDeepCopy(testMemberAccessDate1, ((List<Date>) testMemberAccessRecordList1.get(0).getField("dateListField").getValue()).get(0)); assertDeepCopy(testMemberAccessByte1, ((List<byte[]>) testMemberAccessRecordList1.get(0).getField("byteListField").getValue()).get(0)); assertDeepCopy(testMemberAccessDateList1, testMemberAccessRecordList1.get(1).getField("dateListField").getValue()); assertDeepCopy(testMemberAccessByteList1, testMemberAccessRecordList1.get(1).getField("byteListField").getValue()); assertDeepCopy(testMemberAccessRecordList1.get(1), testMemberAccessRecordList1.get(2)); // member access - map of records Map<Integer, DataRecord> testMemberAccessRecordMap1 = (Map<Integer, DataRecord>) getVariable("testMemberAccessRecordMap1"); assertDeepEquals(testMemberAccessDate1, testMemberAccessRecordMap1.get(0).getField("dateField").getValue()); assertDeepEquals(testMemberAccessByte1, testMemberAccessRecordMap1.get(0).getField("byteField").getValue()); assertDeepEquals(testMemberAccessDate1, ((List<Date>) testMemberAccessRecordMap1.get(0).getField("dateListField").getValue()).get(0)); assertDeepEquals(testMemberAccessByte1, ((List<byte[]>) testMemberAccessRecordMap1.get(0).getField("byteListField").getValue()).get(0)); assertDeepEquals(testMemberAccessDateList1, testMemberAccessRecordMap1.get(1).getField("dateListField").getValue()); assertDeepEquals(testMemberAccessByteList1, testMemberAccessRecordMap1.get(1).getField("byteListField").getValue()); assertDeepEquals(testMemberAccessRecordMap1.get(1), testMemberAccessRecordMap1.get(2)); assertDeepCopy(testMemberAccessDate1, testMemberAccessRecordMap1.get(0).getField("dateField").getValue()); assertDeepCopy(testMemberAccessByte1, testMemberAccessRecordMap1.get(0).getField("byteField").getValue()); assertDeepCopy(testMemberAccessDate1, ((List<Date>) testMemberAccessRecordMap1.get(0).getField("dateListField").getValue()).get(0)); assertDeepCopy(testMemberAccessByte1, ((List<byte[]>) testMemberAccessRecordMap1.get(0).getField("byteListField").getValue()).get(0)); assertDeepCopy(testMemberAccessDateList1, testMemberAccessRecordMap1.get(1).getField("dateListField").getValue()); assertDeepCopy(testMemberAccessByteList1, testMemberAccessRecordMap1.get(1).getField("byteListField").getValue()); assertDeepCopy(testMemberAccessRecordMap1.get(1), testMemberAccessRecordMap1.get(2)); } } @SuppressWarnings("unchecked") public void test_assignment_deepcopy() { doCompile("test_assignment_deepcopy"); List<DataRecord> secondRecordList = (List<DataRecord>) getVariable("secondRecordList"); assertEquals("before", secondRecordList.get(0).getField("Name").getValue().toString()); List<DataRecord> firstRecordList = (List<DataRecord>) getVariable("firstRecordList"); assertEquals("after", firstRecordList.get(0).getField("Name").getValue().toString()); check_assignment_deepcopy_variable_declaration(); check_assignment_deepcopy_array_access_expression(); check_assignment_deepcopy_field_access_expression(); check_assignment_deepcopy_member_access_expression(); } public void test_assignment_deepcopy_field_access_expression() { doCompile("test_assignment_deepcopy_field_access_expression"); DataRecord testFieldAccessRecord1 = (DataRecord) getVariable("testFieldAccessRecord1"); DataRecord firstMultivalueOutput = outputRecords[4]; DataRecord secondMultivalueOutput = outputRecords[5]; DataRecord thirdMultivalueOutput = outputRecords[6]; DataRecord multivalueInput = inputRecords[3]; assertDeepEquals(firstMultivalueOutput, testFieldAccessRecord1); assertDeepEquals(secondMultivalueOutput, multivalueInput); assertDeepEquals(thirdMultivalueOutput, secondMultivalueOutput); assertDeepCopy(firstMultivalueOutput, testFieldAccessRecord1); assertDeepCopy(secondMultivalueOutput, multivalueInput); assertDeepCopy(thirdMultivalueOutput, secondMultivalueOutput); } public void test_assignment_array_access_function_call() { doCompile("test_assignment_array_access_function_call"); Map<String, String> originalMap = new HashMap<String, String>(); originalMap.put("a", "b"); Map<String, String> copiedMap = new HashMap<String, String>(originalMap); copiedMap.put("c", "d"); check("originalMap", originalMap); check("copiedMap", copiedMap); } public void test_assignment_array_access_function_call_wrong_type() { doCompileExpectErrors("test_assignment_array_access_function_call_wrong_type", Arrays.asList( "Expression is not a composite type but is resolved to 'string'", "Type mismatch: cannot convert from 'integer' to 'string'", "Cannot convert from 'integer' to string" )); } @SuppressWarnings("unchecked") public void test_assignment_returnvalue() { doCompile("test_assignment_returnvalue"); { List<String> stringList1 = (List<String>) getVariable("stringList1"); List<String> stringList2 = (List<String>) getVariable("stringList2"); List<String> stringList3 = (List<String>) getVariable("stringList3"); List<DataRecord> recordList1 = (List<DataRecord>) getVariable("recordList1"); Map<Integer, DataRecord> recordMap1 = (Map<Integer, DataRecord>) getVariable("recordMap1"); List<String> stringList4 = (List<String>) getVariable("stringList4"); Map<String, Integer> integerMap1 = (Map<String, Integer>) getVariable("integerMap1"); DataRecord record1 = (DataRecord) getVariable("record1"); DataRecord record2 = (DataRecord) getVariable("record2"); DataRecord firstMultivalueOutput = outputRecords[4]; DataRecord secondMultivalueOutput = outputRecords[5]; DataRecord thirdMultivalueOutput = outputRecords[6]; Date dictionaryDate1 = (Date) getVariable("dictionaryDate1"); Date dictionaryDate = (Date) graph.getDictionary().getValue("a"); Date zeroDate = new Date(0); List<String> testReturnValueDictionary2 = (List<String>) getVariable("testReturnValueDictionary2"); List<String> dictionaryStringList = (List<String>) graph.getDictionary().getValue("stringList"); List<String> testReturnValue10 = (List<String>) getVariable("testReturnValue10"); DataRecord testReturnValue11 = (DataRecord) getVariable("testReturnValue11"); List<String> testReturnValue12 = (List<String>) getVariable("testReturnValue12"); List<String> testReturnValue13 = (List<String>) getVariable("testReturnValue13"); Map<Integer, DataRecord> function_call_original_map = (Map<Integer, DataRecord>) getVariable("function_call_original_map"); Map<Integer, DataRecord> function_call_copied_map = (Map<Integer, DataRecord>) getVariable("function_call_copied_map"); DataRecord function_call_map_newrecord = (DataRecord) getVariable("function_call_map_newrecord"); List<DataRecord> function_call_original_list = (List<DataRecord>) getVariable("function_call_original_list"); List<DataRecord> function_call_copied_list = (List<DataRecord>) getVariable("function_call_copied_list"); DataRecord function_call_list_newrecord = (DataRecord) getVariable("function_call_list_newrecord"); // identifier assertFalse(stringList1.isEmpty()); assertTrue(stringList2.isEmpty()); assertTrue(stringList3.isEmpty()); // array access expression - list assertDeepEquals("unmodified", recordList1.get(0).getField("stringField").getValue()); assertDeepEquals("modified", recordList1.get(1).getField("stringField").getValue()); // array access expression - map assertDeepEquals("unmodified", recordMap1.get(0).getField("stringField").getValue()); assertDeepEquals("modified", recordMap1.get(1).getField("stringField").getValue()); // array access expression - function call assertDeepEquals(null, function_call_original_map.get(2)); assertDeepEquals("unmodified", function_call_map_newrecord.getField("stringField")); assertDeepEquals("modified", function_call_copied_map.get(2).getField("stringField")); assertDeepEquals(Arrays.asList(null, function_call_list_newrecord), function_call_original_list); assertDeepEquals("unmodified", function_call_list_newrecord.getField("stringField")); assertDeepEquals("modified", function_call_copied_list.get(2).getField("stringField")); // field access expression assertFalse(stringList4.isEmpty()); assertTrue(((List<?>) firstMultivalueOutput.getField("stringListField").getValue()).isEmpty()); assertFalse(integerMap1.isEmpty()); assertTrue(((Map<?, ?>) firstMultivalueOutput.getField("integerMapField").getValue()).isEmpty()); assertDeepEquals("unmodified", record1.getField("stringField")); assertDeepEquals("modified", secondMultivalueOutput.getField("stringField").getValue()); assertDeepEquals("unmodified", record2.getField("stringField")); assertDeepEquals("modified", thirdMultivalueOutput.getField("stringField").getValue()); // member access expression - dictionary // There is no function that could modify a date // assertEquals(zeroDate, dictionaryDate); // assertFalse(zeroDate.equals(testReturnValueDictionary1)); assertFalse(testReturnValueDictionary2.isEmpty()); assertTrue(dictionaryStringList.isEmpty()); // member access expression - record assertFalse(testReturnValue10.isEmpty()); assertTrue(((List<?>) testReturnValue11.getField("stringListField").getValue()).isEmpty()); // member access expression - list of records assertFalse(testReturnValue12.isEmpty()); assertTrue(((List<?>) recordList1.get(2).getField("stringListField").getValue()).isEmpty()); // member access expression - map of records assertFalse(testReturnValue13.isEmpty()); assertTrue(((List<?>) recordMap1.get(2).getField("stringListField").getValue()).isEmpty()); } } @SuppressWarnings("unchecked") public void test_type_map() { doCompile("test_type_map"); Map<String, Integer> testMap = (Map<String, Integer>) getVariable("testMap"); assertEquals(Integer.valueOf(1), testMap.get("zero")); assertEquals(Integer.valueOf(2), testMap.get("one")); assertEquals(Integer.valueOf(3), testMap.get("two")); assertEquals(Integer.valueOf(4), testMap.get("three")); assertEquals(4, testMap.size()); Map<Date, String> dayInWeek = (Map<Date, String>) getVariable("dayInWeek"); Calendar c = Calendar.getInstance(); c.set(2009, Calendar.MARCH, 2, 0, 0, 0); c.set(Calendar.MILLISECOND, 0); assertEquals("Monday", dayInWeek.get(c.getTime())); Map<Date, String> dayInWeekCopy = (Map<Date, String>) getVariable("dayInWeekCopy"); c.set(2009, Calendar.MARCH, 3, 0, 0, 0); c.set(Calendar.MILLISECOND, 0); assertEquals("Tuesday", ((Map<Date, String>) getVariable("tuesday")).get(c.getTime())); assertEquals("Tuesday", dayInWeekCopy.get(c.getTime())); c.set(2009, Calendar.MARCH, 4, 0, 0, 0); c.set(Calendar.MILLISECOND, 0); assertEquals("Wednesday", ((Map<Date, String>) getVariable("wednesday")).get(c.getTime())); assertEquals("Wednesday", dayInWeekCopy.get(c.getTime())); assertFalse(dayInWeek.equals(dayInWeekCopy)); { Map<?, ?> preservedOrder = (Map<?, ?>) getVariable("preservedOrder"); assertEquals(100, preservedOrder.size()); int i = 0; for (Map.Entry<?, ?> entry: preservedOrder.entrySet()) { assertEquals("key" + i, entry.getKey()); assertEquals("value" + i, entry.getValue()); i++; } } } public void test_type_record_list() { doCompile("test_type_record_list"); check("resultInt", 6); check("resultString", "string"); check("resultInt2", 10); check("resultString2", "string2"); } public void test_type_record_list_global() { doCompile("test_type_record_list_global"); check("resultInt", 6); check("resultString", "string"); check("resultInt2", 10); check("resultString2", "string2"); } public void test_type_record_map() { doCompile("test_type_record_map"); check("resultInt", 6); check("resultString", "string"); check("resultInt2", 10); check("resultString2", "string2"); } public void test_type_record_map_global() { doCompile("test_type_record_map_global"); check("resultInt", 6); check("resultString", "string"); check("resultInt2", 10); check("resultString2", "string2"); } public void test_type_record() { doCompile("test_type_record"); // expected result DataRecord expected = createDefaultRecord(createDefaultMetadata("expected")); // simple copy assertTrue(recordEquals(expected, inputRecords[0])); assertTrue(recordEquals(expected, (DataRecord) getVariable("copy"))); // copy and modify expected.getField("Name").setValue("empty"); expected.getField("Value").setValue(321); Calendar c = Calendar.getInstance(); c.set(1987, Calendar.NOVEMBER, 13, 0, 0, 0); c.set(Calendar.MILLISECOND, 0); expected.getField("Born").setValue(c.getTime()); assertTrue(recordEquals(expected, (DataRecord) getVariable("modified"))); // 2x modified copy expected.getField("Name").setValue("not empty"); assertTrue(recordEquals(expected, (DataRecord)getVariable("modified2"))); // no modification by reference is possible assertTrue(recordEquals(expected, (DataRecord)getVariable("modified3"))); expected.getField("Value").setValue(654321); assertTrue(recordEquals(expected, (DataRecord)getVariable("reference"))); assertTrue(getVariable("modified3") != getVariable("reference")); // output record assertTrue(recordEquals(expected, outputRecords[1])); // null record expected.setToNull(); assertTrue(recordEquals(expected, (DataRecord)getVariable("nullRecord"))); } public void test_variables() { doCompile("test_variables"); check("b1", true); check("b2", true); check("b4", "hi"); check("i", 2); } public void test_operator_plus() { doCompile("test_operator_plus"); check("iplusj", 10 + 100); check("lplusm", Long.valueOf(Integer.MAX_VALUE) + Long.valueOf(Integer.MAX_VALUE / 10)); check("mplusl", getVariable("lplusm")); check("mplusi", Long.valueOf(Integer.MAX_VALUE) + 10); check("iplusm", getVariable("mplusi")); check("nplusm1", Double.valueOf(0.1D + 0.001D)); check("nplusj", Double.valueOf(100 + 0.1D)); check("jplusn", getVariable("nplusj")); check("m1plusm", Double.valueOf(Long.valueOf(Integer.MAX_VALUE) + 0.001d)); check("mplusm1", getVariable("m1plusm")); check("dplusd1", new BigDecimal("0.1", MAX_PRECISION).add(new BigDecimal("0.0001", MAX_PRECISION), MAX_PRECISION)); check("dplusj", new BigDecimal(100, MAX_PRECISION).add(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION)); check("jplusd", getVariable("dplusj")); check("dplusm", new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION).add(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION)); check("mplusd", getVariable("dplusm")); check("dplusn", new BigDecimal("0.1").add(new BigDecimal(0.1D, MAX_PRECISION))); check("nplusd", getVariable("dplusn")); check("spluss1", "hello world"); check("splusj", "hello100"); check("jpluss", "100hello"); check("splusm", "hello" + Long.valueOf(Integer.MAX_VALUE)); check("mpluss", Long.valueOf(Integer.MAX_VALUE) + "hello"); check("splusm1", "hello" + Double.valueOf(0.001D)); check("m1pluss", Double.valueOf(0.001D) + "hello"); check("splusd1", "hello" + new BigDecimal("0.0001")); check("d1pluss", new BigDecimal("0.0001", MAX_PRECISION) + "hello"); } public void test_operator_minus() { doCompile("test_operator_minus"); check("iminusj", 10 - 100); check("lminusm", Long.valueOf(Integer.MAX_VALUE / 10) - Long.valueOf(Integer.MAX_VALUE)); check("mminusi", Long.valueOf(Integer.MAX_VALUE - 10)); check("iminusm", 10 - Long.valueOf(Integer.MAX_VALUE)); check("nminusm1", Double.valueOf(0.1D - 0.001D)); check("nminusj", Double.valueOf(0.1D - 100)); check("jminusn", Double.valueOf(100 - 0.1D)); check("m1minusm", Double.valueOf(0.001D - Long.valueOf(Integer.MAX_VALUE))); check("mminusm1", Double.valueOf(Long.valueOf(Integer.MAX_VALUE) - 0.001D)); check("dminusd1", new BigDecimal("0.1", MAX_PRECISION).subtract(new BigDecimal("0.0001", MAX_PRECISION), MAX_PRECISION)); check("dminusj", new BigDecimal("0.1", MAX_PRECISION).subtract(new BigDecimal(100, MAX_PRECISION), MAX_PRECISION)); check("jminusd", new BigDecimal(100, MAX_PRECISION).subtract(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION)); check("dminusm", new BigDecimal("0.1", MAX_PRECISION).subtract(new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION), MAX_PRECISION)); check("mminusd", new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION).subtract(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION)); check("dminusn", new BigDecimal("0.1", MAX_PRECISION).subtract(new BigDecimal(0.1D, MAX_PRECISION), MAX_PRECISION)); check("nminusd", new BigDecimal(0.1D, MAX_PRECISION).subtract(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION)); } public void test_operator_multiply() { doCompile("test_operator_multiply"); check("itimesj", 10 * 100); check("ltimesm", Long.valueOf(Integer.MAX_VALUE) * (Long.valueOf(Integer.MAX_VALUE / 10))); check("mtimesl", getVariable("ltimesm")); check("mtimesi", Long.valueOf(Integer.MAX_VALUE) * 10); check("itimesm", getVariable("mtimesi")); check("ntimesm1", Double.valueOf(0.1D * 0.001D)); check("ntimesj", Double.valueOf(0.1) * 100); check("jtimesn", getVariable("ntimesj")); check("m1timesm", Double.valueOf(0.001d * Long.valueOf(Integer.MAX_VALUE))); check("mtimesm1", getVariable("m1timesm")); check("dtimesd1", new BigDecimal("0.1", MAX_PRECISION).multiply(new BigDecimal("0.0001", MAX_PRECISION), MAX_PRECISION)); check("dtimesj", new BigDecimal("0.1", MAX_PRECISION).multiply(new BigDecimal(100, MAX_PRECISION))); check("jtimesd", getVariable("dtimesj")); check("dtimesm", new BigDecimal("0.1", MAX_PRECISION).multiply(new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION), MAX_PRECISION)); check("mtimesd", getVariable("dtimesm")); check("dtimesn", new BigDecimal("0.1", MAX_PRECISION).multiply(new BigDecimal(0.1, MAX_PRECISION), MAX_PRECISION)); check("ntimesd", getVariable("dtimesn")); } public void test_operator_divide() { doCompile("test_operator_divide"); check("idividej", 10 / 100); check("ldividem", Long.valueOf(Integer.MAX_VALUE / 10) / Long.valueOf(Integer.MAX_VALUE)); check("mdividei", Long.valueOf(Integer.MAX_VALUE / 10)); check("idividem", 10 / Long.valueOf(Integer.MAX_VALUE)); check("ndividem1", Double.valueOf(0.1D / 0.001D)); check("ndividej", Double.valueOf(0.1D / 100)); check("jdividen", Double.valueOf(100 / 0.1D)); check("m1dividem", Double.valueOf(0.001D / Long.valueOf(Integer.MAX_VALUE))); check("mdividem1", Double.valueOf(Long.valueOf(Integer.MAX_VALUE) / 0.001D)); check("ddivided1", new BigDecimal("0.1", MAX_PRECISION).divide(new BigDecimal("0.0001", MAX_PRECISION), MAX_PRECISION)); check("ddividej", new BigDecimal("0.1", MAX_PRECISION).divide(new BigDecimal(100, MAX_PRECISION), MAX_PRECISION)); check("jdivided", new BigDecimal(100, MAX_PRECISION).divide(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION)); check("ddividem", new BigDecimal("0.1", MAX_PRECISION).divide(new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION), MAX_PRECISION)); check("mdivided", new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION).divide(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION)); check("ddividen", new BigDecimal("0.1", MAX_PRECISION).divide(new BigDecimal(0.1D, MAX_PRECISION), MAX_PRECISION)); check("ndivided", new BigDecimal(0.1D, MAX_PRECISION).divide(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION)); } public void test_operator_modulus() { doCompile("test_operator_modulus"); check("imoduloj", 10 % 100); check("lmodulom", Long.valueOf(Integer.MAX_VALUE / 10) % Long.valueOf(Integer.MAX_VALUE)); check("mmoduloi", Long.valueOf(Integer.MAX_VALUE % 10)); check("imodulom", 10 % Long.valueOf(Integer.MAX_VALUE)); check("nmodulom1", Double.valueOf(0.1D % 0.001D)); check("nmoduloj", Double.valueOf(0.1D % 100)); check("jmodulon", Double.valueOf(100 % 0.1D)); check("m1modulom", Double.valueOf(0.001D % Long.valueOf(Integer.MAX_VALUE))); check("mmodulom1", Double.valueOf(Long.valueOf(Integer.MAX_VALUE) % 0.001D)); check("dmodulod1", new BigDecimal("0.1", MAX_PRECISION).remainder(new BigDecimal("0.0001", MAX_PRECISION), MAX_PRECISION)); check("dmoduloj", new BigDecimal("0.1", MAX_PRECISION).remainder(new BigDecimal(100, MAX_PRECISION), MAX_PRECISION)); check("jmodulod", new BigDecimal(100, MAX_PRECISION).remainder(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION)); check("dmodulom", new BigDecimal("0.1", MAX_PRECISION).remainder(new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION), MAX_PRECISION)); check("mmodulod", new BigDecimal(Long.valueOf(Integer.MAX_VALUE), MAX_PRECISION).remainder(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION)); check("dmodulon", new BigDecimal("0.1", MAX_PRECISION).remainder(new BigDecimal(0.1D, MAX_PRECISION), MAX_PRECISION)); check("nmodulod", new BigDecimal(0.1D, MAX_PRECISION).remainder(new BigDecimal("0.1", MAX_PRECISION), MAX_PRECISION)); } public void test_operators_unary() { doCompile("test_operators_unary"); // postfix operators // int check("intPlusOrig", Integer.valueOf(10)); check("intPlusPlus", Integer.valueOf(10)); check("intPlus", Integer.valueOf(11)); check("intMinusOrig", Integer.valueOf(10)); check("intMinusMinus", Integer.valueOf(10)); check("intMinus", Integer.valueOf(9)); // long check("longPlusOrig", Long.valueOf(10)); check("longPlusPlus", Long.valueOf(10)); check("longPlus", Long.valueOf(11)); check("longMinusOrig", Long.valueOf(10)); check("longMinusMinus", Long.valueOf(10)); check("longMinus", Long.valueOf(9)); // double check("numberPlusOrig", Double.valueOf(10.1)); check("numberPlusPlus", Double.valueOf(10.1)); check("numberPlus", Double.valueOf(11.1)); check("numberMinusOrig", Double.valueOf(10.1)); check("numberMinusMinus", Double.valueOf(10.1)); check("numberMinus", Double.valueOf(9.1)); // decimal check("decimalPlusOrig", new BigDecimal("10.1")); check("decimalPlusPlus", new BigDecimal("10.1")); check("decimalPlus", new BigDecimal("11.1")); check("decimalMinusOrig", new BigDecimal("10.1")); check("decimalMinusMinus", new BigDecimal("10.1")); check("decimalMinus", new BigDecimal("9.1")); // prefix operators // integer check("plusIntOrig", Integer.valueOf(10)); check("plusPlusInt", Integer.valueOf(11)); check("plusInt", Integer.valueOf(11)); check("minusIntOrig", Integer.valueOf(10)); check("minusMinusInt", Integer.valueOf(9)); check("minusInt", Integer.valueOf(9)); check("unaryInt", Integer.valueOf(-10)); // long check("plusLongOrig", Long.valueOf(10)); check("plusPlusLong", Long.valueOf(11)); check("plusLong", Long.valueOf(11)); check("minusLongOrig", Long.valueOf(10)); check("minusMinusLong", Long.valueOf(9)); check("minusLong", Long.valueOf(9)); check("unaryLong", Long.valueOf(-10)); // double check("plusNumberOrig", Double.valueOf(10.1)); check("plusPlusNumber", Double.valueOf(11.1)); check("plusNumber", Double.valueOf(11.1)); check("minusNumberOrig", Double.valueOf(10.1)); check("minusMinusNumber", Double.valueOf(9.1)); check("minusNumber", Double.valueOf(9.1)); check("unaryNumber", Double.valueOf(-10.1)); // decimal check("plusDecimalOrig", new BigDecimal("10.1")); check("plusPlusDecimal", new BigDecimal("11.1")); check("plusDecimal", new BigDecimal("11.1")); check("minusDecimalOrig", new BigDecimal("10.1")); check("minusMinusDecimal", new BigDecimal("9.1")); check("minusDecimal", new BigDecimal("9.1")); check("unaryDecimal", new BigDecimal("-10.1")); // record values assertEquals(101, ((DataRecord) getVariable("plusPlusRecord")).getField("Value").getValue()); assertEquals(101, ((DataRecord) getVariable("recordPlusPlus")).getField("Value").getValue()); assertEquals(101, ((DataRecord) getVariable("modifiedPlusPlusRecord")).getField("Value").getValue()); assertEquals(101, ((DataRecord) getVariable("modifiedRecordPlusPlus")).getField("Value").getValue()); //record as parameter assertEquals(99, ((DataRecord) getVariable("minusMinusRecord")).getField("Value").getValue()); assertEquals(99, ((DataRecord) getVariable("recordMinusMinus")).getField("Value").getValue()); assertEquals(99, ((DataRecord) getVariable("modifiedMinusMinusRecord")).getField("Value").getValue()); assertEquals(99, ((DataRecord) getVariable("modifiedRecordMinusMinus")).getField("Value").getValue()); // logical not check("booleanValue", true); check("negation", false); check("doubleNegation", true); } public void test_operators_unary_record() { doCompileExpectErrors("test_operators_unary_record", Arrays.asList( "Illegal argument to ++/-- operator", "Illegal argument to ++/-- operator", "Illegal argument to ++/-- operator", "Illegal argument to ++/-- operator", "Input record cannot be assigned to", "Input record cannot be assigned to", "Input record cannot be assigned to", "Input record cannot be assigned to" )); } public void test_operator_equal() { doCompile("test_operator_equal"); check("eq0", true); check("eq1", true); check("eq1a", true); check("eq1b", true); check("eq1c", false); check("eq2", true); check("eq3", true); check("eq4", true); check("eq5", true); check("eq6", false); check("eq7", true); check("eq8", false); check("eq9", true); check("eq10", false); check("eq11", true); check("eq12", false); check("eq13", true); check("eq14", false); check("eq15", false); check("eq16", true); check("eq17", false); check("eq18", false); check("eq19", false); // byte check("eq20", true); check("eq21", true); check("eq22", false); check("eq23", false); check("eq24", true); check("eq25", false); check("eq20c", true); check("eq21c", true); check("eq22c", false); check("eq23c", false); check("eq24c", true); check("eq25c", false); check("eq26", true); check("eq27", true); } public void test_operator_non_equal(){ doCompile("test_operator_non_equal"); check("inei", false); check("inej", true); check("jnei", true); check("jnej", false); check("lnei", false); check("inel", false); check("lnej", true); check("jnel", true); check("lnel", false); check("dnei", false); check("ined", false); check("dnej", true); check("jned", true); check("dnel", false); check("lned", false); check("dned", false); check("dned_different_scale", false); } public void test_operator_in() { doCompile("test_operator_in"); check("a", Integer.valueOf(1)); check("haystack", Collections.EMPTY_LIST); check("needle", Integer.valueOf(2)); check("b1", true); check("b2", false); check("h2", Arrays.asList(2.1D, 2.0D, 2.2D)); check("b3", true); check("h3", Arrays.asList("memento", "mori", "memento mori")); check("n3", "memento mori"); check("b4", true); check("ret1", false); check("ret2", true); check("ret3", false); check("ret4", true); check("ret5", false); check("ret6", true); check("ret7", false); check("ret8", true); check("ret9", false); check("ret10", true); check("ret11", false); check("ret12", true); check("ret13", false); check("ret14", true); check("ret15", false); check("ret16", true); check("ret17", false); check("ret18", false); check("ret19", true); check("ret20", false); check("ret21", false); } public void test_operator_in_expect_error(){ try { doCompile("function integer transform(){long[] lList = null; long l = 15l; boolean b = in(l, lList); return 0;}","test_operator_in_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){map[long, long] lMap = null; long l = 15l; boolean b = in(l, lMap); return 0;}","test_operator_in_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_operator_greater_less() { doCompile("test_operator_greater_less"); check("eq1", true); check("eq2", true); check("eq3", true); check("eq4", false); check("eq5", true); check("eq6", false); check("eq7", true); check("eq8", true); check("eq9", true); } public void test_operator_ternary(){ doCompile("test_operator_ternary"); // simple use check("trueValue", true); check("falseValue", false); check("res1", Integer.valueOf(1)); check("res2", Integer.valueOf(2)); // nesting in positive branch check("res3", Integer.valueOf(1)); check("res4", Integer.valueOf(2)); check("res5", Integer.valueOf(3)); // nesting in negative branch check("res6", Integer.valueOf(2)); check("res7", Integer.valueOf(3)); // nesting in both branches check("res8", Integer.valueOf(1)); check("res9", Integer.valueOf(1)); check("res10", Integer.valueOf(2)); check("res11", Integer.valueOf(3)); check("res12", Integer.valueOf(2)); check("res13", Integer.valueOf(4)); check("res14", Integer.valueOf(3)); check("res15", Integer.valueOf(4)); } public void test_operators_logical(){ doCompile("test_operators_logical"); //TODO: please double check this. check("res1", false); check("res2", false); check("res3", true); check("res4", true); check("res5", false); check("res6", false); check("res7", true); check("res8", false); } public void test_regex(){ doCompile("test_regex"); check("eq0", false); check("eq1", true); check("eq2", false); check("eq3", true); check("eq4", false); check("eq5", true); } public void test_if() { doCompile("test_if"); // if with single statement check("cond1", true); check("res1", true); // if with mutliple statements (block) check("cond2", true); check("res21", true); check("res22", true); // else with single statement check("cond3", false); check("res31", false); check("res32", true); // else with multiple statements (block) check("cond4", false); check("res41", false); check("res42", true); check("res43", true); // if with block, else with block check("cond5", false); check("res51", false); check("res52", false); check("res53", true); check("res54", true); // else-if with single statement check("cond61", false); check("cond62", true); check("res61", false); check("res62", true); // else-if with multiple statements check("cond71", false); check("cond72", true); check("res71", false); check("res72", true); check("res73", true); // if-elseif-else test check("cond81", false); check("cond82", false); check("res81", false); check("res82", false); check("res83", true); // if with single statement + inactive else check("cond9", true); check("res91", true); check("res92", false); // if with multiple statements + inactive else with block check("cond10", true); check("res101", true); check("res102", true); check("res103", false); check("res104", false); // if with condition check("i", 0); check("j", 1); check("res11", true); } public void test_switch() { doCompile("test_switch"); // simple switch check("cond1", 1); check("res11", false); check("res12", true); check("res13", false); // switch, no break check("cond2", 1); check("res21", false); check("res22", true); check("res23", true); // default branch check("cond3", 3); check("res31", false); check("res32", false); check("res33", true); // no default branch => no match check("cond4", 3); check("res41", false); check("res42", false); check("res43", false); // multiple statements in a single case-branch check("cond5", 1); check("res51", false); check("res52", true); check("res53", true); check("res54", false); // single statement shared by several case labels check("cond6", 1); check("res61", false); check("res62", true); check("res63", true); check("res64", false); check("res71", "default case"); check("res72", "null case"); check("res73", "null case"); check("res74", "default case"); } public void test_int_switch(){ doCompile("test_int_switch"); // simple switch check("cond1", 1); check("res11", true); check("res12", false); check("res13", false); // first case is not followed by a break check("cond2", 1); check("res21", true); check("res22", true); check("res23", false); // first and second case have multiple labels check("cond3", 12); check("res31", false); check("res32", true); check("res33", false); // first and second case have multiple labels and no break after first group check("cond4", 11); check("res41", true); check("res42", true); check("res43", false); // default case intermixed with other case labels in the second group check("cond5", 11); check("res51", true); check("res52", true); check("res53", true); // default case intermixed, with break check("cond6", 16); check("res61", false); check("res62", true); check("res63", false); // continue test check("res7", Arrays.asList( false, false, false, true, true, false, true, true, false, false, true, false, false, true, false, false, false, true)); // return test check("res8", Arrays.asList("0123", "123", "23", "3", "4", "3")); } public void test_non_int_switch(){ doCompile("test_non_int_switch"); // simple switch check("cond1", "1"); check("res11", true); check("res12", false); check("res13", false); // first case is not followed by a break check("cond2", "1"); check("res21", true); check("res22", true); check("res23", false); // first and second case have multiple labels check("cond3", "12"); check("res31", false); check("res32", true); check("res33", false); // first and second case have multiple labels and no break after first group check("cond4", "11"); check("res41", true); check("res42", true); check("res43", false); // default case intermixed with other case labels in the second group check("cond5", "11"); check("res51", true); check("res52", true); check("res53", true); // default case intermixed, with break check("cond6", "16"); check("res61", false); check("res62", true); check("res63", false); // continue test check("res7", Arrays.asList( false, false, false, true, true, false, true, true, false, false, true, false, false, true, false, false, false, true)); // return test check("res8", Arrays.asList("0123", "123", "23", "3", "4", "3")); } public void test_while() { doCompile("test_while"); // simple while check("res1", Arrays.asList(0, 1, 2)); // continue check("res2", Arrays.asList(0, 2)); // break check("res3", Arrays.asList(0)); } public void test_do_while() { doCompile("test_do_while"); // simple while check("res1", Arrays.asList(0, 1, 2)); // continue check("res2", Arrays.asList(0, null, 2)); // break check("res3", Arrays.asList(0)); } public void test_for() { doCompile("test_for"); // simple loop check("res1", Arrays.asList(0,1,2)); // continue check("res2", Arrays.asList(0,null,2)); // break check("res3", Arrays.asList(0)); // empty init check("res4", Arrays.asList(0,1,2)); // empty update check("res5", Arrays.asList(0,1,2)); // empty final condition check("res6", Arrays.asList(0,1,2)); // all conditions empty check("res7", Arrays.asList(0,1,2)); } public void test_for1() { //5125: CTL2: "for" cycle is EXTREMELY memory consuming doCompile("test_for1"); checkEquals("counter", "COUNT"); } @SuppressWarnings("unchecked") public void test_foreach() { doCompile("test_foreach"); check("intRes", Arrays.asList(VALUE_VALUE)); check("longRes", Arrays.asList(BORN_MILLISEC_VALUE)); check("doubleRes", Arrays.asList(AGE_VALUE)); check("decimalRes", Arrays.asList(CURRENCY_VALUE)); check("booleanRes", Arrays.asList(FLAG_VALUE)); check("stringRes", Arrays.asList(NAME_VALUE, CITY_VALUE)); check("dateRes", Arrays.asList(BORN_VALUE)); List<?> integerStringMapResTmp = (List<?>) getVariable("integerStringMapRes"); List<String> integerStringMapRes = new ArrayList<String>(integerStringMapResTmp.size()); for (Object o: integerStringMapResTmp) { integerStringMapRes.add(String.valueOf(o)); } List<Integer> stringIntegerMapRes = (List<Integer>) getVariable("stringIntegerMapRes"); List<DataRecord> stringRecordMapRes = (List<DataRecord>) getVariable("stringRecordMapRes"); Collections.sort(integerStringMapRes); Collections.sort(stringIntegerMapRes); assertEquals(Arrays.asList("0", "1", "2", "3", "4"), integerStringMapRes); assertEquals(Arrays.asList(0, 1, 2, 3, 4), stringIntegerMapRes); final int N = 5; assertEquals(N, stringRecordMapRes.size()); int equalRecords = 0; for (int i = 0; i < N; i++) { for (DataRecord r: stringRecordMapRes) { if (Integer.valueOf(i).equals(r.getField("Value").getValue()) && "A string".equals(String.valueOf(r.getField("Name").getValue()))) { equalRecords++; break; } } } assertEquals(N, equalRecords); } public void test_return(){ doCompile("test_return"); check("lhs", Integer.valueOf(1)); check("rhs", Integer.valueOf(2)); check("res", Integer.valueOf(3)); } public void test_return_incorrect() { doCompileExpectError("test_return_incorrect", "Can't convert from 'string' to 'integer'"); } public void test_return_void() { doCompile("test_return_void"); } public void test_overloading() { doCompile("test_overloading"); check("res1", Integer.valueOf(3)); check("res2", "Memento mori"); } public void test_overloading_incorrect() { doCompileExpectErrors("test_overloading_incorrect", Arrays.asList( "Duplicate function 'integer sum(integer, integer)'", "Duplicate function 'integer sum(integer, integer)'")); } //Test case for 4038 public void test_function_parameter_without_type() { doCompileExpectError("test_function_parameter_without_type", "Syntax error on token ')'"); } public void test_duplicate_import() { URL importLoc = getClass().getSuperclass().getResource("test_duplicate_import.ctl"); String expStr = "import '" + importLoc + "';\n"; expStr += "import '" + importLoc + "';\n"; doCompile(expStr, "test_duplicate_import"); } /*TODO: * public void test_invalid_import() { URL importLoc = getClass().getResource("test_duplicate_import.ctl"); String expStr = "import '/a/b/c/d/e/f/g/h/i/j/k/l/m';\n"; expStr += expStr; doCompileExpectError(expStr, "test_invalid_import", Arrays.asList("TODO: Unknown error")); //doCompileExpectError(expStr, "test_duplicate_import", Arrays.asList("TODO: Unknown error")); } */ public void test_built_in_functions(){ doCompile("test_built_in_functions"); check("notNullValue", Integer.valueOf(1)); checkNull("nullValue"); check("isNullRes1", false); check("isNullRes2", true); assertEquals("nvlRes1", getVariable("notNullValue"), getVariable("nvlRes1")); check("nvlRes2", Integer.valueOf(2)); assertEquals("nvl2Res1", getVariable("notNullValue"), getVariable("nvl2Res1")); check("nvl2Res2", Integer.valueOf(2)); check("iifRes1", Integer.valueOf(2)); check("iifRes2", Integer.valueOf(1)); } public void test_local_functions() { // CLO-1246 doCompile("test_local_functions"); } public void test_mapping(){ doCompile("test_mapping"); // simple mappings assertEquals("Name", NAME_VALUE, outputRecords[0].getField("Name").getValue().toString()); assertEquals("Age", AGE_VALUE, outputRecords[0].getField("Age").getValue()); assertEquals("City", CITY_VALUE, outputRecords[0].getField("City").getValue().toString()); assertEquals("Born", BORN_VALUE, outputRecords[0].getField("Born").getValue()); // * mapping assertTrue(recordEquals(inputRecords[1], outputRecords[1])); check("len", 2); } public void test_mapping_null_values() { doCompile("test_mapping_null_values"); assertTrue(recordEquals(inputRecords[2], outputRecords[0])); } public void test_copyByName() { doCompile("test_copyByName"); assertEquals("Field1", null, outputRecords[3].getField("Field1").getValue()); assertEquals("Age", AGE_VALUE, outputRecords[3].getField("Age").getValue()); assertEquals("City", CITY_VALUE, outputRecords[3].getField("City").getValue().toString()); } public void test_copyByName_expect_error(){ try { doCompile("function integer transform(){\n" + "firstInput fi1 = null; firstInput fi2;\n" + "copyByName(fi1, fi2); \n" + "return 0;}","test_copyByName_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){\n" + "firstInput fi1 = null; firstInput fi2 = null;\n" + "copyByName(fi1, fi2); \n" + "return 0;}","test_copyByName_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_copyByName_assignment() { doCompile("test_copyByName_assignment"); assertEquals("Field1", null, outputRecords[3].getField("Field1").getValue()); assertEquals("Age", AGE_VALUE, outputRecords[3].getField("Age").getValue()); assertEquals("City", CITY_VALUE, outputRecords[3].getField("City").getValue().toString()); } public void test_copyByName_assignment1() { doCompile("test_copyByName_assignment1"); assertEquals("Field1", null, outputRecords[3].getField("Field1").getValue()); assertEquals("Age", null, outputRecords[3].getField("Age").getValue()); assertEquals("City", null, outputRecords[3].getField("City").getValue()); } public void test_containerlib_copyByPosition(){ doCompile("test_containerlib_copyByPosition"); assertEquals("Field1", NAME_VALUE, outputRecords[3].getField("Field1").getValue().toString()); assertEquals("Age", AGE_VALUE, outputRecords[3].getField("Age").getValue()); assertEquals("City", CITY_VALUE, outputRecords[3].getField("City").getValue().toString()); } public void test_containerlib_copyByPosition_expect_error(){ try { doCompile("function integer transform(){\n" + "firstInput fi1 = null; firstInput fi2; \n" + "copyByPosition(fi1, fi2);\n" + "return 0;}","test_containerlib_copyByPosition_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){\n" + "firstInput fi1 = null; firstInput fi2 = null; \n" + "copyByPosition(fi1, fi2);\n" + "return 0;}","test_containerlib_copyByPosition_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_sequence(){ doCompile("test_sequence"); check("intRes", Arrays.asList(0,1,2)); check("longRes", Arrays.asList(Long.valueOf(0),Long.valueOf(1),Long.valueOf(2))); check("stringRes", Arrays.asList("0","1","2")); check("intCurrent", Integer.valueOf(2)); check("longCurrent", Long.valueOf(2)); check("stringCurrent", "2"); } //TODO: If this test fails please double check whether the test is correct? public void test_lookup(){ doCompile("test_lookup"); check("alphaResult", Arrays.asList("Andorra la Vella","Andorra la Vella")); check("bravoResult", Arrays.asList("Bruxelles","Bruxelles")); check("charlieResult", Arrays.asList("Chamonix","Chodov","Chomutov","Chamonix","Chodov","Chomutov")); check("countResult", Arrays.asList(3,3)); check("charlieUpdatedCount", 5); check("charlieUpdatedResult", Arrays.asList("Chamonix", "Cheb", "Chodov", "Chomutov", "Chrudim")); check("putResult", true); check("meta", null); check("meta2", null); check("meta3", null); check("meta4", null); check("strRet", "Bratislava"); check("strRet2","Andorra la Vella"); check("intRet", 0); check("intRet2", 1); check("meta7", null); // CLO-1582 check("nonExistingKeyRecord", null); check("nullKeyRecord", null); check("unusedNext", getVariable("unusedNextExpected")); } public void test_lookup_expect_error(){ //CLO-1582 try { doCompile("function integer transform(){string str = lookup(TestLookup).get('Alpha',2).City; return 0;}","test_lookup_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer count = lookup(TestLookup).count('Alpha',1); printErr(count); lookup(TestLookup).next(); string city = lookup(TestLookup).next().City; return 0;}","test_lookup_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){lookupMetadata meta = null; lookup(TestLookup).put(meta); return 0;}","test_lookup_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){lookup(TestLookup).put(null); return 0;}","test_lookup_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_containerlib_append() { doCompile("test_containerlib_append"); check("appendElem", Integer.valueOf(10)); check("appendList", Arrays.asList(1, 2, 3, 4, 5, 10)); check("stringList", Arrays.asList("horse","is","pretty","scary")); check("stringList2", Arrays.asList("horse", null)); check("stringList3", Arrays.asList("horse", "")); check("integerList1", Arrays.asList(1,2,3,4)); check("integerList2", Arrays.asList(1,2,null)); check("numberList1", Arrays.asList(0.21,1.1,2.2)); check("numberList2", Arrays.asList(1.1,null)); check("longList1", Arrays.asList(1l,2l,3L)); check("longList2", Arrays.asList(9L,null)); check("decList1", Arrays.asList(new BigDecimal("2.3"),new BigDecimal("4.5"),new BigDecimal("6.7"))); check("decList2",Arrays.asList(new BigDecimal("1.1"), null)); } public void test_containerlib_append_expect_error(){ try { doCompile("function integer transform(){string[] listInput = null; append(listInput,'aa'); return 0;}","test_containerlib_append_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){byte[] listInput = null; append(listInput,str2byte('third', 'utf-8')); return 0;}","test_containerlib_append_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long[] listInput = null; append(listInput,15L); return 0;}","test_containerlib_append_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer[] listInput = null; append(listInput,12); return 0;}","test_containerlib_append_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){decimal[] listInput = null; append(listInput,12.5d); return 0;}","test_containerlib_append_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){number[] listInput = null; append(listInput,12.36); return 0;}","test_containerlib_append_expect_error"); fail(); } catch (Exception e) { // do nothing } } @SuppressWarnings("unchecked") public void test_containerlib_clear() { doCompile("test_containerlib_clear"); assertTrue(((List<Integer>) getVariable("integerList")).isEmpty()); assertTrue(((List<Integer>) getVariable("strList")).isEmpty()); assertTrue(((List<Integer>) getVariable("longList")).isEmpty()); assertTrue(((List<Integer>) getVariable("decList")).isEmpty()); assertTrue(((List<Integer>) getVariable("numList")).isEmpty()); assertTrue(((List<Integer>) getVariable("byteList")).isEmpty()); assertTrue(((List<Integer>) getVariable("dateList")).isEmpty()); assertTrue(((List<Integer>) getVariable("boolList")).isEmpty()); assertTrue(((List<Integer>) getVariable("emptyList")).isEmpty()); assertTrue(((Map<String,Integer>) getVariable("myMap")).isEmpty()); } public void test_container_clear_expect_error(){ try { doCompile("function integer transform(){boolean[] nullList = null; clear(nullList); return 0;}","test_container_clear_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){map[integer,string] myMap = null; clear(myMap); return 0;}","test_container_clear_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_containerlib_copy() { doCompile("test_containerlib_copy"); check("copyIntList", Arrays.asList(1, 2, 3, 4, 5)); check("returnedIntList", Arrays.asList(1, 2, 3, 4, 5)); check("copyLongList", Arrays.asList(21L,15L, null, 10L)); check("returnedLongList", Arrays.asList(21l, 15l, null, 10L)); check("copyBoolList", Arrays.asList(false,false,null,true)); check("returnedBoolList", Arrays.asList(false,false,null,true)); Calendar cal = Calendar.getInstance(); cal.set(2006, 10, 12, 0, 0, 0); cal.set(Calendar.MILLISECOND, 0); Calendar cal2 = Calendar.getInstance(); cal2.set(2002, 03, 12, 0, 0, 0); cal2.set(Calendar.MILLISECOND, 0); check("copyDateList",Arrays.asList(cal2.getTime(), null, cal.getTime())); check("returnedDateList",Arrays.asList(cal2.getTime(), null, cal.getTime())); check("copyStrList", Arrays.asList("Ashe", "Jax", null, "Rengar")); check("returnedStrList", Arrays.asList("Ashe", "Jax", null, "Rengar")); check("copyNumList", Arrays.asList(12.65d, 458.3d, null, 15.65d)); check("returnedNumList", Arrays.asList(12.65d, 458.3d, null, 15.65d)); check("copyDecList", Arrays.asList(new BigDecimal("2.3"),new BigDecimal("5.9"), null, new BigDecimal("15.3"))); check("returnedDecList", Arrays.asList(new BigDecimal("2.3"),new BigDecimal("5.9"), null, new BigDecimal("15.3"))); Map<String, String> expectedMap = new HashMap<String, String>(); expectedMap.put("a", "a"); expectedMap.put("b", "b"); expectedMap.put("c", "c"); expectedMap.put("d", "d"); check("copyStrMap", expectedMap); check("returnedStrMap", expectedMap); Map<Integer, Integer> intMap = new HashMap<Integer, Integer>(); intMap.put(1,12); intMap.put(2,null); intMap.put(3,15); check("copyIntMap", intMap); check("returnedIntMap", intMap); Map<Long, Long> longMap = new HashMap<Long, Long>(); longMap.put(10L, 453L); longMap.put(11L, null); longMap.put(12L, 54755L); check("copyLongMap", longMap); check("returnedLongMap", longMap); Map<BigDecimal, BigDecimal> decMap = new HashMap<BigDecimal, BigDecimal>(); decMap.put(new BigDecimal("2.2"), new BigDecimal("12.3")); decMap.put(new BigDecimal("2.3"), new BigDecimal("45.6")); check("copyDecMap", decMap); check("returnedDecMap", decMap); Map<Double, Double> doubleMap = new HashMap<Double, Double>(); doubleMap.put(new Double(12.3d), new Double(11.2d)); doubleMap.put(new Double(13.4d), new Double(78.9d)); check("copyNumMap",doubleMap); check("returnedNumMap", doubleMap); List<String> myList = new ArrayList<String>(); check("copyEmptyList", myList); check("returnedEmptyList", myList); assertTrue(((List<String>)(getVariable("copyEmptyList"))).isEmpty()); assertTrue(((List<String>)(getVariable("returnedEmptyList"))).isEmpty()); Map<String, String> emptyMap = new HashMap<String, String>(); check("copyEmptyMap", emptyMap); check("returnedEmptyMap", emptyMap); assertTrue(((HashMap<String,String>)(getVariable("copyEmptyMap"))).isEmpty()); assertTrue(((HashMap<String,String>)(getVariable("returnedEmptyMap"))).isEmpty()); } public void test_containerlib_copy_expect_error(){ try { doCompile("function integer transform(){string[] origList = null; string[] copyList; string[] ret = copy(copyList, origList); return 0;}","test_containerlib_copy_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string[] origList; string[] copyList = null; string[] ret = copy(copyList, origList); return 0;}","test_containerlib_copy_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){map[string, string] orig = null; map[string, string] copy; map[string, string] ret = copy(copy, orig); return 0;}","test_containerlib_copy_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){map[string, string] orig; map[string, string] copy = null; map[string, string] ret = copy(copy, orig); return 0;}","test_containerlib_copy_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_containerlib_insert() { doCompile("test_containerlib_insert"); check("copyStrList",Arrays.asList("Elise","Volibear","Garen","Jarvan IV")); check("retStrList",Arrays.asList("Elise","Volibear","Garen","Jarvan IV")); check("copyStrList2", Arrays.asList("Jax", "Aatrox", "Lisandra", "Ashe")); check("retStrList2", Arrays.asList("Jax", "Aatrox", "Lisandra", "Ashe")); Calendar cal = Calendar.getInstance(); cal.set(2009, 10, 12, 0, 0, 0); cal.set(Calendar.MILLISECOND, 0); Calendar cal1 = Calendar.getInstance(); cal1.set(2008, 2, 7, 0, 0, 0); cal1.set(Calendar.MILLISECOND, 0); Calendar cal2 = Calendar.getInstance(); cal2.set(2003, 01, 1, 0, 0, 0); cal2.set(Calendar.MILLISECOND, 0); check("copyDateList", Arrays.asList(cal1.getTime(),cal.getTime())); check("retDateList", Arrays.asList(cal1.getTime(),cal.getTime())); check("copyDateList2", Arrays.asList(cal2.getTime(),cal1.getTime(),cal.getTime())); check("retDateList2", Arrays.asList(cal2.getTime(),cal1.getTime(),cal.getTime())); check("copyIntList", Arrays.asList(1,2,3,12,4,5,6,7)); check("retIntList", Arrays.asList(1,2,3,12,4,5,6,7)); check("copyLongList", Arrays.asList(14L,15l,16l,17l)); check("retLongList", Arrays.asList(14L,15l,16l,17l)); check("copyLongList2", Arrays.asList(20L,21L,22L,23l)); check("retLongList2", Arrays.asList(20L,21L,22L,23l)); check("copyNumList", Arrays.asList(12.3d,11.1d,15.4d)); check("retNumList", Arrays.asList(12.3d,11.1d,15.4d)); check("copyNumList2", Arrays.asList(22.2d,44.4d,55.5d,33.3d)); check("retNumList2", Arrays.asList(22.2d,44.4d,55.5d,33.3d)); check("copyDecList", Arrays.asList(new BigDecimal("11.1"), new BigDecimal("22.2"), new BigDecimal("33.3"))); check("retDecList", Arrays.asList(new BigDecimal("11.1"), new BigDecimal("22.2"), new BigDecimal("33.3"))); check("copyDecList2",Arrays.asList(new BigDecimal("3.3"), new BigDecimal("4.4"), new BigDecimal("1.1"), new BigDecimal("2.2"))); check("retDecList2",Arrays.asList(new BigDecimal("3.3"), new BigDecimal("4.4"), new BigDecimal("1.1"), new BigDecimal("2.2"))); check("copyEmpty", Arrays.asList(11)); check("retEmpty", Arrays.asList(11)); check("copyEmpty2", Arrays.asList(12,13)); check("retEmpty2", Arrays.asList(12,13)); check("copyEmpty3", Arrays.asList()); check("retEmpty3", Arrays.asList()); } public void test_containerlib_insert_expect_error(){ try { doCompile("function integer transform(){integer[] tmp = null; integer[] ret = insert(tmp,0,12); return 0;}","test_containerlib_insert_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer[] tmp; integer[] toAdd = null; integer[] ret = insert(tmp,0,toAdd); return 0;}","test_containerlib_insert_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer[] tmp = [11,12]; integer[] ret = insert(tmp,-1,12); return 0;}","test_containerlib_insert_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer[] tmp = [11,12]; integer[] ret = insert(tmp,10,12); return 0;}","test_containerlib_insert_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_containerlib_isEmpty() { doCompile("test_containerlib_isEmpty"); check("emptyMap", true); check("emptyMap1", true); check("fullMap", false); check("fullMap1", false); check("emptyList", true); check("emptyList1", true); check("fullList", false); check("fullList1", false); } public void test_containerlib_isEmpty_expect_error(){ try { doCompile("function integer transform(){integer[] i = null; boolean boo = i.isEmpty(); return 0;}","test_containerlib_isEmpty_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){map[string, string] m = null; boolean boo = m.isEmpty(); return 0;}","test_containerlib_isEmpty_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_containerlib_length(){ doCompile("test_containerlib_length"); check("lengthByte", 18); check("lengthByte2", 18); check("recordLength", 9); check("recordLength2", 9); check("listLength", 3); check("listLength2", 3); check("emptyListLength", 0); check("emptyListLength2", 0); check("emptyMapLength", 0); check("emptyMapLength2", 0); check("nullLength1", 0); check("nullLength2", 0); check("nullLength3", 0); check("nullLength4", 0); check("nullLength5", 0); check("nullLength6", 0); } public void test_containerlib_poll() throws UnsupportedEncodingException { doCompile("test_containerlib_poll"); check("intElem", Integer.valueOf(1)); check("intElem1", 2); check("intList", Arrays.asList(3, 4, 5)); check("strElem", "Zyra"); check("strElem2", "Tresh"); check("strList", Arrays.asList("Janna", "Wu Kong")); Calendar cal = Calendar.getInstance(); cal.set(2002, 10, 12, 0, 0, 0); cal.set(Calendar.MILLISECOND, 0); check("dateElem", cal.getTime()); cal.clear(); cal.set(2003,5,12,0,0,0); cal.set(Calendar.MILLISECOND, 0); check("dateElem2", cal.getTime()); cal.clear(); cal.set(2006,9,15,0,0,0); cal.set(Calendar.MILLISECOND, 0); check("dateList", Arrays.asList(cal.getTime())); checkArray("byteElem", "Maoki".getBytes("UTF-8")); checkArray("byteElem2", "Nasus".getBytes("UTF-8")); check("longElem", 12L); check("longElem2", 15L); check("longList", Arrays.asList(16L,23L)); check("numElem", 23.6d); check("numElem2", 15.9d); check("numList", Arrays.asList(78.8d, 57.2d)); check("decElem", new BigDecimal("12.3")); check("decElem2", new BigDecimal("23.4")); check("decList", Arrays.asList(new BigDecimal("34.5"), new BigDecimal("45.6"))); check("emptyElem", null); check("emptyElem2", null); check("emptyList", Arrays.asList()); } public void test_containerlib_poll_expect_error(){ try { doCompile("function integer transform(){integer[] arr = null; integer i = poll(arr); return 0;}","test_containerlib_poll_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer[] arr = null; integer i = arr.poll(); return 0;}","test_containerlib_poll_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_containerlib_pop() { doCompile("test_containerlib_pop"); check("intElem", 5); check("intElem2", 4); check("intList", Arrays.asList(1, 2, 3)); check("longElem", 14L); check("longElem2", 13L); check("longList", Arrays.asList(11L,12L)); check("numElem", 11.5d); check("numElem2", 11.4d); check("numList", Arrays.asList(11.2d,11.3d)); check("decElem", new BigDecimal("22.5")); check("decElem2", new BigDecimal("22.4")); check("decList", Arrays.asList(new BigDecimal("22.2"), new BigDecimal("22.3"))); Calendar cal = Calendar.getInstance(); cal.set(2005, 8, 24, 0, 0, 0); cal.set(Calendar.MILLISECOND, 0); check("dateElem",cal.getTime()); cal.clear(); cal.set(2001, 6, 13, 0, 0, 0); cal.set(Calendar.MILLISECOND, 0); check("dateElem2", cal.getTime()); cal.clear(); cal.set(2010, 5, 11, 0, 0, 0); cal.set(Calendar.MILLISECOND, 0); Calendar cal2 = Calendar.getInstance(); cal2.set(2011,3,3,0,0,0); cal2.set(Calendar.MILLISECOND, 0); check("dateList", Arrays.asList(cal.getTime(),cal2.getTime())); check("strElem", "Ezrael"); check("strElem2", null); check("strList", Arrays.asList("Kha-Zix", "Xerath")); check("emptyElem", null); check("emptyElem2", null); } public void test_containerlib_pop_expect_error(){ try { doCompile("function integer transform(){string[] arr = null; string str = pop(arr); return 0;}","test_containerlib_pop_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string[] arr = null; string str = arr.pop(); return 0;}","test_containerlib_pop_expect_error"); fail(); } catch (Exception e) { // do nothing } } @SuppressWarnings("unchecked") public void test_containerlib_push() { doCompile("test_containerlib_push"); check("intCopy", Arrays.asList(1, 2, 3)); check("intRet", Arrays.asList(1, 2, 3)); check("longCopy", Arrays.asList(12l,13l,14l)); check("longRet", Arrays.asList(12l,13l,14l)); check("numCopy", Arrays.asList(11.1d,11.2d,11.3d)); check("numRet", Arrays.asList(11.1d,11.2d,11.3d)); check("decCopy", Arrays.asList(new BigDecimal("12.2"), new BigDecimal("12.3"), new BigDecimal("12.4"))); check("decRet", Arrays.asList(new BigDecimal("12.2"), new BigDecimal("12.3"), new BigDecimal("12.4"))); check("strCopy", Arrays.asList("Fiora", "Nunu", "Amumu")); check("strRet", Arrays.asList("Fiora", "Nunu", "Amumu")); Calendar cal = Calendar.getInstance(); cal.set(2001, 5, 9, 0, 0, 0); cal.set(Calendar.MILLISECOND, 0); Calendar cal1 = Calendar.getInstance(); cal1.set(2005, 5, 9, 0, 0, 0); cal1.set(Calendar.MILLISECOND, 0); Calendar cal2 = Calendar.getInstance(); cal2.set(2011, 5, 9, 0, 0, 0); cal2.set(Calendar.MILLISECOND, 0); check("dateCopy", Arrays.asList(cal.getTime(),cal1.getTime(),cal2.getTime())); check("dateRet", Arrays.asList(cal.getTime(),cal1.getTime(),cal2.getTime())); String str = null; check("emptyCopy", Arrays.asList(str)); check("emptyRet", Arrays.asList(str)); // there is hardly any way to get an instance of DataRecord // hence we just check if the list has correct size // and if its elements have correct metadata List<DataRecord> recordList = (List<DataRecord>) getVariable("recordList"); List<DataRecordMetadata> mdList = Arrays.asList( graph.getDataRecordMetadata(OUTPUT_1), graph.getDataRecordMetadata(INPUT_2), graph.getDataRecordMetadata(INPUT_1) ); assertEquals(mdList.size(), recordList.size()); for (int i = 0; i < mdList.size(); i++) { assertEquals(mdList.get(i), recordList.get(i).getMetadata()); } } public void test_containerlib_push_expect_error(){ try { doCompile("function integer transform(){string[] str = null; str.push('a'); return 0;}","test_containerlib_push_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string[] str = null; push(str, 'a'); return 0;}","test_containerlib_push_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_containerlib_remove() { doCompile("test_containerlib_remove"); check("intElem", 2); check("intList", Arrays.asList(1, 3, 4, 5)); check("longElem", 13L); check("longList", Arrays.asList(11l,12l,14l)); check("numElem", 11.3d); check("numList", Arrays.asList(11.1d,11.2d,11.4d)); check("decElem", new BigDecimal("11.3")); check("decList", Arrays.asList(new BigDecimal("11.1"),new BigDecimal("11.2"),new BigDecimal("11.4"))); Calendar cal = Calendar.getInstance(); cal.set(2002,10,13,0,0,0); cal.set(Calendar.MILLISECOND, 0); check("dateElem", cal.getTime()); cal.clear(); cal.set(2001,10,13,0,0,0); cal.set(Calendar.MILLISECOND, 0); Calendar cal2 = Calendar.getInstance(); cal2.set(2003,10,13,0,0,0); cal2.set(Calendar.MILLISECOND, 0); check("dateList", Arrays.asList(cal.getTime(), cal2.getTime())); check("strElem", "Shivana"); check("strList", Arrays.asList("Annie","Lux")); } public void test_containerlib_remove_expect_error(){ try { doCompile("function integer transform(){string[] strList; string str = remove(strList,0); return 0;}","test_containerlib_remove_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string[] strList; string str = strList.remove(0); return 0;}","test_containerlib_remove_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string[] strList = ['Teemo']; string str = remove(strList,5); return 0;}","test_containerlib_remove_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string[] strList = ['Teemo']; string str = remove(strList,-1); return 0;}","test_containerlib_remove_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string[] strList = null; string str = remove(strList,0); return 0;}","test_containerlib_remove_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_containerlib_reverse_expect_error(){ try { doCompile("function integer transform(){long[] longList = null; reverse(longList); return 0;}","test_containerlib_reverse_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){reverse(null); return 0;}","test_containerlib_reverse_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long[] longList = null; long[] reversed = longList.reverse(); return 0;}","test_containerlib_reverse_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_containerlib_reverse() { doCompile("test_containerlib_reverse"); check("intList", Arrays.asList(5, 4, 3, 2, 1)); check("intList2", Arrays.asList(5, 4, 3, 2, 1)); check("longList", Arrays.asList(14l,13l,12l,11l)); check("longList2", Arrays.asList(14l,13l,12l,11l)); check("numList", Arrays.asList(1.3d,1.2d,1.1d)); check("numList2", Arrays.asList(1.3d,1.2d,1.1d)); check("decList", Arrays.asList(new BigDecimal("1.3"),new BigDecimal("1.2"),new BigDecimal("1.1"))); check("decList2", Arrays.asList(new BigDecimal("1.3"),new BigDecimal("1.2"),new BigDecimal("1.1"))); check("strList", Arrays.asList(null,"Lulu","Kog Maw")); check("strList2", Arrays.asList(null,"Lulu","Kog Maw")); Calendar cal = Calendar.getInstance(); cal.set(2001,2,1,0,0,0); cal.set(Calendar.MILLISECOND, 0); Calendar cal2 = Calendar.getInstance(); cal2.set(2002,2,1,0,0,0); cal2.set(Calendar.MILLISECOND, 0); check("dateList", Arrays.asList(cal2.getTime(),cal.getTime())); check("dateList2", Arrays.asList(cal2.getTime(),cal.getTime())); } public void test_containerlib_sort() { doCompile("test_containerlib_sort"); check("intList", Arrays.asList(1, 1, 2, 3, 5)); check("intList2", Arrays.asList(1, 1, 2, 3, 5)); check("longList", Arrays.asList(21l,22l,23l,24l)); check("longList2", Arrays.asList(21l,22l,23l,24l)); check("decList", Arrays.asList(new BigDecimal("1.1"),new BigDecimal("1.2"),new BigDecimal("1.3"),new BigDecimal("1.4"))); check("decList2", Arrays.asList(new BigDecimal("1.1"),new BigDecimal("1.2"),new BigDecimal("1.3"),new BigDecimal("1.4"))); check("numList", Arrays.asList(1.1d,1.2d,1.3d,1.4d)); check("numList2", Arrays.asList(1.1d,1.2d,1.3d,1.4d)); Calendar cal = Calendar.getInstance(); cal.set(2002,5,12,0,0,0); cal.set(Calendar.MILLISECOND, 0); Calendar cal2 = Calendar.getInstance(); cal2.set(2003,5,12,0,0,0); cal2.set(Calendar.MILLISECOND, 0); Calendar cal3 = Calendar.getInstance(); cal3.set(2004,5,12,0,0,0); cal3.set(Calendar.MILLISECOND, 0); check("dateList", Arrays.asList(cal.getTime(),cal2.getTime(),cal3.getTime())); check("dateList2", Arrays.asList(cal.getTime(),cal2.getTime(),cal3.getTime())); check("strList", Arrays.asList("","Alistar", "Nocturne", "Soraka")); check("strList2", Arrays.asList("","Alistar", "Nocturne", "Soraka")); check("emptyList", Arrays.asList()); check("emptyList2", Arrays.asList()); } public void test_containerlib_sort_expect_error(){ try { doCompile("function integer transform(){string[] strList = ['Renektor', null, 'Jayce']; sort(strList); return 0;}","test_containerlib_sort_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string[] strList = null; sort(strList); return 0;}","test_containerlib_sort_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_containerlib_containsAll() { doCompile("test_containerlib_containsAll"); check("results", Arrays.asList(true, false, true, false, true, true, true, false, true, true, false)); check("test1", true); check("test2", true); check("test3", true); check("test4", false); check("test5", true); check("test6", false); check("test7", true); check("test8", false); check("test9", true); check("test10", false); check("test11", true); check("test12", false); check("test13", false); check("test14", true); check("test15", false); check("test16", false); } public void test_containerlib_containsAll_expect_error(){ try { doCompile("function integer transform(){integer[] intList = null; boolean b =intList.containsAll([1]); return 0;}","test_containerlib_containsAll_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer[] intList; boolean b =intList.containsAll(null); return 0;}","test_containerlib_containsAll_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "integer[] intList; integer[] intList2 = null;" + "boolean b =intList.containsAll(intList2); return 0;}","test_containerlib_containsAll_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "integer[] intList = null; integer[] intList2 = null;" + "boolean b =intList.containsAll(intList2); return 0;}","test_containerlib_containsAll_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_containerlib_containsKey() { doCompile("test_containerlib_containsKey"); check("results", Arrays.asList(false, true, false, true, false, true)); check("test1", true); check("test2", false); check("test3", true); check("test4", false); check("test5", true); check("test6", false); check("test7", true); check("test8", true); check("test9", true); check("test10", false); check("test11", true); check("test12", true); check("test13", false); check("test14", true); check("test15", true); check("test16", false); check("test17", true); check("test18", true); check("test19", false); check("test20", false); } public void test_containerlib_containsKey_expect_error(){ try { doCompile("function integer transform(){map[string, integer] emptyMap = null; boolean b = emptyMap.containsKey('a'); return 0;}","test_containerlib_containsKey_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_containerlib_containsValue() { doCompile("test_containerlib_containsValue"); check("results", Arrays.asList(true, false, false, true, false, false, true, false)); check("test1", true); check("test2", true); check("test3", false); check("test4", true); check("test5", true); check("test6", false); check("test7", false); check("test8", true); check("test9", true); check("test10", false); check("test11", true); check("test12", true); check("test13", false); check("test14", true); check("test15", true); check("test16", false); check("test17", true); check("test18", true); check("test19", false); check("test20", true); check("test21", true); check("test22", false); check("test23", true); check("test24", true); check("test25", false); check("test26", false); } public void test_convertlib_containsValue_expect_error(){ try { doCompile("function integer transform(){map[integer, long] nullMap = null; boolean b = nullMap.containsValue(18L); return 0;}","test_convertlib_containsValue_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_containerlib_getKeys() { doCompile("test_containerlib_getKeys"); check("stringList", Arrays.asList("a","b")); check("stringList2", Arrays.asList("a","b")); check("integerList", Arrays.asList(5,7,2)); check("integerList2", Arrays.asList(5,7,2)); List<Date> list = new ArrayList<Date>(); Calendar cal = Calendar.getInstance(); cal.set(2008, 10, 12, 0, 0, 0); cal.set(Calendar.MILLISECOND, 0); Calendar cal2 = Calendar.getInstance(); cal2.set(2001, 5, 28, 0, 0, 0); cal2.set(Calendar.MILLISECOND, 0); list.add(cal.getTime()); list.add(cal2.getTime()); check("dateList", list); check("dateList2", list); check("longList", Arrays.asList(14L, 45L)); check("longList2", Arrays.asList(14L, 45L)); check("numList", Arrays.asList(12.3d, 13.4d)); check("numList2", Arrays.asList(12.3d, 13.4d)); check("decList", Arrays.asList(new BigDecimal("34.5"), new BigDecimal("45.6"))); check("decList2", Arrays.asList(new BigDecimal("34.5"), new BigDecimal("45.6"))); check("emptyList", Arrays.asList()); check("emptyList2", Arrays.asList()); } public void test_containerlib_getKeys_expect_error(){ try { doCompile("function integer transform(){map[string,string] strMap = null; string[] str = strMap.getKeys(); return 0;}","test_containerlib_getKeys_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){map[string,string] strMap = null; string[] str = getKeys(strMap); return 0;}","test_containerlib_getKeys_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_stringlib_cache() { doCompile("test_stringlib_cache"); check("rep1", "The cat says meow. All cats say meow."); check("rep2", "The cat says meow. All cats say meow."); check("rep3", "The cat says meow. All cats say meow."); check("find1", Arrays.asList("to", "to", "to", "tro", "to")); check("find2", Arrays.asList("to", "to", "to", "tro", "to")); check("find3", Arrays.asList("to", "to", "to", "tro", "to")); check("split1", Arrays.asList("one", "two", "three", "four", "five")); check("split2", Arrays.asList("one", "two", "three", "four", "five")); check("split3", Arrays.asList("one", "two", "three", "four", "five")); check("chop01", "ting soming choping function"); check("chop02", "ting soming choping function"); check("chop03", "ting soming choping function"); check("chop11", "testing end of lines cutting"); check("chop12", "testing end of lines cutting"); } public void test_stringlib_charAt() { doCompile("test_stringlib_charAt"); String input = "The QUICk !!$ broWn fox juMPS over the lazy DOG "; String[] expected = new String[input.length()]; for (int i = 0; i < expected.length; i++) { expected[i] = String.valueOf(input.charAt(i)); } check("chars", Arrays.asList(expected)); } public void test_stringlib_charAt_error(){ //test: attempt to access char at position, which is out of bounds -> upper bound try { doCompile("string test;function integer transform(){test = charAt('milk', 7);return 0;}", "test_stringlib_charAt_error"); fail(); } catch (Exception e) { // do nothing } //test: attempt to access char at position, which is out of bounds -> lower bound try { doCompile("string test;function integer transform(){test = charAt('milk', -1);return 0;}", "test_stringlib_charAt_error"); fail(); } catch (Exception e) { // do nothing } //test: argument for position is null try { doCompile("string test; integer i = null; function integer transform(){test = charAt('milk', i);return 0;}", "test_stringlib_charAt_error"); fail(); } catch (Exception e) { // do nothing } //test: input is null try { doCompile("string test;function integer transform(){test = charAt(null, 1);return 0;}", "test_stringlib_charAt_error"); fail(); } catch (Exception e) { // do nothing } //test: input is empty string try { doCompile("string test;function integer transform(){test = charAt('', 1);return 0;}", "test_stringlib_charAt_error"); fail(); } catch (Exception e) { // do nothing } } public void test_stringlib_concat() { doCompile("test_stringlib_concat"); final SimpleDateFormat format = new SimpleDateFormat(); format.applyPattern("yyyy MMM dd"); check("concat", ""); check("concat1", "ello hi ELLO 2,today is " + format.format(new Date())); check("concat2", ""); check("concat3", "clover"); check("test_null1", "null"); check("test_null2", "null"); check("test_null3","skynullisnullblue"); } public void test_stringlib_countChar() { doCompile("test_stringlib_countChar"); check("charCount", 3); check("count2", 0); } public void test_stringlib_countChar_emptychar() { // test: attempt to count empty chars in string. try { doCompile("integer charCount;function integer transform() {charCount = countChar('aaa','');return 0;}", "test_stringlib_countChar_emptychar"); fail(); } catch (Exception e) { // do nothing } // test: attempt to count empty chars in empty string. try { doCompile("integer charCount;function integer transform() {charCount = countChar('','');return 0;}", "test_stringlib_countChar_emptychar"); fail(); } catch (Exception e) { // do nothing } //test: null input - test 1 try { doCompile("integer charCount;function integer transform() {charCount = countChar(null,'a');return 0;}", "test_stringlib_countChar_emptychar"); fail(); } catch (Exception e) { // do nothing } //test: null input - test 2 try { doCompile("integer charCount;function integer transform() {charCount = countChar(null,'');return 0;}", "test_stringlib_countChar_emptychar"); fail(); } catch (Exception e) { // do nothing } //test: null input - test 3 try { doCompile("integer charCount;function integer transform() {charCount = countChar(null, null);return 0;}", "test_stringlib_countChar_emptychar"); fail(); } catch (Exception e) { // do nothing } } public void test_stringlib_cut() { doCompile("test_stringlib_cut"); check("cutInput", Arrays.asList("a", "1edf", "h3ijk")); } public void test_string_cut_expect_error() { // test: Attempt to cut substring from position after the end of original string. E.g. string is 6 char long and // user attempt to cut out after position 8. try { doCompile("string input;string[] cutInput;function integer transform() {input = 'abc1edf2geh3ijk10lmn999opq';cutInput = cut(input,[28,3]);return 0;}", "test_stringlib_cut_expect_error"); fail(); } catch (Exception e) { // do nothing } // test: Attempt to cut substring longer then possible. E.g. string is 6 characters long and user cuts from // position // 4 substring 4 characters long try { doCompile("string input;string[] cutInput;function integer transform() {input = 'abc1edf2geh3ijk10lmn999opq';cutInput = cut(input,[20,8]);return 0;}", "test_stringlib_cut_expect_error"); fail(); } catch (Exception e) { // do nothing } // test: Attempt to cut a substring with negative length try { doCompile("string input;string[] cutInput;function integer transform() {input = 'abc1edf2geh3ijk10lmn999opq';cutInput = cut(input,[20,-3]);return 0;}", "test_stringlib_cut_expect_error"); fail(); } catch (Exception e) { // do nothing } // test: Attempt to cut substring from negative position. E.g cut([-3,3]). try { doCompile("string input;string[] cutInput;function integer transform() {input = 'abc1edf2geh3ijk10lmn999opq';cutInput = cut(input,[-3,3]);return 0;}", "test_stringlib_cut_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: input is empty string try { doCompile("string input;string[] cutInput;function integer transform() {input = '';cutInput = cut(input,[0,3]);return 0;}", "test_stringlib_cut_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: second arg is null try { doCompile("string input;string[] cutInput;function integer transform() {input = 'aaaa';cutInput = cut(input,null);return 0;}", "test_stringlib_cut_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: input is null try { doCompile("string input;string[] cutInput;function integer transform() {input = null;cutInput = cut(input,[5,11]);return 0;}", "test_stringlib_cut_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_stringlib_editDistance() { doCompile("test_stringlib_editDistance"); check("dist", 1); check("dist1", 1); check("dist2", 0); check("dist5", 1); check("dist3", 1); check("dist4", 0); check("dist6", 4); check("dist7", 5); check("dist8", 0); check("dist9", 0); } public void test_stringlib_editDistance_expect_error(){ //test: input - empty string - first arg try { doCompile("integer test;function integer transform() {test = editDistance('','mark');return 0;}","test_stringlib_editDistance_expect_error"); } catch ( Exception e) { // do nothing } //test: input - null - first arg try { doCompile("integer test;function integer transform() {test = editDistance(null,'mark');return 0;}","test_stringlib_editDistance_expect_error"); } catch ( Exception e) { // do nothing } //test: input- empty string - second arg try { doCompile("integer test;function integer transform() {test = editDistance('mark','');return 0;}","test_stringlib_editDistance_expect_error"); } catch ( Exception e) { // do nothing } //test: input - null - second argument try { doCompile("integer test;function integer transform() {test = editDistance('mark',null);return 0;}","test_stringlib_editDistance_expect_error"); } catch ( Exception e) { // do nothing } //test: input - both empty try { doCompile("integer test;function integer transform() {test = editDistance('','');return 0;}","test_stringlib_editDistance_expect_error"); } catch ( Exception e) { // do nothing } //test: input - both null try { doCompile("integer test;function integer transform() {test = editDistance(null,null);return 0;}","test_stringlib_editDistance_expect_error"); } catch ( Exception e) { // do nothing } } public void test_stringlib_find() { doCompile("test_stringlib_find"); check("findList", Arrays.asList("The quick br", "wn f", "x jumps ", "ver the lazy d", "g")); check("findList2", Arrays.asList("mark.twain")); check("findList3", Arrays.asList()); check("findList4", Arrays.asList("", "", "", "", "")); check("findList5", Arrays.asList("twain")); check("findList6", Arrays.asList("")); } public void test_stringlib_find_expect_error() { //test: regexp group number higher then count of regexp groups try { doCompile("string[] findList;function integer transform() {findList = find('[email protected]','(^[a-z]*).([a-z]*)',5); return 0;}", "test_stringlib_find_expect_error"); } catch (Exception e) { // do nothing } //test: negative regexp group number try { doCompile("string[] findList;function integer transform() {findList = find('[email protected]','(^[a-z]*).([a-z]*)',-1); return 0;}", "test_stringlib_find_expect_error"); } catch (Exception e) { // do nothing } //test: arg1 null input try { doCompile("string[] findList;function integer transform() {findList = find(null,'(^[a-z]*).([a-z]*)'); return 0;}", "test_stringlib_find_expect_error"); } catch (Exception e) { // do nothing } //test: arg2 null input - test1 try { doCompile("string[] findList;function integer transform() {findList = find('[email protected]',null); return 0;}", "test_stringlib_find_expect_error"); } catch (Exception e) { // do nothing } //test: arg2 null input - test2 try { doCompile("string[] findList;function integer transform() {findList = find('',null); return 0;}", "test_stringlib_find_expect_error"); } catch (Exception e) { // do nothing } //test: arg1 and arg2 null input try { doCompile("string[] findList;function integer transform() {findList = find(null,null); return 0;}", "test_stringlib_find_expect_error"); } catch (Exception e) { // do nothing } } public void test_stringlib_join() { doCompile("test_stringlib_join"); //check("joinedString", "Bagr,3,3.5641,-87L,CTL2"); check("joinedString1", "80=5455.987\"-5=5455.987\"3=0.1"); check("joinedString2", "5.054.6567.0231.0"); //check("joinedString3", "554656723180=5455.987-5=5455.9873=0.1CTL242"); check("test_empty1", "abc"); check("test_empty2", ""); check("test_empty3"," "); check("test_empty4","anullb"); check("test_empty5","80=5455.987-5=5455.9873=0.1"); check("test_empty6","80=5455.987 -5=5455.987 3=0.1"); check("test_null1","abc"); check("test_null2",""); check("test_null3","anullb"); check("test_null4","80=5455.987-5=5455.9873=0.1"); //CLO-1210 check("test_empty7","a=xb=nullc=z"); check("test_empty8","a=x b=null c=z"); check("test_empty9","null=xeco=storm"); check("test_empty10","null=x eco=storm"); check("test_null5","a=xb=nullc=z"); check("test_null6","null=xeco=storm"); } public void test_stringlib_join_expect_error(){ // CLO-1567 - join("", null) is ambiguous // try { // doCompile("function integer transform(){string s = join(';',null);return 0;}","test_stringlib_join_expect_error"); // fail(); // } catch (Exception e) { // // do nothing try { doCompile("function integer transform(){string[] tmp = null; string s = join(';',tmp);return 0;}","test_stringlib_join_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){map[string,string] a = null; string s = join(';',a);return 0;}","test_stringlib_join_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_stringlib_left() { //CLO - 1193 // doCompile("test_stringlib_left"); // check("test1", "aa"); // check("test2", "aaa"); // check("test3", ""); // check("test4", null); // check("test5", "abc"); // check("test6", "ab "); // check("test7", " "); // check("test8", " "); // check("test9", "abc"); // check("test10", "abc"); // check("test11", ""); // check("test12", null); } public void test_stringlib_length() { doCompile("test_stringlib_length"); check("lenght1", new BigDecimal(50)); check("stringLength", 8); check("length_empty", 0); check("length_null1", 0); } public void test_stringlib_lowerCase() { doCompile("test_stringlib_lowerCase"); check("lower", "the quick !!$ brown fox jumps over the lazy dog bagr "); check("lower_empty", ""); check("lower_null", null); } public void test_stringlib_matches() { doCompile("test_stringlib_matches"); check("matches1", true); check("matches2", true); check("matches3", false); check("matches4", true); check("matches5", false); check("matches6", false); check("matches7", false); check("matches8", false); check("matches9", true); check("matches10", true); } public void test_stringlib_matches_expect_error(){ //test: regexp param null - test 1 try { doCompile("boolean test; function integer transform(){test = matches('aaa', null); return 0;}","test_stringlib_matches_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: regexp param null - test 2 try { doCompile("boolean test; function integer transform(){test = matches('', null); return 0;}","test_stringlib_matches_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: regexp param null - test 3 try { doCompile("boolean test; function integer transform(){test = matches(null, null); return 0;}","test_stringlib_matches_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_stringlib_matchGroups() { doCompile("test_stringlib_matchGroups"); check("result1", null); check("result2", Arrays.asList( //"(([^:]*)([:])([\\(]))(.*)(\\))((( "zip:(zip:(/path/name?.zip)#innerfolder/file.zip)#innermostfolder?/filename*.txt", "zip:(", "zip", ":", "(", "zip:(/path/name?.zip)#innerfolder/file.zip", ")", "#innermostfolder?/filename*.txt", "#innermostfolder?/filename*.txt", " "innermostfolder?/filename*.txt", null ) ); check("result3", null); check("test_empty1", null); check("test_empty2", Arrays.asList("")); check("test_null1", null); check("test_null2", null); } public void test_stringlib_matchGroups_expect_error(){ //test: regexp is null - test 1 try { doCompile("string[] test; function integer transform(){test = matchGroups('eat all the cookies',null); return 0;}","test_stringlib_matchGroups_expect_error"); } catch (Exception e) { // do nothing } //test: regexp is null - test 2 try { doCompile("string[] test; function integer transform(){test = matchGroups('',null); return 0;}","test_stringlib_matchGroups_expect_error"); } catch (Exception e) { // do nothing } //test: regexp is null - test 3 try { doCompile("string[] test; function integer transform(){test = matchGroups(null,null); return 0;}","test_stringlib_matchGroups_expect_error"); } catch (Exception e) { // do nothing } } public void test_stringlib_matchGroups_unmodifiable() { try { doCompile("test_stringlib_matchGroups_unmodifiable"); fail(); } catch (RuntimeException re) { }; } public void test_stringlib_metaphone() { doCompile("test_stringlib_metaphone"); check("metaphone1", "XRS"); check("metaphone2", "KWNTLN"); check("metaphone3", "KWNT"); check("metaphone4", ""); check("metaphone5", ""); check("test_empty1", ""); check("test_empty2", ""); check("test_null1", null); check("test_null2", null); } public void test_stringlib_nysiis() { doCompile("test_stringlib_nysiis"); check("nysiis1", "CAP"); check("nysiis2", "CAP"); check("nysiis3", "1234"); check("nysiis4", "C2 PRADACTAN"); check("nysiis_empty", ""); check("nysiis_null", null); } public void test_stringlib_replace() { doCompile("test_stringlib_replace"); final SimpleDateFormat format = new SimpleDateFormat(); format.applyPattern("yyyy MMM dd"); check("rep", format.format(new Date()).replaceAll("[lL]", "t")); check("rep1", "The cat says meow. All cats say meow."); check("rep2", "intruders must die"); check("test_empty1", "a"); check("test_empty2", ""); check("test_null", null); check("test_null2",""); check("test_null3","bbb"); check("test_null4",null); } public void test_stringlib_replace_expect_error(){ //test: regexp null - test1 try { doCompile("string test; function integer transform(){test = replace('a b',null,'b'); return 0;}","test_stringlib_replace_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: regexp null - test2 try { doCompile("string test; function integer transform(){test = replace('',null,'b'); return 0;}","test_stringlib_replace_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: regexp null - test3 try { doCompile("string test; function integer transform(){test = replace(null,null,'b'); return 0;}","test_stringlib_replace_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: arg3 null - test1 try { doCompile("string test; function integer transform(){test = replace('a b','a+',null); return 0;}","test_stringlib_replace_expect_error"); fail(); } catch (Exception e) { // do nothing } // //test: arg3 null - test2 // try { // doCompile("string test; function integer transform(){test = replace('','a+',null); return 0;}","test_stringlib_replace_expect_error"); // fail(); // } catch (Exception e) { // // do nothing // //test: arg3 null - test3 // try { // doCompile("string test; function integer transform(){test = replace(null,'a+',null); return 0;}","test_stringlib_replace_expect_error"); // fail(); // } catch (Exception e) { // // do nothing //test: regexp and arg3 null - test1 try { doCompile("string test; function integer transform(){test = replace('a b',null,null); return 0;}","test_stringlib_replace_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: regexp and arg3 null - test1 try { doCompile("string test; function integer transform(){test = replace(null,null,null); return 0;}","test_stringlib_replace_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_stringlib_right() { doCompile("test_stringlib_right"); check("righ", "y dog"); check("rightNotPadded", "y dog"); check("rightPadded", "y dog"); check("padded", " y dog"); check("notPadded", "y dog"); check("short", "Dog"); check("shortNotPadded", "Dog"); check("shortPadded", " Dog"); check("simple", "milk"); check("test_null1", null); check("test_null2", null); check("test_null3", " "); check("test_empty1", ""); check("test_empty2", ""); check("test_empty3"," "); } public void test_stringlib_soundex() { doCompile("test_stringlib_soundex"); check("soundex1", "W630"); check("soundex2", "W643"); check("test_null", null); check("test_empty", ""); } public void test_stringlib_split() { doCompile("test_stringlib_split"); check("split1", Arrays.asList("The quick br", "wn f", "", " jumps " , "ver the lazy d", "g")); check("test_empty", Arrays.asList("")); check("test_empty2", Arrays.asList("","a","a")); List<String> tmp = new ArrayList<String>(); tmp.add(null); check("test_null", tmp); } public void test_stringlib_split_expect_error(){ //test: regexp null - test1 try { doCompile("function integer transform(){string[] s = split('aaa',null); return 0;}","test_stringlib_split_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: regexp null - test2 try { doCompile("function integer transform(){string[] s = split('',null); return 0;}","test_stringlib_split_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: regexp null - test3 try { doCompile("function integer transform(){string[] s = split(null,null); return 0;}","test_stringlib_split_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_stringlib_substring() { doCompile("test_stringlib_substring"); check("subs", "UICk "); check("test1", ""); check("test_empty", ""); } public void test_stringlib_substring_expect_error(){ try { doCompile("function integer transform(){string test = substring('arabela',4,19);return 0;}","test_stringlib_substring_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string test = substring('arabela',15,3);return 0;}","test_stringlib_substring_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string test = substring('arabela',2,-3);return 0;}","test_stringlib_substring_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string test = substring('arabela',-5,7);return 0;}","test_stringlib_substring_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string test = substring('',0,7);return 0;}","test_stringlib_substring_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string test = substring('',7,7);return 0;}","test_stringlib_substring_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string test = substring(null,0,0);return 0;}","test_stringlib_substring_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string test = substring(null,0,4);return 0;}","test_stringlib_substring_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string test = substring(null,1,4);return 0;}","test_stringlib_substring_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_stringlib_trim() { doCompile("test_stringlib_trim"); check("trim1", "im The QUICk !!$ broWn fox juMPS over the lazy DOG"); check("trim_empty", ""); check("trim_null", null); } public void test_stringlib_upperCase() { doCompile("test_stringlib_upperCase"); check("upper", "THE QUICK !!$ BROWN FOX JUMPS OVER THE LAZY DOG BAGR "); check("test_empty", ""); check("test_null", null); } public void test_stringlib_isFormat() { doCompile("test_stringlib_isFormat"); check("test", "test"); check("isBlank", Boolean.FALSE); check("blank", ""); checkNull("nullValue"); check("isBlank1", true); check("isBlank2", true); check("isAscii1", true); check("isAscii2", false); check("isAscii3", true); check("isAscii4", true); check("isNumber", false); check("isNumber1", false); check("isNumber2", true); check("isNumber3", true); check("isNumber4", false); check("isNumber5", true); check("isNumber6", true); check("isNumber7", false); check("isNumber8", false); check("isInteger", false); check("isInteger1", false); check("isInteger2", false); check("isInteger3", true); check("isInteger4", false); check("isInteger5", false); check("isLong", true); check("isLong1", false); check("isLong2", false); check("isLong3", false); check("isLong4", false); check("isDate", true); check("isDate1", false); // "kk" allows hour to be 1-24 (as opposed to HH allowing hour to be 0-23) check("isDate2", true); check("isDate3", true); check("isDate4", false); check("isDate5", true); check("isDate6", true); check("isDate7", false); check("isDate9", false); check("isDate10", false); check("isDate11", false); check("isDate12", true); check("isDate13", false); check("isDate14", false); // empty string: invalid check("isDate15", false); check("isDate16", false); check("isDate17", true); check("isDate18", true); check("isDate19", false); check("isDate20", false); check("isDate21", false); // CLO-1190 // check("isDate22", false); // check("isDate23", false); check("isDate24", true); check("isDate25", false); } public void test_stringlib_empty_strings() { String[] expressions = new String[] { "isInteger(?)", "isNumber(?)", "isLong(?)", "isAscii(?)", "isBlank(?)", "isDate(?, \"yyyy\")", "isUrl(?)", "string x = ?; length(x)", "lowerCase(?)", "matches(?, \"\")", "NYSIIS(?)", "removeBlankSpace(?)", "removeDiacritic(?)", "removeNonAscii(?)", "removeNonPrintable(?)", "replace(?, \"a\", \"a\")", "translate(?, \"ab\", \"cd\")", "trim(?)", "upperCase(?)", "chop(?)", "concat(?)", "getAlphanumericChars(?)", }; StringBuilder sb = new StringBuilder(); for (String expr : expressions) { String emptyString = expr.replace("?", "\"\""); boolean crashesEmpty = test_expression_crashes(emptyString); assertFalse("Function " + emptyString + " crashed", crashesEmpty); String nullString = expr.replace("?", "null"); boolean crashesNull = test_expression_crashes(nullString); sb.append(String.format("|%20s|%5s|%5s|%n", expr, crashesEmpty ? "CRASH" : "ok", crashesNull ? "CRASH" : "ok")); } System.out.println(sb.toString()); } private boolean test_expression_crashes(String expr) { String expStr = "function integer transform() { " + expr + "; return 0; }"; try { doCompile(expStr, "test_stringlib_empty_null_strings"); return false; } catch (RuntimeException e) { return true; } } public void test_stringlib_removeBlankSpace() { String expStr = "string r1;\n" + "string str_empty;\n" + "string str_null;\n" + "function integer transform() {\n" + "r1=removeBlankSpace(\"" + StringUtils.specCharToString(" a b\nc\rd e \u000Cf\r\n") + "\");\n" + "printErr(r1);\n" + "str_empty = removeBlankSpace('');\n" + "str_null = removeBlankSpace(null);\n" + "return 0;\n" + "}\n"; doCompile(expStr, "test_removeBlankSpace"); check("r1", "abcdef"); check("str_empty", ""); check("str_null", null); } public void test_stringlib_removeNonPrintable() { doCompile("test_stringlib_removeNonPrintable"); check("nonPrintableRemoved", "AHOJ"); check("test_empty", ""); check("test_null", null); } public void test_stringlib_getAlphanumericChars() { String expStr = "string an1;\n " + "string an2;\n" + "string an3;\n" + "string an4;\n" + "string an5;\n" + "string an6;\n" + "string an7;\n" + "string an8;\n" + "string an9;\n" + "string an10;\n" + "string an11;\n" + "string an12;\n" + "string an13;\n" + "string an14;\n" + "string an15;\n" + "function integer transform() {\n" + "an1=getAlphanumericChars(\"" + StringUtils.specCharToString(" a 1b\nc\rd \b e \u000C2f\r\n") + "\");\n" + "an2=getAlphanumericChars(\"" + StringUtils.specCharToString(" a 1b\nc\rd \b e \u000C2f\r\n") + "\",true,true);\n" + "an3=getAlphanumericChars(\"" + StringUtils.specCharToString(" a 1b\nc\rd \b e \u000C2f\r\n") + "\",true,false);\n" + "an4=getAlphanumericChars(\"" + StringUtils.specCharToString(" a 1b\nc\rd \b e \u000C2f\r\n") + "\",false,true);\n" + "an5=getAlphanumericChars(\"\");\n" + "an6=getAlphanumericChars(\"\",true,true);\n"+ "an7=getAlphanumericChars(\"\",true,false);\n"+ "an8=getAlphanumericChars(\"\",false,true);\n"+ "an9=getAlphanumericChars(null);\n" + "an10=getAlphanumericChars(null,false,false);\n" + "an11=getAlphanumericChars(null,true,false);\n" + "an12=getAlphanumericChars(null,false,true);\n" + "an13=getAlphanumericChars(' 0 ľeškó11');\n" + "an14=getAlphanumericChars(' 0 ľeškó11', false, false);\n" + //CLO-1174 "an15=getAlphanumericChars('" + StringUtils.specCharToString(" a 1b\nc\rd \b e \u000C2f\r\n") + "',false,false);\n" + "return 0;\n" + "}\n"; doCompile(expStr, "test_getAlphanumericChars"); check("an1", "a1bcde2f"); check("an2", "a1bcde2f"); check("an3", "abcdef"); check("an4", "12"); check("an5", ""); check("an6", ""); check("an7", ""); check("an8", ""); check("an9", null); check("an10", null); check("an11", null); check("an12", null); check("an13", "0ľeškó11"); check("an14"," 0 ľeškó11"); //CLO-1174 String tmp = StringUtils.specCharToString(" a 1b\nc\rd \b e \u000C2f\r\n"); check("an15", tmp); } public void test_stringlib_indexOf(){ doCompile("test_stringlib_indexOf"); check("index",2); check("index1",9); check("index2",0); check("index3",-1); check("index4",6); check("index5",-1); check("index6",0); check("index7",4); check("index8",4); check("index9", -1); check("index10", 2); check("index_empty1", -1); check("index_empty2", 0); check("index_empty3", 0); check("index_empty4", -1); } public void test_stringlib_indexOf_expect_error(){ //test: second arg is null - test1 try { doCompile("integer index;function integer transform() {index = indexOf('hello world',null); return 0;}","test_stringlib_indexOf_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: second arg is null - test2 try { doCompile("integer index;function integer transform() {index = indexOf('',null); return 0;}","test_stringlib_indexOf_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: first arg is null - test1 try { doCompile("integer index;function integer transform() {index = indexOf(null,'a'); return 0;}","test_stringlib_indexOf_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: first arg is null - test2 try { doCompile("integer index;function integer transform() {index = indexOf(null,''); return 0;}","test_stringlib_indexOf_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: both args are null try { doCompile("integer index;function integer transform() {index = indexOf(null,null); return 0;}","test_stringlib_indexOf_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_stringlib_removeDiacritic(){ doCompile("test_stringlib_removeDiacritic"); check("test","tescik"); check("test1","zabicka"); check("test_empty", ""); check("test_null", null); } public void test_stringlib_translate(){ doCompile("test_stringlib_translate"); check("trans","hippi"); check("trans1","hipp"); check("trans2","hippi"); check("trans3",""); check("trans4","y lanuaX nXXd thX lXttXr X"); check("trans5", "hello"); check("test_empty1", ""); check("test_empty2", ""); check("test_null", null); } public void test_stringlib_translate_expect_error(){ try { doCompile("function integer transform(){string test = translate('bla bla',null,'o');return 0;}","test_stringlib_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string test = translate('bla bla','a',null);return 0;}","test_stringlib_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string test = translate('bla bla',null,null);return 0;}","test_stringlib_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string test = translate(null,'a',null);return 0;}","test_stringlib_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string test = translate(null,null,'a');return 0;}","test_stringlib_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string test = translate(null,null,null);return 0;}","test_stringlib_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_stringlib_removeNonAscii(){ doCompile("test_stringlib_removeNonAscii"); check("test1", "Sun is shining"); check("test2", ""); check("test_empty", ""); check("test_null", null); } public void test_stringlib_chop() { doCompile("test_stringlib_chop"); check("s1", "hello"); check("s6", "hello"); check("s5", "hello"); check("s2", "hello"); check("s7", "helloworld"); check("s3", "hello "); check("s4", "hello"); check("s8", "hello"); check("s9", "world"); check("s10", "hello"); check("s11", "world"); check("s12", "mark.twain"); check("s13", "two words"); check("s14", ""); check("s15", ""); check("s16", ""); check("s17", ""); check("s18", ""); check("s19", "word"); check("s20", ""); check("s21", ""); check("s22", "mark.twain"); } public void test_stringlib_chop_expect_error() { //test: arg is null try { doCompile("string test;function integer transform() {test = chop(null);return 0;}","test_strlib_chop_erxpect_error"); fail(); } catch (Exception e) { // do nothing } //test: regexp pattern is null try { doCompile("string test;function integer transform() {test = chop('aaa', null);return 0;}","test_strlib_chop_erxpect_error"); fail(); } catch (Exception e) { // do nothing } //test: regexp pattern is null - test 2 try { doCompile("string test;function integer transform() {test = chop('', null);return 0;}","test_strlib_chop_erxpect_error"); fail(); } catch (Exception e) { // do nothing } //test: arg is null try { doCompile("string test;function integer transform() {test = chop(null, 'aaa');return 0;}","test_strlib_chop_erxpect_error"); fail(); } catch (Exception e) { // do nothing } //test: arg is null - test2 try { doCompile("string test;function integer transform() {test = chop(null, '');return 0;}","test_strlib_chop_erxpect_error"); fail(); } catch (Exception e) { // do nothing } //test: arg is null - test3 try { doCompile("string test;function integer transform() {test = chop(null, null);return 0;}","test_strlib_chop_erxpect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_bitwise_bitSet(){ doCompile("test_bitwise_bitSet"); check("test1", 3); check("test2", 15); check("test3", 34); check("test4", 3l); check("test5", 15l); check("test6", 34l); } public void test_bitwise_bitSet_expect_error(){ try { doCompile("function integer transform(){" + "integer var1 = null;" + "integer var2 = 3;" + "boolean var3 = false;" + "integer i = bitSet(var1,var2,var3); return 0;}","test_bitwise_bitSet_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "integer var1 = 512;" + "integer var2 = null;" + "boolean var3 = false;" + "integer i = bitSet(var1,var2,var3); return 0;}","test_bitwise_bitSet_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "integer var1 = 512;" + "integer var2 = 3;" + "boolean var3 = null;" + "integer i = bitSet(var1,var2,var3); return 0;}","test_bitwise_bitSet_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "long var1 = 512l;" + "integer var2 = 3;" + "boolean var3 = null;" + "long i = bitSet(var1,var2,var3); return 0;}","test_bitwise_bitSet_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "long var1 = 512l;" + "integer var2 = null;" + "boolean var3 = true;" + "long i = bitSet(var1,var2,var3); return 0;}","test_bitwise_bitSet_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "long var1 = null;" + "integer var2 = 3;" + "boolean var3 = true;" + "long i = bitSet(var1,var2,var3); return 0;}","test_bitwise_bitSet_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_bitwise_bitIsSet(){ doCompile("test_bitwise_bitIsSet"); check("test1", true); check("test2", false); check("test3", false); check("test4", false); check("test5", true); check("test6", false); check("test7", false); check("test8", false); } public void test_bitwise_bitIsSet_expect_error(){ try { doCompile("function integer transform(){integer i = null; boolean b = bitIsSet(i,3); return 0;}","test_bitwise_bitIsSet_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer i = null; boolean b = bitIsSet(11,i); return 0;}","test_bitwise_bitIsSet_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long i = null; boolean b = bitIsSet(i,3); return 0;}","test_bitwise_bitIsSet_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long i = 12l; boolean b = bitIsSet(i,null); return 0;}","test_bitwise_bitIsSet_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_bitwise_or() { doCompile("test_bitwise_or"); check("resultInt1", 1); check("resultInt2", 1); check("resultInt3", 3); check("resultInt4", 3); check("resultLong1", 1l); check("resultLong2", 1l); check("resultLong3", 3l); check("resultLong4", 3l); check("resultMix1", 15L); check("resultMix2", 15L); } public void test_bitwise_or_expect_error(){ try { doCompile("function integer transform(){" + "integer input1 = 12; " + "integer input2 = null; " + "integer i = bitOr(input1, input2); return 0;}","test_bitwise_or_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "integer input1 = null; " + "integer input2 = 13; " + "integer i = bitOr(input1, input2); return 0;}","test_bitwise_or_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "long input1 = null; " + "long input2 = 13l; " + "long i = bitOr(input1, input2); return 0;}","test_bitwise_or_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "long input1 = 23l; " + "long input2 = null; " + "long i = bitOr(input1, input2); return 0;}","test_bitwise_or_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_bitwise_and() { doCompile("test_bitwise_and"); check("resultInt1", 0); check("resultInt2", 1); check("resultInt3", 0); check("resultInt4", 1); check("resultLong1", 0l); check("resultLong2", 1l); check("resultLong3", 0l); check("resultLong4", 1l); check("test_mixed1", 4l); check("test_mixed2", 4l); } public void test_bitwise_and_expect_error(){ try { doCompile("function integer transform(){\n" + "integer a = null; integer b = 16;\n" + "integer i = bitAnd(a,b);\n" + "return 0;}", "test_bitwise_end_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){\n" + "integer a = 16; integer b = null;\n" + "integer i = bitAnd(a,b);\n" + "return 0;}", "test_bitwise_end_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){\n" + "long a = 16l; long b = null;\n" + "long i = bitAnd(a,b);\n" + "return 0;}", "test_bitwise_end_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){\n" + "long a = null; long b = 10l;\n" + "long i = bitAnd(a,b);\n" + "return 0;}", "test_bitwise_end_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_bitwise_xor() { doCompile("test_bitwise_xor"); check("resultInt1", 1); check("resultInt2", 0); check("resultInt3", 3); check("resultInt4", 2); check("resultLong1", 1l); check("resultLong2", 0l); check("resultLong3", 3l); check("resultLong4", 2l); check("test_mixed1", 15L); check("test_mixed2", 60L); } public void test_bitwise_xor_expect_error(){ try { doCompile("function integer transform(){" + "integer var1 = null;" + "integer var2 = 123;" + "integer i = bitXor(var1,var2); return 0;}","test_bitwise_xor_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "integer var1 = 23;" + "integer var2 = null;" + "integer i = bitXor(var1,var2); return 0;}","test_bitwise_xor_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "long var1 = null;" + "long var2 = 123l;" + "long i = bitXor(var1,var2); return 0;}","test_bitwise_xor_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "long var1 = 2135l;" + "long var2 = null;" + "long i = bitXor(var1,var2); return 0;}","test_bitwise_xor_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_bitwise_lshift() { doCompile("test_bitwise_lshift"); check("resultInt1", 2); check("resultInt2", 4); check("resultInt3", 10); check("resultInt4", 20); check("resultInt5", -2147483648); check("resultLong1", 2l); check("resultLong2", 4l); check("resultLong3", 10l); check("resultLong4", 20l); check("resultLong5",-9223372036854775808l); } public void test_bitwise_lshift_expect_error(){ try { doCompile("function integer transform(){integer input = null; integer i = bitLShift(input,2); return 0;}","test_bitwise_lshift_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer input = null; integer i = bitLShift(44,input); return 0;}","test_bitwise_lshift_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long input = null; long i = bitLShift(input,4l); return 0;}","test_bitwise_lshift_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long input = null; long i = bitLShift(444l,input); return 0;}","test_bitwise_lshift_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_bitwise_rshift() { doCompile("test_bitwise_rshift"); check("resultInt1", 2); check("resultInt2", 0); check("resultInt3", 4); check("resultInt4", 2); check("resultLong1", 2l); check("resultLong2", 0l); check("resultLong3", 4l); check("resultLong4", 2l); check("test_neg1", 0); check("test_neg2", 0); check("test_neg3", 0l); check("test_neg4", 0l); // CLO-1399 // check("test_mix1", 2); // check("test_mix2", 2); } public void test_bitwise_rshift_expect_error(){ try { doCompile("function integer transform(){" + "integer var1 = 23;" + "integer var2 = null;" + "integer i = bitRShift(var1,var2);" + "return 0;}","test_bitwise_rshift_expect_error"); fail(); } catch (Exception e) { // do nothing; } try { doCompile("function integer transform(){" + "integer var1 = null;" + "integer var2 = 78;" + "integer u = bitRShift(var1,var2);" + "return 0;}","test_bitwise_rshift_expect_error"); fail(); } catch (Exception e) { // do nothing; } try { doCompile("function integer transform(){" + "long var1 = 23l;" + "long var2 = null;" + "long l =bitRShift(var1,var2);" + "return 0;}","test_bitwise_rshift_expect_error"); fail(); } catch (Exception e) { // do nothing; } try { doCompile("function integer transform(){" + "long var1 = null;" + "long var2 = 84l;" + "long l = bitRShift(var1,var2);" + "return 0;}","test_bitwise_rshift_expect_error"); fail(); } catch (Exception e) { // do nothing; } } public void test_bitwise_negate() { doCompile("test_bitwise_negate"); check("resultInt", -59081717); check("resultLong", -3321654987654105969L); check("test_zero_int", -1); check("test_zero_long", -1l); } public void test_bitwise_negate_expect_error(){ try { doCompile("function integer transform(){integer input = null; integer i = bitNegate(input); return 0;}","test_bitwise_negate_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long input = null; long i = bitNegate(input); return 0;}","test_bitwise_negate_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_set_bit() { doCompile("test_set_bit"); check("resultInt1", 0x2FF); check("resultInt2", 0xFB); check("resultLong1", 0x4000000000000l); check("resultLong2", 0xFFDFFFFFFFFFFFFl); check("resultBool1", true); check("resultBool2", false); check("resultBool3", true); check("resultBool4", false); } public void test_mathlib_abs() { doCompile("test_mathlib_abs"); check("absIntegerPlus", new Integer(10)); check("absIntegerMinus", new Integer(1)); check("absLongPlus", new Long(10)); check("absLongMinus", new Long(1)); check("absDoublePlus", new Double(10.0)); check("absDoubleMinus", new Double(1.0)); check("absDecimalPlus", new BigDecimal(5.0)); check("absDecimalMinus", new BigDecimal(5.0)); } public void test_mathlib_abs_expect_error(){ try { doCompile("function integer transform(){ \n " + "integer tmp;\n " + "tmp = null; \n" + " integer i = abs(tmp); \n " + "return 0;}", "test_mathlib_abs_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){ \n " + "long tmp;\n " + "tmp = null; \n" + "long i = abs(tmp); \n " + "return 0;}", "test_mathlib_abs_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){ \n " + "double tmp;\n " + "tmp = null; \n" + "double i = abs(tmp); \n " + "return 0;}", "test_mathlib_abs_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){ \n " + "decimal tmp;\n " + "tmp = null; \n" + "decimal i = abs(tmp); \n " + "return 0;}", "test_mathlib_abs_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_mathlib_ceil() { doCompile("test_mathlib_ceil"); check("ceil1", -3.0); check("intResult", Arrays.asList(2.0, 3.0)); check("longResult", Arrays.asList(2.0, 3.0)); check("doubleResult", Arrays.asList(3.0, -3.0)); check("decimalResult", Arrays.asList(3.0, -3.0)); } public void test_mathlib_ceil_expect_error(){ try { doCompile("function integer transform(){integer var = null; double d = ceil(var); return 0;}","test_mathlib_ceil_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long var = null; double d = ceil(var); return 0;}","test_mathlib_ceil_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){double var = null; double d = ceil(var); return 0;}","test_mathlib_ceil_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){decimal var = null; double d = ceil(var); return 0;}","test_mathlib_ceil_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_mathlib_e() { doCompile("test_mathlib_e"); check("varE", Math.E); } public void test_mathlib_exp() { doCompile("test_mathlib_exp"); check("ex", Math.exp(1.123)); check("test1", Math.exp(2)); check("test2", Math.exp(22)); check("test3", Math.exp(23)); check("test4", Math.exp(94)); } public void test_mathlib_exp_expect_error(){ try { doCompile("function integer transform(){integer input = null; number n = exp(input); return 0;}","test_mathlib_exp_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long input = null; number n = exp(input); return 0;}","test_mathlib_exp_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){double input = null; number n = exp(input); return 0;}","test_mathlib_exp_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){number input = null; number n = exp(input); return 0;}","test_mathlib_exp_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_mathlib_floor() { doCompile("test_mathlib_floor"); check("floor1", -4.0); check("intResult", Arrays.asList(2.0, 3.0)); check("longResult", Arrays.asList(2.0, 3.0)); check("doubleResult", Arrays.asList(2.0, -4.0)); check("decimalResult", Arrays.asList(2.0, -4.0)); } public void test_math_lib_floor_expect_error(){ try { doCompile("function integer transform(){integer input = null; double d = floor(input); return 0;}","test_math_lib_floor_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long input= null; double d = floor(input); return 0;}","test_math_lib_floor_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){double input = null; double d = floor(input); return 0;}","test_math_lib_floor_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){decimal input = null; double d = floor(input); return 0;}","test_math_lib_floor_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){number input = null; double d = floor(input); return 0;}","test_math_lib_floor_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_mathlib_log() { doCompile("test_mathlib_log"); check("ln", Math.log(3)); check("test_int", Math.log(32)); check("test_long", Math.log(14l)); check("test_double", Math.log(12.9)); check("test_decimal", Math.log(23.7)); } public void test_math_log_expect_error(){ try { doCompile("function integer transform(){integer input = null; number n = log(input); return 0;}","test_math_log_expect_error"); fail(); } catch (Exception e) { // do nothing; } try { doCompile("function integer transform(){long input = null; number n = log(input); return 0;}","test_math_log_expect_error"); fail(); } catch (Exception e) { // do nothing; } try { doCompile("function integer transform(){decimal input = null; number n = log(input); return 0;}","test_math_log_expect_error"); fail(); } catch (Exception e) { // do nothing; } try { doCompile("function integer transform(){double input = null; number n = log(input); return 0;}","test_math_log_expect_error"); fail(); } catch (Exception e) { // do nothing; } } public void test_mathlib_log10() { doCompile("test_mathlib_log10"); check("varLog10", Math.log10(3)); check("test_int", Math.log10(5)); check("test_long", Math.log10(90L)); check("test_decimal", Math.log10(32.1)); check("test_number", Math.log10(84.12)); } public void test_mathlib_log10_expect_error(){ try { doCompile("function integer transform(){integer input = null; number n = log10(input); return 0;}","test_mathlib_log10_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long input = null; number n = log10(input); return 0;}","test_mathlib_log10_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){number input = null; number n = log10(input); return 0;}","test_mathlib_log10_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){decimal input = null; number n = log10(input); return 0;}","test_mathlib_log10_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_mathlib_pi() { doCompile("test_mathlib_pi"); check("varPi", Math.PI); } public void test_mathlib_pow() { doCompile("test_mathlib_pow"); check("power1", Math.pow(3,1.2)); check("power2", Double.NaN); check("intResult", Arrays.asList(8d, 8d, 8d, 8d)); check("longResult", Arrays.asList(8d, 8d, 8d, 8d)); check("doubleResult", Arrays.asList(8d, 8d, 8d, 8d)); check("decimalResult", Arrays.asList(8d, 8d, 8d, 8d)); } public void test_mathlib_pow_expect_error(){ try { doCompile("function integer transform(){integer var1 = 12; integer var2 = null; number n = pow(var1, var2); return 0;}","test_mathlib_pow_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer var1 = null; integer var2 = 2; number n = pow(var1, var2); return 0;}","test_mathlib_pow_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long var1 = 12l; long var2 = null; number n = pow(var1, var2); return 0;}","test_mathlib_pow_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long var1 = null; long var2 = 12L; number n = pow(var1, var2); return 0;}","test_mathlib_pow_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){number var1 = 12.2; number var2 = null; number n = pow(var1, var2); return 0;}","test_mathlib_pow_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){number var1 = null; number var2 = 2.1; number n = pow(var1, var2); return 0;}","test_mathlib_pow_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){decimal var1 = 12.2d; decimal var2 = null; number n = pow(var1, var2); return 0;}","test_mathlib_pow_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){decimal var1 = null; decimal var2 = 45.3d; number n = pow(var1, var2); return 0;}","test_mathlib_pow_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_mathlib_round() { doCompile("test_mathlib_round"); check("round1", -4l); check("intResult", Arrays.asList(2l, 3l)); check("longResult", Arrays.asList(2l, 3l)); check("doubleResult", Arrays.asList(2l, 4l)); check("decimalResult", Arrays.asList(2l, 4l)); } public void test_mathlib_round_expect_error(){ try { doCompile("function integer transform(){number input = null; long l = round(input);return 0;}","test_mathlib_round_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){decimal input = null; long l = round(input);return 0;}","test_mathlib_round_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_mathlib_sqrt() { doCompile("test_mathlib_sqrt"); check("sqrtPi", Math.sqrt(Math.PI)); check("sqrt9", Math.sqrt(9)); check("test_int", 2.0); check("test_long", Math.sqrt(64L)); check("test_num", Math.sqrt(86.9)); check("test_dec", Math.sqrt(34.5)); } public void test_mathlib_sqrt_expect_error(){ try { doCompile("function integer transform(){integer input = null; number num = sqrt(input);return 0;}","test_mathlib_sqrt_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long input = null; number num = sqrt(input);return 0;}","test_mathlib_sqrt_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){number input = null; number num = sqrt(input);return 0;}","test_mathlib_sqrt_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){decimal input = null; number num = sqrt(input);return 0;}","test_mathlib_sqrt_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_mathlib_randomInteger(){ doCompile("test_mathlib_randomInteger"); assertNotNull(getVariable("test1")); check("test2", 2); } public void test_mathlib_randomInteger_expect_error(){ try { doCompile("function integer transform(){integer i = randomInteger(1,null); return 0;}","test_mathlib_randomInteger_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer i = randomInteger(null,null); return 0;}","test_mathlib_randomInteger_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer i = randomInteger(null, -3); return 0;}","test_mathlib_randomInteger_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer i = randomInteger(1,-7); return 0;}","test_mathlib_randomInteger_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_mathlib_randomLong(){ doCompile("test_mathlib_randomLong"); assertNotNull(getVariable("test1")); check("test2", 15L); } public void test_mathlib_randomLong_expect_error(){ try { doCompile("function integer transform(){long lo = randomLong(15L, null); return 0;}","test_mathlib_randomLong_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long lo = randomLong(null, null); return 0;}","test_mathlib_randomLong_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long lo = randomLong(null, 15L); return 0;}","test_mathlib_randomLong_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long lo = randomLong(15L, 10L); return 0;}","test_mathlib_randomLong_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_datelib_cache() { doCompile("test_datelib_cache"); check("b11", true); check("b12", true); check("b21", true); check("b22", true); check("b31", true); check("b32", true); check("b41", true); check("b42", true); checkEquals("date3", "date3d"); checkEquals("date4", "date4d"); checkEquals("date7", "date7d"); checkEquals("date8", "date8d"); } public void test_datelib_trunc() { doCompile("test_datelib_trunc"); check("truncDate", new GregorianCalendar(2004, 00, 02).getTime()); } public void test_datelib_trunc_except_error(){ try { doCompile("function integer transform(){trunc(null); return 0;}","test_datelib_trunc_except_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){date d = null; trunc(d); return 0;}","test_datelib_trunc_except_error"); fail(); } catch (Exception e) { // do nothing } } public void test_datelib_truncDate() { doCompile("test_datelib_truncDate"); Calendar cal = Calendar.getInstance(); cal.setTime(BORN_VALUE); int[] portion = new int[]{cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND),cal.get(Calendar.MILLISECOND)}; cal.clear(); cal.set(Calendar.HOUR_OF_DAY, portion[0]); cal.set(Calendar.MINUTE, portion[1]); cal.set(Calendar.SECOND, portion[2]); cal.set(Calendar.MILLISECOND, portion[3]); check("truncBornDate", cal.getTime()); } public void test_datelib_truncDate_except_error(){ try { doCompile("function integer transform(){truncDate(null); return 0;}","test_datelib_truncDate_except_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){date d = null; truncDate(d); return 0;}","test_datelib_truncDate_except_error"); fail(); } catch (Exception e) { // do nothing } } public void test_datelib_today() { doCompile("test_datelib_today"); Date expectedDate = new Date(); //the returned date does not need to be exactly the same date which is in expectedData variable //let say 1000ms is tolerance for equality assertTrue("todayDate", Math.abs(expectedDate.getTime() - ((Date) getVariable("todayDate")).getTime()) < 1000); } public void test_datelib_zeroDate() { doCompile("test_datelib_zeroDate"); check("zeroDate", new Date(0)); } public void test_datelib_dateDiff() { doCompile("test_datelib_dateDiff"); long diffYears = Years.yearsBetween(new DateTime(), new DateTime(BORN_VALUE)).getYears(); check("ddiff", diffYears); long[] results = {1, 12, 52, 365, 8760, 525600, 31536000, 31536000000L}; String[] vars = {"ddiffYears", "ddiffMonths", "ddiffWeeks", "ddiffDays", "ddiffHours", "ddiffMinutes", "ddiffSeconds", "ddiffMilliseconds"}; for (int i = 0; i < results.length; i++) { check(vars[i], results[i]); } } public void test_datelib_dateDiff_epect_error(){ try { doCompile("function integer transform(){long i = dateDiff(null,today(),millisec);return 0;}","test_datelib_dateDiff_epect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long i = dateDiff(today(),null,millisec);return 0;}","test_datelib_dateDiff_epect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long i = dateDiff(today(),today(),null);return 0;}","test_datelib_dateDiff_epect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_datelib_dateAdd() { doCompile("test_datelib_dateAdd"); check("datum", new Date(BORN_MILLISEC_VALUE + 100)); } public void test_datelib_dateAdd_expect_error(){ try { doCompile("function integer transform(){date d = dateAdd(null,120,second); return 0;}","test_datelib_dateAdd_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){date d = dateAdd(today(),null,second); return 0;}","test_datelib_dateAdd_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){date d = dateAdd(today(),120,null); return 0;}","test_datelib_dateAdd_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_datelib_extractTime() { doCompile("test_datelib_extractTime"); Calendar cal = Calendar.getInstance(); cal.setTime(BORN_VALUE); int[] portion = new int[]{cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE), cal.get(Calendar.SECOND),cal.get(Calendar.MILLISECOND)}; cal.clear(); cal.set(Calendar.HOUR_OF_DAY, portion[0]); cal.set(Calendar.MINUTE, portion[1]); cal.set(Calendar.SECOND, portion[2]); cal.set(Calendar.MILLISECOND, portion[3]); check("bornExtractTime", cal.getTime()); check("originalDate", BORN_VALUE); check("nullDate", null); check("nullDate2", null); } public void test_datelib_extractDate() { doCompile("test_datelib_extractDate"); Calendar cal = Calendar.getInstance(); cal.setTime(BORN_VALUE); int[] portion = new int[]{cal.get(Calendar.DAY_OF_MONTH), cal.get(Calendar.MONTH), cal.get(Calendar.YEAR)}; cal.clear(); cal.set(Calendar.DAY_OF_MONTH, portion[0]); cal.set(Calendar.MONTH, portion[1]); cal.set(Calendar.YEAR, portion[2]); check("bornExtractDate", cal.getTime()); check("originalDate", BORN_VALUE); check("nullDate", null); check("nullDate2", null); } public void test_datelib_createDate() { doCompile("test_datelib_createDate"); Calendar cal = Calendar.getInstance(); // no time zone cal.clear(); cal.set(2013, 5, 11); check("date1", cal.getTime()); cal.clear(); cal.set(2013, 5, 11, 14, 27, 53); check("dateTime1", cal.getTime()); cal.clear(); cal.set(2013, 5, 11, 14, 27, 53); cal.set(Calendar.MILLISECOND, 123); check("dateTimeMillis1", cal.getTime()); // literal cal.setTimeZone(TimeZone.getTimeZone("GMT+5")); cal.clear(); cal.set(2013, 5, 11); check("date2", cal.getTime()); cal.clear(); cal.set(2013, 5, 11, 14, 27, 53); check("dateTime2", cal.getTime()); cal.clear(); cal.set(2013, 5, 11, 14, 27, 53); cal.set(Calendar.MILLISECOND, 123); check("dateTimeMillis2", cal.getTime()); // variable cal.clear(); cal.set(2013, 5, 11); check("date3", cal.getTime()); cal.clear(); cal.set(2013, 5, 11, 14, 27, 53); check("dateTime3", cal.getTime()); cal.clear(); cal.set(2013, 5, 11, 14, 27, 53); cal.set(Calendar.MILLISECOND, 123); check("dateTimeMillis3", cal.getTime()); Calendar cal1 = Calendar.getInstance(); cal1.set(2011, 10, 20, 0, 0, 0); cal1.set(Calendar.MILLISECOND, 0); Date d = cal1.getTime(); // CLO-1674 // check("ret1", d); check("ret2", d); cal1.clear(); cal1.set(2011, 10, 20, 4, 20, 11); cal1.set(Calendar.MILLISECOND, 0); check("ret3", cal1.getTime()); cal1.clear(); cal1.set(2011, 10, 20, 4, 20, 11); cal1.set(Calendar.MILLISECOND, 123); d = cal1.getTime(); check("ret4", d); // CLO-1674 // check("ret5", d); } public void test_datelib_createDate_expect_error(){ try { doCompile("function integer transform(){date d = createDate(null, null, null); return 0;}","test_datelib_createDate_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){date d = createDate(1970, null, null); return 0;}","test_datelib_createDate_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){date d = createDate(1970, 10, null); return 0;}","test_datelib_createDate_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){date d = createDate(1970, 11, 20, null, 5, 45); return 0;}","test_datelib_createDate_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){date d = createDate(1970, 11, 20, 12, null, 45); return 0;}","test_datelib_createDate_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){date d = createDate(1970, 11, 20, 12, 5, null); return 0;}","test_datelib_createDate_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer str = null; date d = createDate(1970, 11, 20, 12, 5, 45, str); return 0;}","test_datelib_createDate_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_datelib_getPart() { doCompile("test_datelib_getPart"); Calendar cal = Calendar.getInstance(); cal.clear(); cal.setTimeZone(TimeZone.getTimeZone("GMT+1")); cal.set(2013, 5, 11, 14, 46, 34); cal.set(Calendar.MILLISECOND, 123); Date date = cal.getTime(); cal = Calendar.getInstance(); cal.setTime(date); // no time zone check("year1", cal.get(Calendar.YEAR)); check("month1", cal.get(Calendar.MONTH) + 1); check("day1", cal.get(Calendar.DAY_OF_MONTH)); check("hour1", cal.get(Calendar.HOUR_OF_DAY)); check("minute1", cal.get(Calendar.MINUTE)); check("second1", cal.get(Calendar.SECOND)); check("millisecond1", cal.get(Calendar.MILLISECOND)); cal.setTimeZone(TimeZone.getTimeZone("GMT+5")); // literal check("year2", cal.get(Calendar.YEAR)); check("month2", cal.get(Calendar.MONTH) + 1); check("day2", cal.get(Calendar.DAY_OF_MONTH)); check("hour2", cal.get(Calendar.HOUR_OF_DAY)); check("minute2", cal.get(Calendar.MINUTE)); check("second2", cal.get(Calendar.SECOND)); check("millisecond2", cal.get(Calendar.MILLISECOND)); // variable check("year3", cal.get(Calendar.YEAR)); check("month3", cal.get(Calendar.MONTH) + 1); check("day3", cal.get(Calendar.DAY_OF_MONTH)); check("hour3", cal.get(Calendar.HOUR_OF_DAY)); check("minute3", cal.get(Calendar.MINUTE)); check("second3", cal.get(Calendar.SECOND)); check("millisecond3", cal.get(Calendar.MILLISECOND)); check("year_null", 2013); check("month_null", 6); check("day_null", 11); check("hour_null", 15); check("minute_null", cal.get(Calendar.MINUTE)); check("second_null", cal.get(Calendar.SECOND)); check("milli_null", cal.get(Calendar.MILLISECOND)); check("year_null2", null); check("month_null2", null); check("day_null2", null); check("hour_null2", null); check("minute_null2", null); check("second_null2", null); check("milli_null2", null); check("year_null3", null); check("month_null3", null); check("day_null3", null); check("hour_null3", null); check("minute_null3", null); check("second_null3", null); check("milli_null3", null); } public void test_datelib_randomDate() { doCompile("test_datelib_randomDate"); final long HOUR = 60L * 60L * 1000L; Date BORN_VALUE_NO_MILLIS = new Date(BORN_VALUE.getTime() / 1000L * 1000L); check("noTimeZone1", BORN_VALUE); check("noTimeZone2", BORN_VALUE_NO_MILLIS); check("withTimeZone1", new Date(BORN_VALUE_NO_MILLIS.getTime() + 2*HOUR)); // timezone changes from GMT+5 to GMT+3 check("withTimeZone2", new Date(BORN_VALUE_NO_MILLIS.getTime() - 2*HOUR)); // timezone changes from GMT+3 to GMT+5 assertNotNull(getVariable("patt_null")); assertNotNull(getVariable("ret1")); assertNotNull(getVariable("ret2")); } public void test_datelib_randomDate_expect_error(){ try { doCompile("function integer transform(){date a = null; date b = today(); " + "date d = randomDate(a,b); return 0;}","test_datelib_randomDate_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){date a = today(); date b = null; " + "date d = randomDate(a,b); return 0;}","test_datelib_randomDate_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){date a = null; date b = null; " + "date d = randomDate(a,b); return 0;}","test_datelib_randomDate_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long a = 843484317231l; long b = null; " + "date d = randomDate(a,b); return 0;}","test_datelib_randomDate_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long a = null; long b = 12115641158l; " + "date d = randomDate(a,b); return 0;}","test_datelib_randomDate_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long a = null; long b = null; " + "date d = randomDate(a,b); return 0;}","test_datelib_randomDate_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "string a = null; string b = '2006-11-12'; string pattern='yyyy-MM-dd';" + "date d = randomDate(a,b,pattern); return 0;}","test_datelib_randomDate_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){" + "string a = '2006-11-12'; string b = null; string pattern='yyyy-MM-dd';" + "date d = randomDate(a,b,pattern); return 0;}","test_datelib_randomDate_expect_error"); fail(); } catch (Exception e) { // do nothing } //wrong format try { doCompile("function integer transform(){" + "string a = '2006-10-12'; string b = '2006-11-12'; string pattern='yyyy:MM:dd';" + "date d = randomDate(a,b,pattern); return 0;}","test_datelib_randomDate_expect_error"); fail(); } catch (Exception e) { // do nothing } //start date bigger then end date try { doCompile("function integer transform(){" + "string a = '2008-10-12'; string b = '2006-11-12'; string pattern='yyyy-MM-dd';" + "date d = randomDate(a,b,pattern); return 0;}","test_datelib_randomDate_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_json2xml(){ doCompile("test_convertlib_json2xml"); String xmlChunk ="" + "<lastName>Smith</lastName>" + "<phoneNumber>" + "<number>212 555-1234</number>" + "<type>home</type>" + "</phoneNumber>" + "<phoneNumber>" + "<number>646 555-4567</number>" + "<type>fax</type>" + "</phoneNumber>" + "<address>" + "<streetAddress>21 2nd Street</streetAddress>" + "<postalCode>10021</postalCode>" + "<state>NY</state>" + "<city>New York</city>" + "</address>" + "<age>25</age>" + "<firstName>John</firstName>"; check("ret", xmlChunk); check("ret2", "<name/>"); check("ret3", "<address></address>"); check("ret4", "</>"); check("ret5", "< check("ret6", "</>/< check("ret7",""); check("ret8", "<>Urgot</>"); } public void test_convertlib_json2xml_expect_error(){ try { doCompile("function integer transform(){string str = json2xml(''); return 0;}","test_convertlib_json2xml_expect_error"); fail(); } catch (Exception e) { // do nothing; } try { doCompile("function integer transform(){string str = json2xml(null); return 0;}","test_convertlib_json2xml_expect_error"); fail(); } catch (Exception e) { // do nothing; } try { doCompile("function integer transform(){string str = json2xml('{\"name\"}'); return 0;}","test_convertlib_json2xml_expect_error"); fail(); } catch (Exception e) { // do nothing; } try { doCompile("function integer transform(){string str = json2xml('{\"name\":}'); return 0;}","test_convertlib_json2xml_expect_error"); fail(); } catch (Exception e) { // do nothing; } try { doCompile("function integer transform(){string str = json2xml('{:\"name\"}'); return 0;}","test_convertlib_json2xml_expect_error"); fail(); } catch (Exception e) { // do nothing; } } public void test_convertlib_xml2json(){ doCompile("test_convertlib_xml2json"); String json = "{\"lastName\":\"Smith\",\"phoneNumber\":[{\"number\":\"212 555-1234\",\"type\":\"home\"},{\"number\":\"646 555-4567\",\"type\":\"fax\"}],\"address\":{\"streetAddress\":\"21 2nd Street\",\"postalCode\":10021,\"state\":\"NY\",\"city\":\"New York\"},\"age\":25,\"firstName\":\"John\"}"; check("ret1", json); check("ret2", "{\"name\":\"Renektor\"}"); check("ret3", "{}"); check("ret4", "{\"address\":\"\"}"); check("ret5", "{\"age\":32}"); check("ret6", "{\"b\":\"\"}"); check("ret7", "{\"char\":{\"name\":\"Anivia\",\"lane\":\"mid\"}}"); check("ret8", "{\" } public void test_convertlib_xml2json_expect_error(){ try { doCompile("function integer transform(){string json = xml2json(null); return 0;}","test_convertlib_xml2json_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string json = xml2json('<></>'); return 0;}","test_convertlib_xml2json_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string json = xml2json('<#>/</>'); return 0;}","test_convertlib_xml2json_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_cache() { // set default locale to en.US so the date is formatted uniformly on all systems Locale.setDefault(Locale.US); doCompile("test_convertlib_cache"); Calendar cal = Calendar.getInstance(); cal.set(2000, 6, 20, 0, 0, 0); cal.set(Calendar.MILLISECOND, 0); Date checkDate = cal.getTime(); final SimpleDateFormat format = new SimpleDateFormat(); format.applyPattern("yyyy MMM dd"); check("sdate1", format.format(new Date())); check("sdate2", format.format(new Date())); check("date01", checkDate); check("date02", checkDate); check("date03", checkDate); check("date04", checkDate); check("date11", checkDate); check("date12", checkDate); check("date13", checkDate); } public void test_convertlib_base64byte() { doCompile("test_convertlib_base64byte"); assertTrue(Arrays.equals((byte[])getVariable("base64input"), Base64.decode("The quick brown fox jumps over the lazy dog"))); } public void test_convertlib_base64byte_expect_error(){ //this test should be expected to success in future try { doCompile("function integer transform(){byte b = base64byte(null); return 0;}","test_convertlib_base64byte_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string s = null; byte b = base64byte(s); return 0;}","test_convertlib_base64byte_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_bits2str() { doCompile("test_convertlib_bits2str"); check("bitsAsString1", "00000000"); check("bitsAsString2", "11111111"); check("bitsAsString3", "010100000100110110100000"); } public void test_convertlib_bits2str_expect_error(){ //this test should be expected to success in future try { doCompile("function integer transform(){string s = bits2str(null); return 0;}","test_convertlib_bits2str_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){byte b = null; string s = bits2str(b); return 0;}","test_convertlib_bits2str_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_bool2num() { doCompile("test_convertlib_bool2num"); check("resultTrue", 1); check("resultFalse", 0); check("nullRet1", null); check("nullRet2", null); } public void test_convertlib_byte2base64() throws UnsupportedEncodingException { doCompile("test_convertlib_byte2base64"); check("inputBase64", Base64.encodeBytes("Abeceda zedla deda".getBytes())); String longText = (String) getVariable("longText"); byte[] longTextBytes = longText.getBytes("UTF-8"); String inputBase64wrapped = Base64.encodeBytes(longTextBytes, Base64.NO_OPTIONS); String inputBase64nowrap = Base64.encodeBytes(longTextBytes, Base64.DONT_BREAK_LINES); check("inputBase64wrapped", inputBase64wrapped); assertTrue(((String) getVariable("inputBase64wrapped")).indexOf('\n') >= 0); check("inputBase64nowrap", inputBase64nowrap); assertTrue(((String) getVariable("inputBase64nowrap")).indexOf('\n') < 0); } public void test_convertlib_byte2base64_expect_error(){ try { doCompile("function integer transform(){string s = byte2base64(null);return 0;}","test_convertlib_byte2base64_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){byte b = null; string s = byte2base64(b);return 0;}","test_convertlib_byte2base64_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){boolean b = null; string s = byte2base64(str2byte('Rengar', 'utf-8'), b);return 0;}","test_convertlib_byte2base64_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string s = byte2base64(str2byte('Rengar', 'utf-8'), null);return 0;}","test_convertlib_byte2base64_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_byte2hex() { doCompile("test_convertlib_byte2hex"); check("hexResult", "41626563656461207a65646c612064656461"); check("test_null1", null); check("test_null2", null); } public void test_convertlib_date2long() { doCompile("test_convertlib_date2long"); check("bornDate", BORN_MILLISEC_VALUE); check("zeroDate", 0l); check("nullRet1", null); check("nullRet2", null); } public void test_convertlib_date2num() { doCompile("test_convertlib_date2num"); Calendar cal = Calendar.getInstance(); cal.setTime(BORN_VALUE); check("yearDate", 1987); check("monthDate", 5); check("secondDate", 0); check("yearBorn", cal.get(Calendar.YEAR)); check("monthBorn", cal.get(Calendar.MONTH) + 1); //Calendar enumerates months from 0, not 1; check("secondBorn", cal.get(Calendar.SECOND)); check("yearMin", 1970); check("monthMin", 1); check("weekMin", 1); check("weekMinCs", 1); check("dayMin", 1); check("hourMin", 1); //TODO: check! check("minuteMin", 0); check("secondMin", 0); check("millisecMin", 0); check("nullRet1", null); check("nullRet2", null); } public void test_convertlib_date2num_expect_error(){ try { doCompile("function integer transform(){number num = date2num(1982-09-02,null); return 0;}","test_convertlib_date2num_expect_error"); fail(); } catch (Exception e) { // do nothing; } try { doCompile("function integer transform(){number num = date2num(1982-09-02,null,null); return 0;}","test_convertlib_date2num_expect_error"); fail(); } catch (Exception e) { // do nothing; } try { doCompile("function integer transform(){string s = null; number num = date2num(1982-09-02,null,s); return 0;}","test_convertlib_date2num_expect_error"); fail(); } catch (Exception e) { // do nothing; } try { doCompile("function integer transform(){string s = null; number num = date2num(1982-09-02,year,s); return 0;}","test_convertlib_date2num_expect_error"); fail(); } catch (Exception e) { // do nothing; } } public void test_convertlib_date2str() { doCompile("test_convertlib_date2str"); check("inputDate", "1987:05:12"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy:MM:dd"); check("bornDate", sdf.format(BORN_VALUE)); SimpleDateFormat sdfCZ = new SimpleDateFormat("yyyy:MMMM:dd", MiscUtils.createLocale("cs.CZ")); check("czechBornDate", sdfCZ.format(BORN_VALUE)); SimpleDateFormat sdfEN = new SimpleDateFormat("yyyy:MMMM:dd", MiscUtils.createLocale("en")); check("englishBornDate", sdfEN.format(BORN_VALUE)); { String[] locales = {"en", "pl", null, "cs.CZ", null}; List<String> expectedDates = new ArrayList<String>(); for (String locale: locales) { expectedDates.add(new SimpleDateFormat("yyyy:MMMM:dd", MiscUtils.createLocale(locale)).format(BORN_VALUE)); } check("loopTest", expectedDates); } SimpleDateFormat sdfGMT8 = new SimpleDateFormat("yyyy:MMMM:dd z", MiscUtils.createLocale("en")); sdfGMT8.setTimeZone(TimeZone.getTimeZone("GMT+8")); check("timeZone", sdfGMT8.format(BORN_VALUE)); check("nullRet", null); check("nullRet2", null); check("nullRet3", "2011-04-15"); check("nullRet4", "2011-04-15"); check("nullRet5", "2011-04-15"); } public void test_convertlib_date2str_expect_error(){ try { doCompile("function integer transform(){string str = date2str(2001-12-15, 'xxx.MM.dd'); printErr(str); return 0;}","test_convertlib_date2str_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_decimal2double() { doCompile("test_convertlib_decimal2double"); check("toDouble", 0.007d); check("nullRet1", null); check("nullRet2", null); } public void test_convertlib_decimal2double_expect_error(){ try { String str ="function integer transform(){" + "decimal dec = str2decimal('9"+ Double.MAX_VALUE +"');" + "double dou = decimal2double(dec);" + "return 0;}" ; doCompile(str,"test_convertlib_decimal2double_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_decimal2integer() { doCompile("test_convertlib_decimal2integer"); check("toInteger", 0); check("toInteger2", -500); check("toInteger3", 1000000); check("nullRet1", null); check("nullRet2", null); } public void test_convertlib_decimal2integer_expect_error(){ try { doCompile("function integer transform(){integer int = decimal2integer(352147483647.23);return 0;}","test_convertlib_decimal2integer_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_decimal2long() { doCompile("test_convertlib_decimal2long"); check("toLong", 0l); check("toLong2", -500l); check("toLong3", 10000000000l); check("nullRet1", null); check("nullRet2", null); } public void test_convertlib_decimal2long_expect_error(){ try { doCompile("function integer transform(){long l = decimal2long(9759223372036854775807.25); return 0;}","test_convertlib_decimal2long_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_double2integer() { doCompile("test_convertlib_double2integer"); check("toInteger", 0); check("toInteger2", -500); check("toInteger3", 1000000); check("nullRet1", null); check("nullRet2", null); } public void test_convertlib_double2integer_expect_error(){ try { doCompile("function integer transform(){integer int = double2integer(352147483647.1); return 0;}","test_convertlib_double2integer_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_double2long() { doCompile("test_convertlib_double2long"); check("toLong", 0l); check("toLong2", -500l); check("toLong3", 10000000000l); check("nullRet1", null); check("nullRet2", null); } public void test_convertlib_double2long_expect_error(){ try { doCompile("function integer transform(){long l = double2long(1.3759739E23); return 0;}","test_convertlib_double2long_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_getFieldName() { doCompile("test_convertlib_getFieldName"); check("fieldNames",Arrays.asList("Name", "Age", "City", "Born", "BornMillisec", "Value", "Flag", "ByteArray", "Currency")); } public void test_convertlib_getFieldType() { doCompile("test_convertlib_getFieldType"); check("fieldTypes",Arrays.asList(DataFieldType.STRING.getName(), DataFieldType.NUMBER.getName(), DataFieldType.STRING.getName(), DataFieldType.DATE.getName(), DataFieldType.LONG.getName(), DataFieldType.INTEGER.getName(), DataFieldType.BOOLEAN.getName(), DataFieldType.BYTE.getName(), DataFieldType.DECIMAL.getName())); } public void test_convertlib_hex2byte() { doCompile("test_convertlib_hex2byte"); assertTrue(Arrays.equals((byte[])getVariable("fromHex"), BYTEARRAY_VALUE)); check("test_null", null); } public void test_convertlib_long2date() { doCompile("test_convertlib_long2date"); check("fromLong1", new Date(0)); check("fromLong2", new Date(50000000000L)); check("fromLong3", new Date(-5000L)); check("nullRet1", null); check("nullRet2", null); } public void test_convertlib_long2integer() { doCompile("test_convertlib_long2integer"); check("fromLong1", 10); check("fromLong2", -10); check("nullRet1", null); check("nullRet2", null); } public void test_convertlib_long2integer_expect_error(){ //this test should be expected to success in future try { doCompile("function integer transform(){integer i = long2integer(200032132463123L); return 0;}","test_convertlib_long2integer_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_long2packDecimal() { doCompile("test_convertlib_long2packDecimal"); assertTrue(Arrays.equals((byte[])getVariable("packedLong"), new byte[] {5, 0, 12})); } public void test_convertlib_long2packDecimal_expect_error(){ try { doCompile("function integer transform(){byte b = long2packDecimal(null); return 0;}","test_convertlib_long2packDecimal_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long l = null; byte b = long2packDecimal(l); return 0;}","test_convertlib_long2packDecimal_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_md5() { doCompile("test_convertlib_md5"); assertTrue(Arrays.equals((byte[])getVariable("md5Hash1"), Digest.digest(DigestType.MD5, "The quick brown fox jumps over the lazy dog"))); assertTrue(Arrays.equals((byte[])getVariable("md5Hash2"), Digest.digest(DigestType.MD5, BYTEARRAY_VALUE))); assertTrue(Arrays.equals((byte[])getVariable("test_empty"), Digest.digest(DigestType.MD5, ""))); } public void test_convertlib_md5_expect_error(){ //CLO-1254 try { doCompile("function integer transform(){string s = null; byte b = md5(s); return 0;}","test_convertlib_md5_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){byte s = null; byte b = md5(s); return 0;}","test_convertlib_md5_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_num2bool() { doCompile("test_convertlib_num2bool"); check("integerTrue", true); check("integerFalse", false); check("longTrue", true); check("longFalse", false); check("doubleTrue", true); check("doubleFalse", false); check("decimalTrue", true); check("decimalFalse", false); check("nullInt", null); check("nullLong", null); check("nullDouble", null); check("nullDecimal", null); } public void test_convertlib_num2str() { System.out.println("num2str() test:"); doCompile("test_convertlib_num2str"); check("intOutput", Arrays.asList("16", "10000", "20", "10", "1.235E3", "12 350 001 Kcs")); check("longOutput", Arrays.asList("16", "10000", "20", "10", "1.235E13", "12 350 001 Kcs")); check("doubleOutput", Arrays.asList("16.16", "0x1.028f5c28f5c29p4", "1.23548E3", "12 350 001,1 Kcs")); check("decimalOutput", Arrays.asList("16.16", "1235.44", "12 350 001,1 Kcs")); check("nullIntRet", Arrays.asList(null,null,null,null,"12","12",null,null)); check("nullLongRet", Arrays.asList(null,null,null,null,"12","12",null,null)); check("nullDoubleRet", Arrays.asList(null,null,null,null,"12.2","12.2",null,null)); check("nullDecRet", Arrays.asList(null,null,null,"12.2","12.2",null,null)); } public void test_convertlib_num2str_expect_error(){ try { doCompile("function integer transform(){integer var = null; string ret = num2str(12, var); return 0;}","test_convertlib_num2str_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer var = null; string ret = num2str(12L, var); return 0;}","test_convertlib_num2str_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer var = null; string ret = num2str(12.3, var); return 0;}","test_convertlib_num2str_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string ret = num2str(12.3, 2); return 0;}","test_convertlib_num2str_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string ret = num2str(12.3, 8); return 0;}","test_convertlib_num2str_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_packdecimal2long() { doCompile("test_convertlib_packDecimal2long"); check("unpackedLong", PackedDecimal.parse(BYTEARRAY_VALUE)); } public void test_convertlib_packdecimal2long_expect_error(){ try { doCompile("function integer transform(){long l = packDecimal2long(null); return 0;}","test_convertlib_packdecimal2long_expect_error"); fail(); } catch (Exception e) { // do nothing; } try { doCompile("function integer transform(){byte b = null; long l = packDecimal2long(b); return 0;}","test_convertlib_packdecimal2long_expect_error"); fail(); } catch (Exception e) { // do nothing; } } public void test_convertlib_sha() { doCompile("test_convertlib_sha"); assertTrue(Arrays.equals((byte[])getVariable("shaHash1"), Digest.digest(DigestType.SHA, "The quick brown fox jumps over the lazy dog"))); assertTrue(Arrays.equals((byte[])getVariable("shaHash2"), Digest.digest(DigestType.SHA, BYTEARRAY_VALUE))); assertTrue(Arrays.equals((byte[])getVariable("test_empty"), Digest.digest(DigestType.SHA, ""))); } public void test_convertlib_sha_expect_error(){ // CLO-1258 try { doCompile("function integer transform(){string s = null; byte b = sha(s); return 0;}","test_convertlib_sha_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){byte s = null; byte b = sha(s); return 0;}","test_convertlib_sha_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_sha256() { doCompile("test_convertlib_sha256"); assertTrue(Arrays.equals((byte[])getVariable("shaHash1"), Digest.digest(DigestType.SHA256, "The quick brown fox jumps over the lazy dog"))); assertTrue(Arrays.equals((byte[])getVariable("shaHash2"), Digest.digest(DigestType.SHA256, BYTEARRAY_VALUE))); assertTrue(Arrays.equals((byte[])getVariable("test_empty"), Digest.digest(DigestType.SHA256, ""))); } public void test_convertlib_sha256_expect_error(){ // CLO-1258 try { doCompile("function integer transform(){string a = null; byte b = sha256(a); return 0;}","test_convertlib_sha256_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){byte a = null; byte b = sha256(a); return 0;}","test_convertlib_sha256_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_str2bits() { doCompile("test_convertlib_str2bits"); //TODO: uncomment -> test will pass, but is that correct? assertTrue(Arrays.equals((byte[]) getVariable("textAsBits1"), new byte[] {0/*, 0, 0, 0, 0, 0, 0, 0*/})); assertTrue(Arrays.equals((byte[]) getVariable("textAsBits2"), new byte[] {-1/*, 0, 0, 0, 0, 0, 0, 0*/})); assertTrue(Arrays.equals((byte[]) getVariable("textAsBits3"), new byte[] {10, -78, 5/*, 0, 0, 0, 0, 0*/})); assertTrue(Arrays.equals((byte[]) getVariable("test_empty"), new byte[] {})); } public void test_convertlib_str2bits_expect_error(){ try { doCompile("function integer transform(){byte b = str2bits(null); return 0;}","test_convertlib_str2bits_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string s = null; byte b = str2bits(s); return 0;}","test_convertlib_str2bits_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_str2bool() { doCompile("test_convertlib_str2bool"); check("fromTrueString", true); check("fromFalseString", false); check("nullRet1", null); check("nullRet2", null); } public void test_convertlib_str2bool_expect_error(){ try { doCompile("function integer transform(){boolean b = str2bool('asd'); return 0;}","test_convertlib_str2bool_expect_error"); fail(); } catch (Exception e) { // do nothing; } try { doCompile("function integer transform(){boolean b = str2bool(''); return 0;}","test_convertlib_str2bool_expect_error"); fail(); } catch (Exception e) { // do nothing; } } public void test_convertlib_str2date() { doCompile("test_convertlib_str2date"); Calendar cal = Calendar.getInstance(); cal.set(2005,10,19,0,0,0); cal.set(Calendar.MILLISECOND, 0); check("date1", cal.getTime()); cal.clear(); cal.set(2050, 4, 19, 0, 0, 0); cal.set(Calendar.MILLISECOND, 0); Date checkDate = cal.getTime(); check("date2", checkDate); check("date3", checkDate); cal.clear(); cal.setTimeZone(TimeZone.getTimeZone("GMT+8")); cal.set(2013, 04, 30, 17, 15, 12); check("withTimeZone1", cal.getTime()); cal.clear(); cal.setTimeZone(TimeZone.getTimeZone("GMT-8")); cal.set(2013, 04, 30, 17, 15, 12); check("withTimeZone2", cal.getTime()); assertFalse(getVariable("withTimeZone1").equals(getVariable("withTimeZone2"))); check("nullRet1", null); check("nullRet2", null); check("nullRet3", null); check("nullRet4", null); check("nullRet5", null); check("nullRet6", null); } public void test_convertlib_str2date_expect_error(){ try { doCompile("function integer transform(){date d = str2date('1987-11-17', 'dd.MM.yyyy'); return 0;}","test_convertlib_str2date_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){date d = str2date('1987-33-17', 'yyyy-MM-dd'); return 0;}","test_convertlib_str2date_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){date d = str2date('17.11.1987', null, 'cs.CZ'); return 0;}","test_convertlib_str2date_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){date d = str2date('17.11.1987', 'yyyy-MM-dd', null); return 0;}","test_convertlib_str2date_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){date d = str2date('17.11.1987', 'yyyy-MM-dd', 'cs.CZ', null); return 0;}","test_convertlib_str2date_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_str2decimal() { doCompile("test_convertlib_str2decimal"); check("parsedDecimal1", new BigDecimal("100.13")); check("parsedDecimal2", new BigDecimal("123123123.123")); check("parsedDecimal3", new BigDecimal("-350000.01")); check("parsedDecimal4", new BigDecimal("1000000")); check("parsedDecimal5", new BigDecimal("1000000.99")); check("parsedDecimal6", new BigDecimal("123123123.123")); check("parsedDecimal7", new BigDecimal("5.01")); check("nullRet1", null); check("nullRet2", null); check("nullRet3", null); check("nullRet4", null); check("nullRet5", null); check("nullRet6", null); check("nullRet7", new BigDecimal("5.05")); // CLO-1614 check("nullRet8", new BigDecimal("5.05")); check("nullRet9", new BigDecimal("5.05")); check("nullRet10", new BigDecimal("5.05")); check("nullRet11", new BigDecimal("5.05")); check("nullRet12", new BigDecimal("5.05")); check("nullRet13", new BigDecimal("5.05")); check("nullRet14", new BigDecimal("5.05")); check("nullRet15", new BigDecimal("5.05")); check("nullRet16", new BigDecimal("5.05")); } public void test_convertlib_str2decimal_expect_result(){ try { doCompile("function integer transform(){decimal d = str2decimal(''); return 0;}","test_convertlib_str2decimal_expect_result"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){decimal d = str2decimal('5.05 CZK','#.#CZ'); return 0;}","test_convertlib_str2decimal_expect_result"); fail(); } catch (Exception e) { // do nothing } // CLO-1614 try { doCompile("function integer transform(){decimal d = str2decimal('5.05 CZK',null); return 0;}","test_convertlib_str2decimal_expect_result"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){decimal d = str2decimal('5.05 CZK',null, null); return 0;}","test_convertlib_str2decimal_expect_result"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_str2double() { doCompile("test_convertlib_str2double"); check("parsedDouble1", 100.13); check("parsedDouble2", 123123123.123); check("parsedDouble3", -350000.01); check("nullRet1", null); check("nullRet2", null); check("nullRet3", null); check("nullRet4", null); check("nullRet5", null); check("nullRet6", null); check("nullRet7", 12.34d); // CLO-1614 check("nullRet8", 12.34d); check("nullRet9", 12.34d); check("nullRet10", 12.34d); check("nullRet11", 12.34d); check("nullRet12", 12.34d); check("nullRet13", 12.34d); check("nullRet14", 12.34d); check("nullRet15", 12.34d); } public void test_convertlib_str2double_expect_error(){ try { doCompile("function integer transform(){double d = str2double(''); return 0;}","test_convertlib_str2double_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){double d = str2double('text'); return 0;}","test_convertlib_str2double_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){double d = str2double('0.90c','#.# c'); return 0;}","test_convertlib_str2double_expect_error"); fail(); } catch (Exception e) { // do nothing } // CLO-1614 try { doCompile("function integer transform(){double d = str2double('0.90c',null); return 0;}","test_convertlib_str2double_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){double d = str2double('0.90c', null); return 0;}","test_convertlib_str2double_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){double d = str2double('0.90c', null, null); return 0;}","test_convertlib_str2double_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_str2integer() { doCompile("test_convertlib_str2integer"); check("parsedInteger1", 123456789); check("parsedInteger2", 123123); check("parsedInteger3", -350000); check("parsedInteger4", 419); check("nullRet1", 123); check("nullRet2", 123); check("nullRet3", null); check("nullRet4", null); check("nullRet5", null); check("nullRet6", null); check("nullRet7", null); check("nullRet8", null); check("nullRet9", null); // CLO-1614 // check("nullRet10", 123); // ambiguous check("nullRet11", 123); check("nullRet12", 123); check("nullRet13", 123); check("nullRet14", 123); check("nullRet15", 123); check("nullRet16", 123); check("nullRet17", 123); } public void test_convertlib_str2integer_expect_error(){ try { doCompile("function integer transform(){integer i = str2integer('abc'); return 0;}","test_convertlib_str2integer_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer i = str2integer(''); return 0;}","test_convertlib_str2integer_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer i = str2integer('123 mil', '###mil'); return 0;}","test_convertlib_str2integer_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string s = null; integer i = str2integer('123,1', s); return 0;}","test_convertlib_str2integer_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string s = null; integer i = str2integer('123,1', s, null); return 0;}","test_convertlib_str2integer_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer i = str2integer('1F', 2); return 0;}","test_convertlib_str2integer_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_str2long() { doCompile("test_convertlib_str2long"); check("parsedLong1", 1234567890123L); check("parsedLong2", 123123123456789L); check("parsedLong3", -350000L); check("parsedLong4", 133L); check("nullRet1", 123l); check("nullRet2", 123l); check("nullRet3", null); check("nullRet4", null); check("nullRet5", null); check("nullRet6", null); check("nullRet7", null); check("nullRet8", null); check("nullRet9", null); // CLO-1614 // check("nullRet10", 123l); // ambiguous check("nullRet11", 123l); check("nullRet12", 123l); check("nullRet13", 123l); check("nullRet14", 123l); check("nullRet15", 123l); check("nullRet16", 123l); check("nullRet17", 123l); } public void test_convertlib_str2long_expect_error(){ try { doCompile("function integer transform(){long i = str2long('abc'); return 0;}","test_convertlib_str2long_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long i = str2long(''); return 0;}","test_convertlib_str2long_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long i = str2long('13', '## bls'); return 0;}","test_convertlib_str2long_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long i = str2long('13', '## bls' , null); return 0;}","test_convertlib_str2long_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long i = str2long('13 L', null, 'cs.Cz'); return 0;}","test_convertlib_str2long_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long i = str2long('1A', 2); return 0;}","test_convertlib_str2long_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_toString() { doCompile("test_convertlib_toString"); check("integerString", "10"); check("longString", "110654321874"); check("doubleString", "1.547874E-14"); check("decimalString", "-6847521431.1545874"); check("listString", "[not ALI A, not ALI B, not ALI D..., but, ALI H!]"); check("mapString", "{1=Testing, 2=makes, 3=me, 4=crazy :-)}"); String byteMapString = getVariable("byteMapString").toString(); assertTrue(byteMapString.contains("1=value1")); assertTrue(byteMapString.contains("2=value2")); String fieldByteMapString = getVariable("fieldByteMapString").toString(); assertTrue(fieldByteMapString.contains("key1=value1")); assertTrue(fieldByteMapString.contains("key2=value2")); check("byteListString", "[firstElement, secondElement]"); check("fieldByteListString", "[firstElement, secondElement]"); // CLO-1262 check("test_null_l", "null"); check("test_null_dec", "null"); check("test_null_d", "null"); check("test_null_i", "null"); } public void test_convertlib_str2byte() { doCompile("test_convertlib_str2byte"); checkArray("utf8Hello", new byte[] { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33 }); checkArray("utf8Horse", new byte[] { 80, -59, -103, -61, -83, 108, 105, -59, -95, 32, -59, -66, 108, 117, -59, -91, 111, 117, -60, -115, 107, -61, -67, 32, 107, -59, -81, -59, -120, 32, 112, -60, -101, 108, 32, -60, -113, -61, -95, 98, 108, 115, 107, -61, -87, 32, -61, -77, 100, 121 }); checkArray("utf8Math", new byte[] { -62, -67, 32, -30, -123, -109, 32, -62, -68, 32, -30, -123, -107, 32, -30, -123, -103, 32, -30, -123, -101, 32, -30, -123, -108, 32, -30, -123, -106, 32, -62, -66, 32, -30, -123, -105, 32, -30, -123, -100, 32, -30, -123, -104, 32, -30, -126, -84, 32, -62, -78, 32, -62, -77, 32, -30, -128, -96, 32, -61, -105, 32, -30, -122, -112, 32, -30, -122, -110, 32, -30, -122, -108, 32, -30, -121, -110, 32, -30, -128, -90, 32, -30, -128, -80, 32, -50, -111, 32, -50, -110, 32, -30, -128, -109, 32, -50, -109, 32, -50, -108, 32, -30, -126, -84, 32, -50, -107, 32, -50, -106, 32, -49, -128, 32, -49, -127, 32, -49, -126, 32, -49, -125, 32, -49, -124, 32, -49, -123, 32, -49, -122, 32, -49, -121, 32, -49, -120, 32, -49, -119 }); checkArray("utf16Hello", new byte[] { -2, -1, 0, 72, 0, 101, 0, 108, 0, 108, 0, 111, 0, 32, 0, 87, 0, 111, 0, 114, 0, 108, 0, 100, 0, 33 }); checkArray("utf16Horse", new byte[] { -2, -1, 0, 80, 1, 89, 0, -19, 0, 108, 0, 105, 1, 97, 0, 32, 1, 126, 0, 108, 0, 117, 1, 101, 0, 111, 0, 117, 1, 13, 0, 107, 0, -3, 0, 32, 0, 107, 1, 111, 1, 72, 0, 32, 0, 112, 1, 27, 0, 108, 0, 32, 1, 15, 0, -31, 0, 98, 0, 108, 0, 115, 0, 107, 0, -23, 0, 32, 0, -13, 0, 100, 0, 121 }); checkArray("utf16Math", new byte[] { -2, -1, 0, -67, 0, 32, 33, 83, 0, 32, 0, -68, 0, 32, 33, 85, 0, 32, 33, 89, 0, 32, 33, 91, 0, 32, 33, 84, 0, 32, 33, 86, 0, 32, 0, -66, 0, 32, 33, 87, 0, 32, 33, 92, 0, 32, 33, 88, 0, 32, 32, -84, 0, 32, 0, -78, 0, 32, 0, -77, 0, 32, 32, 32, 0, 32, 0, -41, 0, 32, 33, -112, 0, 32, 33, -110, 0, 32, 33, -108, 0, 32, 33, -46, 0, 32, 32, 38, 0, 32, 32, 48, 0, 32, 3, -111, 0, 32, 3, -110, 0, 32, 32, 19, 0, 32, 3, -109, 0, 32, 3, -108, 0, 32, 32, -84, 0, 32, 3, -107, 0, 32, 3, -106, 0, 32, 3, -64, 0, 32, 3, -63, 0, 32, 3, -62, 0, 32, 3, -61, 0, 32, 3, -60, 0, 32, 3, -59, 0, 32, 3, -58, 0, 32, 3, -57, 0, 32, 3, -56, 0, 32, 3, -55 }); checkArray("macHello", new byte[] { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33 }); checkArray("macHorse", new byte[] { 80, -34, -110, 108, 105, -28, 32, -20, 108, 117, -23, 111, 117, -117, 107, -7, 32, 107, -13, -53, 32, 112, -98, 108, 32, -109, -121, 98, 108, 115, 107, -114, 32, -105, 100, 121 }); checkArray("asciiHello", new byte[] { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33 }); checkArray("isoHello", new byte[] { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33 }); checkArray("isoHorse", new byte[] { 80, -8, -19, 108, 105, -71, 32, -66, 108, 117, -69, 111, 117, -24, 107, -3, 32, 107, -7, -14, 32, 112, -20, 108, 32, -17, -31, 98, 108, 115, 107, -23, 32, -13, 100, 121 }); checkArray("cpHello", new byte[] { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33 }); checkArray("cpHorse", new byte[] { 80, -8, -19, 108, 105, -102, 32, -98, 108, 117, -99, 111, 117, -24, 107, -3, 32, 107, -7, -14, 32, 112, -20, 108, 32, -17, -31, 98, 108, 115, 107, -23, 32, -13, 100, 121 }); } public void test_convertlib_str2byte_expect_error(){ try { doCompile("function integer transform(){byte b = str2byte(null,'utf-8'); return 0;}","test_convertlib_str2byte_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){byte b = str2byte(null,'utf-16'); return 0;}","test_convertlib_str2byte_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){byte b = str2byte(null,'MacCentralEurope'); return 0;}","test_convertlib_str2byte_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){byte b = str2byte(null,'ascii'); return 0;}","test_convertlib_str2byte_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){byte b = str2byte(null,'iso-8859-2'); return 0;}","test_convertlib_str2byte_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){byte b = str2byte(null,'windows-1250'); return 0;}","test_convertlib_str2byte_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){byte b = str2byte('wallace',null); return 0;}","test_convertlib_str2byte_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){byte b = str2byte('wallace','knock'); return 0;}","test_convertlib_str2byte_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){byte b = str2byte('wallace',null); return 0;}","test_convertlib_str2byte_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_convertlib_byte2str() { doCompile("test_convertlib_byte2str"); String hello = "Hello World!"; String horse = "Příliš žluťoučký kůň pěl ďáblské ódy"; String math = "½ ⅓ ¼ ⅕ ⅙ ⅛ ⅔ ⅖ ¾ ⅗ ⅜ ⅘ € ² ³ † × ← → ↔ ⇒ … ‰ Α Β – Γ Δ € Ε Ζ π ρ ς σ τ υ φ χ ψ ω"; check("utf8Hello", hello); check("utf8Horse", horse); check("utf8Math", math); check("utf16Hello", hello); check("utf16Horse", horse); check("utf16Math", math); check("macHello", hello); check("macHorse", horse); check("asciiHello", hello); check("isoHello", hello); check("isoHorse", horse); check("cpHello", hello); check("cpHorse", horse); } public void test_convertlib_byte2str_expect_error(){ try { doCompile("function integer transform(){string s = byte2str(null,'utf-8'); return 0;}","test_convertlib_byte2str_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){byte input = null; string s = byte2str(input,'utf-8'); return 0;}","test_convertlib_byte2str_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string s = byte2str(null,null); return 0;}","test_convertlib_byte2str_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string s = byte2str(str2byte('hello', 'utf-8'),null); return 0;}","test_convertlib_byte2str_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_conditional_fail() { doCompile("test_conditional_fail"); check("result", 3); } public void test_expression_statement(){ // test case for issue 4174 doCompileExpectErrors("test_expression_statement", Arrays.asList("Syntax error, statement expected","Syntax error, statement expected")); } public void test_dictionary_read() { doCompile("test_dictionary_read"); check("s", "Verdon"); check("i", Integer.valueOf(211)); check("l", Long.valueOf(226)); check("d", BigDecimal.valueOf(239483061)); check("n", Double.valueOf(934.2)); check("a", new GregorianCalendar(1992, GregorianCalendar.AUGUST, 1).getTime()); check("b", true); byte[] y = (byte[]) getVariable("y"); assertEquals(10, y.length); assertEquals(89, y[9]); check("sNull", null); check("iNull", null); check("lNull", null); check("dNull", null); check("nNull", null); check("aNull", null); check("bNull", null); check("yNull", null); check("stringList", Arrays.asList("aa", "bb", null, "cc")); check("dateList", Arrays.asList(new Date(12000), new Date(34000), null, new Date(56000))); @SuppressWarnings("unchecked") List<byte[]> byteList = (List<byte[]>) getVariable("byteList"); assertDeepEquals(byteList, Arrays.asList(new byte[] {0x12}, new byte[] {0x34, 0x56}, null, new byte[] {0x78})); } public void test_dictionary_write() { doCompile("test_dictionary_write"); assertEquals(832, graph.getDictionary().getValue("i") ); assertEquals("Guil", graph.getDictionary().getValue("s")); assertEquals(Long.valueOf(540), graph.getDictionary().getValue("l")); assertEquals(BigDecimal.valueOf(621), graph.getDictionary().getValue("d")); assertEquals(934.2, graph.getDictionary().getValue("n")); assertEquals(new GregorianCalendar(1992, GregorianCalendar.DECEMBER, 2).getTime(), graph.getDictionary().getValue("a")); assertEquals(true, graph.getDictionary().getValue("b")); byte[] y = (byte[]) graph.getDictionary().getValue("y"); assertEquals(2, y.length); assertEquals(18, y[0]); assertEquals(-94, y[1]); assertEquals(Arrays.asList("xx", null), graph.getDictionary().getValue("stringList")); assertEquals(Arrays.asList(new Date(98000), null, new Date(76000)), graph.getDictionary().getValue("dateList")); @SuppressWarnings("unchecked") List<byte[]> byteList = (List<byte[]>) graph.getDictionary().getValue("byteList"); assertDeepEquals(byteList, Arrays.asList(null, new byte[] {(byte) 0xAB, (byte) 0xCD}, new byte[] {(byte) 0xEF})); check("assignmentReturnValue", "Guil"); } public void test_dictionary_write_null() { doCompile("test_dictionary_write_null"); assertEquals(null, graph.getDictionary().getValue("s")); assertEquals(null, graph.getDictionary().getValue("sVerdon")); assertEquals(null, graph.getDictionary().getValue("i") ); assertEquals(null, graph.getDictionary().getValue("i211") ); assertEquals(null, graph.getDictionary().getValue("l")); assertEquals(null, graph.getDictionary().getValue("l452")); assertEquals(null, graph.getDictionary().getValue("d")); assertEquals(null, graph.getDictionary().getValue("d621")); assertEquals(null, graph.getDictionary().getValue("n")); assertEquals(null, graph.getDictionary().getValue("n9342")); assertEquals(null, graph.getDictionary().getValue("a")); assertEquals(null, graph.getDictionary().getValue("a1992")); assertEquals(null, graph.getDictionary().getValue("b")); assertEquals(null, graph.getDictionary().getValue("bTrue")); assertEquals(null, graph.getDictionary().getValue("y")); assertEquals(null, graph.getDictionary().getValue("yFib")); } public void test_dictionary_invalid_key(){ doCompileExpectErrors("test_dictionary_invalid_key", Arrays.asList("Dictionary entry 'invalid' does not exist")); } public void test_dictionary_string_to_int(){ doCompileExpectErrors("test_dictionary_string_to_int", Arrays.asList("Type mismatch: cannot convert from 'string' to 'integer'","Type mismatch: cannot convert from 'string' to 'integer'")); } public void test_utillib_sleep() { long time = System.currentTimeMillis(); doCompile("test_utillib_sleep"); long tmp = System.currentTimeMillis() - time; assertTrue("sleep() function didn't pause execution "+ tmp, tmp >= 1000); } public void test_utillib_random_uuid() { doCompile("test_utillib_random_uuid"); assertNotNull(getVariable("uuid")); } public void test_stringlib_randomString(){ doCompile("string test; function integer transform(){test = randomString(1,3); return 0;}","test_stringlib_randomString"); assertNotNull(getVariable("test")); } public void test_stringlib_validUrl() { doCompile("test_stringlib_url"); check("urlValid", Arrays.asList(true, true, false, true, false, true)); check("protocol", Arrays.asList("http", "https", null, "sandbox", null, "zip")); check("userInfo", Arrays.asList("", "chuck:norris", null, "", null, "")); check("host", Arrays.asList("example.com", "server.javlin.eu", null, "cloveretl.test.scenarios", null, "")); check("port", Arrays.asList(-1, 12345, -2, -1, -2, -1)); check("path", Arrays.asList("", "/backdoor/trojan.cgi", null, "/graph/UDR_FileURL_SFTP_OneGzipFileSpecified.grf", null, "(sftp://test:test@koule/home/test/data-in/file2.zip)")); check("query", Arrays.asList("", "hash=SHA560;god=yes", null, "", null, "")); check("ref", Arrays.asList("", "autodestruct", null, "", null, "innerfolder2/URLIn21.txt")); } public void test_stringlib_escapeUrl() { doCompile("test_stringlib_escapeUrl"); check("escaped", "http://example.com/foo%20bar%5E"); check("unescaped", "http://example.com/foo bar^"); } public void test_stringlib_escapeUrl_unescapeUrl_expect_error(){ //test: escape - empty string try { doCompile("string test; function integer transform() {test = escapeUrl(''); return 0;}","test_stringlib_escapeUrl_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: escape - null string try { doCompile("string test; function integer transform() {test = escapeUrl(null); return 0;}","test_stringlib_escapeUrl_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: unescape - empty string try { doCompile("string test; function integer transform() {test = unescapeUrl(''); return 0;}","test_stringlib_escapeUrl_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: unescape - null try { doCompile("string test; function integer transform() {test = unescapeUrl(null); return 0;}","test_stringlib_escapeUrl_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: escape - invalid URL try { doCompile("string test; function integer transform() {test = escapeUrl('somewhere over the rainbow'); return 0;}","test_stringlib_escapeUrl_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: unescpae - invalid URL try { doCompile("string test; function integer transform() {test = unescapeUrl('mister%20postman'); return 0;}","test_stringlib_escapeUrl_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_stringlib_resolveParams() { doCompile("test_stringlib_resolveParams"); check("resultNoParams", "Special character representing new line is: \\n calling CTL function MESSAGE; $DATAIN_DIR=./data-in"); check("resultFalseFalseParams", "Special character representing new line is: \\n calling CTL function `uppercase(\"message\")`; $DATAIN_DIR=./data-in"); check("resultTrueFalseParams", "Special character representing new line is: \n calling CTL function `uppercase(\"message\")`; $DATAIN_DIR=./data-in"); check("resultFalseTrueParams", "Special character representing new line is: \\n calling CTL function MESSAGE; $DATAIN_DIR=./data-in"); check("resultTrueTrueParams", "Special character representing new line is: \n calling CTL function MESSAGE; $DATAIN_DIR=./data-in"); } public void test_utillib_getEnvironmentVariables() { doCompile("test_utillib_getEnvironmentVariables"); check("empty", false); } public void test_utillib_getJavaProperties() { String key1 = "my.testing.property"; String key2 = "my.testing.property2"; String value = "my value"; String value2; assertNull(System.getProperty(key1)); assertNull(System.getProperty(key2)); System.setProperty(key1, value); try { doCompile("test_utillib_getJavaProperties"); value2 = System.getProperty(key2); } finally { System.clearProperty(key1); assertNull(System.getProperty(key1)); System.clearProperty(key2); assertNull(System.getProperty(key2)); } check("java_specification_name", "Java Platform API Specification"); check("my_testing_property", value); assertEquals("my value 2", value2); } public void test_utillib_getParamValues() { doCompile("test_utillib_getParamValues"); Map<String, String> params = new HashMap<String, String>(); params.put("PROJECT", "."); params.put("DATAIN_DIR", "./data-in"); params.put("COUNT", "3"); params.put("NEWLINE", "\\n"); // special characters should NOT be resolved check("params", params); } public void test_utillib_getParamValue() { doCompile("test_utillib_getParamValue"); Map<String, String> params = new HashMap<String, String>(); params.put("PROJECT", "."); params.put("DATAIN_DIR", "./data-in"); params.put("COUNT", "3"); params.put("NEWLINE", "\\n"); // special characters should NOT be resolved params.put("NONEXISTING", null); check("params", params); } public void test_stringlib_getUrlParts() { doCompile("test_stringlib_getUrlParts"); List<Boolean> isUrl = Arrays.asList(true, true, true, true, false); List<String> path = Arrays.asList( "/users/a6/15e83578ad5cba95c442273ea20bfa/msf-183/out5.txt", "/data-in/fileOperation/input.txt", "/data/file.txt", "/data/file.txt", null); List<String> protocol = Arrays.asList("sftp", "sandbox", "ftp", "https", null); List<String> host = Arrays.asList( "ava-fileManipulator1-devel.getgooddata.com", "cloveretl.test.scenarios", "ftp.test.com", "www.test.com", null); List<Integer> port = Arrays.asList(-1, -1, 21, 80, -2); List<String> userInfo = Arrays.asList( "user%40gooddata.com:password", "", "test:test", "test:test", null); List<String> ref = Arrays.asList("", "", "", "", null); List<String> query = Arrays.asList("", "", "", "", null); check("isUrl", isUrl); check("path", path); check("protocol", protocol); check("host", host); check("port", port); check("userInfo", userInfo); check("ref", ref); check("query", query); check("isURL_empty", false); check("path_empty", null); check("protocol_empty", null); check("host_empty", null); check("port_empty", -2); check("userInfo_empty", null); check("ref_empty", null); check("query_empty", null); check("isURL_null", false); check("path_null", null); check("protocol_null", null); check("host_null", null); check("port_null", -2); check("userInfo_null", null); check("ref_null", null); check("query_empty", null); } public void test_utillib_iif() throws UnsupportedEncodingException{ doCompile("test_utillib_iif"); check("ret1", "Renektor"); Calendar cal = Calendar.getInstance(); cal.set(2005,10,12,0,0,0); cal.set(Calendar.MILLISECOND,0); check("ret2", cal.getTime()); checkArray("ret3", "Akali".getBytes("UTF-8")); check("ret4", 236); check("ret5", 78L); check("ret6", 78.2d); check("ret7", new BigDecimal("87.69")); check("ret8", true); } public void test_utillib_iif_expect_error(){ try { doCompile("function integer transform(){boolean b = null; string str = iif(b, 'Rammus', 'Sion'); return 0;}","test_utillib_iif_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_utillib_isnull(){ doCompile("test_utillib_isnull"); check("ret1", false); check("ret2", true); check("ret3", false); check("ret4", true); check("ret5", false); check("ret6", true); check("ret7", false); check("ret8", true); check("ret9", false); check("ret10", true); check("ret11", false); check("ret12", true); check("ret13", false); check("ret14", true); check("ret15", false); check("ret16", true); check("ret17", false); check("ret18", true); check("ret19", true); } public void test_utillib_nvl() throws UnsupportedEncodingException{ doCompile("test_utillib_nvl"); check("ret1", "Fiora"); check("ret2", "Olaf"); checkArray("ret3", "Elise".getBytes("UTF-8")); checkArray("ret4", "Diana".getBytes("UTF-8")); Calendar cal = Calendar.getInstance(); cal.set(2005,4,13,0,0,0); cal.set(Calendar.MILLISECOND, 0); check("ret5", cal.getTime()); cal.clear(); cal.set(2004,2,14,0,0,0); cal.set(Calendar.MILLISECOND, 0); check("ret6", cal.getTime()); check("ret7", 7); check("ret8", 8); check("ret9", 111l); check("ret10", 112l); check("ret11", 10.1d); check("ret12", 10.2d); check("ret13", new BigDecimal("12.2")); check("ret14", new BigDecimal("12.3")); // check("ret15", null); } public void test_utillib_nvl2() throws UnsupportedEncodingException{ doCompile("test_utillib_nvl2"); check("ret1", "Ahri"); check("ret2", "Galio"); checkArray("ret3", "Mordekaiser".getBytes("UTF-8")); checkArray("ret4", "Zed".getBytes("UTF-8")); Calendar cal = Calendar.getInstance(); cal.set(2010,4,18,0,0,0); cal.set(Calendar.MILLISECOND, 0); check("ret5", cal.getTime()); cal.clear(); cal.set(2008,7,9,0,0,0); cal.set(Calendar.MILLISECOND, 0); check("ret6", cal.getTime()); check("ret7", 11); check("ret8", 18); check("ret9", 20L); check("ret10", 23L); check("ret11", 15.2d); check("ret12", 89.3d); check("ret13", new BigDecimal("22.2")); check("ret14", new BigDecimal("55.5")); check("ret15", null); check("ret16", null); } }
package com.newsblur.activity; import android.app.ActionBar; import android.content.Intent; import android.os.Bundle; import android.preference.PreferenceManager; import android.app.DialogFragment; import android.app.FragmentManager; import android.support.v4.widget.SwipeRefreshLayout; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.widget.AbsListView; import android.widget.TextView; import com.newsblur.R; import com.newsblur.fragment.FolderListFragment; import com.newsblur.fragment.LogoutDialogFragment; import com.newsblur.service.BootReceiver; import com.newsblur.service.NBSyncService; import com.newsblur.util.FeedUtils; import com.newsblur.util.PrefsUtils; import com.newsblur.util.UIUtils; import com.newsblur.view.StateToggleButton.StateChangedListener; public class Main extends NbActivity implements StateChangedListener, SwipeRefreshLayout.OnRefreshListener, AbsListView.OnScrollListener { private ActionBar actionBar; private FolderListFragment folderFeedList; private FragmentManager fragmentManager; private Menu menu; private TextView overlayStatusText; private boolean isLightTheme; private SwipeRefreshLayout swipeLayout; private boolean wasSwipeEnabled = false; @Override public void onCreate(Bundle savedInstanceState) { PreferenceManager.setDefaultValues(this, R.layout.activity_settings, false); isLightTheme = PrefsUtils.isLightThemeSelected(this); requestWindowFeature(Window.FEATURE_PROGRESS); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); setupActionBar(); swipeLayout = (SwipeRefreshLayout)findViewById(R.id.swipe_container); swipeLayout.setColorScheme(R.color.refresh_1, R.color.refresh_2, R.color.refresh_3, R.color.refresh_4); swipeLayout.setOnRefreshListener(this); fragmentManager = getFragmentManager(); folderFeedList = (FolderListFragment) fragmentManager.findFragmentByTag("folderFeedListFragment"); folderFeedList.setRetainInstance(true); this.overlayStatusText = (TextView) findViewById(R.id.main_sync_status); // make sure the interval sync is scheduled, since we are the root Activity BootReceiver.scheduleSyncService(this); } @Override protected void onResume() { super.onResume(); // clear the read-this-session flag from stories so they don't show up in the wrong place FeedUtils.clearReadingSession(this); updateStatusIndicators(); // this view doesn't show stories, it is safe to perform cleanup NBSyncService.holdStories(false); triggerSync(); if (PrefsUtils.isLightThemeSelected(this) != isLightTheme) { UIUtils.restartActivity(this); } } private void setupActionBar() { actionBar = getActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.main, menu); this.menu = menu; return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { if (item.getItemId() == R.id.menu_profile) { Intent profileIntent = new Intent(this, Profile.class); startActivity(profileIntent); return true; } else if (item.getItemId() == R.id.menu_refresh) { NBSyncService.forceFeedsFolders(); triggerSync(); return true; } else if (item.getItemId() == R.id.menu_add_feed) { Intent intent = new Intent(this, SearchForFeeds.class); startActivityForResult(intent, 0); return true; } else if (item.getItemId() == R.id.menu_logout) { DialogFragment newFragment = new LogoutDialogFragment(); newFragment.show(getFragmentManager(), "dialog"); } else if (item.getItemId() == R.id.menu_settings) { Intent settingsIntent = new Intent(this, Settings.class); startActivity(settingsIntent); return true; } return super.onOptionsItemSelected(item); } @Override public void changedState(int state) { folderFeedList.changeState(state); } protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_OK) { folderFeedList.hasUpdated(); } } @Override public void handleUpdate() { folderFeedList.hasUpdated(); updateStatusIndicators(); } private void updateStatusIndicators() { if (NBSyncService.isFeedFolderSyncRunning()) { swipeLayout.setRefreshing(true); } else { swipeLayout.setRefreshing(false); } if (overlayStatusText != null) { String syncStatus = NBSyncService.getSyncStatusMessage(); if (syncStatus != null) { overlayStatusText.setText(syncStatus); overlayStatusText.setVisibility(View.VISIBLE); } else { overlayStatusText.setVisibility(View.GONE); } } } @Override public void onRefresh() { NBSyncService.forceFeedsFolders(); triggerSync(); } @Override public void onScrollStateChanged(AbsListView absListView, int i) { // not required } @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (swipeLayout != null) { boolean enable = (firstVisibleItem == 0); if (wasSwipeEnabled != enable) { swipeLayout.setEnabled(enable); wasSwipeEnabled = enable; } } } }
package ca.patricklam.judodb.client; import java.util.Date; import ca.patricklam.judodb.client.Constants.Division; import com.google.gwt.core.client.JavaScriptObject; import com.google.gwt.core.client.JsArray; import com.google.gwt.i18n.client.DateTimeFormat; public class ClientData extends JavaScriptObject { protected ClientData() {} public final native String getID() /*-{ return this.id; }-*/; public final native void setID(String id) /*-{ this.id = id; }-*/; public final native String getNom() /*-{ return this.nom; }-*/; public final native void setNom(String nom) /*-{ this.nom = nom; }-*/; public final native String getPrenom() /*-{ return this.prenom; }-*/; public final native void setPrenom(String prenom) /*-{ this.prenom = prenom; }-*/; public final native String getDDNString() /*-{ return this.ddn; }-*/; public final native void setDDNString(String ddn) /*-{ this.ddn = ddn; }-*/; public final native String getSexe() /*-{ return this.sexe; }-*/; public final native void setSexe(String sexe) /*-{ this.sexe = sexe; }-*/; public final native String getAdresse() /*-{ return this.adresse; }-*/; public final native void setAdresse(String adresse) /*-{ this.adresse = adresse; }-*/; public final native String getVille() /*-{ return this.ville; }-*/; public final native void setVille(String ville) /*-{ this.ville = ville; }-*/; public final native String getCodePostal() /*-{ return this.code_postal; }-*/; public final native void setCodePostal(String codePostal) /*-{ this.code_postal = codePostal; }-*/; public final native String getTel() /*-{ return this.tel; }-*/; public final native void setTel(String tel) /*-{ this.tel = tel; }-*/; public final native String getCourriel() /*-{ return this.courriel; }-*/; public final native void setCourriel(String courriel) /*-{ this.courriel = courriel; }-*/; public final native String getJudoQC() /*-{ return this.affiliation; }-*/; public final native void setJudoQC(String judoQC) /*-{ this.affiliation = judoQC; }-*/; public final native JsArray<GradeData> getGrades() /*-{ return this.grades; }-*/; public final native void setGrades(JsArray<GradeData> grades) /*-{ this.grades = grades; }-*/; public final native String getCarteResident() /*-{ return this.carte_resident; }-*/; public final native void setCarteResident(String carte_resident) /*-{ this.carte_resident = carte_resident; }-*/; public final native String getNomRecuImpot() /*-{ return this.nom_recu_impot; }-*/; public final native void setNomRecuImpot(String nom_recu_impot) /*-{ this.nom_recu_impot = nom_recu_impot; }-*/; public final native String getNomContactUrgence() /*-{ return this.nom_contact_urgence; }-*/; public final native void setNomContactUrgence(String nom_contact_urgence) /*-{ this.nom_contact_urgence = nom_contact_urgence; }-*/; public final native String getTelContactUrgence() /*-{ return this.tel_contact_urgence; }-*/; public final native void setTelContactUrgence(String tel_contact_urgence) /*-{ this.tel_contact_urgence = tel_contact_urgence; }-*/; public final native JsArray<ServiceData> getServices() /*-{ return this.services; }-*/; public final native void setServices(JsArray<ServiceData> services) /*-{ this.services = services; }-*/; public final int getMostRecentServiceNumber() { JsArray<ServiceData> services = getServices(); if (services == null || services.length() == 0) return -1; int r = 0; for (int i = 0; i < services.length(); i++) { if (services.get(i).getDateInscription().compareTo(services.get(r).getDateInscription()) > 0) r = i; } return r; } public final ServiceData getServiceFor(Constants.Session saison) { JsArray<ServiceData> services = getServices(); if (services == null) return null; if (saison == null) return services.get(getMostRecentServiceNumber()); for (int i = 0; i < services.length(); i++) { if (services.get(i).getSaisons().contains(saison.abbrev)) return services.get(i); } return null; } public final String getAllActiveSaisons() { String r = ""; JsArray<ServiceData> services = getServices(); if (services == null || services.length() == 0) return r; for (int i = 0; i < services.length(); i++) { r += services.get(i).getSaisons(); } return r; } public final GradeData getMostRecentGrade() { JsArray<GradeData> grades = getGrades(); if (grades == null || grades.length() == 0) return null; GradeData m = grades.get(0); for (int i = 0; i < grades.length(); i++) { String dg = grades.get(i).getDateGrade(); if (dg != null && dg.compareTo(m.getDateGrade()) > 0) m = grades.get(i); } return m; } public final String getGrade() { GradeData m = getMostRecentGrade(); return m == null ? "" : m.getGrade(); } public final String getDateGrade() { GradeData m = getMostRecentGrade(); return m == null ? "" : m.getDateGrade(); } public final Date getDDN() { if (getDDNString() == null) return null; try { return Constants.DB_DATE_FORMAT.parse(getDDNString()); } catch (IllegalArgumentException e) { return null; } } public final boolean isNoire() { return getGrade() != null && getGrade().endsWith("D"); } public final Division getDivision(int current_year) { Date d = getDDN(); if (d == null) return Constants.EMPTY_DIVISION; int year = Integer.parseInt(DateTimeFormat.getFormat("yyyy").format(d)); for (int i = 0; i < Constants.DIVISIONS.length; i++) { if (isNoire() == Constants.DIVISIONS[i].noire && ((Constants.DIVISIONS[i].years_ago == 0) || (current_year - Constants.DIVISIONS[i].years_ago < year))) return Constants.DIVISIONS[i]; } return Constants.EMPTY_DIVISION; } /* deprecated */ public final native String getRAMQ() /*-{ return this.RAMQ; }-*/; public static final String DEFAULT_VILLE = "Anjou (QC)"; public static final String DEFAULT_CP = "H1K "; public static final String DEFAULT_TEL = "514-"; public final void makeDefault() { setVille(DEFAULT_VILLE); setCodePostal(DEFAULT_CP); setTel(DEFAULT_TEL); setTelContactUrgence(DEFAULT_TEL); } public final boolean isDefault() { return getAdresse().equals("") && getVille().equals(DEFAULT_VILLE) && getCodePostal().equals(DEFAULT_CP) && getTel().equals(DEFAULT_TEL) && getTelContactUrgence().equals(DEFAULT_TEL) && getCourriel().equals(""); } }
/** * * @author Klemen * * * Main class file for the whole project. UI Thread is located here. * * */ package com.muhavision; import java.awt.Color; import java.awt.Font; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseMotionListener; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException; import java.util.Scanner; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import com.muhavision.control.DroneController; import com.muhavision.cv.image.VisualRenderer; public class Main { JFrame controlTowerFrame = new JFrame("Muha Mission Planner"); private final static int PACKETSIZE = 1024; public float roll, pitch, yaw, height; VisualRenderer visual = new VisualRenderer(this); DroneController controller = new DroneController(visual); public static final boolean DEBUG = true; public Main() { if(!DEBUG) new SplashScreen(); JPanel commands = new JPanel(); commands.setBackground(Color.black); JButton takeoff = new JButton("Take off"); takeoff.setBackground(Color.black); takeoff.setForeground(Color.white); takeoff.setFont(new Font("Arial", Font.PLAIN, 17)); takeoff.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { controller.getDrone().takeOff(); } catch (IOException e1) { e1.printStackTrace(); } } }); takeoff.setFocusable(false); commands.add(takeoff); //main panel JPanel visualHolder = new JPanel(new GridLayout()); visualHolder.add(visual); controlTowerFrame.add("Center", visualHolder); JButton land = new JButton("Land"); land.setBackground(Color.black); land.setForeground(Color.white); land.setFont(new Font("Arial", Font.PLAIN, 17)); land.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { controller.getDrone().land(); } catch (IOException e1) { e1.printStackTrace(); } } }); land.setFocusable(false); commands.add(land); JButton trim = new JButton("Flat trim"); trim.setBackground(Color.black); trim.setForeground(Color.white); trim.setFont(new Font("Arial", Font.PLAIN, 17)); trim.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { try { controller.getDrone().trim(); } catch (IOException e1) { e1.printStackTrace(); } } }); trim.setFocusable(false); commands.add(trim); controlTowerFrame.add("North", commands); //controlTowerFrame.setResizable(false); //controlTowerFrame.setSize(700, 500); //controlTowerFrame.setUndecorated(true); controlTowerFrame.setVisible(true); controlTowerFrame.setExtendedState(JFrame.MAXIMIZED_BOTH); controlTowerFrame.setFocusable(true); controlTowerFrame.setFocusableWindowState(true); controlTowerFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); controlTowerFrame.addKeyListener(new KeyListener() { @Override public void keyTyped(KeyEvent arg0) {} @Override public void keyReleased(KeyEvent arg0) { if(arg0.getKeyChar()=='w') pitch = 0; if(arg0.getKeyChar()=='s') pitch = 0; if(arg0.getKeyChar()=='a') roll = 0; if(arg0.getKeyChar()=='d') roll = 0; reloadControls(); } @Override public void keyPressed(KeyEvent arg0) { if(arg0.getKeyChar()=='\n') try { controller.getDrone().sendEmergencySignal(); } catch (IOException e) { e.printStackTrace(); } if(arg0.getKeyCode()==KeyEvent.VK_ESCAPE){ controlTowerFrame.setVisible(false); try { controller.getDrone().sendEmergencySignal(); } catch (IOException e) { e.printStackTrace(); } } if(arg0.getKeyChar()=='w') pitch = -10; if(arg0.getKeyChar()=='s') pitch = 10; if(arg0.getKeyChar()=='a') roll = -10; if(arg0.getKeyChar()=='d') roll = 10; reloadControls(); } }); try { final DatagramSocket socket = new DatagramSocket(1234); Thread mami_listener = new Thread(){ public void run(){ while(true){ // x;y;z DatagramPacket packet = new DatagramPacket( new byte[PACKETSIZE], PACKETSIZE ) ; try { socket.receive(packet) ; } catch (IOException e) { e.printStackTrace(); } String[] mami_array = new String(packet.getData()).split("\\;"); if(mami_array.length>1){ pitch = Integer.parseInt(mami_array[1].trim()); roll = Integer.parseInt(mami_array[0].trim()); yaw = (Integer.parseInt(mami_array[2].trim()))/5;//reduce response if(Math.abs(yaw)==1)yaw=0; int mamih = Integer.parseInt(mami_array[3].trim()); if(mamih==2) height = 5; else if(mamih == -1) height = -5; else height = 0; reloadControls(); } } } }; mami_listener.start(); } catch (SocketException e1) { e1.printStackTrace(); } try { final DatagramSocket socket = new DatagramSocket(2345); Thread mami_listener = new Thread(){ public void run(){ while(true){ // x;y;z DatagramPacket packet = new DatagramPacket( new byte[PACKETSIZE], PACKETSIZE ) ; try { socket.receive(packet) ; } catch (IOException e) { e.printStackTrace(); } String[] mami_array = new String(packet.getData()).split("\\;"); if(mami_array.length>1){ if(Integer.parseInt(mami_array[2].trim()) == 1){ try { controller.getDrone().takeOff(); } catch (IOException e1) { e1.printStackTrace(); } } if(Integer.parseInt(mami_array[3].trim()) == 1){ try { controller.getDrone().land(); } catch (IOException e1) { e1.printStackTrace(); } } if(Integer.parseInt(mami_array[2].trim()) == 1){ try { controller.getDrone().trim(); } catch (IOException e1) { e1.printStackTrace(); } } } } } }; mami_listener.start(); } catch (SocketException e1) { e1.printStackTrace(); } controlTowerFrame.addMouseMotionListener(new MouseMotionListener() { @Override public void mouseMoved(MouseEvent arg0) { /*int x = arg0.getX(); int w = (int) controlTowerFrame.getSize().getWidth(); int relative = (w/2) - x; if(Math.abs(relative)>50) yaw = ((relative - 50)/30)*-1; else yaw = 0; reloadControls();*/ } @Override public void mouseDragged(MouseEvent arg0) {} }); visual.reloadDatas(null, null, null); visual.setDataProps(controlTowerFrame); } protected void reloadControls() { try { controller.getDrone().move(roll, pitch, 0, yaw); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { new Main(); } }
package com.google.sps.store; import com.google.sps.data.Event; import com.google.sps.data.EventResult; import com.google.sps.data.Keyword; import com.google.sps.utilities.KeywordHelper; import com.google.sps.utilities.SpannerTasks; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.stream.Collectors; /** Store class that uses in-memory map to hold search results. */ public class SearchStore { private static final float WEIGHT_IN_NAME = 0.7f; private static final float WEIGHT_IN_DESCRIPTION = 0.3f; private KeywordHelper keywordHelper; public SearchStore(KeywordHelper keywordHelper) { this.keywordHelper = keywordHelper; } /** * Adds keywords for name and description with mapping to eventId to index. Relevance of each * keyword is the weighted sum of the relevance in the name and the relevance in the description * where the name is weighted by value WEIGHT_IN_NAME and description is weighted by * WEIGHT_IN_DESCRIPTION. * * @param eventId event ID * @param name name of the event * @param description description of the event */ public void addEventToIndex(String eventId, String name, String description) { Map<String, Float> keywordToRanking = new HashMap<String, Float>(); addKeywordsInTextToIndex(eventId, name.toLowerCase(), WEIGHT_IN_NAME, keywordToRanking); addKeywordsInTextToIndex(eventId, description, WEIGHT_IN_DESCRIPTION, keywordToRanking); List<EventResult> entries = keywordToRanking.entrySet().stream() .map(entry -> new EventResult(eventId, entry.getKey(), entry.getValue())) .collect(Collectors.toList()); SpannerTasks.addResultsToPersistentStorageIndex(entries); } /** * Adds result for keywords in the given text. * * @param eventId event ID * @param text text to search keywords for * @param weight weight multiply relevance of keyword by which is proportional to the significance * of the selected piece of text. * @param keywordToRanking the index to update */ private void addKeywordsInTextToIndex( String eventId, String text, float weight, Map<String, Float> keywordToRanking) { keywordHelper.setContent(text); ArrayList<Keyword> keywords = new ArrayList<Keyword>(); try { keywords = keywordHelper.getKeywords(); } catch (IOException e) { System.err.println("IO Exception due to NLP library."); } for (Keyword keyword : keywords) { keywordToRanking.put(keyword.getName(), getRanking(keyword, weight, keywordToRanking)); } } /** * Returns ranking equal to the sum of the existing ranking and the relevance of the keyword * in the text multiplied by the given weight. */ private float getRanking(Keyword keyword, float weight, Map<String, Float> keywordToRanking) { float keywordRank = 0; String name = keyword.getName(); if (keywordToRanking.containsKey(name)) { keywordRank += keywordToRanking.get(name); } keywordRank += weight * keyword.getRelevance(); return keywordRank; } /** * Gets event searchResults for the given keyword search. * * @param keyword keyword to search * @return list of events in descending order of ranking as search result */ public static List<Event> getSearchResults(String keyword) { return SpannerTasks.getEventResultsByKeywordWithDescendingRanking(keyword); } }
package de.learnlib.dhc.mealy; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.logging.Level; import java.util.logging.Logger; import net.automatalib.automata.transout.MealyMachine; import net.automatalib.automata.transout.impl.FastMealy; import net.automatalib.automata.transout.impl.FastMealyState; import net.automatalib.words.Alphabet; import net.automatalib.words.Word; import net.automatalib.words.impl.SimpleAlphabet; import de.learnlib.api.AccessSequenceTransformer; import de.learnlib.api.LearningAlgorithm; import de.learnlib.api.MembershipOracle; import de.learnlib.counterexamples.GlobalSuffixFinder; import de.learnlib.counterexamples.GlobalSuffixFinders; import de.learnlib.oracles.DefaultQuery; /** * * @author Maik Merten <[email protected]> */ public class MealyDHC<I, O> implements LearningAlgorithm<MealyMachine<?, I, ?, O>, I, Word<O>>, AccessSequenceTransformer<I> { private static final Logger log = Logger.getLogger( MealyDHC.class.getName() ); private Alphabet<I> alphabet; private MembershipOracle<I, Word<O>> oracle; private SimpleAlphabet<Word<I>> splitters = new SimpleAlphabet<>(); private FastMealy<I, O> hypothesis; private Map<FastMealyState<O>, QueueElement> accessSequences; private GlobalSuffixFinder<? super I,? super Word<O>> suffixFinder; private class QueueElement { private FastMealyState<O> parentState; private QueueElement parentElement; private I transIn; private O transOut; private QueueElement(FastMealyState<O> parentState, QueueElement parentElement, I transIn, O transOut) { this.parentState = parentState; this.parentElement = parentElement; this.transIn = transIn; this.transOut = transOut; } } public MealyDHC(Alphabet<I> alphabet, MembershipOracle<I, Word<O>> oracle) { this.alphabet = alphabet; this.oracle = oracle; this.suffixFinder = GlobalSuffixFinders.RIVEST_SCHAPIRE; } @Override public void startLearning() { // the effective alphabet is the concatenation of the real alphabet // wrapped in Words and the list of splitters SimpleAlphabet<Word<I>> effectivealpha = new SimpleAlphabet<>(); for (I input : alphabet) { effectivealpha.add(Word.fromLetter(input)); } effectivealpha.addAll(splitters); // initialize structure to store state output signatures Map<List<Word<O>>, FastMealyState<O>> signatures = new HashMap<>(); // set up new hypothesis machine hypothesis = new FastMealy<>(alphabet); // initialize exploration queue Queue<QueueElement> queue = new LinkedList<>(); // initialize storage for access sequences accessSequences = new HashMap<>(); // first element to be explored represents the initial state with no predecessor queue.add(new QueueElement(null, null, null, null)); while (!queue.isEmpty()) { // get element to be explored from queue QueueElement elem = queue.poll(); // determine access sequence for state Word<I> access = assembleAccessSequence(elem); // assemble queries ArrayList<DefaultQuery<I, Word<O>>> queries = new ArrayList<>(effectivealpha.size()); for (Word<I> suffix : effectivealpha) { queries.add(new DefaultQuery<I, Word<O>>(access, suffix)); } // retrieve answers oracle.processQueries(queries); // assemble output signature List<Word<O>> sig = new ArrayList<>(effectivealpha.size()); for (DefaultQuery<I, Word<O>> query : queries) { sig.add(query.getOutput()); } FastMealyState<O> sibling = signatures.get(sig); if (sibling != null) { // this element does not possess a new output signature // create a transition from parent state to sibling hypothesis.addTransition(elem.parentState, elem.transIn, sibling, elem.transOut); } else { // this is actually an observably distinct state! Progress! // Create state and connect via transition to parent FastMealyState<O> state = elem.parentElement == null ? hypothesis.addInitialState() : hypothesis.addState(); if (elem.parentElement != null) { hypothesis.addTransition(elem.parentState, elem.transIn, state, elem.transOut); } signatures.put(sig, state); accessSequences.put(state, elem); scheduleSuccessors(elem, state, queue, sig); } } } private Word<I> assembleAccessSequence(QueueElement elem) { List<I> sequence = new ArrayList<>(); QueueElement pre = elem.parentElement; I sym = elem.transIn; while (pre != null && sym != null) { sequence.add(sym); sym = pre.transIn; pre = pre.parentElement; } Collections.reverse(sequence); return Word.fromList(sequence); } private void scheduleSuccessors(QueueElement elem, FastMealyState<O> state, Queue<QueueElement> queue, List<Word<O>> sig) throws IllegalArgumentException { for (int i = 0; i < alphabet.size(); ++i) { // retrieve I/O for transition I input = alphabet.getSymbol(i); O output = sig.get(i).getSymbol(0); // create successor element and schedule for exploration queue.add(new QueueElement(state, elem, input, output)); } } private void checkInternalState() { if (hypothesis == null) { throw new IllegalStateException("No hypothesis learned yet"); } } @Override public boolean refineHypothesis(DefaultQuery<I, Word<O>> ceQuery) { checkInternalState(); int oldsize = hypothesis.size(); for(Word<I> suf : suffixFinder.findSuffixes(ceQuery, this, hypothesis, oracle)) { if(!splitters.contains(suf)) { splitters.add(suf); log.log(Level.FINE, "added suffix: {0}", suf); } } startLearning(); return oldsize != hypothesis.size(); } @Override public MealyMachine<?, I, ?, O> getHypothesisModel() { checkInternalState(); return (MealyMachine<?, I, ?, O>) hypothesis; } @Override public Word<I> transformAccessSequence(Word<I> word) { checkInternalState(); FastMealyState<O> state = hypothesis.getSuccessor(hypothesis.getInitialState(), word); return assembleAccessSequence(accessSequences.get(state)); } @Override public boolean isAccessSequence(Word<I> word) { checkInternalState(); Word<I> canonical = transformAccessSequence(word); return canonical.equals(word); } }
package org.batfish.main; import com.google.common.cache.Cache; import com.google.common.cache.CacheBuilder; import com.google.common.collect.ImmutableList; import com.uber.jaeger.Configuration.ReporterConfiguration; import com.uber.jaeger.Configuration.SamplerConfiguration; import com.uber.jaeger.samplers.ConstSampler; import io.opentracing.ActiveSpan; import io.opentracing.References; import io.opentracing.SpanContext; import io.opentracing.contrib.jaxrs2.server.ServerTracingDynamicFeature; import io.opentracing.util.GlobalTracer; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.lang.ProcessBuilder.Redirect; import java.lang.management.ManagementFactory; import java.lang.management.RuntimeMXBean; import java.net.URI; import java.nio.file.Paths; import java.util.Arrays; import java.util.Collections; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.SortedMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Nullable; import javax.net.ssl.SSLHandshakeException; import javax.ws.rs.ProcessingException; import javax.ws.rs.client.Client; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.core.UriBuilder; import org.apache.commons.collections4.map.LRUMap; import org.apache.commons.lang3.SystemUtils; import org.apache.commons.lang3.exception.ExceptionUtils; import org.batfish.common.BatfishException; import org.batfish.common.BatfishLogger; import org.batfish.common.BfConsts; import org.batfish.common.BfConsts.TaskStatus; import org.batfish.common.CleanBatfishException; import org.batfish.common.CoordConsts; import org.batfish.common.QuestionException; import org.batfish.common.Snapshot; import org.batfish.common.Task; import org.batfish.common.Task.Batch; import org.batfish.common.Version; import org.batfish.common.util.CommonUtil; import org.batfish.config.ConfigurationLocator; import org.batfish.config.Settings; import org.batfish.config.Settings.EnvironmentSettings; import org.batfish.config.Settings.TestrigSettings; import org.batfish.datamodel.Configuration; import org.batfish.datamodel.DataPlane; import org.batfish.datamodel.answers.Answer; import org.batfish.datamodel.answers.AnswerStatus; import org.batfish.datamodel.collections.BgpAdvertisementsByVrf; import org.batfish.datamodel.collections.RoutesByVrf; import org.codehaus.jettison.json.JSONArray; import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory; import org.glassfish.jersey.jettison.JettisonFeature; import org.glassfish.jersey.server.ResourceConfig; public class Driver { public enum RunMode { WATCHDOG, WORKER, WORKSERVICE, } static final class CheckParentProcessTask implements Runnable { final int _ppid; public CheckParentProcessTask(int ppid) { _ppid = ppid; } @Override public void run() { Driver.checkParentProcess(_ppid); } } private static void checkParentProcess(int ppid) { try { if (!isProcessRunning(ppid)) { _mainLogger.infof("Committing suicide; ppid %d is dead.\n", ppid); System.exit(0); } } catch (Exception e) { _mainLogger.errorf("Exception while checking parent process with pid: %s", ppid); } } private static boolean _idle = true; private static Date _lastPollFromCoordinator = new Date(); private static String[] _mainArgs = null; private static BatfishLogger _mainLogger = null; private static Settings _mainSettings = null; private static ConcurrentMap<String, Task> _taskLog; private static final Cache<TestrigSettings, DataPlane> CACHED_COMPRESSED_DATA_PLANES = buildDataPlaneCache(); private static final Cache<TestrigSettings, DataPlane> CACHED_DATA_PLANES = buildDataPlaneCache(); private static final Map<EnvironmentSettings, SortedMap<String, BgpAdvertisementsByVrf>> CACHED_ENVIRONMENT_BGP_TABLES = buildEnvironmentBgpTablesCache(); private static final Map<EnvironmentSettings, SortedMap<String, RoutesByVrf>> CACHED_ENVIRONMENT_ROUTING_TABLES = buildEnvironmentRoutingTablesCache(); private static final Cache<Snapshot, SortedMap<String, Configuration>> CACHED_TESTRIGS = buildTestrigCache(); private static final int COORDINATOR_CHECK_INTERVAL_MS = 1 * 60 * 1000; // 1 min private static final int COORDINATOR_POLL_TIMEOUT_MS = 30 * 1000; // 30 secs private static final int COORDINATOR_REGISTRATION_RETRY_INTERVAL_MS = 1 * 1000; // 1 sec private static final int PARENT_CHECK_INTERVAL_MS = 1 * 1000; // 1 sec static Logger httpServerLogger = Logger.getLogger(org.glassfish.grizzly.http.server.HttpServer.class.getName()); private static final int MAX_CACHED_DATA_PLANES = 2; private static final int MAX_CACHED_ENVIRONMENT_BGP_TABLES = 4; private static final int MAX_CACHED_ENVIRONMENT_ROUTING_TABLES = 4; private static final int MAX_CACHED_TESTRIGS = 5; static Logger networkListenerLogger = Logger.getLogger("org.glassfish.grizzly.http.server.NetworkListener"); private static Cache<TestrigSettings, DataPlane> buildDataPlaneCache() { return CacheBuilder.newBuilder().maximumSize(MAX_CACHED_DATA_PLANES).weakValues().build(); } private static Map<EnvironmentSettings, SortedMap<String, BgpAdvertisementsByVrf>> buildEnvironmentBgpTablesCache() { return Collections.synchronizedMap( new LRUMap<EnvironmentSettings, SortedMap<String, BgpAdvertisementsByVrf>>( MAX_CACHED_ENVIRONMENT_BGP_TABLES)); } private static Map<EnvironmentSettings, SortedMap<String, RoutesByVrf>> buildEnvironmentRoutingTablesCache() { return Collections.synchronizedMap( new LRUMap<EnvironmentSettings, SortedMap<String, RoutesByVrf>>( MAX_CACHED_ENVIRONMENT_ROUTING_TABLES)); } private static Cache<Snapshot, SortedMap<String, Configuration>> buildTestrigCache() { return CacheBuilder.newBuilder().maximumSize(MAX_CACHED_TESTRIGS).build(); } private static synchronized boolean claimIdle() { if (_idle) { _idle = false; return true; } return false; } public static synchronized boolean getIdle() { _lastPollFromCoordinator = new Date(); return _idle; } public static BatfishLogger getMainLogger() { return _mainLogger; } @Nullable private static synchronized Task getTask(Settings settings) { String taskId = settings.getTaskId(); if (taskId == null) { return null; } else { return _taskLog.get(taskId); } } @Nullable public static synchronized Task getTaskFromLog(String taskId) { return _taskLog.get(taskId); } private static void initTracer() { GlobalTracer.register( new com.uber.jaeger.Configuration( _mainSettings.getServiceName(), new SamplerConfiguration(ConstSampler.TYPE, 1), new ReporterConfiguration( false, _mainSettings.getTracingAgentHost(), _mainSettings.getTracingAgentPort(), /* flush interval in ms */ 1000, /* max buffered Spans */ 10000)) .getTracer()); } private static boolean isProcessRunning(int pid) throws IOException { // all of this would be a lot simpler in Java 9, using processHandle if (SystemUtils.IS_OS_WINDOWS) { throw new UnsupportedOperationException("Process monitoring is not supported on Windows"); } else { ProcessBuilder builder = new ProcessBuilder("ps", "-x", String.valueOf(pid)); builder.redirectErrorStream(true); Process process = builder.start(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) { String line; while ((line = reader.readLine()) != null) { String[] columns = line.trim().split("\\s+"); if (String.valueOf(pid).equals(columns[0])) { return true; } } } } return false; } @Nullable public static synchronized Task killTask(String taskId) { Task task = _taskLog.get(taskId); if (_mainSettings.getParentPid() <= 0) { throw new BatfishException("Cannot kill tasks when started in non-watchdog mode"); } else if (task == null) { throw new BatfishException("Task with provided id not found: " + taskId); } else if (task.getStatus().isTerminated()) { throw new BatfishException("Task with provided id already terminated " + taskId); } else { // update task details in case a new query for status check comes in task.newBatch("Got kill request"); task.setStatus(TaskStatus.TerminatedByUser); task.setTerminated(new Date()); task.setErrMessage("Terminated by user"); // we die after a little bit, to allow for the response making it back to the coordinator new java.util.Timer() .schedule( new java.util.TimerTask() { @Override public void run() { System.exit(0); } }, 3000); return task; } } private static synchronized void logTask(String taskId, Task task) throws Exception { if (_taskLog.containsKey(taskId)) { throw new Exception("duplicate UUID for task"); } else { _taskLog.put(taskId, task); } } public static void main(String[] args) { mainInit(args); _mainLogger = new BatfishLogger( _mainSettings.getLogLevel(), _mainSettings.getTimestamp(), _mainSettings.getLogFile(), _mainSettings.getLogTee(), true); mainRun(); } public static void main(String[] args, BatfishLogger logger) { mainInit(args); _mainLogger = logger; mainRun(); } private static void mainInit(String[] args) { _taskLog = new ConcurrentHashMap<>(); _mainArgs = args; try { _mainSettings = new Settings(args); networkListenerLogger.setLevel(Level.WARNING); httpServerLogger.setLevel(Level.WARNING); } catch (Exception e) { System.err.println( "batfish: Initialization failed. Reason: " + ExceptionUtils.getStackTrace(e)); System.exit(1); } } private static void mainRun() { System.setErr(_mainLogger.getPrintStream()); System.setOut(_mainLogger.getPrintStream()); _mainSettings.setLogger(_mainLogger); switch (_mainSettings.getRunMode()) { case WATCHDOG: mainRunWatchdog(); break; case WORKER: mainRunWorker(); break; case WORKSERVICE: mainRunWorkService(); break; default: System.err.println( "batfish: Initialization failed. Unknown runmode: " + _mainSettings.getRunMode()); System.exit(1); } } private static void mainRunWatchdog() { while (true) { RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean(); String classPath = runtimeMxBean.getClassPath(); List<String> jvmArguments = runtimeMxBean .getInputArguments() .stream() .filter(arg -> !arg.startsWith("-agentlib:")) // remove IntelliJ hooks .collect(ImmutableList.toImmutableList()); int myPid = Integer.parseInt(runtimeMxBean.getName().split("@")[0]); List<String> command = new ImmutableList.Builder<String>() .add( Paths.get(System.getProperty("java.home"), "bin", "java") .toAbsolutePath() .toString()) .addAll(jvmArguments) .add("-cp") .add(classPath) .add(Driver.class.getCanonicalName()) // if we add runmode here, any runmode argument in mainArgs is ignored .add("-" + Settings.ARG_RUN_MODE) .add(RunMode.WORKSERVICE.toString()) .add("-" + Settings.ARG_PARENT_PID) .add(Integer.toString(myPid)) .addAll(Arrays.asList(_mainArgs)) .build(); _mainLogger.debugf("Will start workservice with arguments: %s\n", command); ProcessBuilder builder = new ProcessBuilder(command); builder.redirectErrorStream(true); builder.redirectInput(Redirect.INHERIT); Process process; try { process = builder.start(); } catch (IOException e) { _mainLogger.errorf("Exception starting process: %s", ExceptionUtils.getStackTrace(e)); _mainLogger.errorf("Will try again in 1 second\n"); try { Thread.sleep(1000); } catch (InterruptedException e1) { _mainLogger.errorf("Sleep was interrrupted: %s", ExceptionUtils.getStackTrace(e1)); } continue; } try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) { reader.lines().forEach(line -> _mainLogger.output(line + "\n")); } catch (IOException e) { _mainLogger.errorf( "Interrupted while reading subprocess stream: %s", ExceptionUtils.getStackTrace(e)); } try { process.waitFor(); } catch (InterruptedException e) { _mainLogger.infof( "Subprocess was killed: %s.\nRestarting", ExceptionUtils.getStackTrace(e)); } } } private static void mainRunWorker() { if (_mainSettings.canExecute()) { _mainSettings.setLogger(_mainLogger); Batfish.initTestrigSettings(_mainSettings); if (runBatfish(_mainSettings) != null) { System.exit(1); } } } private static void mainRunWorkService() { if (_mainSettings.getTracingEnable() && !GlobalTracer.isRegistered()) { initTracer(); } String protocol = _mainSettings.getSslDisable() ? "http" : "https"; String baseUrl = String.format("%s://%s", protocol, _mainSettings.getServiceBindHost()); URI baseUri = UriBuilder.fromUri(baseUrl).port(_mainSettings.getServicePort()).build(); _mainLogger.debug(String.format("Starting server at %s\n", baseUri)); ResourceConfig rc = new ResourceConfig(Service.class).register(new JettisonFeature()); if (_mainSettings.getTracingEnable()) { rc.register(ServerTracingDynamicFeature.class); } try { if (_mainSettings.getSslDisable()) { GrizzlyHttpServerFactory.createHttpServer(baseUri, rc); } else { CommonUtil.startSslServer( rc, baseUri, _mainSettings.getSslKeystoreFile(), _mainSettings.getSslKeystorePassword(), _mainSettings.getSslTrustAllCerts(), _mainSettings.getSslTruststoreFile(), _mainSettings.getSslTruststorePassword(), ConfigurationLocator.class, Driver.class); } if (_mainSettings.getCoordinatorRegister()) { // this function does not return until registration succeeds registerWithCoordinatorPersistent(); } if (_mainSettings.getParentPid() > 0) { if (SystemUtils.IS_OS_WINDOWS) { _mainLogger.errorf( "Parent process monitoring is not supported on Windows. We'll live without it."); } else { Executors.newScheduledThreadPool(1) .scheduleAtFixedRate( new CheckParentProcessTask(_mainSettings.getParentPid()), 0, PARENT_CHECK_INTERVAL_MS, TimeUnit.MILLISECONDS); } } // sleep indefinitely, check for parent pid and coordinator each time while (true) { Thread.sleep(COORDINATOR_CHECK_INTERVAL_MS); /* * every time we wake up, we check if the coordinator has polled us recently * if not, re-register the service. the coordinator might have died and come back. */ if (_mainSettings.getCoordinatorRegister() && new Date().getTime() - _lastPollFromCoordinator.getTime() > COORDINATOR_POLL_TIMEOUT_MS) { // this function does not return until registration succeeds registerWithCoordinatorPersistent(); } } } catch (ProcessingException e) { String msg = "FATAL ERROR: " + e.getMessage() + "\n"; _mainLogger.error(msg); System.exit(1); } catch (Exception ex) { String stackTrace = ExceptionUtils.getStackTrace(ex); _mainLogger.error(stackTrace); System.exit(1); } } private static synchronized void makeIdle() { _idle = true; } public static synchronized AtomicInteger newBatch( Settings settings, String description, int jobs) { Batch batch = null; Task task = getTask(settings); if (task != null) { batch = task.newBatch(description); batch.setSize(jobs); return batch.getCompleted(); } else { return new AtomicInteger(); } } private static boolean registerWithCoordinator(String poolRegUrl) { Map<String, String> params = new HashMap<>(); params.put( CoordConsts.SVC_KEY_ADD_WORKER, _mainSettings.getServiceHost() + ":" + _mainSettings.getServicePort()); params.put(CoordConsts.SVC_KEY_VERSION, Version.getVersion()); Object response = talkToCoordinator(poolRegUrl, params, _mainLogger); return response != null; } private static void registerWithCoordinatorPersistent() throws InterruptedException { boolean registrationSuccess; String protocol = _mainSettings.getSslDisable() ? "http" : "https"; String poolRegUrl = String.format( "%s://%s:%s%s/%s", protocol, _mainSettings.getCoordinatorHost(), +_mainSettings.getCoordinatorPoolPort(), CoordConsts.SVC_CFG_POOL_MGR, CoordConsts.SVC_RSC_POOL_UPDATE); do { registrationSuccess = registerWithCoordinator(poolRegUrl); if (!registrationSuccess) { Thread.sleep(COORDINATOR_REGISTRATION_RETRY_INTERVAL_MS); } } while (!registrationSuccess); } @SuppressWarnings("deprecation") private static String runBatfish(final Settings settings) { final BatfishLogger logger = settings.getLogger(); try { final Batfish batfish = new Batfish( settings, CACHED_TESTRIGS, CACHED_COMPRESSED_DATA_PLANES, CACHED_DATA_PLANES, CACHED_ENVIRONMENT_BGP_TABLES, CACHED_ENVIRONMENT_ROUTING_TABLES); @Nullable SpanContext runBatfishSpanContext = GlobalTracer.get().activeSpan() == null ? null : GlobalTracer.get().activeSpan().context(); Thread thread = new Thread() { @Override public void run() { try (ActiveSpan runBatfishSpan = GlobalTracer.get() .buildSpan("Run Batfish job in a new thread and get the answer") .addReference(References.FOLLOWS_FROM, runBatfishSpanContext) .startActive()) { assert runBatfishSpan != null; Answer answer = null; try { answer = batfish.run(); if (answer.getStatus() == null) { answer.setStatus(AnswerStatus.SUCCESS); } } catch (CleanBatfishException e) { String msg = "FATAL ERROR: " + e.getMessage(); logger.error(msg); batfish.setTerminatingExceptionMessage( e.getClass().getName() + ": " + e.getMessage()); answer = Answer.failureAnswer(msg, null); } catch (QuestionException e) { String stackTrace = ExceptionUtils.getStackTrace(e); logger.error(stackTrace); batfish.setTerminatingExceptionMessage( e.getClass().getName() + ": " + e.getMessage()); answer = e.getAnswer(); answer.setStatus(AnswerStatus.FAILURE); } catch (BatfishException e) { String stackTrace = ExceptionUtils.getStackTrace(e); logger.error(stackTrace); batfish.setTerminatingExceptionMessage( e.getClass().getName() + ": " + e.getMessage()); answer = new Answer(); answer.setStatus(AnswerStatus.FAILURE); answer.addAnswerElement(e.getBatfishStackTrace()); } catch (Throwable e) { String stackTrace = ExceptionUtils.getStackTrace(e); logger.error(stackTrace); batfish.setTerminatingExceptionMessage( e.getClass().getName() + ": " + e.getMessage()); answer = new Answer(); answer.setStatus(AnswerStatus.FAILURE); answer.addAnswerElement( new BatfishException("Batfish job failed", e).getBatfishStackTrace()); } finally { try (ActiveSpan outputAnswerSpan = GlobalTracer.get().buildSpan("Outputting answer").startActive()) { assert outputAnswerSpan != null; if (settings.getAnswerJsonPath() != null) { batfish.outputAnswerWithLog(answer); } } } } } }; thread.start(); thread.join(settings.getMaxRuntimeMs()); if (thread.isAlive()) { // this is deprecated but we should be safe since we don't have // locks and such // AF: This doesn't do what you think it does, esp. not in Java 8. // It needs to be replaced. TODO thread.stop(); logger.error("Batfish worker took too long. Terminated."); batfish.setTerminatingExceptionMessage("Batfish worker took too long. Terminated."); } return batfish.getTerminatingExceptionMessage(); } catch (Exception e) { String stackTrace = ExceptionUtils.getStackTrace(e); logger.error(stackTrace); return stackTrace; } } public static List<String> runBatfishThroughService(final String taskId, String[] args) { final Settings settings; try { settings = new Settings(_mainSettings); settings.setRunMode(RunMode.WORKER); settings.parseCommandLine(args); // assign taskId for status updates, termination requests settings.setTaskId(taskId); } catch (Exception e) { return Arrays.asList("failure", "Initialization failed: " + ExceptionUtils.getStackTrace(e)); } try { Batfish.initTestrigSettings(settings); } catch (Exception e) { return Arrays.asList( "failure", "Failed while applying auto basedir. (All arguments are supplied?): " + e.getMessage()); } if (settings.canExecute()) { if (claimIdle()) { // lets put a try-catch around all the code around claimIdle // so that we never the worker non-idle accidentally try { final BatfishLogger jobLogger = new BatfishLogger( settings.getLogLevel(), settings.getTimestamp(), settings.getLogFile(), settings.getLogTee(), false); settings.setLogger(jobLogger); final Task task = new Task(args); logTask(taskId, task); @Nullable SpanContext runTaskSpanContext = GlobalTracer.get().activeSpan() == null ? null : GlobalTracer.get().activeSpan().context(); // run batfish on a new thread and set idle to true when done Thread thread = new Thread() { @Override public void run() { try (ActiveSpan runBatfishSpan = GlobalTracer.get() .buildSpan("Initialize Batfish in a new thread") .addReference(References.FOLLOWS_FROM, runTaskSpanContext) .startActive()) { assert runBatfishSpan != null; // avoid unused warning task.setStatus(TaskStatus.InProgress); String errMsg = runBatfish(settings); if (errMsg == null) { task.setStatus(TaskStatus.TerminatedNormally); } else { task.setStatus(TaskStatus.TerminatedAbnormally); task.setErrMessage(errMsg); } task.setTerminated(new Date()); jobLogger.close(); makeIdle(); } } }; thread.start(); return Arrays.asList(BfConsts.SVC_SUCCESS_KEY, "running now"); } catch (Exception e) { _mainLogger.error("Exception while running task: " + e.getMessage()); makeIdle(); return Arrays.asList(BfConsts.SVC_FAILURE_KEY, e.getMessage()); } } else { return Arrays.asList(BfConsts.SVC_FAILURE_KEY, "Not idle"); } } else { return Arrays.asList(BfConsts.SVC_FAILURE_KEY, "Non-executable command"); } } public static Object talkToCoordinator( String url, Map<String, String> params, BatfishLogger logger) { Client client = null; try { client = CommonUtil.createHttpClientBuilder( _mainSettings.getSslDisable(), _mainSettings.getSslTrustAllCerts(), _mainSettings.getSslKeystoreFile(), _mainSettings.getSslKeystorePassword(), _mainSettings.getSslTruststoreFile(), _mainSettings.getSslTruststorePassword()) .build(); WebTarget webTarget = client.target(url); for (Map.Entry<String, String> entry : params.entrySet()) { webTarget = webTarget.queryParam(entry.getKey(), entry.getValue()); } Response response = webTarget.request(MediaType.APPLICATION_JSON).get(); logger.debug( "BF: " + response.getStatus() + " " + response.getStatusInfo() + " " + response + "\n"); if (response.getStatus() != Response.Status.OK.getStatusCode()) { logger.error("Did not get an OK response\n"); return null; } String sobj = response.readEntity(String.class); JSONArray array = new JSONArray(sobj); logger.debugf("BF: response: %s [%s] [%s]\n", array, array.get(0), array.get(1)); if (!array.get(0).equals(CoordConsts.SVC_KEY_SUCCESS)) { logger.errorf( "BF: got error while talking to coordinator: %s %s\n", array.get(0), array.get(1)); return null; } return array.get(1); } catch (ProcessingException e) { if (CommonUtil.causedBy(e, SSLHandshakeException.class) || CommonUtil.causedByMessage(e, "Unexpected end of file from server")) { throw new BatfishException("Unrecoverable connection error", e); } logger.errorf("BF: unable to connect to coordinator pool mgr at %s\n", url); logger.debug(ExceptionUtils.getStackTrace(e) + "\n"); return null; } catch (Exception e) { logger.errorf("exception: " + ExceptionUtils.getStackTrace(e)); return null; } finally { if (client != null) { client.close(); } } } }
package ru.yandex.qatools.allure; import io.airlift.command.*; import io.airlift.command.Cli.CliBuilder; import ru.yandex.qatools.allure.data.AllureReportGenerator; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.jar.JarFile; import java.util.Enumeration; import java.util.jar.JarEntry; public class AllureCli { private static final String DEFAULT_OUTPUT_PATH = "output"; private static final String REPORT_FACE_DIRECTORY = "allure-report-face"; public static void main(String[] args) { final CliBuilder<Runnable> builder = Cli.<Runnable>builder("allure") .withDescription("Allure command line client") .withDefaultCommand(Help.class) .withCommands(Help.class, GenerateCommand.class); final Cli<Runnable> parser = builder.build(); parser.parse(args).run(); } @Command(name = "generate", description = "Generate HTML report from XML files") public static class GenerateCommand implements Runnable { @Option(type = OptionType.COMMAND, name = {"-o", "--outputPath"}, description = "Directory to output report files to (default is \"" + DEFAULT_OUTPUT_PATH + "\")") public String outputPath = DEFAULT_OUTPUT_PATH; @Arguments(title = "inputPaths", required = true, description = "A list of input directories to be processed") public List<String> inputPaths; public void run() { try { final File outputDirectory = new File(outputPath); if (!outputDirectory.exists()) { outputDirectory.mkdir(); } final List<File> inputDirectories = new ArrayList<>(); for (final String inputDirectory : inputPaths) { inputDirectories.add(new File(inputDirectory)); } final AllureReportGenerator generator = new AllureReportGenerator(inputDirectories.toArray(new File[inputDirectories.size()])); generator.generate(outputDirectory); final String reportFaceWildcard = REPORT_FACE_DIRECTORY + File.separator + ".*"; copyStaticReportData(getCurrentJarFilePath(), outputDirectory, reportFaceWildcard); System.out.println("Successfully generated report to " + outputDirectory.getAbsolutePath() + "."); } catch (Exception e) { throw new RuntimeException(e); } } private static void copyStaticReportData(final File currentJarFile, final File outputDirectory, final String wildcard) throws IOException { final JarFile jar = new java.util.jar.JarFile(currentJarFile); final Enumeration entries = jar.entries(); while (entries.hasMoreElements()) { final JarEntry file = (java.util.jar.JarEntry) entries.nextElement(); if (file.getName().matches(wildcard)) { final String newFileName = file.getName().replace(REPORT_FACE_DIRECTORY + File.separator, ""); if (newFileName.length() > 0) { final String newFilePath = outputDirectory + File.separator + newFileName; final File f = new File(newFilePath); if (file.isDirectory() && !f.exists()) { f.mkdir(); continue; } final InputStream inputStream = jar.getInputStream(file); final FileOutputStream fileOutputStream = new FileOutputStream(f); while (inputStream.available() > 0) { fileOutputStream.write(inputStream.read()); } fileOutputStream.close(); inputStream.close(); } } } } private static File getCurrentJarFilePath() { return new File(AllureCli.class.getProtectionDomain().getCodeSource().getLocation().getPath()); } } }
package com.psychowood.henkaku; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.AbstractMap.SimpleEntry; import java.util.Arrays; import java.util.HashMap; import java.util.Map; public class HENprocess { private static boolean debug = false; private static final byte[] URL_PLACEHOLDER = getArrayOfByte((byte) 'x',256); private static byte[] getArrayOfByte(byte b,int length) { byte[] arr = new byte[length]; for (int i=0;i<length; i++) { arr[i] = b; } return arr; } public HENprocess() { super(); } public static void main(String[] argv) { if (argv.length < 3) { logErr("Usage for write_pkg_url: java HENprocess write_pkg_url filename url"); logErr("Usage for preprocess: java HENprocess preprocess urop.bin output-payload.js"); System.exit(-2); } debug = debug || (argv.length > 3); final String operation = argv[0]; OutputStream output = null; InputStream input = null; try { if (operation.equalsIgnoreCase("write_pkg_url")) { final String srcFile = argv[1]; final String url = argv[2]; byte[] contents = read(srcFile) ; output = new BufferedOutputStream(new FileOutputStream(srcFile)); writePkgUrl(contents, output, url); } else if (operation.equalsIgnoreCase("preprocess")) { final String uropFile = argv[1]; final String outputFile = argv[2]; input = new BufferedInputStream(new FileInputStream(uropFile)); output = new BufferedOutputStream(new FileOutputStream(outputFile)); boolean isJs = outputFile.endsWith(".js"); preprocess(input, output, isJs); } else { throw new Exception("Unsupported operation: " + operation); } } catch (Exception e) { logErr(e); System.exit(-2); } finally { if (output != null) { try { output.close(); } catch(Exception e) {} } if (input!= null) { try { input.close(); } catch(Exception e) {} } } } /*** * preprocess.py script, does the HENkaku magic. Don't ask. * @param inputStream the InputStream with the contents to be mangled. the stream will be closed * @param output write here the output * @param jsOutput true if it should output the payload.js file * @throws Exception */ public static void preprocess(InputStream inputStream, OutputStream output, boolean jsOutput) throws Exception { byte[] urop = readAndClose(inputStream); while (urop.length % 4 != 0) { final int N = urop.length; urop = Arrays.copyOf(urop, N + 1); urop[N] = (byte) 0; } int header_size = 0x40; int dsize = u32(urop, 0x10); int csize = u32(urop, 0x20); int reloc_size = u32(urop, 0x30); int symtab_size = u32(urop, 0x38); if (csize % 4 != 0) { throw new Exception("csize % 4 != 0???"); } int reloc_offset = header_size + dsize + csize; int symtab = reloc_offset + reloc_size; int strtab = symtab + symtab_size; int symtab_n = getFloor(symtab_size, 8); Map<Integer,String> reloc_map = new HashMap<Integer,String>(); for (int x=0; x < symtab_n; x++) { int sym_id = u32(urop, symtab + 8 * x); int str_offset = u32(urop, symtab + 8 * x + 4); int begin = str_offset; int end = str_offset; while (urop[end] != 0) { end += 1; } String name = new String(Arrays.copyOfRange(urop, begin, end),"ascii"); reloc_map.put(sym_id,name); } // mapping between roptool (symbol_name, reloc_type) and exploit hardcoded types // note that in exploit type=0 means no relocation Map<SimpleEntry<String, Integer>,Integer> reloc_type_map = new HashMap<SimpleEntry<String, Integer>,Integer>(); reloc_type_map.put(new SimpleEntry<String, Integer>("rop.data",0),1); // dest += rop_data_base reloc_type_map.put(new SimpleEntry<String, Integer>("SceWebKit",0),2); // dest += SceWebKit_base reloc_type_map.put(new SimpleEntry<String, Integer>("SceLibKernel",0),3); // dest += SceLibKernel_base reloc_type_map.put(new SimpleEntry<String, Integer>("SceLibc",0),4); // dest += SceLibc_base reloc_type_map.put(new SimpleEntry<String, Integer>("SceLibHttp",0),5); // dest += SceLibHttp_base reloc_type_map.put(new SimpleEntry<String, Integer>("SceNet",0),6); // dest += SceNet_base reloc_type_map.put(new SimpleEntry<String, Integer>("SceAppMgr",0),7); // dest += SceAppMgr_base // we don't need symtab/strtab/relocs int want_len = 0x40 + dsize + csize; byte[] relocs = getArrayOfByte((byte)0, getFloor(want_len, 4)); int reloc_n = getFloor(reloc_size, 8); for (int x=0; x < reloc_n; x++) { int reloc_type = u16(urop, reloc_offset + 8 * x); int sym_id = u16(urop, reloc_offset + 8 * x + 2); int offset = u32(urop, reloc_offset + 8 * x + 4); String err = null; //log("type " + reloc_type + " sym " + reloc_map.get(sym_id) + " offset " + offset); if (offset % 4 != 0) { err = "offset % 4 != 0???"; } int relocsIndex = getFloor(offset, 4); if (relocs[relocsIndex] != 0) { err = "symbol relocated twice, not supported"; } Integer wk_reloc_type = reloc_type_map.get(new SimpleEntry<String, Integer>(reloc_map.get(sym_id),reloc_type)); if (wk_reloc_type == null) { err = "unsupported relocation type"; } if (err != null) { //logErr("type " + reloc_type + " sym " + reloc_map.get(sym_id) + " offset " + offset); throw new Exception(err); } relocs[relocsIndex] = wk_reloc_type.byteValue(); } long[] urop_js = new long[want_len/4]; for (int x=0, y=0; x < want_len; x = x+4, y++) { long val = (long) u32(urop, x); if (val < 0) { val = -1*((long) (Integer.MAX_VALUE+1)*2-val); } urop_js[y] = val; } if (jsOutput) { output.write('\n'); output.write("payload = [".getBytes()); for (int x=0; x < urop_js.length; x++) { output.write(Long.toString(urop_js[x]).getBytes()); if (x!= urop_js.length-1) { output.write(','); } } output.write("];\n".getBytes()); output.write("relocs = [".getBytes()); for (int x=0; x < relocs.length; x++) { output.write(Long.toString(relocs[x]).getBytes()); if (x!= relocs.length-1) { output.write(','); } } output.write("];\n".getBytes()); } else { long pos = 0; byte[] data = ByteBuffer.allocate(4) .putInt(getFloor(want_len, 4)) .order(ByteOrder.LITTLE_ENDIAN) .array(); for(int j = data.length; j > 0; j output.write(data[j-1]); } pos = pos + 4; for (int x=0; x < urop_js.length; x++) { data = ByteBuffer.allocate(4) .putInt((int)urop_js[x]) .order(ByteOrder.LITTLE_ENDIAN) .array(); for(int j = data.length; j > 0; j output.write(data[j-1]); } pos = pos + 4; } for (int x=0; x < relocs.length; x++) { data = ByteBuffer.allocate(1) .put(relocs[x]) .array(); output.write(data); pos = pos + 1; } while (pos % 4 != 0 ) { output.write('\0'); pos = pos +1; } } } private static int getFloor(double value, int divider) { return (int) Math.floor( value / divider ); } private static int u32(byte[] data,int offset) { byte[] fourBytes = Arrays.copyOfRange(data,offset,offset+4); final int anInt = (ByteBuffer.wrap(fourBytes) .order(ByteOrder.LITTLE_ENDIAN).getInt()); return (int) anInt; } private static int u16(byte[] data, int offset) { byte[] fourBytes = Arrays.copyOfRange(data,offset,offset+2); final int anInt = (ByteBuffer.wrap(fourBytes) .order(ByteOrder.LITTLE_ENDIAN).getShort()); return (int) anInt; } /*** * Write the given URL (with lentgh below 255 chars) in the contents array, writing the result * in output * @param source the InputStream to search for the placeholder * @param output where to write the byte[] with the injected url * @param url the URL to inject * @throws Exception in case of url.length > 255, of placeholder not found or if writing to the output stream fails */ public static void writePkgUrl(InputStream source, OutputStream output, String url) throws Exception { byte[] contents = readAndClose(source); writePkgUrl(contents,output,url); } /*** * @see private static void writePkgUrl(InputStream source, OutputStream output, String url) throws Exception */ private static void writePkgUrl(byte[] contents, OutputStream output, String url) throws Exception { if (url.length() >= 255) { throw new Exception("url must be at most 255 characters!"); } Integer pos = bytesIndexOf(contents,URL_PLACEHOLDER,0); if (pos < 0) { throw new Exception("URL placeholder not found!"); } try { output.write(Arrays.copyOfRange(contents,0,pos)); output.write(url.getBytes()); byte[] chars = new byte[256 - url.length()]; Arrays.fill(chars, (byte) 0); output.write(chars); output.write(Arrays.copyOfRange(contents,pos+256,contents.length)); } catch(IOException ex){ throw new Exception(ex); } } /** * Searchs for a subarray in a given array, starting from a specific index * @param Source the source array to search in * @param Search the array to look for in Source * @param fromIndex the starting index * @return The Search arrau position in Source, or -1 if not found */ private static Integer bytesIndexOf(byte[] Source, byte[] Search, int fromIndex) { boolean Find = false; int i; for (i = fromIndex;i<Source.length-Search.length;i++){ if(Source[i]==Search[0]){ Find = true; for (int j = 0;j<Search.length;j++){ if (Source[i+j]!=Search[j]){ Find = false; } } } if(Find){ break; } } if(!Find){ return new Integer(-1); } return new Integer(i); } /*** * Read the given binary file, and return its contents as a byte array. * @param aInputFileName The filename * @return A byte[] with the file contents * @throws IOException */ static byte[] read(String aInputFileName) throws IOException{ File file = new File(aInputFileName); byte[] result = null; InputStream input = new BufferedInputStream(new FileInputStream(file)); result = readAndClose(input); return result; } /*** * Read an input stream, and return it as a byte array. * @param aInput The InputStream to read * @return A byte[] with the InputStream contents * @throws IOException */ public static byte[] readAndClose(InputStream aInput) throws IOException { byte[] bucket = new byte[32*1024]; ByteArrayOutputStream result = null; try { result = new ByteArrayOutputStream(bucket.length); int bytesRead = 0; while(bytesRead != -1){ bytesRead = aInput.read(bucket); if(bytesRead > 0){ result.write(bucket, 0, bytesRead); } } } finally { aInput.close(); } return result.toByteArray(); } private static void logErr(Object aThing){ log(aThing,true); } private static void log(Object aThing){ log(aThing,false); } private static void log(Object aThing, boolean force){ if (debug || force) System.out.println(String.valueOf(aThing)); } }
package com.psychowood.henkaku; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.AbstractMap.SimpleEntry; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.Map; public class HENprocess { private static boolean debug = false; private static final byte[] URL_PLACEHOLDER = getArrayOfByte((byte) 'x',256); private static byte[] getArrayOfByte(byte b,int length) { byte[] arr = new byte[length]; for (int i=0;i<length; i++) { arr[i] = b; } return arr; } public HENprocess() { super(); } public static void main(String[] argv) { if (argv.length < 3) { logErr("Usage for write_pkg_url: java HENprocess write_pkg_url filename url"); logErr("Usage for preprocess: java HENprocess preprocess urop.bin output-payload.js"); System.exit(-2); } debug = debug || (argv.length > 3); final String operation = argv[0]; OutputStream output = null; InputStream input = null; try { if (operation.equalsIgnoreCase("write_pkg_url")) { final String srcFile = argv[1]; final String url = argv[2]; byte[] contents = read(srcFile) ; output = new BufferedOutputStream(new FileOutputStream(srcFile)); writePkgUrl(contents, output, url); } else if (operation.equalsIgnoreCase("preprocess")) { final String uropFile = argv[1]; final String outputFile = argv[2]; input = new BufferedInputStream(new FileInputStream(uropFile)); output = new BufferedOutputStream(new FileOutputStream(outputFile)); boolean isJs = outputFile.endsWith(".js"); preprocess(input, output, isJs); } else { throw new Exception("Unsupported operation: " + operation); } } catch (Exception e) { logErr(e); System.exit(-2); } finally { if (output != null) { try { output.close(); } catch(Exception e) {} } if (input!= null) { try { input.close(); } catch(Exception e) {} } } } /*** * preprocess.py script, does the HENkaku magic. Don't ask. * @param inputStream the InputStream with the contents to be mangled. the stream will be closed * @param output write here the output * @param jsOutput true if it should output the payload.js file * @throws Exception */ public static void preprocess(InputStream inputStream, OutputStream output, boolean jsOutput) throws Exception { byte[] urop = readAndClose(inputStream); while (urop.length % 4 != 0) { final int N = urop.length; urop = Arrays.copyOf(urop, N + 1); urop[N] = (byte) 0; } int header_size = 0x40; int dsize = u32(urop, 0x10); int csize = u32(urop, 0x20); int reloc_size = u32(urop, 0x30); int symtab_size = u32(urop, 0x38); if (csize % 4 != 0) { throw new Exception("csize % 4 != 0???"); } int reloc_offset = header_size + dsize + csize; int symtab = reloc_offset + reloc_size; int strtab = symtab + symtab_size; int symtab_n = getFloor(symtab_size, 8); Map<Integer,String> reloc_map = new HashMap<Integer,String>(); for (int x=0; x < symtab_n; x++) { int sym_id = u32(urop, symtab + 8 * x); int str_offset = u32(urop, symtab + 8 * x + 4); int begin = str_offset; int end = str_offset; while (urop[end] != 0) { end += 1; } String name = new String(Arrays.copyOfRange(urop, begin, end),"ascii"); reloc_map.put(sym_id,name); } // mapping between roptool (symbol_name, reloc_type) and exploit hardcoded types // note that in exploit type=0 means no relocation Map<SimpleEntry<String, Integer>,Integer> reloc_type_map = new HashMap<SimpleEntry<String, Integer>,Integer>(); reloc_type_map.put(new SimpleEntry<String, Integer>("rop.data",0),1); // dest += rop_data_base reloc_type_map.put(new SimpleEntry<String, Integer>("SceWebKit",0),2); // dest += SceWebKit_base reloc_type_map.put(new SimpleEntry<String, Integer>("SceLibKernel",0),3); // dest += SceLibKernel_base reloc_type_map.put(new SimpleEntry<String, Integer>("SceLibc",0),4); // dest += SceLibc_base reloc_type_map.put(new SimpleEntry<String, Integer>("SceLibHttp",0),5); // dest += SceLibHttp_base reloc_type_map.put(new SimpleEntry<String, Integer>("SceNet",0),6); // dest += SceNet_base reloc_type_map.put(new SimpleEntry<String, Integer>("SceAppMgr",0),7); // dest += SceAppMgr_base // we don't need symtab/strtab/relocs int want_len = 0x40 + dsize + csize; byte[] relocs = getArrayOfByte((byte)0, getFloor(want_len, 4)); int reloc_n = getFloor(reloc_size, 8); for (int x=0; x < reloc_n; x++) { int reloc_type = u16(urop, reloc_offset + 8 * x); int sym_id = u16(urop, reloc_offset + 8 * x + 2); int offset = u32(urop, reloc_offset + 8 * x + 4); String err = null; //log("type " + reloc_type + " sym " + reloc_map.get(sym_id) + " offset " + offset); if (offset % 4 != 0) { err = "offset % 4 != 0???"; } int relocsIndex = getFloor(offset, 4); if (relocs[relocsIndex] != 0) { err = "symbol relocated twice, not supported"; } Integer wk_reloc_type = reloc_type_map.get(new SimpleEntry<String, Integer>(reloc_map.get(sym_id),reloc_type)); if (wk_reloc_type == null) { err = "unsupported relocation type"; } if (err != null) { //logErr("type " + reloc_type + " sym " + reloc_map.get(sym_id) + " offset " + offset); throw new Exception(err); } relocs[relocsIndex] = wk_reloc_type.byteValue(); } long[] urop_js = getLongs(urop, want_len); if (jsOutput) { output.write('\n'); output.write("payload = [".getBytes()); for (int x=0; x < urop_js.length; x++) { output.write(Long.toString(urop_js[x]).getBytes()); if (x!= urop_js.length-1) { output.write(','); } } output.write("];\n".getBytes()); output.write("relocs = [".getBytes()); for (int x=0; x < relocs.length; x++) { output.write(Long.toString(relocs[x]).getBytes()); if (x!= relocs.length-1) { output.write(','); } } output.write("];\n".getBytes()); } else { long pos = 0; byte[] data = ByteBuffer.allocate(4) .putInt(getFloor(want_len, 4)) .order(ByteOrder.LITTLE_ENDIAN) .array(); for(int j = data.length; j > 0; j output.write(data[j-1]); } pos = pos + 4; for (int x=0; x < urop_js.length; x++) { data = ByteBuffer.allocate(4) .putInt((int)urop_js[x]) .order(ByteOrder.LITTLE_ENDIAN) .array(); for(int j = data.length; j > 0; j output.write(data[j-1]); } pos = pos + 4; } for (int x=0; x < relocs.length; x++) { data = ByteBuffer.allocate(1) .put(relocs[x]) .array(); output.write(data); pos = pos + 1; } while (pos % 4 != 0 ) { output.write('\0'); pos = pos +1; } } } public static long[] getLongs(byte[] urop, int want_len) { long[] urop_js = new long[want_len/4]; for (int x=0, y=0; x < want_len; x = x+4, y++) { long val = (long) u32(urop, x); if (val < 0) { val = -1*((long) (Integer.MAX_VALUE+1)*2-val); } urop_js[y] = val; } return urop_js; } private static int getFloor(double value, int divider) { return (int) Math.floor( value / divider ); } private static int u32(byte[] data,int offset) { byte[] fourBytes = Arrays.copyOfRange(data,offset,offset+4); final int anInt = (ByteBuffer.wrap(fourBytes) .order(ByteOrder.LITTLE_ENDIAN).getInt()); return (int) anInt; } private static int u16(byte[] data, int offset) { byte[] fourBytes = Arrays.copyOfRange(data,offset,offset+2); final int anInt = (ByteBuffer.wrap(fourBytes) .order(ByteOrder.LITTLE_ENDIAN).getShort()); return (int) anInt; } /*** * Write the given URL (with lentgh below 255 chars) in the contents array, writing the result * in output * @param source the InputStream to search for the placeholder * @param output where to write the byte[] with the injected url * @param url the URL to inject * @throws Exception in case of url.length > 255, of placeholder not found or if writing to the output stream fails */ public static void writePkgUrl(InputStream source, OutputStream output, String url) throws Exception { byte[] contents = readAndClose(source); writePkgUrl(contents,output,url); } /*** * @see private static void writePkgUrl(InputStream source, OutputStream output, String url) throws Exception */ private static void writePkgUrl(byte[] contents, OutputStream output, String url) throws Exception { if (url.length() >= 255) { throw new Exception("url must be at most 255 characters!"); } Integer pos = bytesIndexOf(contents,URL_PLACEHOLDER,0); if (pos < 0) { throw new Exception("URL placeholder not found!"); } try { output.write(Arrays.copyOfRange(contents,0,pos)); output.write(url.getBytes()); byte[] chars = new byte[256 - url.length()]; Arrays.fill(chars, (byte) 0); output.write(chars); output.write(Arrays.copyOfRange(contents,pos+256,contents.length)); } catch(IOException ex){ throw new Exception(ex); } } public static byte[] patchExploit(byte[] exploit, Map<String, String> params) throws Exception { if (params.size() != 7) { throw new Exception("invalid argument count"); } ArrayList<Long> args = new ArrayList<>(); args.add(0L); for (int i = 1; i <= 7; ++i) { String arg = String.format("a%s", i); if (params.containsKey(arg)) { args.add(Long.parseLong(params.get(arg), 16)); } else { throw new Exception(String.format("argument %s is missing", arg)); } } byte[] copy = new byte[exploit.length]; System.arraycopy(exploit, 0, copy, 0, exploit.length); ByteBuffer buf = ByteBuffer.wrap(copy).order(ByteOrder.LITTLE_ENDIAN); int size_words = buf.getInt(0); int dsize = buf.getInt(4 + 0x10); int csize = buf.getInt(4 + 0x20); long data_base = args.get(1) + csize; for (int i = 1; i < size_words; ++i) { long add = 0; byte x = buf.get(size_words * 4 + 4 + i - 1); if (x == 1) { add = data_base; } else if (x != 0) { add = args.get(x); } buf.putInt(i * 4, buf.getInt(i * 4) + (int) add); } byte[] out = new byte[dsize + csize]; System.arraycopy(copy, 4 + 0x40, out, csize, dsize); System.arraycopy(copy, 4 + 0x40 + dsize, out, 0, csize); return out; } /** * Searchs for a subarray in a given array, starting from a specific index * @param Source the source array to search in * @param Search the array to look for in Source * @param fromIndex the starting index * @return The Search arrau position in Source, or -1 if not found */ private static Integer bytesIndexOf(byte[] Source, byte[] Search, int fromIndex) { boolean Find = false; int i; for (i = fromIndex;i<Source.length-Search.length;i++){ if(Source[i]==Search[0]){ Find = true; for (int j = 0;j<Search.length;j++){ if (Source[i+j]!=Search[j]){ Find = false; } } } if(Find){ break; } } if(!Find){ return new Integer(-1); } return new Integer(i); } /*** * Read the given binary file, and return its contents as a byte array. * @param aInputFileName The filename * @return A byte[] with the file contents * @throws IOException */ public static byte[] read(String aInputFileName) throws IOException{ File file = new File(aInputFileName); byte[] result = null; InputStream input = new BufferedInputStream(new FileInputStream(file)); result = readAndClose(input); return result; } /*** * Read an input stream, and return it as a byte array. * @param aInput The InputStream to read * @return A byte[] with the InputStream contents * @throws IOException */ public static byte[] readAndClose(InputStream aInput) throws IOException { byte[] bucket = new byte[32*1024]; ByteArrayOutputStream result = null; try { result = new ByteArrayOutputStream(bucket.length); int bytesRead = 0; while(bytesRead != -1){ bytesRead = aInput.read(bucket); if(bytesRead > 0){ result.write(bucket, 0, bytesRead); } } } finally { aInput.close(); } return result.toByteArray(); } private static void logErr(Object aThing){ log(aThing,true); } private static void log(Object aThing){ log(aThing,false); } private static void log(Object aThing, boolean force){ if (debug || force) System.out.println(String.valueOf(aThing)); } }
package io.fullstack.firestack; import android.util.Log; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.facebook.react.bridge.ReactContext; import com.facebook.react.modules.core.DeviceEventManagerModule; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.Callback; import com.facebook.react.bridge.WritableMap; import com.facebook.react.bridge.ReadableMap; import com.facebook.react.bridge.ReadableArray; import com.facebook.react.bridge.ReadableMapKeySetIterator; import com.facebook.react.bridge.ReadableType; import com.google.firebase.database.DataSnapshot; public class FirestackUtils { private static final String TAG = "FirestackUtils"; // TODO NOTE public static void todoNote(final String tag, final String name, final Callback callback) { Log.e(tag, "The method " + name + " has not yet been implemented."); Log.e(tag, "Feel free to contribute to finish the method in the source."); WritableMap errorMap = Arguments.createMap(); errorMap.putString("error", "unimplemented"); callback.invoke(null, errorMap); } /** * send a JS event **/ public static void sendEvent(final ReactContext context, String eventName, WritableMap params) { context .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) .emit(eventName, params); } // snapshot public static WritableMap dataSnapshotToMap(String name, DataSnapshot dataSnapshot) { WritableMap data = Arguments.createMap(); data.putString("key", dataSnapshot.getKey()); data.putBoolean("exists", dataSnapshot.exists()); data.putBoolean("hasChildren", dataSnapshot.hasChildren()); data.putDouble("childrenCount", dataSnapshot.getChildrenCount()); if (!dataSnapshot.hasChildren() && dataSnapshot.getValue() != null) { String type = dataSnapshot.getValue().getClass().getName(); switch (type) { case "java.lang.Boolean": data.putBoolean("value", (Boolean) dataSnapshot.getValue()); break; case "java.lang.Long": data.putInt("value",(Integer)(((Long) dataSnapshot.getValue()).intValue())); break; case "java.lang.Double": data.putDouble("value",(Double) dataSnapshot.getValue()); break; case "java.lang.String": data.putString("value",(String) dataSnapshot.getValue()); break; default: data.putString("value", null); } }else{ WritableMap valueMap = FirestackUtils.castSnapshotValue(dataSnapshot); data.putMap("value", valueMap); } Object priority = dataSnapshot.getPriority(); if (priority == null) { data.putString("priority", null); } else { data.putString("priority", priority.toString()); } WritableMap eventMap = Arguments.createMap(); eventMap.putString("eventName", name); eventMap.putMap("snapshot", data); return eventMap; } public static <Any> Any castSnapshotValue(DataSnapshot snapshot) { if (snapshot.hasChildren()) { WritableMap data = Arguments.createMap(); for (DataSnapshot child : snapshot.getChildren()) { Any castedChild = castSnapshotValue(child); switch (castedChild.getClass().getName()) { case "java.lang.Boolean": data.putBoolean(child.getKey(), (Boolean) castedChild); break; case "java.lang.Integer": data.putInt(child.getKey(), (Integer) castedChild); break; case "java.lang.Double": data.putDouble(child.getKey(), (Double) castedChild); break; case "java.lang.String": data.putString(child.getKey(), (String) castedChild); break; case "com.facebook.react.bridge.WritableNativeMap": data.putMap(child.getKey(), (WritableMap) castedChild); break; } } return (Any) data; } else { if (snapshot.getValue() != null) { String type = snapshot.getValue().getClass().getName(); switch (type) { case "java.lang.Boolean": return (Any)((Boolean) snapshot.getValue()); case "java.lang.Long": return (Any)((Integer)(((Long) snapshot.getValue()).intValue())); case "java.lang.Double": return (Any)((Double) snapshot.getValue()); case "java.lang.String": return (Any)((String) snapshot.getValue()); default: return (Any) null; } } else { return (Any) null; } } } public static Map<String, Object> recursivelyDeconstructReadableMap(ReadableMap readableMap) { ReadableMapKeySetIterator iterator = readableMap.keySetIterator(); Map<String, Object> deconstructedMap = new HashMap<>(); while (iterator.hasNextKey()) { String key = iterator.nextKey(); ReadableType type = readableMap.getType(key); switch (type) { case Null: deconstructedMap.put(key, null); break; case Boolean: deconstructedMap.put(key, readableMap.getBoolean(key)); break; case Number: deconstructedMap.put(key, readableMap.getDouble(key)); break; case String: deconstructedMap.put(key, readableMap.getString(key)); break; case Map: deconstructedMap.put(key, FirestackUtils.recursivelyDeconstructReadableMap(readableMap.getMap(key))); break; case Array: deconstructedMap.put(key, FirestackUtils.recursivelyDeconstructReadableArray(readableMap.getArray(key))); break; default: throw new IllegalArgumentException("Could not convert object with key: " + key + "."); } } return deconstructedMap; } public static List<Object> recursivelyDeconstructReadableArray(ReadableArray readableArray) { List<Object> deconstructedList = new ArrayList<>(readableArray.size()); for (int i = 0; i < readableArray.size(); i++) { ReadableType indexType = readableArray.getType(i); switch(indexType) { case Null: deconstructedList.add(i, null); break; case Boolean: deconstructedList.add(i, readableArray.getBoolean(i)); break; case Number: deconstructedList.add(i, readableArray.getDouble(i)); break; case String: deconstructedList.add(i, readableArray.getString(i)); break; case Map: deconstructedList.add(i, FirestackUtils.recursivelyDeconstructReadableMap(readableArray.getMap(i))); break; case Array: deconstructedList.add(i, FirestackUtils.recursivelyDeconstructReadableArray(readableArray.getArray(i))); break; default: throw new IllegalArgumentException("Could not convert object at index " + i + "."); } } return deconstructedList; } }
package cubrikproject.tud.likelines.pipelets; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.eclipse.smila.blackboard.Blackboard; import org.eclipse.smila.blackboard.BlackboardAccessException; import org.eclipse.smila.datamodel.AnyMap; import org.eclipse.smila.datamodel.AnySeq; import org.eclipse.smila.processing.Pipelet; import org.eclipse.smila.processing.ProcessingException; import org.eclipse.smila.processing.parameters.ParameterAccessor; import org.eclipse.smila.processing.util.ProcessingConstants; import org.eclipse.smila.processing.util.ResultCollector; import org.eclipse.smila.utils.service.ServiceUtils; import cubrikproject.tud.likelines.service.interfaces.LLIndexer; import cubrikproject.tud.likelines.webservice.Aggregate; import cubrikproject.tud.likelines.webservice.LikeLinesWebService; /** * The LikeLines pipelet communicates with a LikeLines server in order to * compute the top N most interesting keyframes. * * @author R. Vliegendhart */ public class LikeLines implements Pipelet { /** config property name for attribute name to read the video ID from. */ private static final String PARAM_ATTRIBUTE = "input_field"; /** config property name for the LikeLines server to use (opt.). */ private static final String PARAM_SERVER = "server"; /** default server */ private static final String DEFAULT_SERVER = "http://likelines-shinnonoir.dotcloud.com"; /** config property name for the number of top keyframes to find. */ private static final String PARAM_N = "n"; /** config property name-prefix for storing the output. */ private static final String PARAM_OUTPUT = "output_field"; /** the pipelet's configuration. */ private AnyMap _config; /** local logger. */ private final Log _log = LogFactory.getLog(getClass()); /** LikeLines indexer service */ private LLIndexer _indexer; /** Threshold for MCA */ public final int PERFORM_MCA_THRESHOLD = 5; @Override public void configure(AnyMap configuration) { _config = configuration; } private synchronized LLIndexer getLLIndexer() throws ProcessingException { if (_indexer == null) { try { _indexer = ServiceUtils.getService(LLIndexer.class); } catch (final Exception e) { _log.warn("Error while waiting for LLIndexer service to come up.", e); } if (_indexer == null) { throw new ProcessingException("No LLIndexer service available, giving up"); } } return _indexer; } @Override public String[] process(Blackboard blackboard, String[] recordIds) throws ProcessingException { _indexer = getLLIndexer(); final ParameterAccessor paramAccessor = new ParameterAccessor(blackboard, _config); final ResultCollector resultCollector = new ResultCollector(paramAccessor, _log, ProcessingConstants.FAIL_ON_ERROR_DEFAULT); final String serverUrl = paramAccessor.getParameter(PARAM_SERVER, DEFAULT_SERVER); final int N = Integer.parseInt(paramAccessor.getRequiredParameter(PARAM_N)); final String inputField = paramAccessor.getRequiredParameter(PARAM_ATTRIBUTE); final String outputField = paramAccessor.getRequiredParameter(PARAM_OUTPUT); for (String id : recordIds) { try { final String videoId = blackboard.getMetadata(id).getStringValue(inputField); final AnySeq timecodes = blackboard.getMetadata(id).getSeq(outputField, true); if (videoId == null) throw new ProcessingException("Missing videoId"); LikeLinesWebService server = new LikeLinesWebService(serverUrl); Aggregate agg = server.aggregate(videoId); for (double d : server.getNKeyFrames(N, agg)) { timecodes.add(d); } resultCollector.addResult(id); if (agg.playbacks.size() < PERFORM_MCA_THRESHOLD) _indexer.scheduleMCA(videoId, server); } catch (Exception e) { e.printStackTrace(); resultCollector.addFailedResult(id, e); } } return recordIds; } }
package com.xqbase.metric; import java.io.ByteArrayInputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress; import java.sql.Driver; import java.sql.SQLException; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Properties; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BiConsumer; import java.util.logging.Logger; import java.util.zip.InflaterInputStream; import com.xqbase.metric.common.Metric; import com.xqbase.metric.common.MetricEntry; import com.xqbase.metric.common.MetricValue; import com.xqbase.metric.util.CollectionsEx; import com.xqbase.metric.util.Kryos; import com.xqbase.util.ByteArrayQueue; import com.xqbase.util.Conf; import com.xqbase.util.Log; import com.xqbase.util.Numbers; import com.xqbase.util.Runnables; import com.xqbase.util.Service; import com.xqbase.util.Strings; import com.xqbase.util.Time; import com.xqbase.util.db.ConnectionPool; import com.xqbase.util.db.Row; class MetricRow { int time; long count; double sum, max, min, sqr; Map<String, String> tags; } class MetricName { int id, minuteSize, quarterSize, aggregatedTime; String name; } public class Collector { private static final int MAX_BUFFER_SIZE = 1048576; private static final int MAX_METRIC_LEN = 64; private static final String QUERY_ID = "SELECT id FROM metric_name WHERE name = ?"; private static final String CREATE_ID = "INSERT INTO metric_name (name) VALUES (?)"; private static final String QUERY_NAME = "SELECT id, name, minute_size, quarter_size, aggregated_time FROM metric_name"; private static final String INSERT_MINUTE = "INSERT INTO metric_minute " + "(id, time, \"_count\", \"_sum\", \"_max\", \"_min\", \"_sqr\", tags) VALUES "; private static final String INSERT_QUARTER = "INSERT INTO metric_quarter " + "(id, time, \"_count\", \"_sum\", \"_max\", \"_min\", \"_sqr\", tags) VALUES "; private static final String INCREMENT_MINUTE = "UPDATE metric_name SET minute_size = minute_size + ? WHERE id = ?"; private static final String INCREMENT_QUARTER = "UPDATE metric_name SET quarter_size = quarter_size + ? WHERE id = ?"; private static final String DELETE_TAGS_BY_ID = "DELETE FROM metric_tags_quarter WHERE id = ?"; private static final String DELETE_TAGS_BY_TIME = "DELETE FROM metric_tags_quarter WHERE time <= ?"; private static final String DELETE_NAME = "DELETE FROM metric_name WHERE id = ?"; private static final String DELETE_MINUTE = "DELETE FROM metric_minute WHERE id = ? AND time <= ?"; private static final String DELETE_QUARTER = "DELETE FROM metric_quarter WHERE id = ? AND time <= ?"; private static final String AGGREGATE_FROM = "SELECT \"_count\", \"_sum\", \"_max\", \"_min\", \"_sqr\", tags " + "FROM metric_minute WHERE id = ? AND time >= ? AND time <= ?"; private static final String AGGREGATE_TO = "INSERT INTO metric_tags_quarter (id, time, tags) VALUES (?, ?, ?)"; private static final String AGGREGATE_TAGS_FROM = "SELECT tags FROM metric_tags_quarter WHERE id = ?"; private static final String UPDATE_NAME = "UPDATE metric_name SET minute_size = minute_size - ?, " + "quarter_size = quarter_size - ?, aggregated_time = ?, tags = ? WHERE id = ?"; private static String decode(String s, int limit) { String result = Strings.decodeUrl(s); return limit > 0 ? Strings.truncate(result, limit) : result; } private static void put(HashMap<String, ArrayList<MetricRow>> rowsMap, String name, MetricRow row) { ArrayList<MetricRow> rows = rowsMap.get(name); if (rows == null) { rows = new ArrayList<>(); rowsMap.put(name, rows); } rows.add(row); } private static int MAX_PARAMS = 256; private static void insert(Integer id, List<MetricRow> rows, boolean quarter) throws SQLException { ArrayList<Object> ins = new ArrayList<>(); StringBuilder sb = new StringBuilder(quarter ? insertQuarterSql : insertMinuteSql); for (MetricRow row : rows) { sb.append("(?, ?, ?, ?, ?, ?, ?, ?), "); ins.add(id); ins.add(Integer.valueOf(row.time)); ins.add(Long.valueOf(row.count)); ins.add(Double.valueOf(row.sum)); ins.add(Double.valueOf(row.max)); ins.add(Double.valueOf(row.min)); ins.add(Double.valueOf(row.sqr)); ins.add(Kryos.serialize(row.tags)); } DB.updateEx(sb.substring(0, sb.length() - 2), ins.toArray()); } private static void insert(String name, ArrayList<MetricRow> rows, boolean quarter) throws SQLException { if (rows.isEmpty()) { return; } int id; Row idRow = DB.queryEx(QUERY_ID, name); if (idRow == null) { long[] id_ = new long[1]; if (DB.updateEx(id_, CREATE_ID, name) <= 0) { Log.w("Unable to create name " + name); return; } id = (int) id_[0]; } else { id = idRow.getInt("id"); } Integer id_ = Integer.valueOf(id); int len1 = rows.size(); int len0 = len1 / MAX_PARAMS * MAX_PARAMS; for (int off = 0; off < len0; off += MAX_PARAMS) { insert(id_, rows.subList(off, off + MAX_PARAMS), quarter); } if (len0 < len1) { insert(id_, rows.subList(len0, len1), quarter); } DB.update(quarter ? INCREMENT_QUARTER : INCREMENT_MINUTE, rows.size(), id); } private static void insert(HashMap<String, ArrayList<MetricRow>> rowsMap) throws SQLException { for (Map.Entry<String, ArrayList<MetricRow>> entry : rowsMap.entrySet()) { insert(entry.getKey(), entry.getValue(), false); } } private static Service service = new Service(); private static ConnectionPool DB = null; private static String insertMinuteSql, insertQuarterSql, aggregateFromSql; private static int serverId, expire, tagsExpire, maxTags, maxTagValues, maxTagCombinations, maxTagNameLen, maxTagValueLen; private static boolean verbose; private static MetricRow row(Map<String, String> tagMap, int now, long count, double sum, double max, double min, double sqr) { MetricRow row = new MetricRow(); if (maxTags > 0 && tagMap.size() > maxTags) { row.tags = new HashMap<>(); CollectionsEx.forEach(CollectionsEx.min(tagMap.entrySet(), Comparator.comparing(Map.Entry::getKey), maxTags), row.tags::put); } else { row.tags = tagMap; } row.time = now; row.count = count; row.sum = sum; row.max = max; row.min = min; row.sqr = sqr; return row; } private static ArrayList<MetricName> getNames() throws SQLException { ArrayList<MetricName> names = new ArrayList<>(); DB.query(row -> { MetricName name = new MetricName(); name.id = row.getInt("id"); name.name = row.getString("name"); name.minuteSize = row.getInt("minute_size"); name.quarterSize = row.getInt("quarter_size"); name.aggregatedTime = row.getInt("aggregated_time"); names.add(name); }, QUERY_NAME); return names; } private static void minutely(int minute) throws SQLException { // Insert aggregation-during-collection metrics HashMap<String, ArrayList<MetricRow>> rowsMap = new HashMap<>(); for (MetricEntry entry : Metric.removeAll()) { MetricRow row = row(entry.getTagMap(), minute, entry.getCount(), entry.getSum(), entry.getMax(), entry.getMin(), entry.getSqr()); put(rowsMap, entry.getName(), row); } if (!rowsMap.isEmpty()) { insert(rowsMap); } // Ensure index and calculate metric size by master collector if (serverId != 0) { return; } for (MetricName name : getNames()) { Metric.put("metric.size", name.minuteSize, "name", name.name); Metric.put("metric.size", name.quarterSize, "name", "_quarter." + name.name); } } private static void putTagValue(HashMap<String, HashMap<String, MetricValue>> tagMap, String tagKey, String tagValue, MetricValue value) { HashMap<String, MetricValue> tagValues = tagMap.get(tagKey); if (tagValues == null) { tagValues = new HashMap<>(); tagMap.put(tagKey, tagValues); // Must use "value.clone()" here, because many tags may share one "value" tagValues.put(tagValue, value.clone()); } else { MetricValue oldValue = tagValues.get(tagValue); if (oldValue == null) { // Must use "value.clone()" here tagValues.put(tagValue, value.clone()); } else { oldValue.add(value); } } } private static HashMap<String, HashMap<String, MetricValue>> limit(HashMap<String, HashMap<String, MetricValue>> tagMap) { HashMap<String, HashMap<String, MetricValue>> tags = new HashMap<>(); BiConsumer<String, HashMap<String, MetricValue>> action = (tagName, valueMap) -> { HashMap<String, MetricValue> tagValues = new HashMap<>(); if (maxTagValues > 0 && valueMap.size() > maxTagValues) { CollectionsEx.forEach(CollectionsEx.max(valueMap.entrySet(), Comparator.comparingLong(metricValue -> metricValue.getValue().getCount()), maxTagValues), tagValues::put); } else { tagValues.putAll(valueMap); } tags.put(tagName, tagValues); }; if (maxTags > 0 && tagMap.size() > maxTags) { CollectionsEx.forEach(CollectionsEx.min(tagMap.entrySet(), Comparator.comparing(Map.Entry::getKey), maxTags), action); } else { tagMap.forEach(action); } return tags; } private static void quarterly(int quarter) throws SQLException { DB.update(DELETE_TAGS_BY_TIME, quarter - tagsExpire); for (MetricName name : getNames()) { if (name.minuteSize <= 0 && name.quarterSize <= 0) { DB.update(DELETE_TAGS_BY_ID, name.id); DB.update(DELETE_NAME, name.id); continue; } int deletedMinute = DB.update(DELETE_MINUTE, name.id, quarter * 15 - expire); int deletedQuarter = DB.update(DELETE_QUARTER, name.id, quarter - expire); int start = name.aggregatedTime == 0 ? quarter - expire : name.aggregatedTime; for (int i = start + 1; i <= quarter; i ++) { ArrayList<MetricRow> rows = new ArrayList<>(); HashMap<HashMap<String, String>, MetricValue> result = new HashMap<>(); DB.query(row -> { @SuppressWarnings("unchecked") HashMap<String, String> tags = Kryos.deserialize(row.getBytes("tags"), HashMap.class); if (tags == null) { tags = new HashMap<>(); } // Aggregate to "_quarter.*" MetricValue newValue = new MetricValue(row.getLong("_count"), ((Number) row.get("_sum")).doubleValue(), ((Number) row.get("_max")).doubleValue(), ((Number) row.get("_min")).doubleValue(), ((Number) row.get("_sqr")).doubleValue()); MetricValue value = result.get(tags); if (value == null) { result.put(tags, newValue); } else { value.add(newValue); } }, aggregateFromSql, name.id, i * 15 - 14, i * 15); if (result.isEmpty()) { continue; } int combinations = result.size(); Metric.put("metric.tags.combinations", combinations, "name", name.name); HashMap<String, HashMap<String, MetricValue>> tagMap = new HashMap<>(); int i_ = i; BiConsumer<HashMap<String, String>, MetricValue> action = (tags, value) -> { // {"_quarter": i}, but not {"_quarter": quarter} ! rows.add(row(tags, i_, value.getCount(), value.getSum(), value.getMax(), value.getMin(), value.getSqr())); // Aggregate to "_meta.tags_quarter" tags.forEach((tagKey, tagValue) -> putTagValue(tagMap, tagKey, tagValue, value)); }; if (maxTagCombinations > 0 && combinations > maxTagCombinations) { CollectionsEx.forEach(CollectionsEx.max(result.entrySet(), Comparator.comparingLong(entry -> entry.getValue().getCount()), maxTagCombinations), action); } else { result.forEach(action); } insert(name.name, rows, true); // Aggregate to "_meta.tags_quarter" tagMap.forEach((tagKey, tagValue) -> { Metric.put("metric.tags.values", tagValue.size(), "name", name.name, "key", tagKey); }); // {"_quarter": i}, but not {"_quarter": quarter} ! DB.updateEx(AGGREGATE_TO, Integer.valueOf(name.id), Integer.valueOf(i), Kryos.serialize(limit(tagMap))); } // Aggregate "_meta.tags_quarter" to "_meta.tags_all"; HashMap<String, HashMap<String, MetricValue>> tagMap = new HashMap<>(); DB.query(row -> { @SuppressWarnings("unchecked") HashMap<String, HashMap<String, MetricValue>> tags = Kryos.deserialize(row.getBytes("tags"), HashMap.class); if (tags == null) { return; } tags.forEach((tagKey, tagValues) -> { tagValues.forEach((value, metric) -> { putTagValue(tagMap, tagKey, value, metric); }); }); }, AGGREGATE_TAGS_FROM, name.id); DB.updateEx(UPDATE_NAME, Integer.valueOf(deletedMinute), Integer.valueOf(deletedQuarter), Integer.valueOf(quarter), Kryos.serialize(limit(tagMap)), Integer.valueOf(name.id)); } } public static void main(String[] args) { if (!service.startup(args)) { return; } System.setProperty("java.util.logging.SimpleFormatter.format", "%1$tY-%1$tm-%1$td %1$tk:%1$tM:%1$tS.%1$tL %2$s%n%4$s: %5$s%6$s%n"); Logger logger = Log.getAndSet(Conf.openLogger("Collector.", 16777216, 10)); ExecutorService executor = Executors.newCachedThreadPool(); ScheduledThreadPoolExecutor timer = new ScheduledThreadPoolExecutor(1); Properties p = Conf.load("Collector"); int port = Numbers.parseInt(p.getProperty("port"), 5514); String host = p.getProperty("host"); host = host == null || host.isEmpty() ? "0.0.0.0" : host; serverId = Numbers.parseInt(p.getProperty("server_id"), 0); expire = Numbers.parseInt(p.getProperty("expire"), 2880); tagsExpire = Numbers.parseInt(p.getProperty("tags_expire"), 96); maxTags = Numbers.parseInt(p.getProperty("max_tags")); maxTagValues = Numbers.parseInt(p.getProperty("max_tag_values")); maxTagCombinations = Numbers.parseInt(p.getProperty("max_tag_combinations")); maxTagNameLen = Numbers.parseInt(p.getProperty("max_tag_name_len")); maxTagValueLen = Numbers.parseInt(p.getProperty("max_tag_value_len")); int quarterDelay = Numbers.parseInt(p.getProperty("quarter_delay"), 2); boolean enableRemoteAddr = Conf.getBoolean(p.getProperty("remote_addr"), true); String allowedRemote = p.getProperty("allowed_remote"); HashSet<String> allowedRemotes = null; if (allowedRemote != null) { allowedRemotes = new HashSet<>(Arrays.asList(allowedRemote.split("[,;]"))); } verbose = Conf.getBoolean(p.getProperty("verbose"), false); long start = System.currentTimeMillis(); AtomicInteger currentMinute = new AtomicInteger((int) (start / Time.MINUTE)); p = Conf.load("jdbc"); Runnable minutely = null; try (DatagramSocket socket = new DatagramSocket(new InetSocketAddress(host, port))) { boolean createTable = false; Driver driver = (Driver) Class.forName(p. getProperty("driver")).newInstance(); String url = p.getProperty("url", ""); int colon = url.indexOf(":h2:"); if (colon >= 0) { String dataDir = Conf.getAbsolutePath("data"); new File(dataDir).mkdir(); createTable = !new File(dataDir + "/metric.mv.db").exists(); url = url.substring(0, colon + 4) + dataDir.replace('\\', '/') + "/metric;mode=mysql;cache_size=0"; } insertMinuteSql = INSERT_MINUTE.replace("\"", ""); insertQuarterSql = INSERT_QUARTER.replace("\"", ""); aggregateFromSql = AGGREGATE_FROM.replace("\"", ""); DB = new ConnectionPool(driver, url, p.getProperty("user"), p.getProperty("password")); if (createTable) { ByteArrayQueue baq = new ByteArrayQueue(); try (InputStream in = Collector.class. getResourceAsStream("/sql/metric.sql")) { baq.readFrom(in); } String[] sqls = baq.toString().split(";"); for (String s : sqls) { String sql = s.trim(); if (!sql.isEmpty()) { try { DB.update(sql); } catch (SQLException e) { Log.w(sql + ": " + e.getMessage()); } } } } Dashboard.startup(DB, false); minutely = Runnables.wrap(() -> { int minute = currentMinute.incrementAndGet(); try { minutely(minute); if (serverId == 0 && !service.isInterrupted() && minute % 15 == quarterDelay) { // Skip "quarterly" when shutdown quarterly(minute / 15); } } catch (SQLException e) { Log.e(e); } }); timer.scheduleAtFixedRate(minutely, Time.MINUTE - start % Time.MINUTE, Time.MINUTE, TimeUnit.MILLISECONDS); service.register(socket); Log.i("Metric Collector Started on UDP " + host + ":" + port); while (!Thread.interrupted()) { // Receive byte[] buf = new byte[65536]; DatagramPacket packet = new DatagramPacket(buf, buf.length); // Blocked, or closed by shutdown handler socket.receive(packet); int len = packet.getLength(); String remoteAddr = packet.getAddress().getHostAddress(); if (allowedRemotes != null && !allowedRemotes.contains(remoteAddr)) { Log.w(remoteAddr + " not allowed"); continue; } if (enableRemoteAddr) { Metric.put("metric.throughput", len, "remote_addr", remoteAddr, "server_id", "" + serverId); } else { Metric.put("metric.throughput", len, "server_id", "" + serverId); } // Inflate ByteArrayQueue baq = new ByteArrayQueue(); byte[] buf_ = new byte[2048]; try (InflaterInputStream inflater = new InflaterInputStream(new ByteArrayInputStream(buf, 0, len))) { int bytesRead; while ((bytesRead = inflater.read(buf_)) > 0) { baq.add(buf_, 0, bytesRead); // Prevent attack if (baq.length() > MAX_BUFFER_SIZE) { break; } } } catch (IOException e) { Log.w("Unable to inflate packet from " + remoteAddr); // Continue to parse rows } HashMap<String, ArrayList<MetricRow>> rowsMap = new HashMap<>(); HashMap<String, Integer> countMap = new HashMap<>(); for (String line : baq.toString().split("\n")) { // Truncate tailing '\r' int length = line.length(); if (length > 0 && line.charAt(length - 1) == '\r') { line = line.substring(0, length - 1); } // Parse name, aggregation, value and tags // <name>/<aggregation>/<value>[?<tag>=<value>[&...]] String[] paths; HashMap<String, String> tagMap = new HashMap<>(); int index = line.indexOf('?'); if (index < 0) { paths = line.split("/"); } else { paths = line.substring(0, index).split("/"); String tags = line.substring(index + 1); for (String tag : tags.split("&")) { index = tag.indexOf('='); if (index > 0) { tagMap.put(decode(tag.substring(0, index), maxTagNameLen), decode(tag.substring(index + 1), maxTagValueLen)); } } } if (paths.length < 2) { Log.w("Incorrect format: [" + line + "]"); continue; } String name = decode(paths[0], MAX_METRIC_LEN); if (name.isEmpty()) { Log.w("Incorrect format: [" + line + "]"); continue; } if (enableRemoteAddr) { tagMap.put("remote_addr", remoteAddr); Metric.put("metric.rows", 1, "name", name, "remote_addr", remoteAddr, "server_id", "" + serverId); } else { Metric.put("metric.rows", 1, "name", name, "server_id", "" + serverId); } if (paths.length > 6) { // For aggregation-before-collection metric, insert immediately long count = Numbers.parseLong(paths[2]); double sum = Numbers.parseDouble(paths[3]); put(rowsMap, name, row(tagMap, Numbers.parseInt(paths[1], currentMinute.get()), count, sum, Numbers.parseDouble(paths[4]), Numbers.parseDouble(paths[5]), Numbers.parseDouble(paths[6]))); } else { // For aggregation-during-collection metric, aggregate first Metric.put(name, Numbers.parseDouble(paths[1]), tagMap); } if (verbose) { Integer count = countMap.get(name); countMap.put(name, Integer.valueOf(count == null ? 1 : count.intValue() + 1)); } } if (!countMap.isEmpty()) { Log.d("Metrics received from " + remoteAddr + ": " + countMap); } // Insert aggregation-before-collection metrics if (!rowsMap.isEmpty()) { executor.execute(Runnables.wrap(() -> { try { insert(rowsMap); } catch (SQLException e) { Log.e(e); } })); } } } catch (IOException | ReflectiveOperationException e) { Log.w(e.getMessage()); } catch (Error | RuntimeException e) { Log.e(e); } Runnables.shutdown(timer); // Do not do SQL operations in main thread (may be interrupted) if (minutely != null) { executor.execute(minutely); } Runnables.shutdown(executor); Dashboard.shutdown(); if (DB != null) { DB.close(); } Log.i("Metric Collector Stopped"); Conf.closeLogger(Log.getAndSet(logger)); service.shutdown(); } }
package ee.ria.DigiDoc.common; import android.webkit.URLUtil; import java.io.File; import java.io.IOException; public class FileUtil { private static final String ALLOWED_CHARACTERS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_,.:;&()"; private static final String ALLOWED_URL_CHARACTERS = ALLOWED_CHARACTERS + "!+=@?%/"; /** * Check if file path is in cache directory * * @param file File to check * @return Boolean indicating if file is in the cache directory. */ public static File getFileInDirectory(File file, File directory) throws IOException { if (file.getCanonicalPath().startsWith(directory.getCanonicalPath())) { return file; } throw new IOException("Invalid file path"); } /** * Replace invalid string characters * * @param input Input to replace invalid characters * @param replacement Replacement to replace invalid characters with * @return String with valid characters */ public static String sanitizeString(String input, char replacement) { if (input == null) { return null; } String characterSet = ALLOWED_CHARACTERS; if (URLUtil.isValidUrl(input)) { characterSet = ALLOWED_URL_CHARACTERS; } StringBuilder sb = new StringBuilder(input.length()); for (int offset = 0; offset < input.length(); offset++) { char c = input.charAt(offset); if (characterSet.indexOf(c) == -1) { sb.append(replacement); } else { // Coverity does not want to see usages of the original string sb.append(characterSet.charAt(characterSet.indexOf(c))); } } return sb.toString(); } }
package io.bisq.common.locale; import io.bisq.common.GlobalSettings; import io.bisq.common.app.DevEnv; import lombok.extern.slf4j.Slf4j; import java.util.*; import java.util.stream.Collectors; @Slf4j public class CurrencyUtil { private static String baseCurrencyCode = "BTC"; public static void setBaseCurrencyCode(String baseCurrencyCode) { CurrencyUtil.baseCurrencyCode = baseCurrencyCode; } private static List<FiatCurrency> allSortedFiatCurrencies; private static List<FiatCurrency> createAllSortedFiatCurrenciesList() { Set<FiatCurrency> set = CountryUtil.getAllCountries().stream() .map(country -> getCurrencyByCountryCode(country.code)) .collect(Collectors.toSet()); List<FiatCurrency> list = new ArrayList<>(set); list.sort(TradeCurrency::compareTo); return list; } public static List<FiatCurrency> getAllSortedFiatCurrencies() { if (Objects.isNull(allSortedFiatCurrencies)) { allSortedFiatCurrencies = createAllSortedFiatCurrenciesList(); } return allSortedFiatCurrencies; } public static List<FiatCurrency> getMainFiatCurrencies() { TradeCurrency defaultTradeCurrency = getDefaultTradeCurrency(); List<FiatCurrency> list = new ArrayList<>(); // Top traded currencies list.add(new FiatCurrency("USD")); list.add(new FiatCurrency("EUR")); list.add(new FiatCurrency("GBP")); list.add(new FiatCurrency("CAD")); list.add(new FiatCurrency("AUD")); list.add(new FiatCurrency("RUB")); list.add(new FiatCurrency("INR")); list.sort(TradeCurrency::compareTo); FiatCurrency defaultFiatCurrency = defaultTradeCurrency instanceof FiatCurrency ? (FiatCurrency) defaultTradeCurrency : null; if (defaultFiatCurrency != null && list.contains(defaultFiatCurrency)) { //noinspection SuspiciousMethodCalls list.remove(defaultTradeCurrency); list.add(0, defaultFiatCurrency); } return list; } private static List<CryptoCurrency> allSortedCryptoCurrencies; public static List<CryptoCurrency> getAllSortedCryptoCurrencies() { if (allSortedCryptoCurrencies == null) allSortedCryptoCurrencies = createAllSortedCryptoCurrenciesList(); return allSortedCryptoCurrencies; } // Don't make a PR for adding a coin but follow the steps described here: public static List<CryptoCurrency> createAllSortedCryptoCurrenciesList() { final List<CryptoCurrency> result = new ArrayList<>(); result.add(new CryptoCurrency("BETR", "Better Betting", true)); if (DevEnv.DAO_TRADING_ACTIVATED) result.add(new CryptoCurrency("BSQ", "Bisq Token")); if (!baseCurrencyCode.equals("BTC")) result.add(new CryptoCurrency("BTC", "Bitcoin")); result.add(new CryptoCurrency("BCH", "Bitcoin Cash")); result.add(new CryptoCurrency("BCHC", "Bitcoin Clashic")); result.add(new CryptoCurrency("BTG", "Bitcoin Gold")); result.add(new CryptoCurrency("BURST", "Burstcoin")); result.add(new CryptoCurrency("GBYTE", "Byte")); result.add(new CryptoCurrency("CAGE", "Cagecoin")); result.add(new CryptoCurrency("XCP", "Counterparty")); result.add(new CryptoCurrency("CREA", "Creativecoin")); result.add(new CryptoCurrency("XCN", "Cryptonite")); result.add(new CryptoCurrency("DNET", "DarkNet")); if (!baseCurrencyCode.equals("DASH")) result.add(new CryptoCurrency("DASH", "Dash")); result.add(new CryptoCurrency("DCT", "DECENT")); result.add(new CryptoCurrency("DCR", "Decred")); result.add(new CryptoCurrency("ONION", "DeepOnion")); if (!baseCurrencyCode.equals("DOGE")) result.add(new CryptoCurrency("DOGE", "Dogecoin")); result.add(new CryptoCurrency("DMC", "DynamicCoin")); result.add(new CryptoCurrency("ELLA", "Ellaism")); result.add(new CryptoCurrency("ESP", "Espers")); result.add(new CryptoCurrency("ETH", "Ether")); result.add(new CryptoCurrency("ETC", "Ether Classic")); result.add(new CryptoCurrency("XIN", "Infinity Economics")); result.add(new CryptoCurrency("IOP", "Internet Of People")); result.add(new CryptoCurrency("INXT", "Internext", true)); result.add(new CryptoCurrency("GRC", "Gridcoin")); result.add(new CryptoCurrency("LBC", "LBRY Credits")); result.add(new CryptoCurrency("LSK", "Lisk")); if (!baseCurrencyCode.equals("LTC")) result.add(new CryptoCurrency("LTC", "Litecoin")); result.add(new CryptoCurrency("MAID", "MaidSafeCoin")); result.add(new CryptoCurrency("MDC", "Madcoin")); result.add(new CryptoCurrency("XMR", "Monero")); result.add(new CryptoCurrency("MT", "Mycelium Token", true)); result.add(new CryptoCurrency("NAV", "Nav Coin")); result.add(new CryptoCurrency("NMC", "Namecoin")); result.add(new CryptoCurrency("NBT", "NuBits")); result.add(new CryptoCurrency("NXT", "Nxt")); result.add(new CryptoCurrency("888", "OctoCoin")); result.add(new CryptoCurrency("PART", "Particl")); result.add(new CryptoCurrency("PASC", "Pascal Coin", true)); result.add(new CryptoCurrency("PEPECASH", "Pepe Cash")); result.add(new CryptoCurrency("PIVX", "PIVX")); result.add(new CryptoCurrency("POST", "PostCoin")); result.add(new CryptoCurrency("PNC", "Pranacoin")); result.add(new CryptoCurrency("RDD", "ReddCoin")); result.add(new CryptoCurrency("SFSC", "Safe FileSystem Coin")); result.add(new CryptoCurrency("SC", "Siacoin")); result.add(new CryptoCurrency("SF", "Siafund")); result.add(new CryptoCurrency("SIB", "Sibcoin")); result.add(new CryptoCurrency("XSPEC", "Spectrecoin")); result.add(new CryptoCurrency("STEEM", "STEEM")); result.add(new CryptoCurrency("TRC", "Terracoin")); result.add(new CryptoCurrency("MVT", "The Movement", true)); result.add(new CryptoCurrency("UNO", "Unobtanium")); result.add(new CryptoCurrency("CRED", "Verify", true)); result.add(new CryptoCurrency("WAC", "WACoins")); result.add(new CryptoCurrency("WILD", "WILD Token", true)); result.add(new CryptoCurrency("XZC", "Zcoin")); result.add(new CryptoCurrency("ZEC", "Zcash")); result.add(new CryptoCurrency("ZEN", "ZenCash")); result.sort(TradeCurrency::compareTo); // Util for printing all altcoins for adding to FAQ page /* StringBuilder sb = new StringBuilder(); result.stream().forEach(e -> sb.append("<li>&#8220;") .append(e.getCode()) .append("&#8221;, &#8220;") .append(e.getName()) .append("&#8221;</li>") .append("\n")); log.info(sb.toString());*/ return result; } public static List<CryptoCurrency> getMainCryptoCurrencies() { final List<CryptoCurrency> result = new ArrayList<>(); if (DevEnv.DAO_TRADING_ACTIVATED) result.add(new CryptoCurrency("BSQ", "Bisq Token")); if (!baseCurrencyCode.equals("BTC")) result.add(new CryptoCurrency("BTC", "Bitcoin")); if (!baseCurrencyCode.equals("DASH")) result.add(new CryptoCurrency("DASH", "Dash")); result.add(new CryptoCurrency("DCR", "Decred")); if (!baseCurrencyCode.equals("DOGE")) result.add(new CryptoCurrency("DOGE", "Dogecoin")); result.add(new CryptoCurrency("ETH", "Ether")); result.add(new CryptoCurrency("ETC", "Ether Classic")); result.add(new CryptoCurrency("GRC", "Gridcoin")); if (!baseCurrencyCode.equals("LTC")) result.add(new CryptoCurrency("LTC", "Litecoin")); result.add(new CryptoCurrency("XMR", "Monero")); result.add(new CryptoCurrency("MT", "Mycelium Token", true)); result.add(new CryptoCurrency("NMC", "Namecoin")); result.add(new CryptoCurrency("SC", "Siacoin")); result.add(new CryptoCurrency("SF", "Siafund")); result.add(new CryptoCurrency("UNO", "Unobtanium")); result.add(new CryptoCurrency("ZEC", "Zcash")); result.sort(TradeCurrency::compareTo); return result; } /** * @return Sorted list of SEPA currencies with EUR as first item */ private static Set<TradeCurrency> getSortedSEPACurrencyCodes() { return CountryUtil.getAllSepaCountries().stream() .map(country -> getCurrencyByCountryCode(country.code)) .collect(Collectors.toSet()); } // At OKPay you can exchange internally those currencies public static List<TradeCurrency> getAllOKPayCurrencies() { ArrayList<TradeCurrency> currencies = new ArrayList<>(Arrays.asList( new FiatCurrency("EUR"), new FiatCurrency("USD"), new FiatCurrency("GBP"), new FiatCurrency("CHF"), new FiatCurrency("RUB"), new FiatCurrency("PLN"), new FiatCurrency("JPY"), new FiatCurrency("CAD"), new FiatCurrency("AUD"), new FiatCurrency("CZK"), new FiatCurrency("NOK"), new FiatCurrency("SEK"), new FiatCurrency("DKK"), new FiatCurrency("HRK"), new FiatCurrency("HUF"), new FiatCurrency("NZD"), new FiatCurrency("RON"), new FiatCurrency("TRY"), new FiatCurrency("ZAR"), new FiatCurrency("HKD"), new FiatCurrency("CNY") )); currencies.sort(TradeCurrency::compareTo); return currencies; } public static boolean isFiatCurrency(String currencyCode) { try { return currencyCode != null && !currencyCode.isEmpty() && !isCryptoCurrency(currencyCode) && Currency.getInstance(currencyCode) != null; } catch (Throwable t) { return false; } } public static Optional<FiatCurrency> getFiatCurrency(String currencyCode) { return getAllSortedFiatCurrencies().stream().filter(e -> e.getCode().equals(currencyCode)).findAny(); } @SuppressWarnings("WeakerAccess") public static boolean isCryptoCurrency(String currencyCode) { return getCryptoCurrency(currencyCode).isPresent(); } public static Optional<CryptoCurrency> getCryptoCurrency(String currencyCode) { return getAllSortedCryptoCurrencies().stream().filter(e -> e.getCode().equals(currencyCode)).findAny(); } public static Optional<TradeCurrency> getTradeCurrency(String currencyCode) { Optional<FiatCurrency> fiatCurrencyOptional = getFiatCurrency(currencyCode); if (isFiatCurrency(currencyCode) && fiatCurrencyOptional.isPresent()) { return Optional.of(fiatCurrencyOptional.get()); } else { Optional<CryptoCurrency> cryptoCurrencyOptional = getCryptoCurrency(currencyCode); if (isCryptoCurrency(currencyCode) && cryptoCurrencyOptional.isPresent()) { return Optional.of(cryptoCurrencyOptional.get()); } else { return Optional.<TradeCurrency>empty(); } } } public static FiatCurrency getCurrencyByCountryCode(String countryCode) { if (countryCode.equals("XK")) return new FiatCurrency("EUR"); else return new FiatCurrency(Currency.getInstance(new Locale(LanguageUtil.getDefaultLanguage(), countryCode)).getCurrencyCode()); } public static String getNameByCode(String currencyCode) { if (isCryptoCurrency(currencyCode)) return getCryptoCurrency(currencyCode).get().getName(); else try { return Currency.getInstance(currencyCode).getDisplayName(); } catch (Throwable t) { log.debug("No currency name available " + t.getMessage()); return currencyCode; } } public static String getNameAndCode(String currencyCode) { return getNameByCode(currencyCode) + " (" + currencyCode + ")"; } public static TradeCurrency getDefaultTradeCurrency() { return GlobalSettings.getDefaultTradeCurrency(); } }
package org.duracloud.common.util; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; public class DateUtil { private DateUtil() { // Ensures no instances are made of this class, as there are only static members. } public enum DateFormat { LONG_FORMAT("yyyy-MM-dd'T'HH:mm:ss.sss"), DEFAULT_FORMAT("yyyy-MM-dd'T'HH:mm:ss"), MID_FORMAT("yyyy-MM-dd'T'HH:mm"), SHORT_FORMAT("yyyy-MM-dd"), YEAR_MONTH_FORMAT("yyyy-MM"), VERBOSE_FORMAT("EEE, d MMM yyyy HH:mm:ss z"), PLAIN_FORMAT("yyyy-MM-dd-HH-mm-ss"); private final SimpleDateFormat format; DateFormat(String pattern) { this.format = new SimpleDateFormat(pattern, Locale.ENGLISH); this.format.setLenient(false); } public String getPattern() { return format.toPattern(); } } public static Date convertToDate(String text, DateFormat format) throws ParseException { SimpleDateFormat dateFormat = format.format; synchronized (dateFormat) { return dateFormat.parse(text); } } public static Date convertToDate(String text) throws ParseException { return convertToDate(text, DateFormat.DEFAULT_FORMAT); } public static String now() { long now = System.currentTimeMillis(); return convertToString(now, DateFormat.DEFAULT_FORMAT); } public static String nowLong() { long now = System.currentTimeMillis(); return convertToString(now, DateFormat.LONG_FORMAT); } public static String nowMid() { long now = System.currentTimeMillis(); return convertToString(now, DateFormat.MID_FORMAT); } public static String nowShort() { long now = System.currentTimeMillis(); return convertToString(now, DateFormat.SHORT_FORMAT); } public static String nowVerbose() { long now = System.currentTimeMillis(); return convertToString(now, DateFormat.VERBOSE_FORMAT); } public static String nowPlain() { long now = System.currentTimeMillis(); return convertToString(now, DateFormat.PLAIN_FORMAT); } public static String convertToString(long millis, DateFormat format) { SimpleDateFormat dateFormat = format.format; synchronized (dateFormat) { return dateFormat.format(millis); } } public static String convertToString(long millis) { return convertToString(millis, DateFormat.DEFAULT_FORMAT); } public static String convertToStringLong(long millis) { return convertToString(millis, DateFormat.LONG_FORMAT); } public static String convertToStringMid(long millis) { return convertToString(millis, DateFormat.MID_FORMAT); } public static String convertToStringShort(long millis) { return convertToString(millis, DateFormat.SHORT_FORMAT); } public static String convertToStringVerbose(long millis) { return convertToString(millis, DateFormat.VERBOSE_FORMAT); } public static String convertToStringPlain(long millis) { return convertToString(millis, DateFormat.PLAIN_FORMAT); } public static String convertToStringYearMonth(long millis) { return convertToString(millis, DateFormat.YEAR_MONTH_FORMAT); } }
package com.mapswithme.maps.bookmarks; import com.mapswithme.maps.R; import com.mapswithme.maps.bookmarks.data.Bookmark; import com.mapswithme.maps.bookmarks.data.BookmarkManager; import com.mapswithme.maps.bookmarks.data.ParcelablePoint; import android.content.Context; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.Bitmap.Config; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Paint.Style; import android.graphics.Path; import android.graphics.Point; import android.graphics.PorterDuff.Mode; import android.graphics.Rect; import android.text.TextPaint; import android.text.TextUtils; import android.text.TextUtils.TruncateAt; import android.util.AttributeSet; import android.util.Log; import android.view.View; public class PopupLayout extends View { private static final String DEACTIVATION = "deactivation"; private final int m_thriangleHeight; private Bitmap m_AddButton; private Bitmap m_editButton; private Bitmap m_pin; private Bitmap m_popup; volatile private Bookmark m_bmk; private Paint m_backgroundPaint; private Paint m_borderPaint; private Paint m_buttonPaint = new Paint(); private Path m_popupPath; private TextPaint m_textPaint; private Rect m_textBounds = new Rect(); private Rect m_popupRect = new Rect(); private Point m_popupAnchor = new Point(); private int m_width; private int m_height; public PopupLayout(Context context) { this(context, null, 0); } public PopupLayout(Context context, AttributeSet attrs) { this(context, attrs, 0); } public PopupLayout(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); m_AddButton = BitmapFactory.decodeResource(getContext().getResources(), R.drawable.add); m_editButton = BitmapFactory.decodeResource(getContext().getResources(), R.drawable.arrow); m_pin = BitmapFactory.decodeResource(getContext().getResources(), R.drawable.placemark_red); m_thriangleHeight = (int) (10 * getResources().getDisplayMetrics().density); m_backgroundPaint = new Paint(); m_backgroundPaint.setColor(Color.BLACK); m_backgroundPaint.setStyle(Paint.Style.FILL); m_borderPaint = new Paint(); m_borderPaint.setStyle(Style.STROKE); m_borderPaint.setColor(Color.GRAY); m_borderPaint.setStrokeWidth(2); m_borderPaint.setAntiAlias(true); m_popupPath = new Path(); m_textPaint = new TextPaint(); m_textPaint.setTextSize(20 * getResources().getDisplayMetrics().density); m_textPaint.setAntiAlias(true); m_textPaint.setColor(Color.WHITE); } public synchronized void activate(final Bookmark bmk) { m_bmk = bmk; nDrawBookmark(bmk.getPosition().x, bmk.getPosition().y); m_popup = prepareBitmap(m_bmk); postInvalidate(); } public synchronized void deactivate() { m_bmk = null; nRemoveBookmark(); if(m_popup != null) { Bitmap b = m_popup; m_popup = null; b.recycle(); } Log.d(DEACTIVATION, "deactivated"); postInvalidate(); } public synchronized boolean isActive() { return m_bmk != null; } private Point anchor; @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); anchor = new Point(w / 2, h / 2); } public void requestInvalidation() { if (isActive()) postInvalidate(); } private Bitmap prepareBitmap(Bookmark bmk) { anchor = bmk.getPosition(); Bitmap btn; if (bmk.isPreviewBookmark()) { btn = m_AddButton; } else { btn = m_editButton; BookmarkManager.getBookmarkManager(getContext()).getCategoryById(bmk.getCategoryId()).setVisibility(true); } String bmkName = bmk.getName(); int pWidth = getWidth() / 2; int pHeight = m_height = btn.getHeight() + 10; int maxTextWidth = pWidth - btn.getWidth() - 10; int currentTextWidth = Math.round(m_textPaint.measureText(bmkName)); String text; if (currentTextWidth > maxTextWidth) { text = TextUtils.ellipsize(bmkName, m_textPaint, maxTextWidth, TruncateAt.END).toString(); currentTextWidth = Math.round(m_textPaint.measureText(text));; } else { text = bmkName; } pWidth = m_width = currentTextWidth + btn.getWidth() + 10; m_popupPath.reset(); m_popupPath.moveTo(0, 0); m_popupPath.lineTo(pWidth, 0); m_popupPath.lineTo(pWidth, 0 + pHeight); m_popupPath.lineTo(m_width/2 + m_thriangleHeight, pHeight); m_popupPath.lineTo(m_width/2, pHeight + m_thriangleHeight); m_popupPath.lineTo(m_width/2 - m_thriangleHeight, pHeight); m_popupPath.lineTo(0, pHeight); m_popupPath.lineTo(0, 0); Bitmap b = Bitmap.createBitmap(pWidth, pHeight + m_thriangleHeight, Config.ARGB_8888); Canvas canvas = new Canvas(b); canvas.drawPath(m_popupPath, m_backgroundPaint); canvas.drawBitmap(btn, pWidth - btn.getWidth()-5, + 5, m_buttonPaint); canvas.drawPath(m_popupPath, m_borderPaint); m_textPaint.getTextBounds(text, 0, text.length(), m_textBounds); int textHeight = m_textBounds.bottom - m_textBounds.top; canvas.drawText(text, 2, - (pHeight - textHeight) / 2 + pHeight, m_textPaint); return b; } @Override protected void onDraw(Canvas canvas) { Bookmark bmk = m_bmk; Log.d(DEACTIVATION, "invalidate"); Log.d(DEACTIVATION, "invalidate"); Log.d(DEACTIVATION, "invalidate"); Log.d(DEACTIVATION, "invalidate"); Log.d(DEACTIVATION, "" + (bmk == null)); if (bmk != null) { Log.d(DEACTIVATION, "i'm still drawing"); int pinHeight = Math.round(35/1.5f * getResources().getDisplayMetrics().density); m_popupAnchor.x = bmk.getPosition().x - m_width / 2; m_popupAnchor.y = bmk.getPosition().y - pinHeight - m_thriangleHeight - m_height; m_popupRect.left = m_popupAnchor.x; m_popupRect.top = m_popupAnchor.y; m_popupRect.right = m_popupAnchor.x + m_width; m_popupRect.bottom = m_popupAnchor.y + m_height; if (m_popup != null) { canvas.drawBitmap(m_popup, m_popupAnchor.x, m_popupAnchor.y, m_buttonPaint); } } else { canvas.drawColor(0, Mode.CLEAR); super.onDraw(canvas); } } private native void nDrawBookmark(double x, double y); private native void nRemoveBookmark(); /** * * @param x * @param y * @return true if we start {@link BookmarkActivity}, false otherwise */ public synchronized boolean handleClick(int x, int y, boolean ispro) { if (m_bmk != null) { if ( m_popupRect.contains(x, y) ) { if (ispro) { if (m_bmk.isPreviewBookmark()) { //m_bmk.setCategoryId(BookmarkManager.getBookmarkManager(getContext()).getCategoriesCount()-1); getContext().startActivity(new Intent(getContext(), BookmarkActivity.class). putExtra(BookmarkActivity.BOOKMARK_POSITION, new ParcelablePoint(m_bmk.getPosition())). putExtra(BookmarkActivity.BOOKMARK_NAME, m_bmk.getName())); } else { getContext().startActivity(new Intent(getContext(), BookmarkActivity.class).putExtra(BookmarkActivity.PIN, new ParcelablePoint(m_bmk.getCategoryId(), m_bmk.getBookmarkId()))); } } return true; } deactivate(); } return false; } }
package com.jetbrains.env.django; import com.google.common.collect.Lists; import com.intellij.execution.configurations.ConfigurationFactory; import com.intellij.openapi.util.io.FileUtil; import com.jetbrains.django.run.DjangoServerRunConfiguration; import com.jetbrains.django.run.DjangoServerRunConfigurationType; import com.jetbrains.django.testRunner.DjangoTestsConfigurationType; import com.jetbrains.django.testRunner.DjangoTestsRunConfiguration; import com.jetbrains.env.python.debug.PyEnvTestCase; import com.jetbrains.python.run.AbstractPythonRunConfiguration; import junit.framework.Assert; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.util.ArrayList; /** * User : catherine */ public class DjangoPathTest extends PyEnvTestCase { public void testRunserverPath() throws IOException { runPythonTest(new DjangoPathTestTask() { @Override protected void configure(AbstractPythonRunConfiguration config) throws IOException { final int[] ports = DjangoTemplateDebuggerTest.findFreePorts(2); ((DjangoServerRunConfiguration)config).setPort(ports[1]); } @Override public ConfigurationFactory getFactory() { return DjangoServerRunConfigurationType.getInstance().getConfigurationFactories()[0]; } public void testing() throws Exception { waitForOutput("Development server is running"); doTest(output(), getTestDataPath()); } }); } private static void doTest(String output, String testDataPath) { final String[] splittedOutput = output.split("\\n"); final ArrayList<String> outputList = Lists.newArrayList(); for (String s : splittedOutput) { if (s.equals("The end of sys.path")) { break; } outputList.add(norm(s)); } testDataPath = norm(testDataPath); Assert.assertEquals(testDataPath, outputList.get(1)); assertEquals(outputList.indexOf(testDataPath), outputList.lastIndexOf(testDataPath)); } private static String norm(String testDataPath) { return FileUtil.toSystemIndependentName(testDataPath); } public void testTestPath() throws IOException { runPythonTest(new DjangoPathTestTask() { @Override public ConfigurationFactory getFactory() { return DjangoTestsConfigurationType.getInstance().getConfigurationFactories()[0]; } @Override protected void configure(AbstractPythonRunConfiguration config) { ((DjangoTestsRunConfiguration)config).setTarget("site.SimpleTest"); } public void testing() throws Exception { waitForOutput("The end of sys.path"); doTest(output(), getTestDataPath()); } }); } public void testManagePath() throws IOException { runPythonTest(new DjangoPathTestTask() { @Nullable @Override public ConfigurationFactory getFactory() { return null; } public void testing() throws Exception { waitForOutput("The end of sys.path"); final String[] splittedOutput = output().split("\\n"); final ArrayList<String> outputList = Lists.newArrayList(); for (String s : splittedOutput) { if (s.equals("The end of sys.path")) { break; } outputList.add(s); } assertEquals(getTestDataPath(), outputList.get(1)); assertEquals(outputList.indexOf(getTestDataPath()), outputList.lastIndexOf(getTestDataPath())); } }); } }
// ImageInfo.java package loci.formats.tools; import java.awt.image.BufferedImage; import java.io.IOException; import java.util.Hashtable; import java.util.StringTokenizer; import loci.common.ByteArrayHandle; import loci.common.DataTools; import loci.common.DebugTools; import loci.common.Location; import loci.common.RandomAccessInputStream; import loci.common.services.DependencyException; import loci.common.services.ServiceException; import loci.common.services.ServiceFactory; import loci.common.xml.XMLTools; import loci.formats.ChannelFiller; import loci.formats.ChannelMerger; import loci.formats.ChannelSeparator; import loci.formats.DimensionSwapper; import loci.formats.FilePattern; import loci.formats.FileStitcher; import loci.formats.FormatException; import loci.formats.FormatTools; import loci.formats.IFormatReader; import loci.formats.ImageReader; import loci.formats.ImageTools; import loci.formats.MetadataTools; import loci.formats.MinMaxCalculator; import loci.formats.MissingLibraryException; import loci.formats.gui.AWTImageTools; import loci.formats.gui.BufferedImageReader; import loci.formats.gui.ImageViewer; import loci.formats.in.DefaultMetadataOptions; import loci.formats.in.MetadataLevel; import loci.formats.in.MetadataOptions; import loci.formats.in.OMETiffReader; import loci.formats.meta.MetadataRetrieve; import loci.formats.meta.MetadataStore; import loci.formats.services.OMEXMLService; import loci.formats.services.OMEXMLServiceImpl; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ImageInfo { // -- Constants -- private static final Logger LOGGER = LoggerFactory.getLogger(ImageInfo.class); private static final String NEWLINE = System.getProperty("line.separator"); // -- Fields -- private String id = null; private boolean printVersion = false; private boolean pixels = true; private boolean doCore = true; private boolean doMeta = true; private boolean filter = true; private boolean thumbs = false; private boolean minmax = false; private boolean merge = false; private boolean stitch = false; private boolean group = true; private boolean separate = false; private boolean expand = false; private boolean omexml = false; private boolean normalize = false; private boolean fastBlit = false; private boolean autoscale = false; private boolean preload = false; private boolean ascii = false; private boolean usedFiles = true; private boolean omexmlOnly = false; private boolean validate = true; private String omexmlVersion = null; private int start = 0; private int end = Integer.MAX_VALUE; private int series = 0; private int xCoordinate = 0, yCoordinate = 0, width = 0, height = 0; private String swapOrder = null, shuffleOrder = null; private String map = null; private String format = null; private IFormatReader reader; private IFormatReader baseReader; private MinMaxCalculator minMaxCalc; private DimensionSwapper dimSwapper; private BufferedImageReader biReader; private Double[] preGlobalMin = null, preGlobalMax = null; private Double[] preKnownMin = null, preKnownMax = null; private Double[] prePlaneMin = null, prePlaneMax = null; private boolean preIsMinMaxPop = false; // -- ImageInfo methods -- public boolean parseArgs(String[] args) { id = null; printVersion = false; pixels = true; doCore = true; doMeta = true; filter = true; thumbs = false; minmax = false; merge = false; stitch = false; group = true; separate = false; expand = false; omexml = false; normalize = false; fastBlit = false; autoscale = false; preload = false; usedFiles = true; omexmlOnly = false; validate = true; omexmlVersion = null; start = 0; end = Integer.MAX_VALUE; series = 0; xCoordinate = 0; yCoordinate = 0; width = 0; height = 0; swapOrder = null; shuffleOrder = null; map = null; if (args == null) return false; for (int i=0; i<args.length; i++) { if (args[i].startsWith("-")) { if (args[i].equals("-nopix")) pixels = false; else if (args[i].equals("-version")) printVersion = true; else if (args[i].equals("-nocore")) doCore = false; else if (args[i].equals("-nometa")) doMeta = false; else if (args[i].equals("-nofilter")) filter = false; else if (args[i].equals("-thumbs")) thumbs = true; else if (args[i].equals("-minmax")) minmax = true; else if (args[i].equals("-merge")) merge = true; else if (args[i].equals("-stitch")) stitch = true; else if (args[i].equals("-nogroup")) group = false; else if (args[i].equals("-separate")) separate = true; else if (args[i].equals("-expand")) expand = true; else if (args[i].equals("-omexml")) omexml = true; else if (args[i].equals("-normalize")) normalize = true; else if (args[i].equals("-fast")) fastBlit = true; else if (args[i].equals("-autoscale")) autoscale = true; else if (args[i].equals("-novalid")) validate = false; else if (args[i].equals("-debug")) { DebugTools.enableLogging("DEBUG"); } else if (args[i].equals("-omexml-only")) { omexmlOnly = true; omexml = true; DebugTools.enableLogging("OFF"); } else if (args[i].equals("-preload")) preload = true; else if (args[i].equals("-ascii")) ascii = true; else if (args[i].equals("-nousedfiles")) usedFiles = false; else if (args[i].equals("-xmlversion")) omexmlVersion = args[++i]; else if (args[i].equals("-crop")) { StringTokenizer st = new StringTokenizer(args[++i], ","); xCoordinate = Integer.parseInt(st.nextToken()); yCoordinate = Integer.parseInt(st.nextToken()); width = Integer.parseInt(st.nextToken()); height = Integer.parseInt(st.nextToken()); } else if (args[i].equals("-range")) { try { start = Integer.parseInt(args[++i]); end = Integer.parseInt(args[++i]); } catch (NumberFormatException exc) { } } else if (args[i].equals("-series")) { try { series = Integer.parseInt(args[++i]); } catch (NumberFormatException exc) { } } else if (args[i].equals("-swap")) { swapOrder = args[++i].toUpperCase(); } else if (args[i].equals("-shuffle")) { shuffleOrder = args[++i].toUpperCase(); } else if (args[i].equals("-map")) map = args[++i]; else if (args[i].equals("-format")) format = args[++i]; else { LOGGER.error("Found unknown command flag: {}; exiting.", args[i]); return false; } } else { if (id == null) id = args[i]; else { LOGGER.error("Found unknown argument: {}; exiting.", args[i]); return false; } } } return true; } public void printUsage() { String fmt = reader instanceof ImageReader ? "any" : reader.getFormat(); String[] s = { "To test read a file in " + fmt + " format, run:", " showinf file [-nopix] [-nocore] [-nometa] [-thumbs] [-minmax] ", " [-merge] [-nogroup] [-stitch] [-separate] [-expand] [-omexml]", " [-normalize] [-fast] [-debug] [-range start end] [-series num]", " [-swap inputOrder] [-shuffle outputOrder] [-map id] [-preload]", " [-crop x,y,w,h] [-autoscale] [-novalid] [-omexml-only]", " [-format Format]", "", " -version: print the library version and exit", " file: the image file to read", " -nopix: read metadata only, not pixels", " -nocore: do not output core metadata", " -nometa: do not parse format-specific metadata table", " -nofilter: do not filter metadata fields", " -thumbs: read thumbnails instead of normal pixels", " -minmax: compute min/max statistics", " -merge: combine separate channels into RGB image", " -nogroup: force multi-file datasets to be read as individual files", " -stitch: stitch files with similar names", " -separate: split RGB image into separate channels", " -expand: expand indexed color to RGB", " -omexml: populate OME-XML metadata", " -normalize: normalize floating point images*", " -fast: paint RGB images as quickly as possible*", " -debug: turn on debugging output", " -range: specify range of planes to read (inclusive)", " -series: specify which image series to read", " -swap: override the default input dimension order", " -shuffle: override the default output dimension order", " -map: specify file on disk to which name should be mapped", " -preload: pre-read entire file into a buffer; significantly", " reduces the time required to read the images, but", " requires more memory", " -crop: crop images before displaying; argument is 'x,y,w,h'", " -autoscale: used in combination with '-fast' to automatically adjust", " brightness and contrast", " -novalid: do not perform validation of OME-XML", "-omexml-only: only output the generated OME-XML", " -format: read file with a particular reader (e.g., ZeissZVI)", "", "* = may result in loss of precision", "" }; for (int i=0; i<s.length; i++) LOGGER.info(s[i]); } public void setReader(IFormatReader reader) { this.reader = reader; } public void createReader() { if (reader != null) return; // reader was set programmatically if (format != null) { // create reader of a specific format type try { Class<?> c = Class.forName("loci.formats.in." + format + "Reader"); reader = (IFormatReader) c.newInstance(); } catch (ClassNotFoundException exc) { LOGGER.warn("Unknown reader: {}", format); LOGGER.debug("", exc); } catch (InstantiationException exc) { LOGGER.warn("Cannot instantiate reader: {}", format); LOGGER.debug("", exc); } catch (IllegalAccessException exc) { LOGGER.warn("Cannot access reader: {}", format); LOGGER.debug("", exc); } } if (reader == null) reader = new ImageReader(); baseReader = reader; } public void mapLocation() throws IOException { if (map != null) Location.mapId(id, map); else if (preload) { RandomAccessInputStream f = new RandomAccessInputStream(id); int len = (int) f.length(); LOGGER.info("Caching {} bytes:", len); byte[] b = new byte[len]; int blockSize = 8 * 1024 * 1024; // 8 MB int read = 0, left = len; while (left > 0) { int r = f.read(b, read, blockSize < left ? blockSize : left); read += r; left -= r; float ratio = (float) read / len; int p = (int) (100 * ratio); LOGGER.info("\tRead {} bytes ({}% complete)", read, p); } f.close(); ByteArrayHandle file = new ByteArrayHandle(b); Location.mapFile(id, file); } } public void configureReaderPreInit() throws FormatException, IOException { if (omexml) { reader.setOriginalMetadataPopulated(true); try { ServiceFactory factory = new ServiceFactory(); OMEXMLService service = factory.getInstance(OMEXMLService.class); reader.setMetadataStore( service.createOMEXMLMetadata(null, omexmlVersion)); } catch (DependencyException de) { throw new MissingLibraryException(OMEXMLServiceImpl.NO_OME_XML_MSG, de); } catch (ServiceException se) { throw new FormatException(se); } } // check file format if (reader instanceof ImageReader) { // determine format ImageReader ir = (ImageReader) reader; if (new Location(id).exists()) { LOGGER.info("Checking file format [{}]", ir.getFormat(id)); } } else { // verify format LOGGER.info("Checking {} format [{}]", reader.getFormat(), reader.isThisType(id) ? "yes" : "no"); } LOGGER.info("Initializing reader"); if (stitch) { reader = new FileStitcher(reader, true); Location f = new Location(id); String pat = null; if (!f.exists()) { ((FileStitcher) reader).setUsingPatternIds(true); pat = id; } else { pat = FilePattern.findPattern(f); } if (pat != null) id = pat; } if (expand) reader = new ChannelFiller(reader); if (separate) reader = new ChannelSeparator(reader); if (merge) reader = new ChannelMerger(reader); minMaxCalc = null; if (minmax || autoscale) reader = minMaxCalc = new MinMaxCalculator(reader); dimSwapper = null; if (swapOrder != null || shuffleOrder != null) { reader = dimSwapper = new DimensionSwapper(reader); } reader = biReader = new BufferedImageReader(reader); reader.close(); reader.setNormalized(normalize); reader.setMetadataFiltered(filter); reader.setGroupFiles(group); MetadataOptions metaOptions = new DefaultMetadataOptions(doMeta ? MetadataLevel.ALL : MetadataLevel.MINIMUM); reader.setMetadataOptions(metaOptions); } public void configureReaderPostInit() { if (swapOrder != null) dimSwapper.swapDimensions(swapOrder); if (shuffleOrder != null) dimSwapper.setOutputOrder(shuffleOrder); } public void checkWarnings() { if (!normalize && (reader.getPixelType() == FormatTools.FLOAT || reader.getPixelType() == FormatTools.DOUBLE)) { LOGGER.warn(""); LOGGER.warn("Java does not support " + "display of unnormalized floating point data."); LOGGER.warn("Please use the '-normalize' option " + "to avoid receiving a cryptic exception."); } if (reader.isRGB() && reader.getRGBChannelCount() > 4) { LOGGER.warn(""); LOGGER.warn("Java does not support merging more than 4 channels."); LOGGER.warn("Please use the '-separate' option " + "to avoid losing channels beyond the 4th."); } } public void readCoreMetadata() throws FormatException, IOException { if (!doCore) return; // skip core metadata printout // read basic metadata LOGGER.info(""); LOGGER.info("Reading core metadata"); LOGGER.info("{} = {}", stitch ? "File pattern" : "Filename", stitch ? id : reader.getCurrentFile()); if (map != null) LOGGER.info("Mapped filename = {}", map); if (usedFiles) { String[] used = reader.getUsedFiles(); boolean usedValid = used != null && used.length > 0; if (usedValid) { for (int u=0; u<used.length; u++) { if (used[u] == null) { usedValid = false; break; } } } if (!usedValid) { LOGGER.warn("************ invalid used files list ************"); } if (used == null) { LOGGER.info("Used files = null"); } else if (used.length == 0) { LOGGER.info("Used files = []"); } else if (used.length > 1) { LOGGER.info("Used files:"); for (int u=0; u<used.length; u++) LOGGER.info("\t{}", used[u]); } else if (!id.equals(used[0])) { LOGGER.info("Used files = [{}]", used[0]); } } int seriesCount = reader.getSeriesCount(); LOGGER.info("Series count = {}", seriesCount); MetadataStore ms = reader.getMetadataStore(); MetadataRetrieve mr = ms instanceof MetadataRetrieve ? (MetadataRetrieve) ms : null; for (int j=0; j<seriesCount; j++) { reader.setSeries(j); // read basic metadata for series int imageCount = reader.getImageCount(); boolean rgb = reader.isRGB(); int sizeX = reader.getSizeX(); int sizeY = reader.getSizeY(); int sizeZ = reader.getSizeZ(); int sizeC = reader.getSizeC(); int sizeT = reader.getSizeT(); int pixelType = reader.getPixelType(); int validBits = reader.getBitsPerPixel(); int effSizeC = reader.getEffectiveSizeC(); int rgbChanCount = reader.getRGBChannelCount(); boolean indexed = reader.isIndexed(); boolean falseColor = reader.isFalseColor(); byte[][] table8 = reader.get8BitLookupTable(); short[][] table16 = reader.get16BitLookupTable(); int[] cLengths = reader.getChannelDimLengths(); String[] cTypes = reader.getChannelDimTypes(); int thumbSizeX = reader.getThumbSizeX(); int thumbSizeY = reader.getThumbSizeY(); boolean little = reader.isLittleEndian(); String dimOrder = reader.getDimensionOrder(); boolean orderCertain = reader.isOrderCertain(); boolean thumbnail = reader.isThumbnailSeries(); boolean interleaved = reader.isInterleaved(); boolean metadataComplete = reader.isMetadataComplete(); // output basic metadata for series String seriesName = mr == null ? null : mr.getImageName(j); LOGGER.info("Series new Object[] {j, seriesName == null ? " " : " seriesName == null ? "" : seriesName}); LOGGER.info("\tImage count = {}", imageCount); LOGGER.info("\tRGB = {} ({}) {}", new Object[] {rgb, rgbChanCount, merge ? "(merged)" : separate ? "(separated)" : ""}); if (rgb != (rgbChanCount != 1)) { LOGGER.warn("\t************ RGB mismatch ************"); } LOGGER.info("\tInterleaved = {}", interleaved); StringBuilder sb = new StringBuilder(); sb.append("\tIndexed = "); sb.append(indexed); sb.append(" ("); sb.append(!falseColor); sb.append(" color"); if (table8 != null) { sb.append(", 8-bit LUT: "); sb.append(table8.length); sb.append(" x "); sb.append(table8[0] == null ? "null" : "" + table8[0].length); } if (table16 != null) { sb.append(", 16-bit LUT: "); sb.append(table16.length); sb.append(" x "); sb.append(table16[0] == null ? "null" : "" + table16[0].length); } sb.append(")"); LOGGER.info(sb.toString()); if (table8 != null && table16 != null) { LOGGER.warn("\t************ multiple LUTs ************"); } LOGGER.info("\tWidth = {}", sizeX); LOGGER.info("\tHeight = {}", sizeY); LOGGER.info("\tSizeZ = {}", sizeZ); LOGGER.info("\tSizeT = {}", sizeT); sb.setLength(0); sb.append("\tSizeC = "); sb.append(sizeC); if (sizeC != effSizeC) { sb.append(" (effectively "); sb.append(effSizeC); sb.append(")"); } int cProduct = 1; if (cLengths.length == 1 && FormatTools.CHANNEL.equals(cTypes[0])) { cProduct = cLengths[0]; } else { sb.append(" ("); for (int i=0; i<cLengths.length; i++) { if (i > 0) sb.append(" x "); sb.append(cLengths[i]); sb.append(" "); sb.append(cTypes[i]); cProduct *= cLengths[i]; } sb.append(")"); } LOGGER.info(sb.toString()); if (cLengths.length == 0 || cProduct != sizeC) { LOGGER.warn("\t************ C dimension mismatch ************"); } if (imageCount != sizeZ * effSizeC * sizeT) { LOGGER.info("\t************ ZCT mismatch ************"); } LOGGER.info("\tThumbnail size = {} x {}", thumbSizeX, thumbSizeY); LOGGER.info("\tEndianness = {}", little ? "intel (little)" : "motorola (big)"); LOGGER.info("\tDimension order = {} ({})", dimOrder, orderCertain ? "certain" : "uncertain"); LOGGER.info("\tPixel type = {}", FormatTools.getPixelTypeString(pixelType)); LOGGER.info("\tValid bits per pixel = {}", validBits); LOGGER.info("\tMetadata complete = {}", metadataComplete); LOGGER.info("\tThumbnail series = {}", thumbnail); if (doMeta) { LOGGER.info("\t int[] indices; if (imageCount > 6) { int q = imageCount / 2; indices = new int[] { 0, q - 2, q - 1, q, q + 1, q + 2, imageCount - 1 }; } else if (imageCount > 2) { indices = new int[] {0, imageCount / 2, imageCount - 1}; } else if (imageCount > 1) indices = new int[] {0, 1}; else indices = new int[] {0}; int[][] zct = new int[indices.length][]; int[] indices2 = new int[indices.length]; sb.setLength(0); for (int i=0; i<indices.length; i++) { zct[i] = reader.getZCTCoords(indices[i]); indices2[i] = reader.getIndex(zct[i][0], zct[i][1], zct[i][2]); sb.append("\tPlane sb.append(indices[i]); sb.append(" <=> Z "); sb.append(zct[i][0]); sb.append(", C "); sb.append(zct[i][1]); sb.append(", T "); sb.append(zct[i][2]); if (indices[i] != indices2[i]) { sb.append(" [mismatch: "); sb.append(indices2[i]); sb.append("]"); sb.append(NEWLINE); } else sb.append(NEWLINE); } LOGGER.info(sb.toString()); } } } public void initPreMinMaxValues() throws FormatException, IOException { // get a priori min/max values preGlobalMin = preGlobalMax = null; preKnownMin = preKnownMax = null; prePlaneMin = prePlaneMax = null; preIsMinMaxPop = false; if (minmax) { int sizeC = reader.getSizeC(); preGlobalMin = new Double[sizeC]; preGlobalMax = new Double[sizeC]; preKnownMin = new Double[sizeC]; preKnownMax = new Double[sizeC]; for (int c=0; c<sizeC; c++) { preGlobalMin[c] = minMaxCalc.getChannelGlobalMinimum(c); preGlobalMax[c] = minMaxCalc.getChannelGlobalMaximum(c); preKnownMin[c] = minMaxCalc.getChannelKnownMinimum(c); preKnownMax[c] = minMaxCalc.getChannelKnownMaximum(c); } prePlaneMin = minMaxCalc.getPlaneMinimum(0); prePlaneMax = minMaxCalc.getPlaneMaximum(0); preIsMinMaxPop = minMaxCalc.isMinMaxPopulated(); } } public void printMinMaxValues() throws FormatException, IOException { // get computed min/max values int sizeC = reader.getSizeC(); Double[] globalMin = new Double[sizeC]; Double[] globalMax = new Double[sizeC]; Double[] knownMin = new Double[sizeC]; Double[] knownMax = new Double[sizeC]; for (int c=0; c<sizeC; c++) { globalMin[c] = minMaxCalc.getChannelGlobalMinimum(c); globalMax[c] = minMaxCalc.getChannelGlobalMaximum(c); knownMin[c] = minMaxCalc.getChannelKnownMinimum(c); knownMax[c] = minMaxCalc.getChannelKnownMaximum(c); } Double[] planeMin = minMaxCalc.getPlaneMinimum(0); Double[] planeMax = minMaxCalc.getPlaneMaximum(0); boolean isMinMaxPop = minMaxCalc.isMinMaxPopulated(); // output min/max results LOGGER.info(""); LOGGER.info("Min/max values:"); for (int c=0; c<sizeC; c++) { LOGGER.info("\tChannel {}:", c); LOGGER.info("\t\tGlobal minimum = {} (initially {})", globalMin[c], preGlobalMin[c]); LOGGER.info("\t\tGlobal maximum = {} (initially {})", globalMax[c], preGlobalMax[c]); LOGGER.info("\t\tKnown minimum = {} (initially {})", knownMin[c], preKnownMin[c]); LOGGER.info("\t\tKnown maximum = {} (initially {})", knownMax[c], preKnownMax[c]); } StringBuilder sb = new StringBuilder(); sb.append("\tFirst plane minimum(s) ="); if (planeMin == null) sb.append(" none"); else { for (int subC=0; subC<planeMin.length; subC++) { sb.append(" "); sb.append(planeMin[subC]); } } sb.append(" (initially"); if (prePlaneMin == null) sb.append(" none"); else { for (int subC=0; subC<prePlaneMin.length; subC++) { sb.append(" "); sb.append(prePlaneMin[subC]); } } sb.append(")"); LOGGER.info(sb.toString()); sb.setLength(0); sb.append("\tFirst plane maximum(s) ="); if (planeMax == null) sb.append(" none"); else { for (int subC=0; subC<planeMax.length; subC++) { sb.append(" "); sb.append(planeMax[subC]); } } sb.append(" (initially"); if (prePlaneMax == null) sb.append(" none"); else { for (int subC=0; subC<prePlaneMax.length; subC++) { sb.append(" "); sb.append(prePlaneMax[subC]); } } sb.append(")"); LOGGER.info(sb.toString()); LOGGER.info("\tMin/max populated = {} (initially {})", isMinMaxPop, preIsMinMaxPop); } public void readPixels() throws FormatException, IOException { String seriesLabel = reader.getSeriesCount() > 1 ? (" series #" + series) : ""; LOGGER.info(""); int num = reader.getImageCount(); if (start < 0) start = 0; if (start >= num) start = num - 1; if (end < 0) end = 0; if (end >= num) end = num - 1; if (end < start) end = start; LOGGER.info("Reading{} pixel data ({}-{})", new Object[] {seriesLabel, start, end}); int sizeX = reader.getSizeX(); int sizeY = reader.getSizeY(); if (width == 0) width = sizeX; if (height == 0) height = sizeY; int pixelType = reader.getPixelType(); BufferedImage[] images = new BufferedImage[end - start + 1]; long s = System.currentTimeMillis(); long timeLastLogged = s; for (int i=start; i<=end; i++) { if (!fastBlit) { images[i - start] = thumbs ? biReader.openThumbImage(i) : biReader.openImage(i, xCoordinate, yCoordinate, width, height); } else { byte[] b = thumbs ? reader.openThumbBytes(i) : reader.openBytes(i, xCoordinate, yCoordinate, width, height); Object pix = DataTools.makeDataArray(b, FormatTools.getBytesPerPixel(pixelType), FormatTools.isFloatingPoint(pixelType), reader.isLittleEndian()); Double min = null, max = null; if (autoscale) { Double[] planeMin = minMaxCalc.getPlaneMinimum(i); Double[] planeMax = minMaxCalc.getPlaneMaximum(i); if (planeMin != null && planeMax != null) { min = planeMin[0]; max = planeMax[0]; for (int j=1; j<planeMin.length; j++) { if (planeMin[j].doubleValue() < min.doubleValue()) { min = planeMin[j]; } if (planeMax[j].doubleValue() > max.doubleValue()) { max = planeMax[j]; } } } } else if (normalize) { min = new Double(0); max = new Double(1); } if (normalize) { if (pix instanceof float[]) { pix = DataTools.normalizeFloats((float[]) pix); } else if (pix instanceof double[]) { pix = DataTools.normalizeDoubles((double[]) pix); } } images[i - start] = AWTImageTools.makeImage(ImageTools.make24Bits(pix, sizeX, sizeY, reader.isInterleaved(), false, min, max), sizeX, sizeY, FormatTools.isSigned(pixelType)); } if (images[i - start] == null) { LOGGER.warn("\t************ Failed to read plane } if (reader.isIndexed() && reader.get8BitLookupTable() == null && reader.get16BitLookupTable() == null) { LOGGER.warn("\t************ no LUT for plane } // check for pixel type mismatch int pixType = AWTImageTools.getPixelType(images[i - start]); if (pixType != pixelType && pixType != pixelType + 1 && !fastBlit) { LOGGER.info("\tPlane #{}: pixel type mismatch: {}/{}", new Object[] {i, FormatTools.getPixelTypeString(pixType), FormatTools.getPixelTypeString(pixelType)}); } else { // log number of planes read every second or so long t = System.currentTimeMillis(); if (i == end || (t - timeLastLogged) / 1000 > 0) { int current = i - start + 1; int total = end - start + 1; int percent = 100 * current / total; LOGGER.info("\tRead {}/{} planes ({}%)", new Object[] { current, total, percent }); timeLastLogged = t; } } } long e = System.currentTimeMillis(); LOGGER.info("[done]"); // output timing results float sec = (e - s) / 1000f; float avg = (float) (e - s) / images.length; LOGGER.info("{}s elapsed ({}ms per plane)", sec, avg); if (minmax) printMinMaxValues(); // display pixels in image viewer if (ascii) { for (int i=0; i<images.length; i++) { final BufferedImage img = images[i]; LOGGER.info(""); LOGGER.info("Image LOGGER.info(new AsciiImage(img).toString()); } } else { LOGGER.info(""); LOGGER.info("Launching image viewer"); ImageViewer viewer = new ImageViewer(); viewer.setImages(reader, images); viewer.setVisible(true); } } public void printGlobalMetadata() { LOGGER.info(""); LOGGER.info("Reading global metadata"); Hashtable<String, Object> meta = reader.getGlobalMetadata(); String[] keys = MetadataTools.keys(meta); for (String key : keys) { LOGGER.info("{}: {}", key, meta.get(key)); } } public void printOriginalMetadata() { String seriesLabel = reader.getSeriesCount() > 1 ? (" series #" + series) : ""; LOGGER.info(""); LOGGER.info("Reading{} metadata", seriesLabel); Hashtable<String, Object> meta = reader.getSeriesMetadata(); String[] keys = MetadataTools.keys(meta); for (int i=0; i<keys.length; i++) { LOGGER.info("{}: {}", keys[i], meta.get(keys[i])); } } public void printOMEXML() throws MissingLibraryException, ServiceException { LOGGER.info(""); MetadataStore ms = reader.getMetadataStore(); if (baseReader instanceof ImageReader) { baseReader = ((ImageReader) baseReader).getReader(); } if (baseReader instanceof OMETiffReader) { ms = ((OMETiffReader) baseReader).getMetadataStoreForDisplay(); } OMEXMLService service; try { ServiceFactory factory = new ServiceFactory(); service = factory.getInstance(OMEXMLService.class); } catch (DependencyException de) { throw new MissingLibraryException(OMEXMLServiceImpl.NO_OME_XML_MSG, de); } String version = service.getOMEXMLVersion(ms); if (version == null) LOGGER.info("Generating OME-XML"); else { LOGGER.info("Generating OME-XML (schema version {})", version); } if (ms instanceof MetadataRetrieve) { if (omexmlOnly) { DebugTools.enableLogging("INFO"); } String xml = service.getOMEXML((MetadataRetrieve) ms); LOGGER.info("{}", XMLTools.indentXML(xml, true)); if (omexmlOnly) { DebugTools.enableLogging("OFF"); } if (validate) { service.validateOMEXML(xml); } } else { LOGGER.info("The metadata could not be converted to OME-XML."); if (omexmlVersion == null) { LOGGER.info("The OME-XML Java library is probably not available."); } else { LOGGER.info("{} is probably not a legal schema version.", omexmlVersion); } } } /** * A utility method for reading a file from the command line, * and displaying the results in a simple display. */ public boolean testRead(String[] args) throws FormatException, ServiceException, IOException { DebugTools.enableLogging("INFO"); boolean validArgs = parseArgs(args); if (!validArgs) return false; if (printVersion) { LOGGER.info("Version: {}", FormatTools.VERSION); LOGGER.info("VCS revision: {}", FormatTools.VCS_REVISION); LOGGER.info("Build date: {}", FormatTools.DATE); return true; } createReader(); if (id == null) { printUsage(); return false; } mapLocation(); configureReaderPreInit(); // initialize reader long s = System.currentTimeMillis(); reader.setId(id); long e = System.currentTimeMillis(); float sec = (e - s) / 1000f; LOGGER.info("Initialization took {}s", sec); configureReaderPostInit(); checkWarnings(); readCoreMetadata(); reader.setSeries(series); initPreMinMaxValues(); // read pixels if (pixels) readPixels(); // read format-specific metadata table if (doMeta) { printGlobalMetadata(); printOriginalMetadata(); } // output and validate OME-XML if (omexml) printOMEXML(); if (!pixels) { reader.close(); } return true; } // -- Main method -- public static void main(String[] args) throws Exception { if (!new ImageInfo().testRead(args)) System.exit(1); } }
package org.jscep.transaction; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.util.Arrays; import java.util.concurrent.atomic.AtomicLong; import org.jscep.util.HexUtil; /** * This class represents the SCEP <code>transactionID</code> attribute. * * @author David Grant */ public final class TransactionId { private static final AtomicLong ID_SOURCE = new AtomicLong(); private final byte[] id; public TransactionId(byte[] id) { this.id = id; } private TransactionId(PublicKey pubKey, String digestAlgorithm) { MessageDigest digest; try { digest = MessageDigest.getInstance(digestAlgorithm); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } id = HexUtil.toHex(digest.digest(pubKey.getEncoded())); } private TransactionId() { id = Long.toHexString(ID_SOURCE.getAndIncrement()).getBytes(); } public byte[] getBytes() { return id; } /** * Creates a new Transaction Id * <p> * Each call to this method will return the same transaction ID for the same parameters. * * @param pubKey public key * @param digestAlgorithm digest algorithm * @return the new Transaction Id */ public static TransactionId createTransactionId(PublicKey pubKey, String digestAlgorithm) { return new TransactionId(pubKey, digestAlgorithm); } /** * Creates a new Transaction Id * <p> * Each call to this method will return a different transaction ID. * * @return the new Transaction Id */ public static TransactionId createTransactionId() { return new TransactionId(); } @Override public String toString() { return new String(id); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; TransactionId that = (TransactionId) o; if (!Arrays.equals(id, that.id)) return false; return true; } @Override public int hashCode() { return id != null ? Arrays.hashCode(id) : 0; } }
package com.github.vovas11.courses.dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import javax.sql.DataSource; /** * Provides methods for communication between application and the database and manipulates * with table 'students'. Part of DAO design pattern. * * @author vovas11 * @see User * @see DaoFactory */ public class UserDao { /* link to the connection (interface) to the database */ DataSource datasrc; /* Predefined SQL statements that are used for execution requests in the database, table 'students' */ final static String SELECT_USER_SQL = "SELECT * FROM students WHERE login=? AND password=?"; final static String SELECT_LOGIN_SQL = "SELECT * FROM students WHERE login=?"; final static String INSERT_USER_SQL = "INSERT INTO students" + "(firstname, lastname, login, password, department)" + " VALUES(?, ?, ?, ?, ?)"; final static String SELECT_ALL_USERS_SQL = "SELECT * FROM students"; final static String GET_USER_FIELDS_SQL = "SELECT student_id, firstname, lastname, department" + " FROM students WHERE login = ?"; public UserDao(DataSource datasrc) { this.datasrc = datasrc; } /** * Checks if the user with specified login and password exists in the database. * * @param user the current user * @return {@code true} if the user exists and {@code false} if does not */ public boolean isExist(User user) { /* link to the current database */ Connection conn = null; try { /* gets connection to the database from Connection pool */ conn = datasrc.getConnection(); /* prepares SQL statement with parameters */ PreparedStatement prepStmt = conn.prepareStatement(SELECT_USER_SQL); prepStmt.setString(1, user.getLogin()); prepStmt.setString(2, user.getPassword()); /* executes the query and receives the result table */ ResultSet result = prepStmt.executeQuery(); /* returns true if result is not empty */ return result.next(); } catch (SQLException e) { e.printStackTrace(); } finally { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } return false; } /** * Checks if the user with specified login exists in the database. * * @param user the current user * @return {@code true} if the user exists and {@code false} if does not */ public boolean isLoginExist(User user) { /* link to the current database */ Connection conn = null; try { /* gets connection to the database from Connection pool */ conn = datasrc.getConnection(); /* prepares SQL statement with parameters */ PreparedStatement prepStmt = conn.prepareStatement(SELECT_LOGIN_SQL); prepStmt.setString(1, user.getLogin()); /* executes the query and receives the result table */ ResultSet result = prepStmt.executeQuery(); /* returns true if result is not empty */ return result.next(); } catch (SQLException e) { e.printStackTrace(); } finally { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } return true; // less changes in the database if something is wrong } /** * Executes request into the database (table 'students') to insert the current user. * * @param user the current user */ public void insert(User user) { /* link to the current database */ Connection conn = null; try { /* gets connection to the database from Connection pool */ conn = datasrc.getConnection(); /* prepares SQL statement with parameters */ PreparedStatement prepStmt = conn.prepareStatement(INSERT_USER_SQL); prepStmt.setString(1, user.getFirstName()); prepStmt.setString(2, user.getLastName()); prepStmt.setString(3, user.getLogin()); prepStmt.setString(4, user.getPassword()); prepStmt.setString(5, user.getDepartment()); /* executes the query without returning anything */ prepStmt.execute(); } catch (SQLException e) { e.printStackTrace(); } finally { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } /** * Executes request into the database and returns list of all users * * @return list of all users from the database */ public List<User> getAllUsers() { /* list of users to be returned */ List<User> allUsers = new ArrayList<User>(); /* link to the current database */ Connection conn = null; try { /* gets connection to the database from Connection pool */ conn = datasrc.getConnection(); /* creates simple SQL statement */ Statement stmt = conn.createStatement(); /* executes the query and receives the result table */ ResultSet result = stmt.executeQuery(SELECT_ALL_USERS_SQL); /* runs through all rows of the result table, creates an instance of the User, * fills in the instance's fields, and put it into result list */ while (result.next()) { User user = new User(); user.setId(result.getInt(1)); user.setLogin(result.getString(4)); user.setPassword(result.getString(5)); user.setFirstName(result.getString(2)); user.setLastName(result.getString(3)); user.setDepartment(result.getString(6)); allUsers.add(user); } } catch (SQLException e) { e.printStackTrace(); } finally { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } return allUsers; } /** * Adds rest of the fields into the object. * @param user the current user */ public void getFieldsForUser(User user) { /* link to the current database */ Connection connection = null; try { /* gets connection to the database from Connection pool */ connection = datasrc.getConnection(); /* prepares SQL statement with parameters */ PreparedStatement prepStmt = connection.prepareStatement(GET_USER_FIELDS_SQL); prepStmt.setString(1, user.getLogin()); /* executes the query and receives the result table */ ResultSet result = prepStmt.executeQuery(); /* fills in the instance's fields */ while (result.next()) { user.setId(result.getInt(1)); user.setFirstName(result.getString(2)); user.setLastName(result.getString(3)); user.setDepartment(result.getString(4)); } } catch (SQLException e) { e.printStackTrace(); } finally { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
package com.hippo.ehviewer.gallery; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Color; import android.graphics.Movie; import android.graphics.Rect; import android.graphics.RectF; import android.view.MotionEvent; import com.hippo.ehviewer.R; import com.hippo.ehviewer.gallery.data.ImageSet; import com.hippo.ehviewer.gallery.glrenderer.BitmapTexture; import com.hippo.ehviewer.gallery.glrenderer.ColorTexture; import com.hippo.ehviewer.gallery.glrenderer.GLCanvas; import com.hippo.ehviewer.gallery.glrenderer.GLPaint; import com.hippo.ehviewer.gallery.glrenderer.MovieTexture; import com.hippo.ehviewer.gallery.glrenderer.StringTexture; import com.hippo.ehviewer.gallery.glrenderer.UploadedTexture; import com.hippo.ehviewer.gallery.ui.GLView; import com.hippo.ehviewer.gallery.ui.GestureRecognizer; import com.hippo.ehviewer.gallery.util.GalleryUtils; import com.hippo.ehviewer.util.Config; import com.hippo.ehviewer.util.Log; import com.hippo.ehviewer.util.ThreadPool; import com.hippo.ehviewer.util.ThreadPool.Job; import com.hippo.ehviewer.util.ThreadPool.JobContext; import com.hippo.ehviewer.util.TimeRunner; import com.hippo.ehviewer.util.Ui; // TODO // TODO // TODO public class GalleryView extends GLView { @SuppressWarnings("unused") private static final String TAG = "GalleryView"; public static final int INVALID_ID = -1; private static final int STATE_FIRST = 0x1; private static final int STATE_LAST = 0x2; private static final int STATE_NONE = 0x0; // scale mode private static final int ORGIN = 0x0; private static final int FIT_WIDTH = 0x1; private static final int FIT_HEIGHT = 0x2; private static final int FIT = 0x3; private static final int FIXED = 0x4; // start position mode private static final int TOP_LEFT = 0x0; private static final int TOP_RIGHT = 0x1; private static final int BOTTOM_LEFT = 0x2; private static final int BOTTOM_RIGHT = 0x3; private static final int CENTER = 0x4; // Scroll state private static final int SCROLL_NONE = 0x0; private static final int SCROLL_LEFT = 0x1; private static final int SCROLL_RIGHT = 0x2; private static final int SCROLL_ANIME_LEFT = 0x3; private static final int SCROLL_ANIME_RIGHT = 0x4; private static final int PRE_TARGET_INDEX = 0; private static final int CUR_TARGET_INDEX = 1; private static final int NEXT_TARGET_INDEX = 2; private static final int TARGET_INDEX_SIZE = 3; // Area private static final float[] LEFT_AREA_SCALE = {0, 0, 2/7.0f, 1}; private static final float[] TOP_AREA_SCALE = {2/7.0f, 0, 5/7.0f, 3/8.0f}; private static final float[] RIGHT_AREA_SCALE = {5/7.0f, 0, 1, 1}; private static final float[] BOTTOM_AREA_SCALE = {2/7.0f, 5/8.0f, 5/7.0f, 1}; private static final float[] CENTER_AREA_SCALE = {2/7.0f, 3/8.0f, 5/7.0f, 5/8.0f}; private static final float MILLSEC_PER_DIX = 0.2f; private static final float CHANGE_PAGE_PROPORTION = 0.05f; // TODO in dip private static final float CHANGE_PAGE_OFFSET = 20; // TODO private static final float SCALE_MIN = 1/4.0f; private static final float SCALE_MAX = 4; private static final float LINE_WIDTH = Ui.dp2pix(3); private static final int LINE_COLOR = -1; // White private static final int TAP_AREA_TEXT_COLOR = -1; // White private static final int TAP_AREA_TEXT_SIZE = Ui.dp2pix(24); private static final int TAP_AREA_MASK_COLOR = 0x88000000; // TODO private static final int BACKGROUND_COLOR = Color.BLACK; @SuppressWarnings("unused") private static final int MASK_COLOR = 0x88000000; private final GestureRecognizer mGestureRecognizer; private Context mContext; private ImageSet mImageSet; private int mState; // scale and scroll only can choose one private boolean isScale = false; private int scaleMode; private int startMode; private int mScrollState = SCROLL_NONE; private int scrollXOffset = 0; private int scrollYOffset = 0; private int stopScrollXOffset = 0; @SuppressWarnings("unused") private int stopScrollYOffset = 0; private float mScale = 1; private boolean mShowEdegTip = true; private int mWidth = -1; private int mHeight = -1; // at most keep three item private ShowItem[] showItems; private int mCurIndex; private int mSize; private boolean mInit = false; private int[] leftArea; private int[] topArea; private int[] rightArea; private int[] bottomArea; private int[] centerArea; private Text leftText; private Text topText; private Text rightText; private Text bottomText; private Text centerText; private boolean mShowTapArea = false; private boolean mShowTapAreaTurn = false; private OnEdgeListener mOnEdgeListener; private OnTapTextListener mOnTapTextListener; private OnScrollPageListener mOnScrollPageListener; public interface OnEdgeListener { public void onFirstPageEdge(); public void onLastPageEdge(); } public interface OnTapTextListener { public void onTapText(int index); public void onTapDoubleText(int index); } public interface OnScrollPageListener { public void onScrollPage(int index); } public void setOnEdgeListener(OnEdgeListener l) { mOnEdgeListener = l; } public void setOnTapTextListener(OnTapTextListener l) { mOnTapTextListener = l; } public void setOnScrollPageListener(OnScrollPageListener l) { mOnScrollPageListener = l; } public GalleryView(Context context, ImageSet imageSet, int startIndex) { mContext = context; mImageSet = imageSet; mSize = imageSet.getSize(); mCurIndex = startIndex; // adjust mCurIndex if (mCurIndex < 0 || mCurIndex >= mSize) mCurIndex = 0; setState(); mGestureRecognizer = new GestureRecognizer(mContext, new MyGestureListener()); setBackgroundColor(GalleryUtils.intColorToFloatARGBArray(BACKGROUND_COLOR)); showItems = new ShowItem[TARGET_INDEX_SIZE]; // Init config scaleMode = Config.getPageScalingMode(); startMode = Config.getStartPosition(); imageSet.setOnStateChangeListener(new ImageSet.OnStateChangeListener() { @Override public void onStateChange(int index, int state) { int targetIndex = index - mCurIndex + 1; if (targetIndex >= PRE_TARGET_INDEX && targetIndex <= NEXT_TARGET_INDEX) { loadImage(index); } } }); } private void setState() { mState = STATE_NONE; if (mCurIndex == 0) mState |= STATE_FIRST; if (mCurIndex == mSize - 1) mState |= STATE_LAST; } private void drawTapArea(GLCanvas canvas) { // Background canvas.fillRect(0, 0, mWidth, mHeight, TAP_AREA_MASK_COLOR); drawRect(canvas, leftArea); drawRect(canvas, topArea); drawRect(canvas, rightArea); drawRect(canvas, bottomArea); drawRect(canvas, centerArea); leftText.draw(canvas); topText.draw(canvas); rightText.draw(canvas); bottomText.draw(canvas); centerText.draw(canvas); } private void drawRect(GLCanvas canvas, int[] rect) { int left = rect[0]; int top = rect[1]; int right = rect[2]; int bottom = rect[3]; GLPaint paint = new GLPaint(LINE_COLOR, LINE_WIDTH); canvas.drawLine(left, top, right, top, paint); canvas.drawLine(left, bottom, right, bottom, paint); canvas.drawLine(left, top, left, bottom, paint); canvas.drawLine(right, top, right, bottom, paint); } @Override protected void render(GLCanvas canvas) { super.render(canvas); boolean hasMovie = false; ShowItem item; switch (mScrollState) { case SCROLL_NONE: item = showItems[CUR_TARGET_INDEX]; if (item != null) item.draw(canvas); if (item instanceof MovieImage) hasMovie |= true; break; case SCROLL_LEFT: case SCROLL_ANIME_LEFT: item = showItems[PRE_TARGET_INDEX]; if (item != null) item.draw(canvas, scrollXOffset, scrollYOffset); if (item instanceof MovieImage) hasMovie |= true; item = showItems[CUR_TARGET_INDEX]; if (item != null) item.draw(canvas, scrollXOffset, scrollYOffset); if (item instanceof MovieImage) hasMovie |= true; break; case SCROLL_RIGHT: case SCROLL_ANIME_RIGHT: item = showItems[CUR_TARGET_INDEX]; if (item != null) item.draw(canvas, scrollXOffset, scrollYOffset); if (item instanceof MovieImage) hasMovie |= true; item = showItems[NEXT_TARGET_INDEX]; if (item != null) item.draw(canvas, scrollXOffset, scrollYOffset); if (item instanceof MovieImage) hasMovie |= true; break; } // Add mInit to make show the leftArea or other is not null if (mShowTapArea && mInit) drawTapArea(canvas); // TODO Mask to reduce brightness //canvas.fillRect(0, 0, mWidth, mHeight, MASK_COLOR); if (hasMovie) invalidate(); } private void resetSizePosition() { resetSizePosition(PRE_TARGET_INDEX); resetSizePosition(CUR_TARGET_INDEX); resetSizePosition(NEXT_TARGET_INDEX); } private void resetSizePosition(int targeIndex) { ShowItem showItem = showItems[targeIndex]; if (showItem == null) return; int sumXOffset; switch (targeIndex) { case PRE_TARGET_INDEX: sumXOffset = -mWidth; break; case NEXT_TARGET_INDEX: sumXOffset = mWidth; break; case CUR_TARGET_INDEX: default: sumXOffset = 0; break; } if (showItem instanceof Text) { Text text = (Text)showItem; int xOffset; int yOffset; Rect rect = text.mRect; xOffset = (mWidth - text.width)/2; yOffset = (mHeight - text.height)/2; rect.left = sumXOffset + xOffset; rect.top = yOffset; rect.right = rect.left + text.width; rect.bottom = rect.top + text.height; return; } if (showItem instanceof Image) { Image image = (Image)showItem; // Set scale int showWidth = 0; int showHeight = 0; Rect rect = image.mRect; switch (scaleMode) { case ORGIN: image.imageScale = 1; showWidth = image.width; showHeight = image.height; break; case FIT_WIDTH: image.imageScale = (float)mWidth/image.width; showWidth = mWidth; showHeight = (int)(image.height * image.imageScale); break; case FIT_HEIGHT: image.imageScale = (float)mHeight/image.height; showWidth = (int)(image.width * image.imageScale); showHeight = mHeight; break; case FIT: float scaleX = (float)mWidth/image.width; float scaleY = (float)mHeight/image.height; if (scaleX < scaleY) { image.imageScale = scaleX; showWidth = mWidth; showHeight = (int)(image.height * image.imageScale); } else { image.imageScale = scaleY; showWidth = (int)(image.width * image.imageScale); showHeight = mHeight; break; } break; case FIXED: default: image.imageScale = mScale; showWidth = (int)(image.width * mScale); showHeight = (int)(image.height * mScale); break; } // adjust scale if (image.imageScale < SCALE_MIN) { image.imageScale = SCALE_MIN; showWidth = (int)(image.width * SCALE_MIN); showHeight = (int)(image.height * SCALE_MIN); } else if (image.imageScale > SCALE_MAX) { image.imageScale = SCALE_MAX; showWidth = (int)(image.width * SCALE_MAX); showHeight = (int)(image.height * SCALE_MAX); } // set start position int xOffset; int yOffset; switch (startMode) { case TOP_LEFT: xOffset = 0; yOffset = 0; break; case TOP_RIGHT: xOffset = mWidth - showWidth; yOffset = 0; break; case BOTTOM_LEFT: xOffset = 0; yOffset = mHeight - showHeight; break; case BOTTOM_RIGHT: xOffset = mWidth - showWidth; yOffset = mHeight - showHeight; break; case CENTER: default: xOffset = (mWidth - showWidth)/2; yOffset = (mHeight - showHeight)/2; break; } rect.left = sumXOffset + xOffset; rect.right = rect.left + showWidth; rect.top = yOffset; rect.bottom = rect.top + showHeight; // adjust position adjustPosition(image); } invalidate(); } private void setCenterInArea(int[] area, ShowItem showItem) { int xOffset = ((area[2] - area[0]) - showItem.width)/2; int yOffset = ((area[3] - area[1]) - showItem.height)/2; Rect rect = showItem.mRect; rect.left = area[0] + xOffset; rect.right = rect.left + showItem.width; rect.top = area[1] + yOffset; rect.bottom = rect.top + showItem.height; } private void setTapArea() { leftArea = new int[]{ (int)(LEFT_AREA_SCALE[0] * mWidth), (int)(LEFT_AREA_SCALE[1] * mHeight), (int)(LEFT_AREA_SCALE[2] * mWidth), (int)(LEFT_AREA_SCALE[3] * mHeight)}; topArea = new int[]{ (int)(TOP_AREA_SCALE[0] * mWidth), (int)(TOP_AREA_SCALE[1] * mHeight), (int)(TOP_AREA_SCALE[2] * mWidth), (int)(TOP_AREA_SCALE[3] * mHeight)}; rightArea = new int[]{ (int)(RIGHT_AREA_SCALE[0] * mWidth), (int)(RIGHT_AREA_SCALE[1] * mHeight), (int)(RIGHT_AREA_SCALE[2] * mWidth), (int)(RIGHT_AREA_SCALE[3] * mHeight)}; bottomArea = new int[]{ (int)(BOTTOM_AREA_SCALE[0] * mWidth), (int)(BOTTOM_AREA_SCALE[1] * mHeight), (int)(BOTTOM_AREA_SCALE[2] * mWidth), (int)(BOTTOM_AREA_SCALE[3] * mHeight)}; centerArea = new int[]{ (int)(CENTER_AREA_SCALE[0] * mWidth), (int)(CENTER_AREA_SCALE[1] * mHeight), (int)(CENTER_AREA_SCALE[2] * mWidth), (int)(CENTER_AREA_SCALE[3] * mHeight)}; if (leftText == null) leftText = new Text(mContext.getString(R.string.pre_page), TAP_AREA_TEXT_SIZE, TAP_AREA_TEXT_COLOR); if (topText == null) topText = new Text(mContext.getString(R.string.zoom_in), TAP_AREA_TEXT_SIZE, TAP_AREA_TEXT_COLOR); if (rightText == null) rightText = new Text(mContext.getString(R.string.next_page), TAP_AREA_TEXT_SIZE, TAP_AREA_TEXT_COLOR); if (bottomText == null) bottomText = new Text(mContext.getString(R.string.zoom_out), TAP_AREA_TEXT_SIZE, TAP_AREA_TEXT_COLOR); if (centerText == null) centerText = new Text(mContext.getString(R.string.menu), TAP_AREA_TEXT_SIZE, TAP_AREA_TEXT_COLOR); setCenterInArea(leftArea, leftText); setCenterInArea(topArea, topText); setCenterInArea(rightArea, rightText); setCenterInArea(bottomArea, bottomText); setCenterInArea(centerArea, centerText); } @Override protected void onLayout( boolean changeSize, int left, int top, int right, int bottom) { mWidth = right - left; mHeight = bottom - top; if (!mInit) { mInit = true; loadImage(mCurIndex); if ((mState & STATE_LAST) == 0) loadImage(mCurIndex + 1); if ((mState & STATE_FIRST) == 0) loadImage(mCurIndex - 1); } else { resetSizePosition(); } setTapArea(); invalidate(); } private void loadImage(int index) { int targetIndex = index - mCurIndex + 1; int state = mImageSet.getImage(index, new DecodeImageListener()); ShowItem showItem = showItems[targetIndex]; if (showItem != null) showItem.recycle(); if (state == ImageSet.STATE_LOADED) showItems[targetIndex] = new EmptyItem(); else { showItems[targetIndex] = new Text(getErrorStateString(state)); } resetSizePosition(targetIndex); } private String getErrorStateString(int state) { switch (state) { case ImageSet.INVALID_ID: return " index"; case ImageSet.STATE_NONE: return ""; case ImageSet.STATE_LOADING: return ""; case ImageSet.STATE_FAIL: return ""; default: return ""; } } /** * If cur page is first page return true * @return */ private boolean isFirstPage() { return (mState & STATE_FIRST) != 0; } /** * If cur page is last page return true * @return */ private boolean isLastPage() { return (mState & STATE_LAST) != 0; } class DecodeImageListener implements ImageSet.OnDecodeOverListener { @Override public void onDecodeOver(Object res, int index) { int targetIndex = index - mCurIndex + 1; if (targetIndex < 0 || targetIndex > 2 || !(showItems[targetIndex] instanceof EmptyItem)) {// If it do not need any more if (res != null && res instanceof Bitmap) ((Bitmap)res).recycle(); } else { if (res == null) { showItems[targetIndex] = new Text(""); // TODO } else { if (res instanceof Bitmap) { BitmapImage bi = new BitmapImage(); bi.load((Bitmap)res); showItems[targetIndex] = bi; } else { MovieImage mi = new MovieImage(); mi.load((Movie)res); showItems[targetIndex] = mi; } } resetSizePosition(targetIndex); } } } /** * * @param mode * true zoom in, false zoom out * @return */ private boolean zoom(boolean mode) { ShowItem curShowItem; curShowItem = showItems[CUR_TARGET_INDEX]; if (curShowItem == null || !(curShowItem instanceof Image)) return false; Image image = (Image)curShowItem; float newScale; if (mode) { newScale = image.imageScale * 1.1f; if (newScale == SCALE_MAX) return false; if (newScale > SCALE_MAX) newScale = SCALE_MAX; } else { newScale = image.imageScale * 0.9f; if (newScale == SCALE_MIN) return false; if (newScale < SCALE_MIN) newScale = SCALE_MIN; } image.imageScale = newScale; mScale = newScale; Rect rect = image.mRect; int width = (int)(image.width * newScale); int height = (int)(image.height * newScale); int xOffset = (width - rect.width())/2; int yOffset = (height - rect.height())/2; rect.set(rect.left - xOffset, rect.top - yOffset, rect.right + xOffset, rect.bottom + yOffset); adjustPosition(curShowItem); invalidate(); return true; } /** * You'd better resetSizePosition(PRE_TARGET_INDEX) before * @return */ private boolean goToPrePage() { if (isFirstPage()) return false; ShowItem showItem; showItem = showItems[NEXT_TARGET_INDEX]; if (showItem != null) showItem.recycle(); showItems[NEXT_TARGET_INDEX] = showItems[CUR_TARGET_INDEX]; showItems[CUR_TARGET_INDEX] = showItems[PRE_TARGET_INDEX]; showItems[PRE_TARGET_INDEX] = null; // adjust rect showItem = showItems[NEXT_TARGET_INDEX]; if (showItem != null) { showItem.mRect.offset(mWidth, 0); } showItem = showItems[CUR_TARGET_INDEX]; if (showItem != null) { showItem.mRect.offset(mWidth, 0); } mCurIndex setState(); loadImage(mCurIndex-1); if (mOnScrollPageListener != null) { mOnScrollPageListener.onScrollPage(mCurIndex); } invalidate(); return true; } /** * You'd better resetSizePosition(NEXT_TARGET_INDEX) before * @return */ private boolean goToNextPage() { if (isLastPage()) return false; ShowItem showItem; showItem = showItems[PRE_TARGET_INDEX]; if (showItem != null) showItem.recycle(); showItems[PRE_TARGET_INDEX] = showItems[CUR_TARGET_INDEX]; showItems[CUR_TARGET_INDEX] = showItems[NEXT_TARGET_INDEX]; showItems[NEXT_TARGET_INDEX] = null; // adjust rect showItem = showItems[PRE_TARGET_INDEX]; if (showItem != null) { showItem.mRect.offset(-mWidth, 0); } showItem = showItems[CUR_TARGET_INDEX]; if (showItem != null) { showItem.mRect.offset(-mWidth, 0); } mCurIndex++; setState(); loadImage(mCurIndex+1); if (mOnScrollPageListener != null) { mOnScrollPageListener.onScrollPage(mCurIndex); } invalidate(); return true; } @Override protected boolean onTouch(MotionEvent event) { mGestureRecognizer.onTouchEvent(event); return true; } private class MyGestureListener implements GestureRecognizer.Listener { public MyGestureListener() { mToPreTimeRunner.setOnTimerListener(new TimeRunner.OnTimeListener() { @Override public void onStart() {} @Override public void onEnd() { scrollXOffset = 0; goToPrePage(); mScrollState = SCROLL_NONE; } }); mToNextTimeRunner.setOnTimerListener(new TimeRunner.OnTimeListener() { @Override public void onStart() {} @Override public void onEnd() { scrollXOffset = 0; goToNextPage(); mScrollState = SCROLL_NONE; } }); mReturnTimeRunner.setOnTimerListener(new TimeRunner.OnTimeListener() { @Override public void onStart() {} @Override public void onEnd() { scrollXOffset = 0; mScrollState = SCROLL_NONE; invalidate(); } }); } private boolean isInArea(int[] area, int x, int y) { if (area.length != 4) throw new IllegalArgumentException( "area's length should be 4, but it's length is " + area.length); if (x >= area[0] && x < area[2] && y >= area[1] && y < area[3]) return true; else return false; } @Override public boolean onSingleTapConfirmed(float x, float y) { if (mScrollState != SCROLL_NONE) { return false; } if (mShowTapAreaTurn) { mShowTapAreaTurn = false; return false; } if ( showItems[CUR_TARGET_INDEX] == null || showItems[CUR_TARGET_INDEX] instanceof Text) { if (mOnTapTextListener != null) mOnTapTextListener.onTapText(mCurIndex); //return true; } if (leftArea == null || topArea == null || rightArea == null || bottomArea == null || centerArea == null) return true; if (isInArea(leftArea, (int)x, (int)y)) { // TODO goto bottom first the to pre page resetSizePosition(PRE_TARGET_INDEX); if (!goToPrePage() && mOnEdgeListener != null) mOnEdgeListener.onFirstPageEdge(); } else if (isInArea(topArea, (int)x, (int)y)) { zoom(true); } else if (isInArea(rightArea, (int)x, (int)y)) { // TODO goto bottom first the to pre page resetSizePosition(NEXT_TARGET_INDEX); if (!goToNextPage() && mOnEdgeListener != null) mOnEdgeListener.onLastPageEdge(); } else if (isInArea(bottomArea, (int)x, (int)y)) { zoom(false); } else if (isInArea(centerArea, (int)x, (int)y)) { mShowTapArea = true; mShowTapAreaTurn = true; invalidate(); } else { // Can't catch tap } return true; } @Override public boolean onDoubleTap(float x, float y) { Log.d(TAG, "onDoubleTap"); return true; } @Override public void onLongPress(MotionEvent e) { // TODO Auto-generated method stub } @Override public boolean onScrollBegin(float dx, float dy, float totalX, float totalY) { return this.onScroll(dx, dy, totalX, totalY); } /** * dx totalX */ @Override public boolean onScroll(float dx, float dy, float totalX, float totalY) { if (isScale) return false; ShowItem curShowItem = showItems[CUR_TARGET_INDEX]; if (curShowItem == null) // If not load now return true; switch(mScrollState) { case SCROLL_ANIME_LEFT: case SCROLL_ANIME_RIGHT: return false; case SCROLL_NONE: boolean changePage = false; Rect rect = curShowItem.mRect; // Check change page or not if (curShowItem == null || !(curShowItem instanceof Image)) changePage = true; else{ if ( Math.abs(totalX/totalY) > 1 && ((totalX > CHANGE_PAGE_OFFSET && dx < 0 && rect.left >= 0) || (totalX < -CHANGE_PAGE_OFFSET && dx > 0 && rect.right <= mWidth))) changePage = true; } if (changePage) { // If change page if (dx < 0) { // Go to left if (!isFirstPage()) { // Not first page scrollXOffset = 0; mScrollState = SCROLL_LEFT; resetSizePosition(PRE_TARGET_INDEX); } else { changePage = false; if (mShowEdegTip) { // First page mShowEdegTip = false; if (mOnEdgeListener != null) mOnEdgeListener.onFirstPageEdge(); } } } else { // Go to righ if (!isLastPage()) { // Not last page scrollXOffset = 0; mScrollState = SCROLL_RIGHT; resetSizePosition(NEXT_TARGET_INDEX); } else { changePage = false; if (mShowEdegTip) { // last page mShowEdegTip = false; if (mOnEdgeListener != null) mOnEdgeListener.onLastPageEdge(); } } } } if (!changePage){ // Move cur image int actDx = -(int)dx; int actDy = -(int)dy; if (rect.width() <= mWidth) actDx = 0; if (rect.height() <= mHeight) actDy = 0; rect.offset(actDx, actDy); // Fix position adjustPosition(curShowItem); } break; case SCROLL_LEFT: scrollXOffset -= dx; if (scrollXOffset <= 0) { scrollXOffset = 0; mScrollState = SCROLL_NONE; } break; case SCROLL_RIGHT: scrollXOffset -= dx; if (scrollXOffset >= 0) { scrollXOffset = 0; mScrollState = SCROLL_NONE; } break; } invalidate(); return true; } @Override public boolean onScrollEnd() { if (isScale) return false; switch(mScrollState) { case SCROLL_ANIME_LEFT: case SCROLL_ANIME_RIGHT: return false; case SCROLL_LEFT: stopScrollXOffset = scrollXOffset; stopScrollYOffset = scrollYOffset; mScrollState = SCROLL_ANIME_LEFT; if (stopScrollXOffset > mWidth * CHANGE_PAGE_PROPORTION) { // Go to pre page mToPreTimeRunner.setDuration((int)(MILLSEC_PER_DIX * (mWidth-stopScrollXOffset))); mToPreTimeRunner.start(); } else { mReturnTimeRunner.setDuration((int)(MILLSEC_PER_DIX * stopScrollXOffset)); mReturnTimeRunner.start(); } break; case SCROLL_RIGHT: stopScrollXOffset = scrollXOffset; stopScrollYOffset = scrollYOffset; mScrollState = SCROLL_ANIME_RIGHT; if (-stopScrollXOffset > mWidth * CHANGE_PAGE_PROPORTION) { // Go to next page mToNextTimeRunner.setDuration((int)(MILLSEC_PER_DIX * (mWidth+stopScrollXOffset))); mToNextTimeRunner.start(); } else { mReturnTimeRunner.setDuration((int)(MILLSEC_PER_DIX * -stopScrollXOffset)); mReturnTimeRunner.start(); } break; } return true; } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { return true; } @Override public boolean onScaleBegin(float focusX, float focusY) { isScale = true; return true; } @Override public boolean onScale(float focusX, float focusY, float scale) { if (mScrollState == SCROLL_ANIME_LEFT || mScrollState == SCROLL_ANIME_RIGHT) return true; if (mScrollState == SCROLL_LEFT || mScrollState == SCROLL_RIGHT) { scrollXOffset = 0; scrollYOffset = 0; mScrollState = SCROLL_NONE; } ShowItem curShowItem = showItems[CUR_TARGET_INDEX]; if (curShowItem == null || !(curShowItem instanceof Image)) return true; Image image = (Image)curShowItem; float newScale = image.imageScale * scale; if (newScale > SCALE_MAX || newScale < SCALE_MIN) return true; image.imageScale = newScale; mScale = newScale; Rect rect = image.mRect; int left = rect.left; int top = rect.top; left = (int)(focusX - ((focusX - left) * scale)); top = (int)(focusY - ((focusY - top) * scale)); rect.set(left, top, (int)(left + (image.width * image.imageScale)), (int)(top + (image.height * image.imageScale))); // adjust adjustPosition(image); invalidate(); return true; } @Override public void onScaleEnd() { isScale = false; } @Override public void onDown(float x, float y) { mShowTapArea = false; invalidate(); } @Override public void onUp() { mShowEdegTip = true; // if use onSingleTapUp, use below /* * if (mShowTapAreaTurn) { mShowTapAreaTurn = false; */ } TimeRunner mToPreTimeRunner = new TimeRunner() { @Override protected void run(float interpolatedTime, int runningTime) { scrollXOffset = (int)(stopScrollXOffset + ((mWidth - stopScrollXOffset) * interpolatedTime)); invalidate(); } }; TimeRunner mToNextTimeRunner = new TimeRunner() { @Override protected void run(float interpolatedTime, int runningTime) { scrollXOffset = (int)(stopScrollXOffset + ((-mWidth - stopScrollXOffset) * interpolatedTime)); invalidate(); } }; TimeRunner mReturnTimeRunner = new TimeRunner() { @Override protected void run(float interpolatedTime, int runningTime) { scrollXOffset = (int)((1 - interpolatedTime) * stopScrollXOffset); invalidate(); } }; } /** * If side is shorter then parent's, make it in parent's center * If side is longer then parent's, make sure it fill parent * * @param showItem */ private void adjustPosition(ShowItem showItem) { Rect rect = showItem.mRect; int showWidth = rect.width(); int showHeight = rect.height(); int sumXOffset; int sumYOffset = 0; int targetIndex = getTargetIndex(showItem); switch (targetIndex) { case PRE_TARGET_INDEX: sumXOffset = -mWidth; break; case NEXT_TARGET_INDEX: sumXOffset = mWidth; break; case CUR_TARGET_INDEX: default: sumXOffset = 0; } if (showWidth > mWidth) { int fixXOffset = rect.left - sumXOffset; if (fixXOffset > 0) { rect.left -= fixXOffset; rect.right -= fixXOffset; } else if ((fixXOffset = sumXOffset + mWidth - rect.right) > 0) { rect.left += fixXOffset; rect.right += fixXOffset; } } else { int left = sumXOffset + (mWidth - showWidth) / 2; rect.offsetTo(left, rect.top); } if (showHeight > mHeight) { int fixYOffset = rect.top - sumYOffset; if (fixYOffset > 0) { rect.top -= fixYOffset; rect.bottom -= fixYOffset; } else if ((fixYOffset = sumYOffset + mHeight - rect.bottom) > 0) { rect.top += fixYOffset; rect.bottom += fixYOffset; } } else { int top = sumYOffset + (mHeight - showHeight) / 2; rect.offsetTo(rect.left, top); } } public int getTargetIndex(ShowItem showItem) { if (mImageSet == null) return INVALID_ID; for (int i = 0; i < TARGET_INDEX_SIZE; i++) { if (showItem == showItems[i]) return i; } return INVALID_ID; } private abstract class ShowItem { protected int width = 1; protected int height = 1; public Rect mRect = new Rect(); public void draw(GLCanvas canvas) { this.draw(canvas, 0, 0); } public abstract void draw(GLCanvas canvas, int xOffset, int yOffset); public abstract void recycle(); } private class EmptyItem extends ShowItem{ private ColorTexture mTexture; public EmptyItem() { mTexture = new ColorTexture(BACKGROUND_COLOR); } @Override public void recycle() { mTexture = null; } @Override public void draw(GLCanvas canvas, int xOffset, int yOffset) { mTexture.draw(canvas, xOffset, yOffset); } } private abstract class Image extends ShowItem{ private UploadedTexture mTexture; public float imageScale = 1; /** * You must call init before draw * @param texture */ public void init(UploadedTexture texture) { mTexture = texture; imageScale = 1; } @Override public void draw(GLCanvas canvas, int xOffset, int yOffset) { if (mTexture != null) { int targetIndex; if ((targetIndex = getTargetIndex(this)) == INVALID_ID) mTexture.draw(canvas, mRect.left + xOffset, mRect.top + yOffset, mRect.width(), mRect.height()); else { int leftBound = mWidth; int topBound = 0; int rightBound = 2 * mWidth; int bottomBound = mHeight; switch (targetIndex) { case PRE_TARGET_INDEX: leftBound = -leftBound; rightBound = 0; break; case CUR_TARGET_INDEX: rightBound = leftBound; leftBound = 0; break; case NEXT_TARGET_INDEX: default: break; } int left = mRect.left; int top = mRect.top; int right = mRect.right; int bottom = mRect.bottom; // Only show what in the own box // TODO only what can be seen if (left < leftBound || top < topBound || right > rightBound || bottom > bottomBound) { RectF source = new RectF(); RectF target = new RectF(); if (left < leftBound) { target.left = leftBound; source.left = (leftBound - left) / imageScale; } else { target.left = left; source.left = 0; } if (top < topBound) { target.top = topBound; source.top = (topBound - top) / imageScale; } else { target.top = top; source.top = 0; } if (right > rightBound) { target.right = rightBound; source.right = width - ((right - rightBound) / imageScale); } else { target.right = right; source.right = width; } if (bottom > bottomBound) { target.bottom = bottomBound; source.bottom = height - ((bottom - bottomBound) / imageScale); } else { target.bottom = bottom; source.bottom = height; } target.left += xOffset; target.top += yOffset; target.right += xOffset; target.bottom += yOffset; mTexture.draw(canvas, source, target); } else { mTexture.draw(canvas, left + xOffset, top + yOffset, right - left, bottom - top); } } } } } private class BitmapImage extends Image{ private BitmapTexture mTexture; private Bitmap mContextBmp; public void load(Bitmap bmp) { if (mTexture != null) recycle(); mContextBmp = bmp; mTexture = new BitmapTexture(bmp); width = mContextBmp.getWidth(); height = mContextBmp.getHeight(); super.init(mTexture); } @Override public void recycle() { if (mTexture == null) return; mTexture.recycle(); mContextBmp.recycle(); mTexture = null; mContextBmp = null; } } private class MovieImage extends Image{ private MovieTexture mTexture; private Movie mContextMovie; public void load(Movie movie) { if (mTexture != null) recycle(); mContextMovie = movie; mTexture = MovieTexture.newInstance(mContextMovie); width = mContextMovie.width(); height = mContextMovie.height(); super.init(mTexture); } @Override public void recycle() { if (mTexture == null) return; mTexture.recycle(); mTexture = null; mContextMovie = null; } } private class Text extends ShowItem{ private StringTexture mTexture; public Text(String str) { load(str); } public Text(String str, float size, int color) { load(str, size, color); } public void load(String str) { load(str, 100, -1); } public void load(String str, float size, int color) { if (mTexture != null) recycle(); mTexture = StringTexture.newInstance(str, size, color); width = mTexture.getWidth(); height = mTexture.getHeight(); } @Override public void draw(GLCanvas canvas, int xOffset, int yOffset) { if (mTexture != null) mTexture.draw(canvas, mRect.left + xOffset, mRect.top + yOffset); } @Override public void recycle() { if (mTexture == null) return; mTexture.recycle(); } } }
package com.rubber.services; import com.sun.javafx.Utils; import javax.swing.JFrame; /** * * @author Iegor */ public class EnvironmentService extends JFrame implements IServiceEvent { @Override public void invoke() { if(Utils.isUnix() || Utils.isMac()) javax.swing.JOptionPane.showMessageDialog(this, "The linux and mac versions of this program are in a experimental phase.\nIf you continue with the execution of this program will be your responsability.", "Notice", javax.swing.JOptionPane.INFORMATION_MESSAGE); } }
package pt.uminho.ceb.biosystems.mew.core.strainoptimization.controlcenter; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; import org.junit.Assert; import org.junit.Test; import pt.uminho.ceb.biosystems.jecoli.algorithm.components.terminationcriteria.ITerminationCriteria; import pt.uminho.ceb.biosystems.jecoli.algorithm.components.terminationcriteria.NumFunctionEvaluationsListenerHybridTerminationCriteria; import pt.uminho.ceb.biosystems.mew.biocomponents.container.Container; import pt.uminho.ceb.biosystems.mew.biocomponents.container.io.readers.JSBMLReader; import pt.uminho.ceb.biosystems.mew.core.criticality.CriticalReactions; import pt.uminho.ceb.biosystems.mew.core.model.converters.ContainerConverter; import pt.uminho.ceb.biosystems.mew.core.model.steadystatemodel.ISteadyStateModel; import pt.uminho.ceb.biosystems.mew.core.model.steadystatemodel.SteadyStateModel; import pt.uminho.ceb.biosystems.mew.core.simulation.components.FluxValueMap; import pt.uminho.ceb.biosystems.mew.core.simulation.components.GeneticConditions; import pt.uminho.ceb.biosystems.mew.core.simulation.components.ReactionChangesList; import pt.uminho.ceb.biosystems.mew.core.simulation.components.SimulationProperties; import pt.uminho.ceb.biosystems.mew.core.simulation.components.SimulationSteadyStateControlCenter; import pt.uminho.ceb.biosystems.mew.core.simulation.components.SteadyStateSimulationResult; import pt.uminho.ceb.biosystems.mew.core.strainoptimization.configuration.GenericOptimizationProperties; import pt.uminho.ceb.biosystems.mew.core.strainoptimization.objectivefunctions.IObjectiveFunction; import pt.uminho.ceb.biosystems.mew.core.strainoptimization.objectivefunctions.ofs.BPCYObjectiveFunction; import pt.uminho.ceb.biosystems.mew.core.strainoptimization.optimizationresult.simplification.IStrainOptimizationResultsSimplifier; import pt.uminho.ceb.biosystems.mew.core.strainoptimization.optimizationresult.simplification.StrainOptimizationSimplificationFactory; import pt.uminho.ceb.biosystems.mew.core.strainoptimization.optimizationresult.solution.GOUSolution; import pt.uminho.ceb.biosystems.mew.core.strainoptimization.optimizationresult.solution.RKSolution; import pt.uminho.ceb.biosystems.mew.core.strainoptimization.optimizationresult.solution.ROUSolution; import pt.uminho.ceb.biosystems.mew.core.strainoptimization.optimizationresult.solutionset.GOUSolutionSet; import pt.uminho.ceb.biosystems.mew.core.strainoptimization.optimizationresult.solutionset.RKSolutionSet; import pt.uminho.ceb.biosystems.mew.core.strainoptimization.optimizationresult.solutionset.ROUSolutionSet; import pt.uminho.ceb.biosystems.mew.core.strainoptimization.strainoptimizationalgorithms.jecoli.JecoliGenericConfiguration; import pt.uminho.ceb.biosystems.mew.core.strainoptimization.strainoptimizationalgorithms.jecoli.JecoliOptimizationProperties; import pt.uminho.ceb.biosystems.mew.solvers.SolverType; import pt.uminho.ceb.biosystems.mew.solvers.lp.CplexParamConfiguration; import pt.uminho.ceb.biosystems.mew.utilities.datastructures.map.indexedhashmap.IndexedHashMap; /** * * @author hgiesteira * */ public class AnotherStrainOptimizationControlCenterTest { @Test public void testUOZeroFluxesException() throws Exception { SolverType solverToUse = SolverType.CPLEX3; URL nyData = getClass().getClassLoader().getResource("models/ecoli_core_model.xml"); CplexParamConfiguration.setDoubleParam("EpRHS", 1e-9); JSBMLReader reader = new JSBMLReader(nyData.getFile(), "1", false); Container cont = new Container(reader); Set<String> met = cont.identifyMetabolitesIdByPattern(Pattern.compile(".*_b")); cont.removeMetabolites(met); ISteadyStateModel model = (SteadyStateModel) ContainerConverter.convert(cont); StrainOptimizationControlCenter cc = new StrainOptimizationControlCenter(); ITerminationCriteria termination = new NumFunctionEvaluationsListenerHybridTerminationCriteria(10000); CriticalReactions cr = new CriticalReactions(model, null, solverToUse); cr.identifyCriticalReactions(); cr.setDrainReactionsAsCritical(); cr.setTransportReactionsAsCritical(); FluxValueMap wtReference = SimulationProperties.simulateWT(model, null, solverToUse); Set<String> allZeroFluxes = new HashSet<String>(); for (String flux : wtReference.keySet()) { if(wtReference.get(flux) == 0.0){ allZeroFluxes.add(flux); } } IndexedHashMap<IObjectiveFunction, String> objFunctions = new IndexedHashMap<IObjectiveFunction, String>(); BPCYObjectiveFunction objFunc1 = new BPCYObjectiveFunction(model.getBiomassFlux(), "R_EX_succ_e", "R_EX_glc_e"); objFunctions.put(objFunc1, SimulationProperties.PFBA + "T"); Map<String, Map<String, Object>> simulationConfiguration = new HashMap<>(); Map<String, Double> of = new HashMap<>(); of.put(model.getBiomassFlux(), 1.0); // FBA Map<String, Object> methodConf = new HashMap<>(); methodConf.put(SimulationProperties.METHOD_ID, SimulationProperties.PFBA); methodConf.put(SimulationProperties.MODEL, model); methodConf.put(SimulationProperties.IS_MAXIMIZATION, true); methodConf.put(SimulationProperties.SOLVER, solverToUse); methodConf.put(SimulationProperties.OVERUNDER_2STEP_APPROACH, true); methodConf.put(SimulationProperties.IS_OVERUNDER_SIMULATION, true); // methodConf.put(SimulationProperties.OBJECTIVE_FUNCTION, of); // methodConf.put(SimulationProperties.ENVIRONMENTAL_CONDITIONS, envCond); // methodConf.put(SimulationProperties.GENETIC_CONDITIONS,new GeneticConditions(new ReactionChangesList())); simulationConfiguration.put(SimulationProperties.PFBA + "T", methodConf); JecoliGenericConfiguration jecoliConf = new JecoliGenericConfiguration(); jecoliConf.setProperty(GenericOptimizationProperties.OPTIMIZATION_STRATEGY, "ROU"); jecoliConf.setProperty(GenericOptimizationProperties.OPTIMIZATION_ALGORITHM, "SPEA2"); jecoliConf.setProperty(JecoliOptimizationProperties.IS_VARIABLE_SIZE_GENOME, true); jecoliConf.setProperty(GenericOptimizationProperties.STEADY_STATE_MODEL, model); jecoliConf.setProperty(JecoliOptimizationProperties.TERMINATION_CRITERIA, termination); jecoliConf.setProperty(GenericOptimizationProperties.MAP_OF2_SIM, objFunctions); jecoliConf.setProperty(GenericOptimizationProperties.SIMULATION_CONFIGURATION, simulationConfiguration); jecoliConf.setProperty(GenericOptimizationProperties.MAX_SET_SIZE, 6); jecoliConf.setProperty(GenericOptimizationProperties.IS_OVER_UNDER_EXPRESSION, true); // jecoliConf.setProperty(GenericOptimizationProperties.NOT_ALLOWED_IDS, cr.getCriticalReactionIds()); ROUSolutionSet<JecoliGenericConfiguration> rouSolutionSet = (ROUSolutionSet) cc.execute(jecoliConf); StrainOptimizationSimplificationFactory simpFactory = new StrainOptimizationSimplificationFactory(); IStrainOptimizationResultsSimplifier simplifier = simpFactory.getSimplifierInstance("ROU", jecoliConf); ROUSolutionSet<JecoliGenericConfiguration> newROUSolutionSet = (ROUSolutionSet<JecoliGenericConfiguration>) simplifier.getSimplifiedResultSetDiscardRepeated(rouSolutionSet); ArrayList<ROUSolution> solutionList = (ArrayList<ROUSolution>) newROUSolutionSet.getResultList(); // System.out.println("Number of solutions:" +solutionList.size()); HashMap<String, List<Double>> fluxesFromOptimization = new HashMap<String, List<Double>>(); for (int i = 0; i < solutionList.size(); i++) { GeneticConditions geneCond = solutionList.get(i).getGeneticConditions(); // System.out.println(geneCond + "\t" + solutionList.get(i).getAttributes()); for (String reaction : geneCond.getReactionList().keySet()) { List<Double> values = new ArrayList<>(); if(fluxesFromOptimization.containsKey(reaction)) values = fluxesFromOptimization.get(reaction); values.add(geneCond.getReactionList().get(reaction).doubleValue()); fluxesFromOptimization.put(reaction, values); } } boolean solutionContainsZero = false; for (String flux : fluxesFromOptimization.keySet()) { if(allZeroFluxes.contains(flux)){ System.err.println("Reaction: " + flux + "\tValues: " + fluxesFromOptimization.get(flux)); for (Double d : fluxesFromOptimization.get(flux)) { if(d != 0.0){ System.out.println("Reaction: " + flux + "\tValue: " + d); solutionContainsZero = true; } } } } Assert.assertEquals("There are wt zero fluxes that are suggested as modifications", false, solutionContainsZero); } @Test public void testUOMultipleReferencesException() throws Exception { SolverType solverToUse = SolverType.CPLEX3; URL nyData = getClass().getClassLoader().getResource("models/ecoli_core_model.xml"); CplexParamConfiguration.setDoubleParam("EpRHS", 1e-9); JSBMLReader reader = new JSBMLReader(nyData.getFile(), "1", false); Container cont = new Container(reader); Set<String> met = cont.identifyMetabolitesIdByPattern(Pattern.compile(".*_b")); cont.removeMetabolites(met); ISteadyStateModel model = (SteadyStateModel) ContainerConverter.convert(cont); StrainOptimizationControlCenter cc = new StrainOptimizationControlCenter(); ITerminationCriteria termination = new NumFunctionEvaluationsListenerHybridTerminationCriteria(5000); // CriticalReactions cr = new CriticalReactions(model, null, solverToUse); // cr.identifyCriticalReactions(); // cr.setDrainReactionsAsCritical(); // cr.setTransportReactionsAsCritical(); // FluxValueMap wtReference = SimulationProperties.simulateWT(model, null, solverToUse); // Set<String> allZeroFluxes = new HashSet<String>(); // for (String flux : wtReference.keySet()) { // if(wtReference.get(flux) == 0.0){ // allZeroFluxes.add(flux); IndexedHashMap<IObjectiveFunction, String> objFunctions = new IndexedHashMap<IObjectiveFunction, String>(); BPCYObjectiveFunction objFunc1 = new BPCYObjectiveFunction(model.getBiomassFlux(), "R_EX_succ_e", "R_EX_glc_e"); // NumKnockoutsObjectiveFunction objFunc2 = new NumKnockoutsObjectiveFunction(false); // objFunctions.put(objFunc1, SimulationProperties.FBA + "T"); objFunctions.put(objFunc1, SimulationProperties.MOMA + "T"); Map<String, Map<String, Object>> simulationConfiguration = new HashMap<>(); Map<String, Double> of = new HashMap<>(); of.put(model.getBiomassFlux(), 1.0); SimulationSteadyStateControlCenter simCC = new SimulationSteadyStateControlCenter(null, null, model, SimulationProperties.PFBA); simCC.setMaximization(true); simCC.setSolver(solverToUse); // FBA Map<String, Object> methodConfFBA1 = new HashMap<>(); methodConfFBA1.put(SimulationProperties.METHOD_ID, SimulationProperties.FBA); methodConfFBA1.put(SimulationProperties.MODEL, model); methodConfFBA1.put(SimulationProperties.IS_MAXIMIZATION, true); methodConfFBA1.put(SimulationProperties.SOLVER, solverToUse); methodConfFBA1.put(SimulationProperties.OVERUNDER_2STEP_APPROACH, true); methodConfFBA1.put(SimulationProperties.IS_OVERUNDER_SIMULATION, true); // methodConf.put(SimulationProperties.OBJECTIVE_FUNCTION, of); // methodConf.put(SimulationProperties.GENETIC_CONDITIONS,new GeneticConditions(new ReactionChangesList())); // simulationConfiguration.put(SimulationProperties.FBA + "T", methodConfFBA1); Map<String, Object> methodConfMOMA1 = new HashMap<>(); methodConfMOMA1.put(SimulationProperties.METHOD_ID, SimulationProperties.ROOM); methodConfMOMA1.put(SimulationProperties.MODEL, model); methodConfMOMA1.put(SimulationProperties.IS_MAXIMIZATION, true); methodConfMOMA1.put(SimulationProperties.SOLVER, solverToUse); // methodConfMOMA1.put(SimulationProperties.OVERUNDER_2STEP_APPROACH, true); methodConfMOMA1.put(SimulationProperties.IS_OVERUNDER_SIMULATION, true); // methodConf.put(SimulationProperties.OBJECTIVE_FUNCTION, of); // methodConf.put(SimulationProperties.GENETIC_CONDITIONS,new GeneticConditions(new ReactionChangesList())); simulationConfiguration.put(SimulationProperties.MOMA + "T", methodConfMOMA1); JecoliGenericConfiguration jecoliConf = new JecoliGenericConfiguration(); jecoliConf.setProperty(GenericOptimizationProperties.OPTIMIZATION_STRATEGY, "ROU"); jecoliConf.setProperty(GenericOptimizationProperties.OPTIMIZATION_ALGORITHM, "SPEA2"); jecoliConf.setProperty(JecoliOptimizationProperties.IS_VARIABLE_SIZE_GENOME, true); jecoliConf.setProperty(GenericOptimizationProperties.STEADY_STATE_MODEL, model); jecoliConf.setProperty(JecoliOptimizationProperties.TERMINATION_CRITERIA, termination); jecoliConf.setProperty(GenericOptimizationProperties.MAP_OF2_SIM, objFunctions); jecoliConf.setProperty(GenericOptimizationProperties.SIMULATION_CONFIGURATION, simulationConfiguration); jecoliConf.setProperty(GenericOptimizationProperties.MAX_SET_SIZE, 6); jecoliConf.setProperty(GenericOptimizationProperties.IS_OVER_UNDER_EXPRESSION, true); // jecoliConf.setProperty(GenericOptimizationProperties.NOT_ALLOWED_IDS, cr.getCriticalReactionIds()); ROUSolutionSet<JecoliGenericConfiguration> rouSolutionSet = (ROUSolutionSet) cc.execute(jecoliConf); StrainOptimizationSimplificationFactory simpFactory = new StrainOptimizationSimplificationFactory(); IStrainOptimizationResultsSimplifier simplifier = simpFactory.getSimplifierInstance("ROU", jecoliConf); ROUSolutionSet<JecoliGenericConfiguration> newROUSolutionSet = (ROUSolutionSet<JecoliGenericConfiguration>) simplifier.getSimplifiedResultSetDiscardRepeated(rouSolutionSet); ArrayList<ROUSolution> solutionList = (ArrayList<ROUSolution>) newROUSolutionSet.getResultList(); System.out.println("Number of solutions:" +solutionList.size()); HashMap<String, List<Double>> fluxesFromOptimization = new HashMap<String, List<Double>>(); for (int i = 0; i < solutionList.size(); i++) { GeneticConditions geneCond = solutionList.get(i).getGeneticConditions(); System.out.println(geneCond + "\t" + solutionList.get(i).getAttributes()); for (String reaction : geneCond.getReactionList().keySet()) { List<Double> values = new ArrayList<>(); if(fluxesFromOptimization.containsKey(reaction)) values = fluxesFromOptimization.get(reaction); values.add(geneCond.getReactionList().get(reaction).doubleValue()); fluxesFromOptimization.put(reaction, values); } } // for (String flux : fluxesFromOptimization.keySet()) { // if(allZeroFluxes.contains(flux)) // System.err.println("Reaction: " + flux + "\tValues: " + fluxesFromOptimization.get(flux)); } /** * * @param geneCondString e.g. R_FUM=0.5,R_PYK=2.0,R_ADK1=0.125,R_ACKr=0.5 * @return */ protected GeneticConditions parseGeneticCondtionsFromString(String geneCondString, boolean isOverUnder){ String[] rawReactions = geneCondString.trim().split(","); Map<String, Double> reactionsMap = new HashMap<>(); for (int i = 0; i < rawReactions.length; i++) { String[] reactions = rawReactions[i].trim().split("="); reactionsMap.put(reactions[0], Double.parseDouble(reactions[1])); } ReactionChangesList rcl = new ReactionChangesList(reactionsMap); return new GeneticConditions(rcl, isOverUnder); } @Test public void simulationTest() throws Exception { SolverType solverToUse = SolverType.CPLEX3; URL nyData = getClass().getClassLoader().getResource("models/ecoli_core_model.xml"); CplexParamConfiguration.setDoubleParam("EpRHS", 1e-6); CplexParamConfiguration.setDoubleParam("TiLim", 10.0); JSBMLReader reader = new JSBMLReader(nyData.getFile(), "1", false); Container cont = new Container(reader); Set<String> met = cont.identifyMetabolitesIdByPattern(Pattern.compile(".*_b")); cont.removeMetabolites(met); ISteadyStateModel model = (SteadyStateModel) ContainerConverter.convert(cont); GeneticConditions geneticConditions = parseGeneticCondtionsFromString("R_TKT1=2.0,R_PGL=0.0,R_PFK=0.0", true); // GeneticConditions geneticConditions = parseGeneticCondtionsFromString("R_FBA=0.0,R_PPCK=0.03125,R_MALS=16.0,R_GLUDy=0.0,R_PPC=0.0625,R_G6PDH2r=0.0", true); // GeneticConditions geneticConditions = parseGeneticCondtionsFromString("R_FBA=0.0,R_PPCK=8.0,R_ADK1=0.5,R_ACALD=4.0,R_TKT2=0.0,R_PDH=0.5", true); // GeneticConditions geneticConditions = parseGeneticCondtionsFromString("R_TPI=0.0,R_PPCK=4.0,R_TKT2=0.0,R_SUCDi=2.0,R_NADTRHD=2.0,R_FRD7=8.0", true); SimulationSteadyStateControlCenter cc = new SimulationSteadyStateControlCenter(null, geneticConditions, model, SimulationProperties.MOMA); cc.setSolver(solverToUse); cc.setMaximization(true); cc.setOverUnder2StepApproach(true); SteadyStateSimulationResult result = cc.simulate(); System.out.println(result.getOFvalue()); System.out.println(result.getSolutionType()); // GeneticConditions noADK1 = parseGeneticCondtionsFromString("R_FUM=0.5,R_PYK=2.0,R_ACKr=0.5", true); // cc.setGeneticConditions(noADK1); // System.out.println(cc.simulate().getOFvalue()); // GeneticConditions koADK1 = parseGeneticCondtionsFromString("R_FUM=0.5,R_PYK=2.0,R_ACKr=0.5,R_ADK1=0.0", true); // cc.setGeneticConditions(koADK1); // System.out.println(cc.simulate().getOFvalue()); } @Test public void testUO2StepApproachException() throws Exception { SolverType solverToUse = SolverType.CPLEX3; String simMethod = SimulationProperties.MOMA; URL nyData = getClass().getClassLoader().getResource("models/ecoli_core_model.xml"); // CplexParamConfiguration.setDoubleParam("EpRHS", 1e-9); CplexParamConfiguration.setDoubleParam("TiLim", 10.0); JSBMLReader reader = new JSBMLReader(nyData.getFile(), "1", false); Container cont = new Container(reader); Set<String> met = cont.identifyMetabolitesIdByPattern(Pattern.compile(".*_b")); cont.removeMetabolites(met); ISteadyStateModel model = (SteadyStateModel) ContainerConverter.convert(cont); StrainOptimizationControlCenter cc = new StrainOptimizationControlCenter(); ITerminationCriteria termination = new NumFunctionEvaluationsListenerHybridTerminationCriteria(500); CriticalReactions cr = new CriticalReactions(model, null, solverToUse); cr.identifyCriticalReactions(); cr.setDrainReactionsAsCritical(); cr.setTransportReactionsAsCritical(); // FluxValueMap wtReference = SimulationProperties.simulateWT(model, null, solverToUse); // Set<String> allZeroFluxes = new HashSet<String>(); // for (String flux : wtReference.keySet()) { // if(wtReference.get(flux) == 0.0){ // allZeroFluxes.add(flux); IndexedHashMap<IObjectiveFunction, String> objFunctions = new IndexedHashMap<IObjectiveFunction, String>(); BPCYObjectiveFunction objFunc1 = new BPCYObjectiveFunction(model.getBiomassFlux(), "R_EX_succ_e", "R_EX_glc_e"); objFunctions.put(objFunc1, simMethod + "T"); Map<String, Map<String, Object>> simulationConfiguration = new HashMap<>(); Map<String, Double> of = new HashMap<>(); of.put(model.getBiomassFlux(), 1.0); // FBA Map<String, Object> methodConf = new HashMap<>(); methodConf.put(SimulationProperties.METHOD_ID, simMethod); methodConf.put(SimulationProperties.MODEL, model); methodConf.put(SimulationProperties.IS_MAXIMIZATION, true); methodConf.put(SimulationProperties.SOLVER, solverToUse); methodConf.put(SimulationProperties.OVERUNDER_2STEP_APPROACH, true); methodConf.put(SimulationProperties.IS_OVERUNDER_SIMULATION, true); simulationConfiguration.put(simMethod + "T", methodConf); JecoliGenericConfiguration jecoliConf = new JecoliGenericConfiguration(); jecoliConf.setProperty(GenericOptimizationProperties.OPTIMIZATION_STRATEGY, "ROU"); jecoliConf.setProperty(GenericOptimizationProperties.OPTIMIZATION_ALGORITHM, "SPEA2"); jecoliConf.setProperty(JecoliOptimizationProperties.IS_VARIABLE_SIZE_GENOME, true); jecoliConf.setProperty(GenericOptimizationProperties.STEADY_STATE_MODEL, model); jecoliConf.setProperty(JecoliOptimizationProperties.TERMINATION_CRITERIA, termination); jecoliConf.setProperty(GenericOptimizationProperties.MAP_OF2_SIM, objFunctions); jecoliConf.setProperty(GenericOptimizationProperties.SIMULATION_CONFIGURATION, simulationConfiguration); jecoliConf.setProperty(GenericOptimizationProperties.MAX_SET_SIZE, 6); jecoliConf.setProperty(GenericOptimizationProperties.IS_OVER_UNDER_EXPRESSION, true); jecoliConf.setProperty(GenericOptimizationProperties.NOT_ALLOWED_IDS, cr.getCriticalReactionIds()); ROUSolutionSet<JecoliGenericConfiguration> rouSolutionSet = (ROUSolutionSet) cc.execute(jecoliConf); // StrainOptimizationSimplificationFactory simpFactory = new StrainOptimizationSimplificationFactory(); // IStrainOptimizationResultsSimplifier simplifier = simpFactory.getSimplifierInstance("ROU", jecoliConf); // System.out.println("Number of Solutions before simplification: " + rouSolutionSet.getResultList().size()); // ROUSolutionSet<JecoliGenericConfiguration> newROUSolutionSet = (ROUSolutionSet<JecoliGenericConfiguration>) simplifier.getSimplifiedResultSetDiscardRepeated(rouSolutionSet); ArrayList<ROUSolution> solutionList = (ArrayList<ROUSolution>) rouSolutionSet.getResultList(); // System.out.println("Number of solutions:" +solutionList.size()); HashMap<String, List<Double>> fluxesFromOptimization = new HashMap<String, List<Double>>(); for (int i = 0; i < solutionList.size(); i++) { GeneticConditions geneCond = solutionList.get(i).getGeneticConditions(); System.out.println(geneCond + "\t" + solutionList.get(i).getAttributes()); for (String reaction : geneCond.getReactionList().keySet()) { List<Double> values = new ArrayList<>(); if(fluxesFromOptimization.containsKey(reaction)) values = fluxesFromOptimization.get(reaction); values.add(geneCond.getReactionList().get(reaction).doubleValue()); fluxesFromOptimization.put(reaction, values); } } // boolean solutionContainsZero = false; // for (String flux : fluxesFromOptimization.keySet()) { // if(allZeroFluxes.contains(flux)){ // System.err.println("Reaction: " + flux + "\tValues: " + fluxesFromOptimization.get(flux)); // for (Double d : fluxesFromOptimization.get(flux)) { // if(d != 0.0){ // System.out.println("Reaction: " + flux + "\tValue: " + d); // solutionContainsZero = true; // Assert.assertEquals("There are wt zero fluxes that are suggested as modifications", false, solutionContainsZero); } @Test public void testRKSolutionsWithoutSimplification() throws Exception { SolverType solverToUse = SolverType.CPLEX3; String simMethod = SimulationProperties.FBA; URL nyData = getClass().getClassLoader().getResource("models/ecoli_core_model.xml"); CplexParamConfiguration.setDoubleParam("EpRHS", 1e-9); CplexParamConfiguration.setDoubleParam("TiLim", 10.0); JSBMLReader reader = new JSBMLReader(nyData.getFile(), "1", false); Container cont = new Container(reader); Set<String> met = cont.identifyMetabolitesIdByPattern(Pattern.compile(".*_b")); cont.removeMetabolites(met); ISteadyStateModel model = (SteadyStateModel) ContainerConverter.convert(cont); StrainOptimizationControlCenter cc = new StrainOptimizationControlCenter(); ITerminationCriteria termination = new NumFunctionEvaluationsListenerHybridTerminationCriteria(2000); CriticalReactions cr = new CriticalReactions(model, null, solverToUse); cr.identifyCriticalReactions(); cr.setDrainReactionsAsCritical(); cr.setTransportReactionsAsCritical(); IndexedHashMap<IObjectiveFunction, String> objFunctions = new IndexedHashMap<IObjectiveFunction, String>(); BPCYObjectiveFunction objFunc1 = new BPCYObjectiveFunction(model.getBiomassFlux(), "R_EX_succ_e", "R_EX_glc_e"); objFunctions.put(objFunc1, simMethod + "T"); Map<String, Map<String, Object>> simulationConfiguration = new HashMap<>(); Map<String, Double> of = new HashMap<>(); of.put(model.getBiomassFlux(), 1.0); // FBA Map<String, Object> methodConf = new HashMap<>(); methodConf.put(SimulationProperties.METHOD_ID, simMethod); methodConf.put(SimulationProperties.MODEL, model); methodConf.put(SimulationProperties.IS_MAXIMIZATION, true); methodConf.put(SimulationProperties.SOLVER, solverToUse); methodConf.put(SimulationProperties.OVERUNDER_2STEP_APPROACH, false); methodConf.put(SimulationProperties.IS_OVERUNDER_SIMULATION, false); simulationConfiguration.put(simMethod + "T", methodConf); JecoliGenericConfiguration jecoliConf = new JecoliGenericConfiguration(); jecoliConf.setProperty(GenericOptimizationProperties.OPTIMIZATION_STRATEGY, "RK"); jecoliConf.setProperty(GenericOptimizationProperties.OPTIMIZATION_ALGORITHM, "SPEA2"); jecoliConf.setProperty(JecoliOptimizationProperties.IS_VARIABLE_SIZE_GENOME, true); jecoliConf.setProperty(GenericOptimizationProperties.STEADY_STATE_MODEL, model); jecoliConf.setProperty(JecoliOptimizationProperties.TERMINATION_CRITERIA, termination); jecoliConf.setProperty(GenericOptimizationProperties.MAP_OF2_SIM, objFunctions); jecoliConf.setProperty(GenericOptimizationProperties.SIMULATION_CONFIGURATION, simulationConfiguration); jecoliConf.setProperty(GenericOptimizationProperties.MAX_SET_SIZE, 6); jecoliConf.setProperty(GenericOptimizationProperties.IS_OVER_UNDER_EXPRESSION, false); jecoliConf.setProperty(GenericOptimizationProperties.NOT_ALLOWED_IDS, cr.getCriticalReactionIds()); for (int j = 0; j < 10; j++) { boolean hasInfeasible = false; RKSolutionSet<JecoliGenericConfiguration> rkSolutionSet = (RKSolutionSet) cc.execute(jecoliConf); // StrainOptimizationSimplificationFactory simpFactory = new StrainOptimizationSimplificationFactory(); // IStrainOptimizationResultsSimplifier simplifier = simpFactory.getSimplifierInstance("ROU", jecoliConf); // System.out.println("Number of Solutions before simplification: " + rouSolutionSet.getResultList().size()); // ROUSolutionSet<JecoliGenericConfiguration> newROUSolutionSet = (ROUSolutionSet<JecoliGenericConfiguration>) simplifier.getSimplifiedResultSetDiscardRepeated(rouSolutionSet); ArrayList<RKSolution> solutionList = (ArrayList<RKSolution>) rkSolutionSet.getResultList(); System.out.println(solutionList.size()); HashMap<String, List<Double>> fluxesFromOptimization = new HashMap<String, List<Double>>(); Set<String> methods = new HashSet<String>(); for (String methodID : jecoliConf.getSimulationConfiguration().keySet()) { methods.add((String)jecoliConf.getSimulationConfiguration().get(methodID).get(SimulationProperties.METHOD_ID)); methods.add(methodID); } for (int i = 0; i < solutionList.size(); i++) { // GeneticConditions geneCond = solutionList.get(i).getGeneticConditions(); //// System.out.println(geneCond + "\t" + solutionList.get(i).getAttributes()); // for (String reaction : geneCond.getReactionList().keySet()) { // List<Double> values = new ArrayList<>(); // if(fluxesFromOptimization.containsKey(reaction)) // values = fluxesFromOptimization.get(reaction); // values.add(geneCond.getReactionList().get(reaction).doubleValue()); // fluxesFromOptimization.put(reaction, values); // System.out.println(solutionList.get(i).getAttributes()); RKSolution singularResult = solutionList.get(i); // List<IStrainOptimizationResult> results = (List<IStrainOptimizationResult>) solutionList.get(i).get.getResultList(); // for (IStrainOptimizationResult singularResult : res.get) { for (String method : methods) { if(singularResult.getSimulationResultForMethod(method) != null){ FluxValueMap fluxes = singularResult.getSimulationResultForMethod(method).getFluxValues(); if(fluxes.containsValue(Double.NaN)){ System.err.println(singularResult.getSimulationResultForMethod(method).getSolutionType()); System.err.println(singularResult.getGeneticConditions().toUniqueString()); hasInfeasible = true; // return false; } } } } Assert.assertTrue("Found infeasable!", hasInfeasible == false); } } @Test public void testGOUSolutionsWithoutSimplification() throws Exception { SolverType solverToUse = SolverType.CPLEX3; String simMethod = SimulationProperties.FBA; URL nyData = getClass().getClassLoader().getResource("models/ecoli_core_model.xml"); CplexParamConfiguration.setDoubleParam("EpRHS", 1e-9); CplexParamConfiguration.setDoubleParam("TiLim", 10.0); JSBMLReader reader = new JSBMLReader(nyData.getFile(), "1", false); Container cont = new Container(reader); Set<String> met = cont.identifyMetabolitesIdByPattern(Pattern.compile(".*_b")); cont.removeMetabolites(met); ISteadyStateModel model = (SteadyStateModel) ContainerConverter.convert(cont); StrainOptimizationControlCenter cc = new StrainOptimizationControlCenter(); ITerminationCriteria termination = new NumFunctionEvaluationsListenerHybridTerminationCriteria(2000); CriticalReactions cr = new CriticalReactions(model, null, solverToUse); cr.identifyCriticalReactions(); cr.setDrainReactionsAsCritical(); cr.setTransportReactionsAsCritical(); IndexedHashMap<IObjectiveFunction, String> objFunctions = new IndexedHashMap<IObjectiveFunction, String>(); BPCYObjectiveFunction objFunc1 = new BPCYObjectiveFunction(model.getBiomassFlux(), "R_EX_succ_e", "R_EX_glc_e"); objFunctions.put(objFunc1, simMethod + "T"); Map<String, Map<String, Object>> simulationConfiguration = new HashMap<>(); Map<String, Double> of = new HashMap<>(); of.put(model.getBiomassFlux(), 1.0); // FBA Map<String, Object> methodConf = new HashMap<>(); methodConf.put(SimulationProperties.METHOD_ID, simMethod); methodConf.put(SimulationProperties.MODEL, model); methodConf.put(SimulationProperties.IS_MAXIMIZATION, true); methodConf.put(SimulationProperties.SOLVER, solverToUse); methodConf.put(SimulationProperties.OVERUNDER_2STEP_APPROACH, true); methodConf.put(SimulationProperties.IS_OVERUNDER_SIMULATION, true); simulationConfiguration.put(simMethod + "T", methodConf); JecoliGenericConfiguration jecoliConf = new JecoliGenericConfiguration(); jecoliConf.setProperty(GenericOptimizationProperties.OPTIMIZATION_STRATEGY, "GOU"); jecoliConf.setProperty(GenericOptimizationProperties.OPTIMIZATION_ALGORITHM, "SA"); jecoliConf.setProperty(JecoliOptimizationProperties.IS_VARIABLE_SIZE_GENOME, true); jecoliConf.setProperty(GenericOptimizationProperties.STEADY_STATE_MODEL, model); jecoliConf.setProperty(JecoliOptimizationProperties.TERMINATION_CRITERIA, termination); jecoliConf.setProperty(GenericOptimizationProperties.MAP_OF2_SIM, objFunctions); jecoliConf.setProperty(GenericOptimizationProperties.SIMULATION_CONFIGURATION, simulationConfiguration); jecoliConf.setProperty(GenericOptimizationProperties.MAX_SET_SIZE, 6); jecoliConf.setProperty(GenericOptimizationProperties.IS_OVER_UNDER_EXPRESSION, true); jecoliConf.setProperty(GenericOptimizationProperties.NOT_ALLOWED_IDS, cr.getCriticalReactionIds()); for (int j = 0; j < 10; j++) { GOUSolutionSet<JecoliGenericConfiguration> rkSolutionSet = (GOUSolutionSet) cc.execute(jecoliConf); // StrainOptimizationSimplificationFactory simpFactory = new StrainOptimizationSimplificationFactory(); // IStrainOptimizationResultsSimplifier simplifier = simpFactory.getSimplifierInstance("ROU", jecoliConf); // System.out.println("Number of Solutions before simplification: " + rouSolutionSet.getResultList().size()); // ROUSolutionSet<JecoliGenericConfiguration> newROUSolutionSet = (ROUSolutionSet<JecoliGenericConfiguration>) simplifier.getSimplifiedResultSetDiscardRepeated(rouSolutionSet); ArrayList<GOUSolution> solutionList = (ArrayList<GOUSolution>) rkSolutionSet.getResultList(); System.out.println(solutionList.size()); HashMap<String, List<Double>> fluxesFromOptimization = new HashMap<String, List<Double>>(); // Set<String> methods = new HashSet<String>(); // for (String methodID : jecoliConf.getSimulationConfiguration().keySet()) { // methods.add((String)jecoliConf.getSimulationConfiguration().get(methodID).get(SimulationProperties.METHOD_ID)); // methods.add(methodID); Assert.assertTrue("No results!", !solutionList.isEmpty()); } } }
package com.ticktac.controllers; import java.io.IOException; import java.util.HashMap; import javax.annotation.Resource; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.transaction.UserTransaction; import com.ticktac.utils.RequestHandler; import com.ticktac.utils.SubmitCredentialsRequestHandler; /** * BankController */ @WebServlet(description = "Controller that processes information about bank actions", urlPatterns = { "/submitcredentials" }) public class BankController extends HttpServlet { private static final long serialVersionUID = 1L; private HashMap<String, Object> handlersMap = new HashMap<String, Object>(); @PersistenceContext(unitName="ticktacUP") EntityManager em; @Resource UserTransaction tr; public BankController() { super(); } public void init() { handlersMap.put("submitcredentials", new SubmitCredentialsRequestHandler()); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String path = request.getServletPath(); String viewURL = "notfound.html"; RequestHandler handler = (RequestHandler) handlersMap.get(path); if(handler != null) viewURL = handler.handleRequest(request, response, em, tr); request.getRequestDispatcher(viewURL).forward(request, response); } }
package step.plugins.datatable.formatters.custom; import java.util.Iterator; import org.bson.Document; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import step.core.GlobalContext; import step.core.artefacts.reports.ReportNode; import step.core.artefacts.reports.ReportNodeAccessor; import step.core.deployment.JacksonMapperProvider; import step.plugins.datatable.formatters.Formatter; public class RootReportNodeFormatter implements Formatter { protected ReportNodeAccessor reportNodeAccessor; protected ObjectMapper mapper; private static final Logger logger = LoggerFactory.getLogger(RootReportNodeFormatter.class); public RootReportNodeFormatter(GlobalContext context) { super(); reportNodeAccessor = context.getReportAccessor(); mapper = JacksonMapperProvider.createMapper(); } @Override public String format(Object value, Document row) { String eid = row.get("_id").toString(); ReportNode rootReportNode = reportNodeAccessor.getRootReportNode(eid); Iterator<ReportNode> rootReportNodeChildren = reportNodeAccessor.getChildren(rootReportNode.getId()); if(rootReportNodeChildren.hasNext()) { rootReportNode = rootReportNodeChildren.next(); if(rootReportNode != null) { try { return mapper.writeValueAsString(rootReportNode); } catch (JsonProcessingException e) { logger.error("Error while serializing report node "+rootReportNode, e); } } else { logger.error("Error while getting root report node for execution. " + "Iterator.next() returned null although Iterator.hasNext() returned true. " + "This should not occur "+eid); } } else { logger.debug("No children found for report node with id "+rootReportNode.getId()); } return "{}"; } @Override public Object parse(String formattedValue) { throw new RuntimeException("Not implemented"); } }
package org.miod.program; import java.util.HashMap; import java.util.Map; import org.miod.program.errors.SymbolRedefinitionError; /** * * @author yur */ public abstract class BaseSymbolTable implements SymbolTable { private Map<String, SymItem> items = new HashMap<>(); protected SymbolTable parent; public static final String NAMESPACE_SEP = "::"; BaseSymbolTable(SymbolTable parent) { this.parent = parent; } @Override public SymItem get(String id) { return items.get(id); } @Override public void put(String id, SymItem item) { if (get(id) == null) { items.put(id, item); } else { throw new SymbolRedefinitionError(item); } } @Override public SymItem resolve(String id) { // TODO use parent // TODO split by "::" and try to resolve if (id.startsWith(NAMESPACE_SEP)) { if (parent != null) return parent.resolve(id.substring(NAMESPACE_SEP.length())); } return null; } }
package com.vaadin.data.util; import java.util.LinkedList; import com.vaadin.data.Property; /** * Formatting proxy for a property. * * <p> * This class can be used to implement formatting for any type of Property * datasources. The idea is to connect this as proxy between UI component and * the original datasource. * </p> * * <p> * For example <code> * textfield.setPropertyDataSource(new PropertyFormatter(property) { public String format(Object value) { return ((Double) value).toString() + "000000000"; } public Object parse(String formattedValue) throws Exception { return Double.parseDouble(formattedValue); } });</code> adds formatter for Double-typed property that extends standard * "1.0" notation with more zeroes. * </p> * * @author IT Mill Ltd. * @since 5.3.0 */ @SuppressWarnings("serial") public abstract class PropertyFormatter implements Property, Property.ValueChangeNotifier, Property.ValueChangeListener, Property.ReadOnlyStatusChangeListener, Property.ReadOnlyStatusChangeNotifier { /** * Internal list of registered value change listeners. */ private LinkedList valueChangeListeners = null; /** * Internal list of registered read-only status change listeners. */ private LinkedList readOnlyStatusChangeListeners = null; /** Datasource that stores the actual value. */ Property dataSource; /** * Construct a new formatter that is connected to given datasource. * * @param propertyDataSource * to connect this property to. */ public PropertyFormatter(Property propertyDataSource) { setPropertyDataSource(propertyDataSource); } /** * Gets the current data source of the formatter, if any. * * @return the current data source as a Property, or <code>null</code> if * none defined. */ public Property getPropertyDataSource() { return dataSource; } /** * Sets the specified Property as the data source for the formatter. * * * <p> * Remember that new data sources getValue() must return objects that are * compatible with parse() and format() methods. * </p> * * @param newDataSource * the new data source Property. */ public void setPropertyDataSource(Property newDataSource) { boolean readOnly = false; String prevValue = null; if (dataSource != null) { if (dataSource instanceof Property.ValueChangeNotifier) { ((Property.ValueChangeNotifier) dataSource) .removeListener(this); } if (dataSource instanceof Property.ReadOnlyStatusChangeListener) { ((Property.ReadOnlyStatusChangeNotifier) dataSource) .removeListener(this); } readOnly = isReadOnly(); prevValue = toString(); } dataSource = newDataSource; if (dataSource != null) { if (dataSource instanceof Property.ValueChangeNotifier) { ((Property.ValueChangeNotifier) dataSource).addListener(this); } if (dataSource instanceof Property.ReadOnlyStatusChangeListener) { ((Property.ReadOnlyStatusChangeNotifier) dataSource) .addListener(this); } } if (isReadOnly() != readOnly) { fireReadOnlyStatusChange(); } String newVal = toString(); if ((prevValue == null && newVal != null) || (prevValue != null && !prevValue.equals(newVal))) { fireValueChange(); } } /* Documented in the interface */ public Class getType() { return String.class; } /** * Get the formatted value. * * @return If the datasource returns null, this is null. Otherwise this is * String given by format(). */ public Object getValue() { return toString(); } /** * Get the formatted value. * * @return If the datasource returns null, this is null. Otherwise this is * String given by format(). */ @Override public String toString() { Object value = dataSource == null ? false : dataSource.getValue(); if (value == null) { return null; } return format(value); } /** Reflects the read-only status of the datasource. */ public boolean isReadOnly() { return dataSource == null ? false : dataSource.isReadOnly(); } /** * This method must be implemented to format the values received from * DataSource. * * @param value * Value object got from the datasource. This is guaranteed to be * non-null and of the type compatible with getType() of the * datasource. * @return */ abstract public String format(Object value); /** * Parse string and convert it to format compatible with datasource. * * The method is required to assure that parse(format(x)) equals x. * * @param formattedValue * This is guaranteed to be non-null string. * @return Non-null value compatible with datasource. * @throws Exception * Any type of exception can be thrown to indicate that the * conversion was not succesful. */ abstract public Object parse(String formattedValue) throws Exception; /** * Sets the Property's read-only mode to the specified status. * * @param newStatus * the new read-only status of the Property. */ public void setReadOnly(boolean newStatus) { if (dataSource != null) { dataSource.setReadOnly(newStatus); } } public void setValue(Object newValue) throws ReadOnlyException, ConversionException { if (dataSource == null) { return; } if (newValue == null) { if (dataSource.getValue() != null) { dataSource.setValue(null); fireValueChange(); } } else { try { dataSource.setValue(parse((String) newValue)); if (!newValue.equals(toString())) { fireValueChange(); } } catch (Exception e) { if (e instanceof ConversionException) { throw (ConversionException) e; } else { throw new ConversionException(e); } } } } /** * An <code>Event</code> object specifying the ObjectProperty whose value * has changed. * * @author IT Mill Ltd. * @since 5.3.0 */ private class ValueChangeEvent extends java.util.EventObject implements Property.ValueChangeEvent { /** * Constructs a new value change event for this object. * * @param source * the source object of the event. */ protected ValueChangeEvent(PropertyFormatter source) { super(source); } /** * Gets the Property whose read-only state has changed. * * @return source the Property of the event. */ public Property getProperty() { return (Property) getSource(); } } /** * An <code>Event</code> object specifying the Property whose read-only * status has been changed. * * @author IT Mill Ltd. * @since 5.3.0 */ private class ReadOnlyStatusChangeEvent extends java.util.EventObject implements Property.ReadOnlyStatusChangeEvent { /** * Constructs a new read-only status change event for this object. * * @param source * source object of the event */ protected ReadOnlyStatusChangeEvent(PropertyFormatter source) { super(source); } /** * Gets the Property whose read-only state has changed. * * @return source Property of the event. */ public Property getProperty() { return (Property) getSource(); } } /** * Removes a previously registered value change listener. * * @param listener * the listener to be removed. */ public void removeListener(Property.ValueChangeListener listener) { if (valueChangeListeners != null) { valueChangeListeners.remove(listener); } } /** * Registers a new value change listener for this ObjectProperty. * * @param listener * the new Listener to be registered */ public void addListener(Property.ValueChangeListener listener) { if (valueChangeListeners == null) { valueChangeListeners = new LinkedList(); } valueChangeListeners.add(listener); } /** * Registers a new read-only status change listener for this Property. * * @param listener * the new Listener to be registered */ public void addListener(Property.ReadOnlyStatusChangeListener listener) { if (readOnlyStatusChangeListeners == null) { readOnlyStatusChangeListeners = new LinkedList(); } readOnlyStatusChangeListeners.add(listener); } /** * Removes a previously registered read-only status change listener. * * @param listener * the listener to be removed. */ public void removeListener(Property.ReadOnlyStatusChangeListener listener) { if (readOnlyStatusChangeListeners != null) { readOnlyStatusChangeListeners.remove(listener); } } /** * Sends a value change event to all registered listeners. */ private void fireValueChange() { if (valueChangeListeners != null) { final Object[] l = valueChangeListeners.toArray(); final Property.ValueChangeEvent event = new ValueChangeEvent(this); for (int i = 0; i < l.length; i++) { ((Property.ValueChangeListener) l[i]).valueChange(event); } } } /** * Sends a read only status change event to all registered listeners. */ private void fireReadOnlyStatusChange() { if (readOnlyStatusChangeListeners != null) { final Object[] l = readOnlyStatusChangeListeners.toArray(); final Property.ReadOnlyStatusChangeEvent event = new ReadOnlyStatusChangeEvent( this); for (int i = 0; i < l.length; i++) { ((Property.ReadOnlyStatusChangeListener) l[i]) .readOnlyStatusChange(event); } } } /** * Listens for changes in the datasource. * * This should not be called directly. */ public void valueChange(com.vaadin.data.Property.ValueChangeEvent event) { fireValueChange(); } /** * Listens for changes in the datasource. * * This should not be called directly. */ public void readOnlyStatusChange( com.vaadin.data.Property.ReadOnlyStatusChangeEvent event) { fireReadOnlyStatusChange(); } }
package org.keycloak.testsuite.openshift; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.StringEntity; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.keycloak.OAuth2Constants; import org.keycloak.admin.client.resource.ClientResource; import org.keycloak.admin.client.resource.RealmResource; import org.keycloak.common.util.Base64Url; import org.keycloak.crypto.Algorithm; import org.keycloak.events.Details; import org.keycloak.jose.jws.JWSInput; import org.keycloak.protocol.oidc.OIDCConfigAttributes; import org.keycloak.protocol.oidc.OIDCLoginProtocol; import org.keycloak.protocol.oidc.mappers.GroupMembershipMapper; import org.keycloak.protocol.oidc.mappers.OIDCAttributeMapperHelper; import org.keycloak.protocol.openshift.OpenShiftTokenReviewRequestRepresentation; import org.keycloak.protocol.openshift.OpenShiftTokenReviewResponseRepresentation; import org.keycloak.representations.idm.AuthenticationExecutionInfoRepresentation; import org.keycloak.representations.idm.ClientRepresentation; import org.keycloak.representations.idm.ClientScopeRepresentation; import org.keycloak.representations.idm.EventRepresentation; import org.keycloak.representations.idm.ProtocolMapperRepresentation; import org.keycloak.representations.idm.RealmRepresentation; import org.keycloak.testsuite.AbstractTestRealmKeycloakTest; import org.keycloak.testsuite.AssertEvents; import org.keycloak.testsuite.admin.ApiUtil; import org.keycloak.testsuite.arquillian.AuthServerTestEnricher; import org.keycloak.testsuite.arquillian.annotation.RestartContainer; import org.keycloak.testsuite.updaters.ClientAttributeUpdater; import org.keycloak.testsuite.util.OAuthClient; import org.keycloak.testsuite.util.UserBuilder; import org.keycloak.util.JsonSerialization; import javax.ws.rs.core.HttpHeaders; import javax.ws.rs.core.Response; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder; import static org.junit.Assert.*; import static org.keycloak.common.Profile.Feature.OPENSHIFT_INTEGRATION; import static org.keycloak.testsuite.ProfileAssume.assumeFeatureEnabled; @RestartContainer(enableFeatures = OPENSHIFT_INTEGRATION) public class OpenShiftTokenReviewEndpointTest extends AbstractTestRealmKeycloakTest { private static boolean flowConfigured; @Rule public AssertEvents events = new AssertEvents(this); @Override public void configureTestRealm(RealmRepresentation testRealm) { ClientRepresentation client = testRealm.getClients().stream().filter(r -> r.getClientId().equals("test-app")).findFirst().get(); List<ProtocolMapperRepresentation> mappers = new LinkedList<>(); ProtocolMapperRepresentation mapper = new ProtocolMapperRepresentation(); mapper.setName("groups"); mapper.setProtocolMapper(GroupMembershipMapper.PROVIDER_ID); mapper.setProtocol(OIDCLoginProtocol.LOGIN_PROTOCOL); Map<String, String> config = new HashMap<>(); config.put("full.path", "false"); config.put(OIDCAttributeMapperHelper.TOKEN_CLAIM_NAME, "groups"); config.put(OIDCAttributeMapperHelper.INCLUDE_IN_ACCESS_TOKEN, "true"); config.put(OIDCAttributeMapperHelper.INCLUDE_IN_ID_TOKEN, "true"); mapper.setConfig(config); mappers.add(mapper); client.setProtocolMappers(mappers); client.setPublicClient(false); client.setClientAuthenticatorType("testsuite-client-dummy"); testRealm.getUsers().add(UserBuilder.create().username("groups-user").password("password").addGroups("/topGroup", "/topGroup/level2group").build()); } @Before public void enablePassthroughAuthenticator() { assumeFeatureEnabled(OPENSHIFT_INTEGRATION); if (!flowConfigured) { HashMap<String, String> data = new HashMap<>(); data.put("newName", "testsuite-client-dummy"); Response response = testRealm().flows().copy("clients", data); assertEquals(201, response.getStatus()); response.close(); data = new HashMap<>(); data.put("provider", "testsuite-client-dummy"); data.put("requirement", "ALTERNATIVE"); testRealm().flows().addExecution("testsuite-client-dummy", data); RealmRepresentation realmRep = testRealm().toRepresentation(); realmRep.setClientAuthenticationFlow("testsuite-client-dummy"); testRealm().update(realmRep); List<AuthenticationExecutionInfoRepresentation> executions = testRealm().flows().getExecutions("testsuite-client-dummy"); for (AuthenticationExecutionInfoRepresentation e : executions) { if (e.getProviderId().equals("testsuite-client-dummy")) { e.setRequirement("ALTERNATIVE"); testRealm().flows().updateExecutions("testsuite-client-dummy", e); } } flowConfigured = true; } } @Test public void basicTest() { Review r = new Review().invoke(); String userId = testRealm().users().search(r.username).get(0).getId(); OpenShiftTokenReviewResponseRepresentation.User user = r.response.getStatus().getUser(); assertEquals(userId, user.getUid()); assertEquals("test-user@localhost", user.getUsername()); assertNotNull(user.getExtra()); r.assertScope("openid", "email", "profile"); } @Test public void longExpiration() { ClientResource client = ApiUtil.findClientByClientId(adminClient.realm("test"), "test-app"); ClientRepresentation clientRep = client.toRepresentation(); try { clientRep.getAttributes().put(OIDCConfigAttributes.ACCESS_TOKEN_LIFESPAN, "-1"); client.update(clientRep); // Set time offset just before SSO idle, to get session last refresh updated setTimeOffset(1500); Review review = new Review(); review.invoke().assertSuccess(); // Bump last refresh updated again setTimeOffset(3000); review.invoke().assertSuccess(); // And, again setTimeOffset(4500); // Token should still be valid as session last refresh should have been updated review.invoke().assertSuccess(); } finally { clientRep.getAttributes().put(OIDCConfigAttributes.ACCESS_TOKEN_LIFESPAN, null); client.update(clientRep); } } @Test public void hs256() { RealmResource realm = adminClient.realm("test"); RealmRepresentation rep = realm.toRepresentation(); try { rep.setDefaultSignatureAlgorithm(Algorithm.HS256); realm.update(rep); Review r = new Review().algorithm(Algorithm.HS256).invoke() .assertSuccess(); String userId = testRealm().users().search(r.username).get(0).getId(); OpenShiftTokenReviewResponseRepresentation.User user = r.response.getStatus().getUser(); assertEquals(userId, user.getUid()); assertEquals("test-user@localhost", user.getUsername()); assertNotNull(user.getExtra()); r.assertScope("openid", "email", "profile"); } finally { rep.setDefaultSignatureAlgorithm(null); realm.update(rep); } } @Test public void groups() { new Review().username("groups-user") .invoke() .assertSuccess().assertGroups("topGroup", "level2group"); } @Test public void customScopes() { ClientScopeRepresentation clientScope = new ClientScopeRepresentation(); clientScope.setProtocol("openid-connect"); clientScope.setId("user:info"); clientScope.setName("user:info"); testRealm().clientScopes().create(clientScope); ClientRepresentation clientRep = testRealm().clients().findByClientId("test-app").get(0); testRealm().clients().get(clientRep.getId()).addOptionalClientScope("user:info"); try { oauth.scope("user:info"); new Review() .invoke() .assertSuccess().assertScope("openid", "user:info", "profile", "email"); } finally { testRealm().clients().get(clientRep.getId()).removeOptionalClientScope("user:info"); } } @Test public void emptyScope() throws Exception { ClientRepresentation clientRep = testRealm().clients().findByClientId("test-app").get(0); List<ClientScopeRepresentation> scopesBefore = testRealm().clients().get(clientRep.getId()).getDefaultClientScopes(); try (ClientAttributeUpdater cau = ClientAttributeUpdater.forClient(adminClient, "test", clientRep.getClientId()) .setConsentRequired(false) .setFullScopeAllowed(false) .setDefaultClientScopes(Collections.EMPTY_LIST) .update()) { oauth.openid(false); try { new Review() .invoke() .assertSuccess() .assertEmptyScope(); } finally { oauth.openid(true); } } // The default client scopes should be same like before. int scopesAfterSize = testRealm().clients().get(clientRep.getId()).getDefaultClientScopes().size(); assertEquals(scopesBefore.size(), scopesAfterSize); } @Test public void expiredToken() { try { new Review() .runAfterTokenRequest(i -> setTimeOffset(testRealm().toRepresentation().getAccessTokenLifespan() + 10)) .invoke() .assertError(401, "Token verification failure"); } finally { resetTimeOffset(); } } @Test public void invalidPublicKey() { new Review() .runAfterTokenRequest(i -> { String header = i.token.split("\\.")[0]; String s = new String(Base64Url.decode(header)); s = s.replace(",\"kid\" : \"", ",\"kid\" : \"x"); String newHeader = Base64Url.encode(s.getBytes()); i.token = i.token.replaceFirst(header, newHeader); }) .invoke() .assertError(401, "Token verification failure"); } @Test public void noUserSession() { new Review() .runAfterTokenRequest(i -> { String userId = testRealm().users().search(i.username).get(0).getId(); testRealm().users().get(userId).logout(); }) .invoke() .assertError(401, "Token verification failure"); } @Test public void invalidTokenSignature() { new Review() .runAfterTokenRequest(i -> i.token += "x") .invoke() .assertError(401, "Token verification failure"); } @Test public void realmDisabled() { RealmRepresentation r = testRealm().toRepresentation(); try { new Review().runAfterTokenRequest(i -> { r.setEnabled(false); testRealm().update(r); }).invoke().assertError(401, null); } finally { r.setEnabled(true); testRealm().update(r); } } @Test public void publicClientNotPermitted() { ClientRepresentation clientRep = testRealm().clients().findByClientId("test-app").get(0); clientRep.setPublicClient(true); testRealm().clients().get(clientRep.getId()).update(clientRep); try { new Review().invoke().assertError(401, "Public client is not permitted to invoke token review endpoint"); } finally { clientRep.setPublicClient(false); testRealm().clients().get(clientRep.getId()).update(clientRep); } } private class Review { private String realm = "test"; private String clientId = "test-app"; private String username = "test-user@localhost"; private String password = "password"; private String algorithm = Algorithm.RS256; private InvokeRunnable runAfterTokenRequest; private String token; private int responseStatus; private OpenShiftTokenReviewResponseRepresentation response; public Review username(String username) { this.username = username; return this; } public Review algorithm(String algorithm) { this.algorithm = algorithm; return this; } public Review runAfterTokenRequest(InvokeRunnable runnable) { this.runAfterTokenRequest = runnable; return this; } public Review invoke() { try { if (token == null) { String userId = testRealm().users().search(username).get(0).getId(); oauth.doLogin(username, password); EventRepresentation loginEvent = events.expectLogin().user(userId).assertEvent(); String code = oauth.getCurrentQuery().get(OAuth2Constants.CODE); OAuthClient.AccessTokenResponse accessTokenResponse = oauth.doAccessTokenRequest(code, "password"); events.expectCodeToToken(loginEvent.getDetails().get(Details.CODE_ID), loginEvent.getSessionId()).detail("client_auth_method", "testsuite-client-dummy").user(userId).assertEvent(); token = accessTokenResponse.getAccessToken(); } assertEquals(algorithm, new JWSInput(token).getHeader().getAlgorithm().name()); if (runAfterTokenRequest != null) { runAfterTokenRequest.run(this); } try (CloseableHttpClient client = HttpClientBuilder.create().build()) { String url = AuthServerTestEnricher.getAuthServerContextRoot() + "/auth/realms/" + realm + "/protocol/openid-connect/ext/openshift-token-review/" + clientId; OpenShiftTokenReviewRequestRepresentation request = new OpenShiftTokenReviewRequestRepresentation(); OpenShiftTokenReviewRequestRepresentation.Spec spec = new OpenShiftTokenReviewRequestRepresentation.Spec(); spec.setToken(token); request.setSpec(spec); HttpPost post = new HttpPost(url); post.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString()); post.setHeader(HttpHeaders.ACCEPT, ContentType.APPLICATION_JSON.toString()); post.setEntity(new StringEntity(JsonSerialization.writeValueAsString(request))); try (CloseableHttpResponse resp = client.execute(post)) { responseStatus = resp.getStatusLine().getStatusCode(); response = JsonSerialization.readValue(resp.getEntity().getContent(), OpenShiftTokenReviewResponseRepresentation.class); } assertEquals("authentication.k8s.io/v1beta1", response.getApiVersion()); assertEquals("TokenReview", response.getKind()); } return this; } catch (Exception e) { throw new RuntimeException(e); } } public Review assertSuccess() { assertEquals(200, responseStatus); assertTrue(response.getStatus().isAuthenticated()); assertNotNull(response.getStatus().getUser()); return this; } private Review assertError(int expectedStatus, String expectedReason) { assertEquals(expectedStatus, responseStatus); assertFalse(response.getStatus().isAuthenticated()); assertNull(response.getStatus().getUser()); if (expectedReason != null) { EventRepresentation poll = events.poll(); assertEquals(expectedReason, poll.getDetails().get(Details.REASON)); } return this; } private void assertScope(String... expectedScope) { List<String> actualScopes = Arrays.asList(response.getStatus().getUser().getExtra().getScopes()); assertEquals(expectedScope.length, actualScopes.size()); assertThat(actualScopes, containsInAnyOrder(expectedScope)); } private void assertEmptyScope() { assertNull(response.getStatus().getUser().getExtra()); } private void assertGroups(String... expectedGroups) { List<String> actualGroups = new LinkedList<>(response.getStatus().getUser().getGroups()); assertEquals(expectedGroups.length, actualGroups.size()); assertThat(actualGroups, containsInAnyOrder(expectedGroups)); } } private interface InvokeRunnable { void run(Review i); } }
package com.exedio.cope.pattern; import java.io.IOException; import java.util.Date; import java.util.Iterator; import java.util.List; import com.exedio.cope.AbstractLibTest; import com.exedio.cope.Item; import com.exedio.cope.Model; import com.exedio.cope.Type; import com.exedio.cope.pattern.Dispatcher.Failure; public class DispatcherTest extends AbstractLibTest { public/*for web.xml*/ static final Model MODEL = new Model(DispatcherItem.TYPE); public DispatcherTest() { super(MODEL); } DispatcherItem item; DispatcherItem item1; DispatcherItem item2; DispatcherItem item3; DispatcherItem item4; @Override public void setUp() throws Exception { super.setUp(); item1 = deleteOnTearDown(new DispatcherItem("item1", false)); item2 = deleteOnTearDown(new DispatcherItem("item2", true)); item3 = deleteOnTearDown(new DispatcherItem("item3", false)); item4 = deleteOnTearDown(new DispatcherItem("item4", true)); } public void testIt() { final Type<?> failureType = item.upload.getFailureType(); // test model assertEqualsUnmodifiable(list( item.TYPE, failureType ), model.getTypes()); assertEqualsUnmodifiable(list( item.TYPE, failureType ), model.getTypesSortedByHierarchy()); assertEquals(DispatcherItem.class, item.TYPE.getJavaClass()); assertEquals(true, item.TYPE.hasUniqueJavaClass()); assertEquals(null, item.TYPE.getPattern()); assertEqualsUnmodifiable(list( item.TYPE.getThis(), item.body, item.fail, item.dispatchCount, item.dispatchLastElapsed, item.upload, item.upload.getPending(), item.upload.getSuccessDate(), item.upload.getSuccessElapsed() ), item.TYPE.getFeatures()); assertEqualsUnmodifiable(list( failureType.getThis(), item.uploadFailureParent(), item.upload.getFailureDate(), item.upload.getFailureElapsed(), item.upload.getFailureCause() ), failureType.getFeatures()); assertEquals(item.TYPE, item.upload.getType()); assertEquals("upload", item.upload.getName()); assertEquals(3, item.upload.getFailureLimit()); assertEquals(2, item.upload.getSearchSize()); assertEquals("DispatcherItem.uploadFailure", failureType.getID()); assertEquals(Dispatcher.Failure.class, failureType.getJavaClass()); assertEquals(false, failureType.hasUniqueJavaClass()); assertSame(DispatcherItem.upload, failureType.getPattern()); assertEquals(null, failureType.getSupertype()); assertEqualsUnmodifiable(list(), failureType.getSubTypes()); assertEquals(false, failureType.isAbstract()); assertEquals(Item.class, failureType.getThis().getValueClass().getSuperclass()); assertEquals(failureType, failureType.getThis().getValueType()); assertEquals(model, failureType.getModel()); assertEquals(failureType, item.uploadFailureParent().getType()); assertEquals(failureType, item.upload.getFailureDate().getType()); assertEquals(failureType, item.upload.getFailureCause().getType()); assertEquals("parent", item.uploadFailureParent().getName()); assertEquals("date", item.upload.getFailureDate().getName()); assertEquals("cause", item.upload.getFailureCause().getName()); assertSame(DispatcherItem.class, item.uploadFailureParent().getValueClass()); assertSame(DispatcherItem.TYPE, item.uploadFailureParent().getValueType()); try { new Dispatcher(0, 0); fail(); } catch(IllegalArgumentException e) { assertEquals("failureLimit must be greater zero, but was 0.", e.getMessage()); } try { new Dispatcher(-10, 0); fail(); } catch(IllegalArgumentException e) { assertEquals("failureLimit must be greater zero, but was -10.", e.getMessage()); } try { new Dispatcher(1000, 0); fail(); } catch(IllegalArgumentException e) { assertEquals("searchSize must be greater zero, but was 0.", e.getMessage()); } try { new Dispatcher(1000, -10); fail(); } catch(IllegalArgumentException e) { assertEquals("searchSize must be greater zero, but was -10.", e.getMessage()); } try { DispatcherNoneItem.newTypeAccessible(DispatcherNoneItem.class); fail(); } catch(ClassCastException e) { assertEquals( "type of DispatcherNoneItem.wrong must implement " + Dispatchable.class + ", but was " + DispatcherNoneItem.class.getName(), e.getMessage()); } // test persistence assertNotDone(list(), item1); assertNotDone(list(), item2); assertNotDone(list(), item3); assertNotDone(list(), item4); final DateRange d1 = dispatch(); assertDone(d1, list(), item1); assertNotDone(list(d1), item2); assertDone(d1, list(), item3); assertNotDone(list(d1), item4); final DateRange d2 = dispatch(); assertDone(d1, list(), item1); assertNotDone(list(d1, d2), item2); assertDone(d1, list(), item3); assertNotDone(list(d1, d2), item4); item2.setFail(false); final DateRange d3 = dispatch(); assertDone(d1, list(), item1); assertDone(d3, list(d1, d2), item2); assertDone(d1, list(), item3); assertNotDone(list(d1, d2, d3), item4); dispatch(); assertDone(d1, list(), item1); assertDone(d3, list(d1, d2), item2); assertDone(d1, list(), item3); assertNotDone(list(d1, d2, d3), item4); try { DispatcherItem.upload.dispatch(HashItem.class); fail(); } catch(ClassCastException e) { assertEquals("expected " + HashItem.class.getName() + ", but was " + DispatcherItem.class.getName(), e.getMessage()); } } private static class DateRange { final Date before; final Date after; DateRange(final Date before, final Date after) { this.before = before; this.after = after; assertTrue(!after.before(before)); } } private DateRange dispatch() { model.commit(); final Date before = new Date(); item.dispatchUpload(); final Date after = new Date(); model.startTransaction("DispatcherTest"); return new DateRange(before, after); } private static void assertDone(final DateRange date, final List failures, final DispatcherItem item) { assertEquals(false, item.isUploadPending()); assertWithin(date.before, date.after, item.getUploadSuccessDate()); assertTrue( String.valueOf(item.getUploadSuccessElapsed())+">="+item.getDispatchLastElapsed(), item.getUploadSuccessElapsed()>=item.getDispatchLastElapsed()); assertIt(failures.size()+1, failures, item); } private static void assertNotDone(final List failures, final DispatcherItem item) { assertEquals(failures.size()!=3, item.isUploadPending()); assertNull(item.getUploadSuccessDate()); assertNull(item.getUploadSuccessElapsed()); assertIt(failures.size(), failures, item); } private static void assertIt(final int dispatchCount, final List failures, final DispatcherItem item) { assertEquals(dispatchCount, item.getDispatchCount()); final List<Failure> actualFailures = item.getUploadFailures(); assertTrue(actualFailures.size()<=3); assertEquals(failures.size(), actualFailures.size()); final Iterator expectedFailureIter = failures.iterator(); for(final Failure actual : actualFailures) { final DateRange expected = (DateRange)expectedFailureIter.next(); assertSame(item.upload, actual.getPattern()); assertEquals(item, actual.getParent()); assertWithin(expected.before, expected.after, actual.getDate()); assertTrue(String.valueOf(actual.getElapsed()), actual.getElapsed()>=5); assertTrue(actual.getCause(), actual.getCause().startsWith(IOException.class.getName()+": "+item.getBody())); } } }
package edu.pdx.cs410J.j2se15; import java.io.PrintStream; import java.util.Calendar; /** * Demonstrated J2SE 1.5's facilities for <code>printf</code>-style * formatting. * * @see java.util.Formatter * * @author David Whitlock * @version $Revision: 1.2 $ * @since Summer 2004 */ public class Formatting { /** * Formats a number of different kinds of data using J2SE 1.5's * formatting facilities. */ public static void main(String[] args) { PrintStream out = System.out; out.printf("%s%n", "Hello World"); Calendar today = Calendar.getInstance(); out.printf("Today's date is: %tm/%td/%tY%n", today, today, today); out.printf("The current time is: %tl:%tM %tp%n", today, today, today); out.printf("%f/%.2f = %f%n", 2.0, 3.0, (2.0/3.0)); for (int i = 0; i < 3; i++) { out.printf("%5s%5s%5s%n", i, i+1, i+2); } out.printf("%-10s%s%n", "left", "right"); } }
package org.pentaho.ui.xul.gwt.tags; import com.google.gwt.user.client.ui.SimplePanel; import org.pentaho.gwt.widgets.client.toolbar.Toolbar; import org.pentaho.gwt.widgets.client.toolbar.ToolbarButton; import org.pentaho.gwt.widgets.client.toolbar.ToolbarGroup; import org.pentaho.ui.xul.XulComponent; import org.pentaho.ui.xul.components.XulToolbarbutton; import org.pentaho.ui.xul.components.XulToolbarseparator; import org.pentaho.ui.xul.components.XulToolbarspacer; import org.pentaho.ui.xul.components.XulToolbarspring; import org.pentaho.ui.xul.containers.XulToolbar; import org.pentaho.ui.xul.containers.XulToolbarset; import org.pentaho.ui.xul.containers.XulToolbar.ToolbarMode; import org.pentaho.ui.xul.dom.Element; import org.pentaho.ui.xul.gwt.AbstractGwtXulComponent; import org.pentaho.ui.xul.gwt.AbstractGwtXulContainer; import org.pentaho.ui.xul.gwt.GwtXulHandler; import org.pentaho.ui.xul.gwt.GwtXulParser; import com.google.gwt.user.client.ui.Panel; public class GwtToolbar extends AbstractGwtXulContainer implements XulToolbar{ private String toolbarName; private ToolbarMode mode = ToolbarMode.ICONS; private Toolbar toolbar = new Toolbar(); private boolean loaded; public static void register() { GwtXulParser.registerHandler("toolbar", new GwtXulHandler() { public Element newInstance() { return new GwtToolbar(); } }); } public GwtToolbar(){ super("toolbar"); setManagedObject(toolbar); } public String getToolbarName() { return toolbarName; } public void setToolbarName(String name) { this.toolbarName = name; } public void setMode(String mode) { this.mode = ToolbarMode.valueOf(mode.toUpperCase()); } public String getMode(){ return mode.toString(); } @Override public void layout() { toolbar.removeAll(); boolean flexLayout = false; for(XulComponent c : this.getChildNodes()){ if(c.getFlex() > 0){ flexLayout = true; } add(c); } if(! flexLayout){ SimplePanel spacer = new SimplePanel(); spacer.getElement().setAttribute("flex", "1"); toolbar.add(spacer); } if(!loaded){ loaded = true; } } private void add(XulComponent c){ if(c instanceof XulToolbarset){ ToolbarGroup group = (ToolbarGroup) c.getManagedObject(); toolbar.add(group); } else if(c instanceof XulToolbarbutton){ toolbar.add((ToolbarButton) c.getManagedObject()); } else if(c instanceof XulToolbarseparator){ toolbar.add(Toolbar.SEPARATOR); } else if(c instanceof XulToolbarspring){ toolbar.add(Toolbar.GLUE); } else if(c instanceof XulToolbarspacer){ Panel p = (Panel) c.getManagedObject(); toolbar.add(p); } } @Override public void addChild(Element element) { super.addChild(element); if(loaded == true){ // toolbar.removeAll(); this.layout(); } } @Override public void addChildAt(Element element, int idx) { super.addChildAt(element, idx); if(loaded == true){ // toolbar.removeAll(); this.layout(); } } @Override public void removeChild(Element element) { super.removeChild(element); XulComponent child = (XulComponent) element; if(child instanceof XulToolbarbutton){ toolbar.remove(((ToolbarButton) child.getManagedObject()).getPushButton()); } } }
package pt.up.pteid4j.pkcs; import pt.up.pteid4j.PTeID4JException; /** * PTeID4J PKCS Exception Class * * @author Andre Barbosa ([email protected]) */ public class PTeID4JPKCSException extends PTeID4JException { private static final long serialVersionUID = -1278519801897110421L; /** * Class Constructor * * @param message * the PTeID4J PKCS Exception error message */ public PTeID4JPKCSException(String message) { super(message); } /** * Class Constructor * * @param exception * the Exception that triggered the PTeID4J PKCS Exception */ public PTeID4JPKCSException(Exception exception) { super(exception); } }
/* * $Log: SapSender.java,v $ * Revision 1.2 2004-07-15 07:36:24 L190409 * updated javadoc * * Revision 1.1 2004/07/06 07:09:05 Gerrit van Brakel <[email protected]> * moved SAP functionality to extensions * * Revision 1.2 2004/07/05 10:50:18 Gerrit van Brakel <[email protected]> * corrected version setting * * Revision 1.1 2004/06/22 06:56:45 Gerrit van Brakel <[email protected]> * First version of SAP package * */ package nl.nn.adapterframework.extensions.sap; import org.apache.commons.lang.StringUtils; import com.sap.mw.jco.*; import nl.nn.adapterframework.core.ISender; import nl.nn.adapterframework.core.SenderException; import nl.nn.adapterframework.configuration.ConfigurationException; /** * Implementation of {@link ISender} that calls a SAP RFC-function. * <p><b>Configuration:</b> * <table border="1"> * <tr><th>attributes</th><th>description</th><th>default</th></tr> * <tr><td>{@link #setName(String) name}</td><td>Name of the Sender</td><td>&nbsp;</td></tr> * <tr><td>{@link #setFunctionName(String) functionName}</td><td>Name of the RFC-function to be called in the SAP system</td><td>&nbsp;</td></tr> * <tr><td>{@link #setName(String) sapSystemName}</td><td>name of the SapSystem used by this object</td><td>&nbsp;</td></tr> * <tr><td>{@link #setCorrelationIdFieldIndex(int) correlationIdFieldIndex}</td><td>Index of the field in the ImportParameterList of the RFC function that contains the correlationId</td><td>0</td></tr> * <tr><td>{@link #setCorrelationIdFieldName(String) correlationIdFieldName}</td><td>Name of the field in the ImportParameterList of the RFC function that contains the correlationId</td><td>&nbsp;</td></tr> * <tr><td>{@link #setRequestFieldIndex(int) requestFieldIndex}</td><td>Index of the field in the ImportParameterList of the RFC function that contains the whole request message contents</td><td>0</td></tr> * <tr><td>{@link #setRequestFieldName(String) requestFieldName}</td><td>Name of the field in the ImportParameterList of the RFC function that contains the whole request message contents</td><td>&nbsp;</td></tr> * <tr><td>{@link #setReplyFieldIndex(int) replyFieldIndex}</td><td>Index of the field in the ExportParameterList of the RFC function that contains the whole reply message contents</td><td>0</td></tr> * <tr><td>{@link #setReplyFieldName(String) replyFieldName}</td><td>Name of the field in the ExportParameterList of the RFC function that contains the whole reply message contents</td><td>&nbsp;</td></tr> * </table> * N.B. If no requestFieldIndex or requestFieldName is specified, input is converted from xml; * If no replyFieldIndex or replyFieldName is specified, output is converted to xml. * </p> * @author Gerrit van Brakel * @since 4.2 */ public class SapSender extends SapFunctionFacade implements ISender { public static final String version="$Id: SapSender.java,v 1.2 2004-07-15 07:36:24 L190409 Exp $"; //TODO: allow functionName to be set dynamically from a parameter or from the message private String functionName=null; public void configure() throws ConfigurationException { super.configure(); if (StringUtils.isEmpty(getFunctionName())) { throw new ConfigurationException("["+getName()+"]Function name is mandatory"); } } public void open() throws SenderException { try { openFacade(); } catch (SapException e) { throw new SenderException("exception configuring SapFacade", e); } } public void close() { closeFacade(); } public String sendMessage(String correlationID, String message) throws SenderException { JCO.Client client = null; try { JCO.Function function = getFunctionTemplate().getFunction(); message2FunctionCall(function, message, correlationID); client = getSapSystem().getClient(); client.execute(function); return functionResult2message(function); } catch (Exception e) { throw new SenderException(e); } finally { getSapSystem().releaseClient(client); } } /** * allways returns true. */ public boolean isSynchronous() { return true; } public String getFunctionName() { return functionName; } public void setFunctionName(String string) { functionName = string; } }
/* * $Log: SapServer.java,v $ * Revision 1.5 2005-08-02 13:03:35 europe\L190409 * corrected version string * * Revision 1.4 2005/08/02 13:01:09 Gerrit van Brakel <[email protected]> * included logging in transaction handling functions * * Revision 1.3 2005/03/14 17:27:05 Gerrit van Brakel <[email protected]> * increased logging * * Revision 1.2 2004/10/05 10:41:24 Gerrit van Brakel <[email protected]> * removed unused imports * * Revision 1.1 2004/07/06 07:09:05 Gerrit van Brakel <[email protected]> * moved SAP functionality to extensions * * Revision 1.3 2004/06/30 12:38:57 Gerrit van Brakel <[email protected]> * removed self from exceptionlisteners * * Revision 1.2 2004/06/23 11:40:17 Gerrit van Brakel <[email protected]> * included error-logging and added transaction-related function-stubs * * Revision 1.1 2004/06/22 06:56:44 Gerrit van Brakel <[email protected]> * First version of SAP package * */ package nl.nn.adapterframework.extensions.sap; import org.apache.log4j.Logger; import com.sap.mw.jco.JCO; /** * Object that acts as a SAP-server. Currently used to receive RFC-function calls from SAP. * @author Gerrit van Brakel * @since 4.2 */ public class SapServer extends JCO.Server implements JCO.ServerExceptionListener, JCO.ServerErrorListener , JCO.ServerStateChangedListener { public static final String version="$RCSfile: SapServer.java,v $ $Revision: 1.5 $ $Date: 2005-08-02 13:03:35 $"; protected Logger log = Logger.getLogger(this.getClass()); private SapFunctionHandler handler = null; public SapServer(SapSystem system, String progid, SapFunctionHandler handler) { super(system.getGwhost(), system.getGwserv(), progid, system.getRepository()); this.handler = handler; log.info("SapServer connected to ["+system.getGwhost()+":"+system.getGwserv()+"] using progid ["+progid+"]"); // JCO.addServerExceptionListener(this); // JCO.addServerErrorListener(this); JCO.addServerStateChangedListener(this); } /* * Not really necessary to override this function but for demonstration purposes... */ protected JCO.Function getFunction(String function_name) { JCO.Function function = super.getFunction(function_name); return function; } /* * Not really necessary to override this method but for demonstration purposes... */ protected boolean checkAuthorization(String function_name, int authorization_mode, String authorization_partner, byte[] authorization_key) { /*Simply allow everyone to invoke the services */ return true; } protected void handleRequest(JCO.Function function) { try { log.info("sap function called: "+function.getName()); handler.processFunctionCall(function); } catch (Throwable t) { log.warn("Exception caught and handed to SAP",t); throw new JCO.AbapException("IbisException", t.getMessage()); } } /** * SAP JCo.Server javadoc says: * This function will be invoked when a transactional RFC is being called from a * SAP R/3 system. The function has to store the TID in permanent storage and return <code>true</code>. * The method has to return <code>false</code> if the a transaction with this ID has already * been process. Throw an exception if anything goes wrong. The transaction processing will be * aborted thereafter.<b> * Derived servers must override this method to actually implement the transaction ID management. * @param tid the transaction ID * @return <code>true</code> if the ID is valid and not in use otherwise, <code>false</code> otherwise */ protected boolean onCheckTID(String tid) { if (log.isDebugEnabled()) { log.debug("SapServer [" + getProgID() + "] is requested to check TID ["+tid+"]; (currently ignored)"); } return true; } /** * SAP JCo.Server javadoc says: * This function will be called after the <em>local</em> transaction has been completed. * All resources assiciated with this TID can be released.<b> * Derived servers must override this method to actually implement the transaction ID management. * @param tid the transaction ID */ protected void onConfirmTID(String tid) { if (log.isDebugEnabled()) { log.debug("SapServer [" + getProgID() + "] is requested to confirm TID ["+tid+"]; (currently ignored)"); } } /** * SAP JCo.Server javadoc says: * This function will be called after <em>all</em> RFC functions belonging to a certain transaction * have been successfully completed. <b> * Derived servers can override this method to locally commit the transaction. * @param tid the transaction ID */ protected void onCommit(String tid) { if (log.isDebugEnabled()) { log.debug("SapServer [" + getProgID() + "] is requested to commit TID ["+tid+"]; (currently ignored)"); } } /** * SAP JCo.Server javadoc says: * This function will be called if an error in one of the RFC functions belonging to * a certain transaction has occurred.<b> * Derived servers can override this method to locally rollback the transaction. * @param tid the transaction ID */ protected void onRollback(String tid) { if (log.isDebugEnabled()) { log.debug("SapServer [" + getProgID() + "] is requested to rollback TID ["+tid+"]; (currently ignored)"); } } public void serverExceptionOccurred(JCO.Server server, Exception e) { log.error("Exception in SapServer [" + server.getProgID() + "]", e); } public void serverErrorOccurred(JCO.Server server, Error err) { log.error("Error in SapServer [" + server.getProgID() + "]", err); } public String stateToString(int state) { String result=""; if ((state & JCO.STATE_STOPPED ) != 0) result += " STOPPED "; if ((state & JCO.STATE_STARTED ) != 0) result += " STARTED "; if ((state & JCO.STATE_LISTENING ) != 0) result += " LISTENING "; if ((state & JCO.STATE_TRANSACTION) != 0) result += " TRANSACTION "; if ((state & JCO.STATE_BUSY ) != 0) result += " BUSY "; return result; } /* (non-Javadoc) * @see com.sap.mw.jco.JCO.ServerStateChangedListener#serverStateChangeOccurred(com.sap.mw.jco.JCO.Server, int, int) */ public void serverStateChangeOccurred(JCO.Server server, int old_state, int new_state) { log.debug("Server [" + server.getProgID() + "] changed state from [" +stateToString(old_state)+"] to ["+stateToString(new_state)+"]"); } }
package org.mockito.usage.binding; import static org.junit.Assert.*; import org.junit.*; import org.mockito.Mockito; import org.mockito.exceptions.VerificationAssertionError; public class IncorectBindingPuzzleFixedTest { private BaseInteface mock; private void setMock(DerivedInterface mock) { this.mock = mock; } private class BaseMessage { public String toString() { return "BaseMessage"; } } private class Message extends BaseMessage { public String toString() { return "Message"; } } private interface BaseInteface { public void print(BaseMessage message); } private interface DerivedInterface extends BaseInteface { public void print(Message message); } private void print(BaseMessage message) { mock.print(message); } @Ignore @Test public void overriddenInterfaceMethodNotWorking() throws Exception { DerivedInterface derivedMock = Mockito.mock(DerivedInterface.class); setMock(derivedMock); Message message = new Message(); print(message); try { Mockito.verify(derivedMock).print(message); } catch (VerificationAssertionError error) { String expected = "\n" + "Not invoked: DerivedInterface.print(Message)" + "But found: DerivedInterface.print(BaseMessage)"; assertEquals(expected, error.getMessage()); } } @Ignore @Test public void shouldReportNoMoreInteractionsProperly() throws Exception { DerivedInterface derivedMock = Mockito.mock(DerivedInterface.class); setMock(derivedMock); Message message = new Message(); print(message); try { Mockito.verifyNoMoreInteractions(derivedMock); } catch (VerificationAssertionError error) { String expected = "\n" + "No more interactions expected on DerivedInterface but found: DerivedInterface.print(BaseMessage)"; assertEquals(expected, error.getMessage()); } } }
package de.smits_net.games.examples.dodger; import de.smits_net.games.framework.board.Board; import de.smits_net.games.framework.image.AnimatedImage; import de.smits_net.games.framework.sprite.AnimatedSprite; import de.smits_net.games.framework.sprite.Direction; import java.awt.Point; /** * A sun falling from the sky. */ public class Sun extends AnimatedSprite { /** * Create a new sun. * * @param board the game board * @param startPoint point to start sprite * @param speed speed of the animation */ public Sun(Board board, Point startPoint, int speed) { super(board, startPoint, BoundaryPolicy.NONE, new AnimatedImage(50, "assets/dodger", "sun1.png", "sun2.png" )); velocity.setVelocity(Direction.SOUTH, speed); } }
package railo.runtime.engine; import java.io.PrintWriter; import java.util.Map; import railo.commons.io.res.Resource; import railo.commons.io.res.filter.ExtensionResourceFilter; import railo.commons.io.res.filter.ResourceFilter; import railo.commons.io.res.util.ResourceUtil; import railo.commons.lang.SystemOut; import railo.commons.lang.types.RefBoolean; import railo.runtime.CFMLFactoryImpl; import railo.runtime.Mapping; import railo.runtime.MappingImpl; import railo.runtime.PageSource; import railo.runtime.PageSourcePool; import railo.runtime.config.ConfigImpl; import railo.runtime.config.ConfigServer; import railo.runtime.config.ConfigWeb; import railo.runtime.config.ConfigWebImpl; import railo.runtime.type.dt.DateTimeImpl; import railo.runtime.type.scope.ClientFile; import railo.runtime.type.scope.ScopeContext; import railo.runtime.type.util.ArrayUtil; /** * own thread how check the main thread and his data */ public final class Controler extends Thread { private int interval; private long lastMinuteInterval=System.currentTimeMillis(); private long lastHourInterval=System.currentTimeMillis(); int maxPoolSize=500; private Map contextes; private RefBoolean run; //private ScheduleThread scheduleThread; private ConfigServer configServer; /** * @param contextes * @param interval * @param run */ public Controler(ConfigServer configServer,Map contextes,int interval, RefBoolean run) { this.contextes=contextes; this.interval=interval; this.run=run; this.configServer=configServer; } /** * @see java.lang.Runnable#run() */ public void run() { //scheduleThread.start(); boolean firstRun=true; CFMLFactoryImpl factories[]=null; while(run.toBooleanValue()) { try { sleep(interval); } catch (InterruptedException e) { e.printStackTrace(); } long now = System.currentTimeMillis(); //print.out("now:"+new Date(now)); boolean doMinute=lastMinuteInterval+60000<now; if(doMinute)lastMinuteInterval=now; boolean doHour=(lastHourInterval+(1000*60*60))<now; if(doHour)lastHourInterval=now; // if(doMinute) System.gc(); // broadcast cluster scope factories=toFactories(factories,contextes); try { ScopeContext.getClusterScope(configServer,true).broadcast(); } catch (Throwable t) { t.printStackTrace(); } for(int i=0;i<factories.length;i++) { run(factories[i], doMinute, doHour,firstRun); } if(factories.length>0) firstRun=false; } } private CFMLFactoryImpl[] toFactories(CFMLFactoryImpl[] factories,Map contextes) { if(factories==null || factories.length!=contextes.size()) factories=(CFMLFactoryImpl[]) contextes.values().toArray(new CFMLFactoryImpl[contextes.size()]); return factories; } private void run(CFMLFactoryImpl cfmlFactory, boolean doMinute, boolean doHour, boolean firstRun) { try { boolean isRunning=cfmlFactory.getUsedPageContextLength()>0; if(isRunning) { cfmlFactory.checkTimeout(); } ConfigWeb config = null; if(firstRun) { if(config==null) { config = cfmlFactory.getConfig(); ThreadLocalConfig.register(config); } config.reloadTimeServerOffset(); checkOldClientFile(config); try{checkClientFileSize(config);}catch(Throwable t){} try{config.reloadTimeServerOffset();}catch(Throwable t){} try{checkTempDirectorySize(config);}catch(Throwable t){} try{checkCacheFileSize(config);}catch(Throwable t){} } //every Minute if(doMinute) { if(config==null) { config = cfmlFactory.getConfig(); ThreadLocalConfig.register(config); } // clear unused DB Connections try{((ConfigImpl)config).getDatasourceConnectionPool().clear();}catch(Throwable t){} // clear all unused scopes try{cfmlFactory.getScopeContext().clearUnused(cfmlFactory);}catch(Throwable t){} // Memory usage // clear Query Cache try{cfmlFactory.getQueryCache().clearUnused();}catch(Throwable t){} // contract Page Pool try{doClearPagePools((ConfigWebImpl) config);}catch(Throwable t){} try{doCheckMappings(config);}catch(Throwable t){} } // every hour if(doHour) { if(config==null) { config = cfmlFactory.getConfig(); ThreadLocalConfig.register(config); } // time server offset try{config.reloadTimeServerOffset();}catch(Throwable t){} // check file based client scope try{checkClientFileSize(config);}catch(Throwable t){} // check temp directory try{checkTempDirectorySize(config);}catch(Throwable t){} // check cache directory try{checkCacheFileSize(config);}catch(Throwable t){} } } catch(Throwable t){ } finally{ ThreadLocalConfig.release(); } } private void checkClientFileSize(ConfigWeb config) { ExtensionResourceFilter filter = new ExtensionResourceFilter(".script",true); try { long date = new DateTimeImpl(config).getTime()-((ConfigWebImpl)config).getClientTimeout().getMillis(); //long date = DateAdd.invoke("d", -((ConfigWebImpl)config).getClientScopeMaxAge(), new DateTimeImpl(config)).getTime(); ResourceUtil.deleteFileOlderThan(config.getClientScopeDir(),date,filter); ResourceUtil.deleteEmptyFolders(config.getClientScopeDir()); } catch (Exception e) {} checkSize(config,config.getClientScopeDir(),config.getClientScopeDirSize(),new ExtensionResourceFilter(".script",true)); } private void checkOldClientFile(ConfigWeb config) { ExtensionResourceFilter filter = new ExtensionResourceFilter(".script",false); // move old structured file in new structure try { Resource dir = config.getClientScopeDir(),trgres; Resource[] children = dir.listResources(filter); String src,trg; int index; for(int i=0;i<children.length;i++) { src=children[i].getName(); index=src.indexOf('-'); trg=ClientFile.getFolderName(src.substring(0,index), src.substring(index+1),false); trgres=dir.getRealResource(trg); if(!trgres.exists()){ trgres.createFile(true); ResourceUtil.copy(children[i],trgres); } //children[i].moveTo(trgres); children[i].delete(); } } catch (Throwable t) {} } private void checkCacheFileSize(ConfigWeb config) { checkSize(config,config.getCacheDir(),config.getCacheDirSize(),new ExtensionResourceFilter(".cache")); } private void checkTempDirectorySize(ConfigWeb config) { checkSize(config,config.getTempDirectory(),1024*1024*100,null); } private void checkSize(ConfigWeb config,Resource dir,long maxSize, ResourceFilter filter) { if(!dir.exists()) return; Resource res=null; int count=ArrayUtil.size(filter==null?dir.list():dir.list(filter)); long size=ResourceUtil.getRealSize(dir,filter); PrintWriter out = config.getOutWriter(); SystemOut.printDate(out,"check size of directory ["+dir+"]"); SystemOut.printDate(out,"- current size ["+size+"]"); SystemOut.printDate(out,"- max size ["+maxSize+"]"); while(count>100000 || size>maxSize) { Resource[] files = filter==null?dir.listResources():dir.listResources(filter); for(int i=0;i<files.length;i++) { if(res==null || res.lastModified()>files[i].lastModified()) { res=files[i]; } } if(res!=null) { size-=res.length(); if(res.delete()) count } res=null; } } private void doCheckMappings(ConfigWeb config) { Mapping[] mappings = config.getMappings(); for(int i=0;i<mappings.length;i++) { Mapping mapping = mappings[i]; mapping.check(); } } private void doClearPagePools(ConfigWebImpl config) { PageSourcePool[] pools=getPageSourcePools(config); int poolSize=getPageSourcePoolSize(pools); long start =System.currentTimeMillis(); int startsize=poolSize; while(poolSize>maxPoolSize) { removeOldest(pools); poolSize } if(startsize>poolSize) SystemOut.printDate(config.getOutWriter(),"contract pagepools from "+startsize+" to "+poolSize +" in "+(System.currentTimeMillis()-start)+" millis"); } private PageSourcePool[] getPageSourcePools(ConfigWeb config) { Mapping[] mappings = config.getMappings(); PageSourcePool[] pools=new PageSourcePool[mappings.length]; int size=0; for(int i=0;i<mappings.length;i++) { pools[i]=((MappingImpl)mappings[i]).getPageSourcePool(); size+=pools[i].size(); } return pools; } private int getPageSourcePoolSize(PageSourcePool[] pools) { int size=0; for(int i=0;i<pools.length;i++)size+=pools[i].size(); return size; } private void removeOldest(PageSourcePool[] pools) { PageSourcePool pool=null; Object key=null; PageSource ps=null; long date=-1; for(int i=0;i<pools.length;i++) { try { Object[] keys=pools[i].keys(); for(int y=0;y<keys.length;y++) { ps = pools[i].getPageSource(keys[y],false); if(date==-1 || date>ps.getLastAccessTime()) { pool=pools[i]; key=keys[y]; date=ps.getLastAccessTime(); } } } catch(Throwable t) { pools[i].clear(); } } if(pool!=null)pool.remove(key); } /*private void doLogMemoryUsage(ConfigWeb config) { if(config.logMemoryUsage()&& config.getMemoryLogger()!=null) config.getMemoryLogger().write(); }*/ }
import java.net.Socket; import java.net.ServerSocket; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.regex.Pattern; import java.io.*; public class ProxyServer { //constant value //unit this program may resolve //ip address of Servers //port num of Servers public static void process (Socket clientSocket) throws IOException { // open up IO streams BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); /* Write a welcome message to the client */ out.println("Welcome to the Proxy Server!"); out.println("Please input as \"<input> <output> <value>\""); //traverse the osContainer Iterator<String> objIter = osContainer.objServer.keySet().iterator(); while(objIter.hasNext()){ out.println("Available Unit: " + objIter.next()); } /* read and print the client's request */ // readLine() blocks until the server receives a new line from client String userInput; if ((userInput = in.readLine()) == null) { System.out.println("Error reading message"); out.close(); in.close(); clientSocket.close(); } System.out.println("Received message: " + userInput); //--TODO: add your converting functions here, msg = func(userInput); String[] tokens = userInput.split(" "); //Check the input and call other servers if(tokens.length != 3){ out.println("The number of parameter is incorrect"); }else if(!isDouble(tokens[2])){ out.println("The third parameter is not interger"); }else{ /*Set<String> connectRoute = findConnectRoute(obj1,obj2,new LinkedHashSet<String>()); if(connectRoute.size() == 0){ out.println("The convertion is not available"); }else if(connectRoute.size() < 2){ System.err.println("Find Route Err"); }else{ Iterator<String> test = connectRoute.iterator(); while(test.hasNext()) System.out.println(test.next()); Iterator<String> routeIter = connectRoute.iterator(); obj2 = routeIter.next(); String output = null; while(routeIter.hasNext()){ obj1 = obj2; obj2 = routeIter.next(); String input = obj1 + " " + obj2 + " " + val; Server s = osContainer.getServer(obj1,obj2); output = connectServer(s.host, s.port, input); System.out.println(output); if(output == null){ out.println("Connection Failed"); break; } String[] temp = output.split(" "); val = temp[0]; } out.println(output); }*/ } // close IO streams, then socket out.close(); in.close(); clientSocket.close(); } // function to connect the discovery server and get back the result as a Server object public static Server lookupServer(String[] tokens) throws IOException{ String obj1 = tokens[0]; String obj2 = tokens[1]; Server result; Socket discoverySocket; try{ discoverySocket = new Socket(discoveryHost, discoveryPort); }catch(IOException e){ System.err.println("Failed to find discovery server!"); return null; } PrintWriter dout = new PrintWriter(discoverySocket.getOutputStream(),true); BufferedReader din = new BufferedReader(new InputStreamReader(discoverySocket.getInputStream())); dout.println("lookup" + " " + tokens[0] + " " + tokens[1]); String output; switch (output = din.readLine()){ case "ERR001" :{ System.out.println(Constants.getErrInfoString("ERR001")); } case "ERR008" :{ System.out.println(Constants.getErrInfoString("Err008")); } case "ERR009" :{ System.out.println(Constants.getErrInfoString("ERR009")); } default :{ } } String[] answer = output.split(" "); result = new Server(answer[0], Integer.parseInt(answer[1]), new ConObject(obj1), new ConObject(obj2)); return result; } //function using to connect the remote server public static String connectServer(String host, int port, String input) throws IOException{ Socket socket; try{ socket = new Socket(host, port); }catch(IOException e){ System.err.println("Conection Failed!"); return null; } PrintWriter out = new PrintWriter(socket.getOutputStream(),true); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); out.println(input); String output; if((output = in.readLine()) == null || output.equals("Invalid Input!")){ System.err.println("Error reading message"); out.close(); in.close(); socket.close(); return null; } out.close(); in.close(); socket.close(); return output; } // a simple function to check is Double or not //if not return null,if is return double private static boolean isDouble(String str) { try{ Double.parseDouble(str); }catch(NumberFormatException e){ return false; } return true; } public static void main(String[] args) throws Exception { //check if argument length is invalid if(args.length != 1) { System.err.println("Usage: java ConvServer port"); System.exit(-1); } // create socket int port = Integer.parseInt(args[0]); ServerSocket serverSocket = new ServerSocket(port); System.err.println("Started server on port " + port); // wait for connections, and process try { while(true) { // a "blocking" call which waits until a connection is requested Socket clientSocket = serverSocket.accept(); System.err.println("\nAccepted connection from client"); process(clientSocket); } }catch (IOException e) { System.err.println("Connection Error"); } System.exit(0); } } // //read server info from routing table file // //add server to ObjServerContainer // try{ // BufferedReader reader = new BufferedReader(new FileReader("routing_table")); // String strIn = reader.readLine(); // while((strIn = reader.readLine()) != null){ // String[] split = strIn.split(" "); // if(split.length != 4){ // System.err.println("routing_table row length invalid"); // continue; // if(!isInteger(split[1])){ // System.err.println("routing_table port not interger"); // continue; // String host = split[0]; // int port = Integer.parseInt(split[1]); // String obj1 = split[2]; // String obj2 = split[3]; // Server s = new Server(host,port,obj1,obj2); // osContainer.addServer(obj1,obj2,s); // osContainer.addServer(obj2,obj1,s); // }catch(FileNotFoundException fnfe){ // System.err.println(fnfe); // }catch(IOException ioe){ // System.err.println(ioe);
package org.openecard.sal; import iso.std.iso_iec._24727.tech.schema.AccessControlListType; import iso.std.iso_iec._24727.tech.schema.AccessRuleType; import iso.std.iso_iec._24727.tech.schema.ActionNameType; import iso.std.iso_iec._24727.tech.schema.APIAccessEntryPointName; import iso.std.iso_iec._24727.tech.schema.ACLList; import iso.std.iso_iec._24727.tech.schema.ACLListResponse; import iso.std.iso_iec._24727.tech.schema.ACLModify; import iso.std.iso_iec._24727.tech.schema.ACLModifyResponse; import iso.std.iso_iec._24727.tech.schema.CardApplicationConnect; import iso.std.iso_iec._24727.tech.schema.CardApplicationConnectResponse; import iso.std.iso_iec._24727.tech.schema.CardApplicationCreate; import iso.std.iso_iec._24727.tech.schema.CardApplicationCreateResponse; import iso.std.iso_iec._24727.tech.schema.CardApplicationDelete; import iso.std.iso_iec._24727.tech.schema.CardApplicationDeleteResponse; import iso.std.iso_iec._24727.tech.schema.CardApplicationDisconnect; import iso.std.iso_iec._24727.tech.schema.CardApplicationDisconnectResponse; import iso.std.iso_iec._24727.tech.schema.CardApplicationEndSession; import iso.std.iso_iec._24727.tech.schema.CardApplicationEndSessionResponse; import iso.std.iso_iec._24727.tech.schema.CardApplicationList; import iso.std.iso_iec._24727.tech.schema.CardApplicationListResponse; import iso.std.iso_iec._24727.tech.schema.CardApplicationPath; import iso.std.iso_iec._24727.tech.schema.CardApplicationPathResponse; import iso.std.iso_iec._24727.tech.schema.CardApplicationPathType; import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceCreate; import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceCreateResponse; import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceDelete; import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceDeleteResponse; import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceDescribe; import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceDescribeResponse; import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceList; import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceListResponse; import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceListResponse.CardApplicationServiceNameList; import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceLoad; import iso.std.iso_iec._24727.tech.schema.CardApplicationServiceLoadResponse; import iso.std.iso_iec._24727.tech.schema.CardApplicationStartSession; import iso.std.iso_iec._24727.tech.schema.CardApplicationStartSessionResponse; import iso.std.iso_iec._24727.tech.schema.ConnectionHandleType; import iso.std.iso_iec._24727.tech.schema.ConnectionHandleType.RecognitionInfo; import iso.std.iso_iec._24727.tech.schema.DIDAuthenticate; import iso.std.iso_iec._24727.tech.schema.DIDAuthenticateResponse; import iso.std.iso_iec._24727.tech.schema.DIDCreate; import iso.std.iso_iec._24727.tech.schema.DIDCreateResponse; import iso.std.iso_iec._24727.tech.schema.DIDDelete; import iso.std.iso_iec._24727.tech.schema.DIDDeleteResponse; import iso.std.iso_iec._24727.tech.schema.DIDGet; import iso.std.iso_iec._24727.tech.schema.DIDGetResponse; import iso.std.iso_iec._24727.tech.schema.DIDList; import iso.std.iso_iec._24727.tech.schema.DIDListResponse; import iso.std.iso_iec._24727.tech.schema.DIDQualifierType; import iso.std.iso_iec._24727.tech.schema.DIDUpdate; import iso.std.iso_iec._24727.tech.schema.DIDUpdateResponse; import iso.std.iso_iec._24727.tech.schema.DSICreate; import iso.std.iso_iec._24727.tech.schema.DSICreateResponse; import iso.std.iso_iec._24727.tech.schema.DSIDelete; import iso.std.iso_iec._24727.tech.schema.DSIDeleteResponse; import iso.std.iso_iec._24727.tech.schema.DSIList; import iso.std.iso_iec._24727.tech.schema.DSIListResponse; import iso.std.iso_iec._24727.tech.schema.DSIRead; import iso.std.iso_iec._24727.tech.schema.DSIReadResponse; import iso.std.iso_iec._24727.tech.schema.DSIWrite; import iso.std.iso_iec._24727.tech.schema.DSIWriteResponse; import iso.std.iso_iec._24727.tech.schema.DataSetCreate; import iso.std.iso_iec._24727.tech.schema.DataSetCreateResponse; import iso.std.iso_iec._24727.tech.schema.DataSetDelete; import iso.std.iso_iec._24727.tech.schema.DataSetDeleteResponse; import iso.std.iso_iec._24727.tech.schema.DataSetList; import iso.std.iso_iec._24727.tech.schema.DataSetListResponse; import iso.std.iso_iec._24727.tech.schema.DataSetSelect; import iso.std.iso_iec._24727.tech.schema.DataSetSelectResponse; import iso.std.iso_iec._24727.tech.schema.Decipher; import iso.std.iso_iec._24727.tech.schema.DecipherResponse; import iso.std.iso_iec._24727.tech.schema.Encipher; import iso.std.iso_iec._24727.tech.schema.EncipherResponse; import iso.std.iso_iec._24727.tech.schema.EstablishContext; import iso.std.iso_iec._24727.tech.schema.EstablishContextResponse; import iso.std.iso_iec._24727.tech.schema.ExecuteAction; import iso.std.iso_iec._24727.tech.schema.ExecuteActionResponse; import iso.std.iso_iec._24727.tech.schema.GetRandom; import iso.std.iso_iec._24727.tech.schema.GetRandomResponse; import iso.std.iso_iec._24727.tech.schema.Hash; import iso.std.iso_iec._24727.tech.schema.HashResponse; import iso.std.iso_iec._24727.tech.schema.Initialize; import iso.std.iso_iec._24727.tech.schema.InitializeResponse; import iso.std.iso_iec._24727.tech.schema.ListIFDs; import iso.std.iso_iec._24727.tech.schema.ListIFDsResponse; import iso.std.iso_iec._24727.tech.schema.PathType; import iso.std.iso_iec._24727.tech.schema.SecurityConditionType; import iso.std.iso_iec._24727.tech.schema.Sign; import iso.std.iso_iec._24727.tech.schema.SignResponse; import iso.std.iso_iec._24727.tech.schema.TargetNameType; import iso.std.iso_iec._24727.tech.schema.Terminate; import iso.std.iso_iec._24727.tech.schema.TerminateResponse; import iso.std.iso_iec._24727.tech.schema.VerifyCertificate; import iso.std.iso_iec._24727.tech.schema.VerifyCertificateResponse; import iso.std.iso_iec._24727.tech.schema.VerifySignature; import iso.std.iso_iec._24727.tech.schema.VerifySignatureResponse; import java.math.BigInteger; import java.util.Iterator; import java.util.Arrays; import java.util.List; import javax.xml.parsers.ParserConfigurationException; import org.openecard.bouncycastle.util.encoders.Hex; import org.openecard.common.ClientEnv; import org.openecard.common.ECardConstants; import org.openecard.common.enums.EventType; import org.openecard.common.interfaces.Dispatcher; import org.openecard.common.sal.state.CardStateEntry; import org.openecard.common.sal.state.CardStateMap; import org.openecard.common.sal.state.SALStateCallback; import org.openecard.common.util.ByteUtils; import org.openecard.ifd.scio.IFD; import org.openecard.recognition.CardRecognition; import org.openecard.transport.dispatcher.MessageDispatcher; import org.testng.Assert; import org.testng.SkipException; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import static org.testng.Assert.*; public class TinySALTest { //@BeforeClass //public static void disable() { // throw new SkipException("Test completely disabled."); private static ClientEnv env; private static TinySAL instance; private static CardStateMap states; private static IFD ifd; private static Dispatcher dispatcher; // private static CardApplicationPathResponse cardApplicationPathResponse; byte[] appIdentifier_ESIGN = Hex.decode("A000000167455349474E"); byte[] appIdentifier_ROOT = Hex.decode("D2760001448000"); byte[] appIdentifier_IRMA = Hex.decode("F849524D4163617264"); @BeforeClass public static void setUp() throws Exception { env = new ClientEnv(); IFD ifd = new IFD(); states = new CardStateMap(); dispatcher = new MessageDispatcher(env); env.setIFD(ifd); env.setDispatcher(dispatcher); instance = new TinySAL(env, states); } /** * Test of getConnectionHandles method, of class TinySAL. */ @Test(enabled=false) public void testGetConnectionHandles() { System.out.println("getConnectionHandles"); List<ConnectionHandleType> cHandles = instance.getConnectionHandles(); assertTrue(cHandles.isEmpty()); String[] readers = { "Reader 1", "Reader 2" }; ConnectionHandleType cHandle1 = new ConnectionHandleType(); cHandle1.setIFDName(readers[0]); ConnectionHandleType cHandle2 = new ConnectionHandleType(); cHandle2.setIFDName(readers[1]); // add connection handles to microSAL CardStateEntry entry1 = new CardStateEntry(cHandle1, null); // TODO: null works as long as // there is no cif support states.addEntry(entry1); CardStateEntry entry2 = new CardStateEntry(cHandle2, null); states.addEntry(entry2); cHandles = instance.getConnectionHandles(); assertTrue(cHandles.size() == 2); for (int i = 0; i < cHandles.size(); i++) { assertEquals(readers[i], cHandles.get(i).getIFDName()); } // remove one connection handle from microSAL states.removeEntry(cHandle1); cHandles = instance.getConnectionHandles(); assertTrue(cHandles.size() == 1); assertEquals(cHandles.get(0).getIFDName(), readers[1]); } /** * Test card recognition. */ @Test public void testRecognition() { System.out.println("card recognition"); ListIFDsResponse result = instance.performRecognition(); assertEquals(ECardConstants.Major.OK, result.getResult().getResultMajor()); instance.selectIFD(0, new BigInteger("0")); } /** * Test of initialize method, of class TinySAL. */ @Test(priority = 1) public void testInitialize() { System.out.println("initialize"); Initialize parameters = new Initialize(); InitializeResponse result = instance.initialize(parameters); assertEquals(ECardConstants.Major.OK, result.getResult().getResultMajor()); } /** * Test of terminate method, of class TinySAL. */ @Test(priority = 100) public void testTerminate() { System.out.println("terminate"); Terminate parameters = new Terminate(); TerminateResponse result = instance.terminate(parameters); assertEquals(ECardConstants.Major.OK, result.getResult().getResultMajor()); } /** * Test of cardApplicationPath method, of class TinySAL. */ @Test(priority = 2) public void testCardApplicationPath() { System.out.println("cardApplicationPath"); // test normal case CardApplicationPath cardApplicationPath = new CardApplicationPath(); CardApplicationPathType cardApplicationPathType = new CardApplicationPathType(); cardApplicationPathType.setCardApplication(this.appIdentifier_IRMA); cardApplicationPathType.setContextHandle(instance.getContextHandle()); cardApplicationPathType.setSlotIndex(new BigInteger("0")); cardApplicationPath.setCardAppPathRequest(cardApplicationPathType); CardApplicationPathResponse cardApplicationPathResponse = instance.cardApplicationPath(cardApplicationPath); System.out.println(cardApplicationPathResponse.getCardAppPathResultSet().getCardApplicationPathResult().size()); //assertTrue(cardApplicationPathResponse.getCardAppPathResultSet().getCardApplicationPathResult().size() > 0); //assertEquals(cardApplicationPathResponse.getResult().getResultMajor(), ECardConstants.Major.OK); // test return of alpha card application /* cardApplicationPath = new CardApplicationPath(); cardApplicationPathType = new CardApplicationPathType(); cardApplicationPath.setCardAppPathRequest(cardApplicationPathType); cardApplicationPathResponse = instance.cardApplicationPath(cardApplicationPath); assertTrue(cardApplicationPathResponse.getCardAppPathResultSet().getCardApplicationPathResult().size()>0); assertNotNull(cardApplicationPathResponse.getCardAppPathResultSet().getCardApplicationPathResult().get(0).getCardApplication()); assertEquals(cardApplicationPathResponse.getResult().getResultMajor(), ECardConstants.Major.OK); // test non existent card application identifier cardApplicationPathType = new CardApplicationPathType(); cardApplicationPathType.setCardApplication(Hex.decode("C0CA")); cardApplicationPathType.setContextHandle(instance.getContextHandle()); cardApplicationPathType.setSlotIndex(new BigInteger("0")); cardApplicationPath.setCardAppPathRequest(cardApplicationPathType); cardApplicationPathResponse = instance.cardApplicationPath(cardApplicationPath); assertEquals(cardApplicationPathResponse.getCardAppPathResultSet().getCardApplicationPathResult().size(), 0); assertEquals(cardApplicationPathResponse.getResult().getResultMajor(), ECardConstants.Major.OK); // test nullpointer cardApplicationPathType = new CardApplicationPathType(); cardApplicationPath.setCardAppPathRequest(null); cardApplicationPathResponse = instance.cardApplicationPath(cardApplicationPath); assertEquals(cardApplicationPathResponse.getResult().getResultMajor(), ECardConstants.Major.ERROR); assertEquals(cardApplicationPathResponse.getResult().getResultMinor(), ECardConstants.Minor.App.INCORRECT_PARM);*/ } /** * Test of cardApplicationConnect method, of class TinySAL. */ @Test(priority = 3) public void testCardApplicationConnect() { System.out.println("cardApplicationConnect"); // test normal case // get esign path CardApplicationPath cardApplicationPath = new CardApplicationPath(); CardApplicationPathType cardApplicationPathType = new CardApplicationPathType(); cardApplicationPathType.setCardApplication(appIdentifier_IRMA); cardApplicationPath.setCardAppPathRequest(cardApplicationPathType); CardApplicationPathResponse cardApplicationPathResponse = instance.cardApplicationPath(cardApplicationPath); // connect to esign CardApplicationConnect cardApplicationConnect = new CardApplicationConnect(); cardApplicationConnect.setCardApplicationPath(cardApplicationPathResponse.getCardAppPathResultSet().getCardApplicationPathResult().get(0)); CardApplicationConnectResponse result = instance.cardApplicationConnect(cardApplicationConnect); assertEquals(ECardConstants.Major.OK, result.getResult().getResultMajor()); assertEquals(appIdentifier_IRMA, result.getConnectionHandle().getCardApplication()); // test non existent card application path //cardApplicationConnect = new CardApplicationConnect(); //CardApplicationPathType wrongCardApplicationPath = cardApplicationPathResponse.getCardAppPathResultSet().getCardApplicationPathResult().get(0); //wrongCardApplicationPath.setCardApplication(new byte[] { 0x12, 0x23, 0x34 }); //cardApplicationConnect.setCardApplicationPath(wrongCardApplicationPath); //result = instance.cardApplicationConnect(cardApplicationConnect); //assertEquals(ECardConstants.Major.ERROR, result.getResult().getResultMajor()); //assertEquals(ECardConstants.Minor.App.UNKNOWN_ERROR, result.getResult().getResultMinor()); // test nullpointer //cardApplicationConnect = new CardApplicationConnect(); //cardApplicationConnect.setCardApplicationPath(null); //result = instance.cardApplicationConnect(cardApplicationConnect); //assertEquals(ECardConstants.Major.ERROR, result.getResult().getResultMajor()); //assertEquals(ECardConstants.Minor.App.INCORRECT_PARM, result.getResult().getResultMinor()); } /** * Test of cardApplicationDisconnect method, of class TinySAL. */ @Test(enabled=false) public void testCardApplicationDisconnect() { System.out.println("cardApplicationDisconnect"); // test normal case // get esign path CardApplicationPath cardApplicationPath = new CardApplicationPath(); CardApplicationPathType cardApplicationPathType = new CardApplicationPathType(); cardApplicationPathType.setCardApplication(appIdentifier_ESIGN); cardApplicationPath.setCardAppPathRequest(cardApplicationPathType); CardApplicationPathResponse cardApplicationPathResponse = instance.cardApplicationPath(cardApplicationPath); // connect to esign CardApplicationConnect cardApplicationConnect = new CardApplicationConnect(); cardApplicationConnect.setCardApplicationPath(cardApplicationPathResponse.getCardAppPathResultSet().getCardApplicationPathResult().get(0)); CardApplicationConnectResponse result = instance.cardApplicationConnect(cardApplicationConnect); assertEquals(appIdentifier_ESIGN, result.getConnectionHandle().getCardApplication()); assertEquals(ECardConstants.Major.OK, result.getResult().getResultMajor()); // disconnect CardApplicationDisconnect cardApplicationDisconnect = new CardApplicationDisconnect(); cardApplicationDisconnect.setConnectionHandle(result.getConnectionHandle()); CardApplicationDisconnectResponse cardApplicationDisconnectResponse = instance.cardApplicationDisconnect(cardApplicationDisconnect); assertEquals(ECardConstants.Major.OK, result.getResult().getResultMajor()); // test invalid connectionhandle // connect to esign /*cardApplicationConnect = new CardApplicationConnect(); cardApplicationConnect.setCardApplicationPath(cardApplicationPathResponse.getCardAppPathResultSet().getCardApplicationPathResult().get(0)); result = instance.cardApplicationConnect(cardApplicationConnect); assertEquals(appIdentifier_ESIGN, result.getConnectionHandle().getCardApplication()); assertEquals(ECardConstants.Major.OK, result.getResult().getResultMajor()); // disconnect cardApplicationDisconnect = new CardApplicationDisconnect(); cardApplicationDisconnect.setConnectionHandle(result.getConnectionHandle()); cardApplicationDisconnect.getConnectionHandle().setSlotHandle(new byte[]{0x0, 0x0, 0x0}); cardApplicationDisconnectResponse = instance.cardApplicationDisconnect(cardApplicationDisconnect); assertEquals(ECardConstants.Major.ERROR, cardApplicationDisconnectResponse.getResult().getResultMajor()); assertEquals(ECardConstants.Minor.IFD.INVALID_SLOT_HANDLE, cardApplicationDisconnectResponse.getResult().getResultMinor()); // test nullpointer // connect to esign cardApplicationConnect = new CardApplicationConnect(); cardApplicationConnect.setCardApplicationPath(cardApplicationPathResponse.getCardAppPathResultSet().getCardApplicationPathResult().get(0)); result = instance.cardApplicationConnect(cardApplicationConnect); assertEquals(appIdentifier_ESIGN, result.getConnectionHandle().getCardApplication()); assertEquals(ECardConstants.Major.OK, result.getResult().getResultMajor()); // disconnect cardApplicationDisconnect = new CardApplicationDisconnect(); cardApplicationDisconnect.setConnectionHandle(null); cardApplicationDisconnectResponse = instance.cardApplicationDisconnect(cardApplicationDisconnect); assertEquals(ECardConstants.Major.ERROR, cardApplicationDisconnectResponse.getResult().getResultMajor()); assertEquals(ECardConstants.Minor.App.INCORRECT_PARM, cardApplicationDisconnectResponse.getResult().getResultMinor());*/ } /** * Test of cardApplicationStartSession method, of class TinySAL. */ @Test(enabled=false) public void testCardApplicationStartSession() { System.out.println("cardApplicationStartSession"); CardApplicationStartSession parameters = new CardApplicationStartSession(); CardApplicationStartSessionResponse result = instance.cardApplicationStartSession(parameters); assertEquals(ECardConstants.Major.ERROR, result.getResult().getResultMajor()); } /** * Test of cardApplicationEndSession method, of class TinySAL. */ @Test(enabled=false) public void testCardApplicationEndSession() { System.out.println("cardApplicationEndSession"); CardApplicationEndSession parameters = new CardApplicationEndSession(); CardApplicationEndSessionResponse result = instance.cardApplicationEndSession(parameters); assertEquals(ECardConstants.Major.ERROR, result.getResult().getResultMajor()); } /** * Test of cardApplicationList method, of class TinySAL. */ @Test(enabled=false) public void testCardApplicationList() { System.out.println("cardApplicationList"); // get path to root CardApplicationPath cardApplicationPath = new CardApplicationPath(); CardApplicationPathType cardApplicationPathType = new CardApplicationPathType(); cardApplicationPathType.setCardApplication(appIdentifier_ROOT); cardApplicationPath.setCardAppPathRequest(cardApplicationPathType); CardApplicationPathResponse cardApplicationPathResponse = instance.cardApplicationPath(cardApplicationPath); // connect to root CardApplicationConnect cardApplicationConnect = new CardApplicationConnect(); cardApplicationConnect.setCardApplicationPath(cardApplicationPathResponse.getCardAppPathResultSet().getCardApplicationPathResult() .get(0)); CardApplicationConnectResponse result = instance.cardApplicationConnect(cardApplicationConnect); assertEquals(ECardConstants.Major.OK, result.getResult().getResultMajor()); CardApplicationList cardApplicationList = new CardApplicationList(); cardApplicationList.setConnectionHandle(result.getConnectionHandle()); CardApplicationListResponse cardApplicationListResponse = instance.cardApplicationList(cardApplicationList); assertEquals(ECardConstants.Major.OK, cardApplicationListResponse.getResult().getResultMajor()); assertTrue(cardApplicationListResponse.getCardApplicationNameList().getCardApplicationName().size() > 0); // test non existent connectionhandle /* cardApplicationList = new CardApplicationList(); cardApplicationList.setConnectionHandle(result.getConnectionHandle()); cardApplicationList.getConnectionHandle().setIFDName("invalid"); cardApplicationListResponse = instance.cardApplicationList(cardApplicationList); assertEquals(ECardConstants.Major.ERROR, cardApplicationListResponse.getResult().getResultMajor()); assertEquals(ECardConstants.Minor.SAL.UNKNOWN_HANDLE, cardApplicationListResponse.getResult().getResultMinor()); // test nullpointer cardApplicationList = new CardApplicationList(); cardApplicationList.setConnectionHandle(null); cardApplicationListResponse = instance.cardApplicationList(cardApplicationList); assertEquals(ECardConstants.Major.ERROR, cardApplicationListResponse.getResult().getResultMajor()); assertEquals(ECardConstants.Minor.App.INCORRECT_PARM, cardApplicationListResponse.getResult().getResultMinor()); */} /** * Test of cardApplicationCreate method, of class TinySAL. */ @Test(enabled=false) public void testCardApplicationCreate() { System.out.println("cardApplicationCreate"); List<ConnectionHandleType> cHandles = instance.getConnectionHandles(); byte[] appName = {(byte)0x74, (byte)0x65, (byte)0x73, (byte)0x74}; CardApplicationCreate parameters = new CardApplicationCreate(); parameters.setConnectionHandle(cHandles.get(0)); parameters.setCardApplicationName(appName); AccessControlListType cardApplicationACL = new AccessControlListType(); parameters.setCardApplicationACL(cardApplicationACL); CardApplicationCreateResponse result = instance.cardApplicationCreate(parameters); assertEquals(ECardConstants.Major.OK, result.getResult().getResultMajor()); // get path to esign CardApplicationPath cardApplicationPath = new CardApplicationPath(); CardApplicationPathType cardApplicationPathType = new CardApplicationPathType(); cardApplicationPathType.setCardApplication(appIdentifier_ESIGN); cardApplicationPath.setCardAppPathRequest(cardApplicationPathType); CardApplicationPathResponse cardApplicationPathResponse = instance.cardApplicationPath(cardApplicationPath); // connect to esign CardApplicationConnect cardApplicationConnect = new CardApplicationConnect(); cardApplicationConnect.setCardApplicationPath(cardApplicationPathResponse.getCardAppPathResultSet().getCardApplicationPathResult().get(0)); CardApplicationConnectResponse resultConnect = instance.cardApplicationConnect(cardApplicationConnect); assertEquals(ECardConstants.Major.OK, resultConnect.getResult().getResultMajor()); CardApplicationList cardApplicationList = new CardApplicationList(); cardApplicationList.setConnectionHandle(cHandles.get(0)); CardApplicationListResponse cardApplicationListResponse = instance.cardApplicationList(cardApplicationList); Iterator<byte[]> it = cardApplicationListResponse.getCardApplicationNameList().getCardApplicationName().iterator(); boolean appFound = false; try { while (it.hasNext()) { byte[] val = it.next(); if (Arrays.equals(val, appName)) appFound = true; } assertTrue(appFound); } catch (Exception e) { assertTrue(appFound); System.out.println(e); } } /** * Test of cardApplicationDelete method, of class TinySAL. */ @Test(enabled=false) public void testCardApplicationDelete() { System.out.println("cardApplicationDelete"); List<ConnectionHandleType> cHandles = instance.getConnectionHandles(); byte[] appName = {(byte)0x74, (byte)0x65, (byte)0x73, (byte)0x74}; CardApplicationDelete parameters = new CardApplicationDelete(); parameters.setConnectionHandle(cHandles.get(0)); parameters.setCardApplicationName(appName); CardApplicationDeleteResponse result = instance.cardApplicationDelete(parameters); assertEquals(ECardConstants.Major.OK, result.getResult().getResultMajor()); // get path to esign CardApplicationPath cardApplicationPath = new CardApplicationPath(); CardApplicationPathType cardApplicationPathType = new CardApplicationPathType(); cardApplicationPathType.setCardApplication(appIdentifier_ESIGN); cardApplicationPath.setCardAppPathRequest(cardApplicationPathType); CardApplicationPathResponse cardApplicationPathResponse = instance.cardApplicationPath(cardApplicationPath); // connect to esign CardApplicationConnect cardApplicationConnect = new CardApplicationConnect(); cardApplicationConnect.setCardApplicationPath(cardApplicationPathResponse.getCardAppPathResultSet().getCardApplicationPathResult().get(0)); CardApplicationConnectResponse resultConnect = instance.cardApplicationConnect(cardApplicationConnect); assertEquals(ECardConstants.Major.OK, resultConnect.getResult().getResultMajor()); CardApplicationList cardApplicationList = new CardApplicationList(); cardApplicationList.setConnectionHandle(cHandles.get(0)); CardApplicationListResponse cardApplicationListResponse = instance.cardApplicationList(cardApplicationList); Iterator<byte[]> it = cardApplicationListResponse.getCardApplicationNameList().getCardApplicationName().iterator(); boolean appFound = false; try { while (it.hasNext()) { byte[] val = it.next(); if (Arrays.equals(val, appName)) appFound = true; } assertTrue(!appFound); } catch (Exception e) { assertTrue(!appFound); System.out.println(e); } } /** * Test of cardApplicationServiceList method, of class TinySAL. */ @Test(enabled=false) public void testCardApplicationServiceList() { System.out.println("cardApplicationServiceList"); CardApplicationServiceList parameters = new CardApplicationServiceList(); // get path to esign CardApplicationPath cardApplicationPath = new CardApplicationPath(); CardApplicationPathType cardApplicationPathType = new CardApplicationPathType(); cardApplicationPathType.setCardApplication(appIdentifier_ESIGN); cardApplicationPath.setCardAppPathRequest(cardApplicationPathType); CardApplicationPathResponse cardApplicationPathResponse = instance.cardApplicationPath(cardApplicationPath); assertTrue(cardApplicationPathResponse.getCardAppPathResultSet().getCardApplicationPathResult().size() > 0); assertEquals(cardApplicationPathResponse.getResult().getResultMajor(), ECardConstants.Major.OK); // connect to esign CardApplicationConnect cardApplicationConnect = new CardApplicationConnect(); cardApplicationConnect.setCardApplicationPath(cardApplicationPathResponse.getCardAppPathResultSet().getCardApplicationPathResult().get(0)); CardApplicationConnectResponse result = instance.cardApplicationConnect(cardApplicationConnect); assertEquals(ECardConstants.Major.OK, result.getResult().getResultMajor()); assertEquals(appIdentifier_ESIGN, result.getConnectionHandle().getCardApplication()); parameters.setConnectionHandle(result.getConnectionHandle()); CardApplicationServiceListResponse resultServiceList = instance.cardApplicationServiceList(parameters); CardApplicationServiceNameList cardApplicationServiceNameList = resultServiceList.getCardApplicationServiceNameList(); assertEquals(ECardConstants.Major.OK, resultServiceList.getResult().getResultMajor()); assertTrue(cardApplicationServiceNameList.getCardApplicationServiceName().size() == 0); } /** * Test of cardApplicationServiceCreate method, of class TinySAL. */ @Test(enabled=false) public void testCardApplicationServiceCreate() { System.out.println("cardApplicationServiceCreate"); CardApplicationServiceCreate parameters = new CardApplicationServiceCreate(); // get path to esign CardApplicationPath cardApplicationPath = new CardApplicationPath(); CardApplicationPathType cardApplicationPathType = new CardApplicationPathType(); cardApplicationPathType.setCardApplication(appIdentifier_ESIGN); cardApplicationPath.setCardAppPathRequest(cardApplicationPathType); CardApplicationPathResponse cardApplicationPathResponse = instance.cardApplicationPath(cardApplicationPath); assertTrue(cardApplicationPathResponse.getCardAppPathResultSet().getCardApplicationPathResult().size() > 0); assertEquals(cardApplicationPathResponse.getResult().getResultMajor(), ECardConstants.Major.OK); // connect to esign CardApplicationConnect cardApplicationConnect = new CardApplicationConnect(); cardApplicationConnect.setCardApplicationPath(cardApplicationPathResponse.getCardAppPathResultSet().getCardApplicationPathResult().get(0)); CardApplicationConnectResponse result = instance.cardApplicationConnect(cardApplicationConnect); assertEquals(ECardConstants.Major.OK, result.getResult().getResultMajor()); assertEquals(appIdentifier_ESIGN, result.getConnectionHandle().getCardApplication()); parameters.setConnectionHandle(result.getConnectionHandle()); parameters.setCardApplicationServiceName("testService"); CardApplicationServiceCreateResponse resultServiceCreate = instance.cardApplicationServiceCreate(parameters); assertEquals(ECardConstants.Major.OK, resultServiceCreate.getResult().getResultMajor()); CardApplicationServiceList parametersServiceList = new CardApplicationServiceList(); parametersServiceList.setConnectionHandle(result.getConnectionHandle()); CardApplicationServiceListResponse resultServiceList = instance.cardApplicationServiceList(parametersServiceList); CardApplicationServiceNameList cardApplicationServiceNameList = resultServiceList.getCardApplicationServiceNameList(); assertEquals(ECardConstants.Major.OK, resultServiceList.getResult().getResultMajor()); assertTrue(cardApplicationServiceNameList.getCardApplicationServiceName().size() > 0); } /** * Test of cardApplicationServiceLoad method, of class TinySAL. */ @Test(enabled=false) public void testCardApplicationServiceLoad() { System.out.println("cardApplicationServiceLoad"); CardApplicationServiceLoad parameters = new CardApplicationServiceLoad(); CardApplicationServiceLoadResponse result = instance.cardApplicationServiceLoad(parameters); assertEquals(ECardConstants.Major.ERROR, result.getResult().getResultMajor()); } /** * Test of cardApplicationServiceDelete method, of class TinySAL. */ @Test(enabled=false) public void testCardApplicationServiceDelete() { System.out.println("cardApplicationServiceDelete"); CardApplicationServiceDelete parameters = new CardApplicationServiceDelete(); // get path to esign CardApplicationPath cardApplicationPath = new CardApplicationPath(); CardApplicationPathType cardApplicationPathType = new CardApplicationPathType(); cardApplicationPathType.setCardApplication(appIdentifier_ESIGN); cardApplicationPath.setCardAppPathRequest(cardApplicationPathType); CardApplicationPathResponse cardApplicationPathResponse = instance.cardApplicationPath(cardApplicationPath); assertTrue(cardApplicationPathResponse.getCardAppPathResultSet().getCardApplicationPathResult().size() > 0); assertEquals(cardApplicationPathResponse.getResult().getResultMajor(), ECardConstants.Major.OK); // connect to esign CardApplicationConnect cardApplicationConnect = new CardApplicationConnect(); cardApplicationConnect.setCardApplicationPath(cardApplicationPathResponse.getCardAppPathResultSet().getCardApplicationPathResult().get(0)); CardApplicationConnectResponse result = instance.cardApplicationConnect(cardApplicationConnect); assertEquals(ECardConstants.Major.OK, result.getResult().getResultMajor()); assertEquals(appIdentifier_ESIGN, result.getConnectionHandle().getCardApplication()); parameters.setConnectionHandle(result.getConnectionHandle()); parameters.setCardApplicationServiceName("testService"); CardApplicationServiceDeleteResponse resultServiceDelete = instance.cardApplicationServiceDelete(parameters); assertEquals(ECardConstants.Major.OK, resultServiceDelete.getResult().getResultMajor()); CardApplicationServiceList parametersServiceList = new CardApplicationServiceList(); parametersServiceList.setConnectionHandle(result.getConnectionHandle()); CardApplicationServiceListResponse resultServiceList = instance.cardApplicationServiceList(parametersServiceList); CardApplicationServiceNameList cardApplicationServiceNameList = resultServiceList.getCardApplicationServiceNameList(); assertEquals(ECardConstants.Major.OK, resultServiceList.getResult().getResultMajor()); assertTrue(cardApplicationServiceNameList.getCardApplicationServiceName().size() == 0); } /** * Test of cardApplicationServiceDescribe method, of class TinySAL. */ @Test(enabled=false) public void testCardApplicationServiceDescribe() { System.out.println("cardApplicationServiceDescribe"); CardApplicationServiceDescribe parameters = new CardApplicationServiceDescribe(); // get path to esign CardApplicationPath cardApplicationPath = new CardApplicationPath(); CardApplicationPathType cardApplicationPathType = new CardApplicationPathType(); cardApplicationPathType.setCardApplication(appIdentifier_ESIGN); cardApplicationPath.setCardAppPathRequest(cardApplicationPathType); CardApplicationPathResponse cardApplicationPathResponse = instance.cardApplicationPath(cardApplicationPath); assertTrue(cardApplicationPathResponse.getCardAppPathResultSet().getCardApplicationPathResult().size() > 0); assertEquals(cardApplicationPathResponse.getResult().getResultMajor(), ECardConstants.Major.OK); // connect to esign CardApplicationConnect cardApplicationConnect = new CardApplicationConnect(); cardApplicationConnect.setCardApplicationPath(cardApplicationPathResponse.getCardAppPathResultSet().getCardApplicationPathResult().get(0)); CardApplicationConnectResponse result = instance.cardApplicationConnect(cardApplicationConnect); assertEquals(ECardConstants.Major.OK, result.getResult().getResultMajor()); assertEquals(appIdentifier_ESIGN, result.getConnectionHandle().getCardApplication()); parameters.setConnectionHandle(result.getConnectionHandle()); parameters.setCardApplicationServiceName("testService"); CardApplicationServiceDescribeResponse resultServiceDescribe = instance.cardApplicationServiceDescribe(parameters); assertEquals(ECardConstants.Major.OK, resultServiceDescribe.getResult().getResultMajor()); } /** * Test of executeAction method, of class TinySAL. */ @Test(enabled=false) public void testExecuteAction() { System.out.println("executeAction"); ExecuteAction parameters = new ExecuteAction(); ExecuteActionResponse result = instance.executeAction(parameters); assertEquals(ECardConstants.Major.ERROR, result.getResult().getResultMajor()); } /** * Test of dataSetList method, of class TinySAL. */ @Test(enabled=false) public void testDataSetList() { System.out.println("dataSetList"); // get path to esign CardApplicationPath cardApplicationPath = new CardApplicationPath(); CardApplicationPathType cardApplicationPathType = new CardApplicationPathType(); cardApplicationPathType.setCardApplication(appIdentifier_ESIGN); cardApplicationPath.setCardAppPathRequest(cardApplicationPathType); CardApplicationPathResponse cardApplicationPathResponse = instance.cardApplicationPath(cardApplicationPath); // connect to esign CardApplicationConnect cardApplicationConnect = new CardApplicationConnect(); cardApplicationConnect.setCardApplicationPath(cardApplicationPathResponse.getCardAppPathResultSet().getCardApplicationPathResult() .get(0)); CardApplicationConnectResponse result = instance.cardApplicationConnect(cardApplicationConnect); assertEquals(ECardConstants.Major.OK, result.getResult().getResultMajor()); // list datasets of esign DataSetList dataSetList = new DataSetList(); dataSetList.setConnectionHandle(result.getConnectionHandle()); DataSetListResponse dataSetListResponse = instance.dataSetList(dataSetList); System.out.println(ByteUtils.toHexString(result.getConnectionHandle().getSlotHandle())); Assert.assertTrue(dataSetListResponse.getDataSetNameList().getDataSetName().size() > 0); assertEquals(ECardConstants.Major.OK, dataSetListResponse.getResult().getResultMajor()); // test invalid connectionhandle dataSetList = new DataSetList(); ConnectionHandleType wrongConnectionHandle = result.getConnectionHandle(); wrongConnectionHandle.setCardApplication(new byte[] { 0x0, 0x0, 0x0 }); dataSetList.setConnectionHandle(wrongConnectionHandle); dataSetListResponse = instance.dataSetList(dataSetList); assertEquals(ECardConstants.Major.ERROR, dataSetListResponse.getResult().getResultMajor()); assertEquals(ECardConstants.Minor.App.UNKNOWN_ERROR, dataSetListResponse.getResult().getResultMinor()); // test null connectionhandle dataSetList = new DataSetList(); dataSetList.setConnectionHandle(null); dataSetListResponse = instance.dataSetList(dataSetList); assertEquals(ECardConstants.Major.ERROR, dataSetListResponse.getResult().getResultMajor()); assertEquals(ECardConstants.Minor.App.INCORRECT_PARM, dataSetListResponse.getResult().getResultMinor()); // TODO test for unsatisfied security condition } /** * Test of dataSetCreate method, of class TinySAL. */ @Test(enabled=false) public void testDataSetCreate() { System.out.println("dataSetCreate"); DataSetCreate parameters = new DataSetCreate(); // get path to esign CardApplicationPath cardApplicationPath = new CardApplicationPath(); CardApplicationPathType cardApplicationPathType = new CardApplicationPathType(); cardApplicationPathType.setCardApplication(appIdentifier_ESIGN); cardApplicationPath.setCardAppPathRequest(cardApplicationPathType); CardApplicationPathResponse cardApplicationPathResponse = instance.cardApplicationPath(cardApplicationPath); // connect to esign CardApplicationConnect cardApplicationConnect = new CardApplicationConnect(); cardApplicationConnect.setCardApplicationPath(cardApplicationPathResponse.getCardAppPathResultSet().getCardApplicationPathResult() .get(0)); CardApplicationConnectResponse result = instance.cardApplicationConnect(cardApplicationConnect); assertEquals(ECardConstants.Major.OK, result.getResult().getResultMajor()); AccessControlListType accessControlList = new AccessControlListType(); parameters.setConnectionHandle(result.getConnectionHandle()); String dataSetName = "DataSetTest"; parameters.setDataSetName(dataSetName); parameters.setDataSetACL(accessControlList); DataSetCreateResponse resultDataSetCreate = instance.dataSetCreate(parameters); assertEquals(ECardConstants.Major.OK, resultDataSetCreate.getResult().getResultMajor()); // list datasets of esign DataSetList dataSetList = new DataSetList(); dataSetList.setConnectionHandle(result.getConnectionHandle()); DataSetListResponse dataSetListResponse = instance.dataSetList(dataSetList); Iterator<String> it = dataSetListResponse.getDataSetNameList().getDataSetName().iterator(); boolean dataSetFound = false; while (it.hasNext()) { String val = it.next(); if (val.equals(dataSetName)) dataSetFound = true; } assertTrue(dataSetFound); assertEquals(ECardConstants.Major.OK, dataSetListResponse.getResult().getResultMajor()); } /** * Test of dataSetSelect method, of class TinySAL. */ @Test(enabled=false) public void testDataSetSelect() { System.out.println("dataSetSelect"); CardApplicationPath cardApplicationPath = new CardApplicationPath(); CardApplicationPathType cardApplicationPathType = new CardApplicationPathType(); cardApplicationPathType.setCardApplication(appIdentifier_ESIGN); cardApplicationPath.setCardAppPathRequest(cardApplicationPathType); CardApplicationPathResponse cardApplicationPathResponse = instance.cardApplicationPath(cardApplicationPath); CardApplicationConnect parameters = new CardApplicationConnect(); parameters.setCardApplicationPath(cardApplicationPathResponse.getCardAppPathResultSet().getCardApplicationPathResult().get(0)); CardApplicationConnectResponse result = instance.cardApplicationConnect(parameters); assertEquals(ECardConstants.Major.OK, result.getResult().getResultMajor()); // test good case DataSetSelect dataSetSelect = new DataSetSelect(); dataSetSelect.setConnectionHandle(result.getConnectionHandle()); dataSetSelect.setDataSetName("EF.C.CH.AUT"); DataSetSelectResponse dataSetSelectResponse = instance.dataSetSelect(dataSetSelect); assertEquals(ECardConstants.Major.OK, dataSetSelectResponse.getResult().getResultMajor()); // test connectionhanle == null dataSetSelect = new DataSetSelect(); dataSetSelect.setConnectionHandle(null); dataSetSelect.setDataSetName("EF.C.CH.AUT"); dataSetSelectResponse = instance.dataSetSelect(dataSetSelect); assertEquals(ECardConstants.Major.ERROR, dataSetSelectResponse.getResult().getResultMajor()); assertEquals(ECardConstants.Minor.App.INCORRECT_PARM, dataSetSelectResponse.getResult().getResultMinor()); // test datasetname == null dataSetSelect = new DataSetSelect(); dataSetSelect.setConnectionHandle(result.getConnectionHandle()); dataSetSelect.setDataSetName(null); dataSetSelectResponse = instance.dataSetSelect(dataSetSelect); assertEquals(ECardConstants.Major.ERROR, dataSetSelectResponse.getResult().getResultMajor()); assertEquals(ECardConstants.Minor.App.INCORRECT_PARM, dataSetSelectResponse.getResult().getResultMinor()); // test datasetname not found dataSetSelect = new DataSetSelect(); dataSetSelect.setConnectionHandle(result.getConnectionHandle()); dataSetSelect.setDataSetName("INVALID"); dataSetSelectResponse = instance.dataSetSelect(dataSetSelect); assertEquals(ECardConstants.Major.ERROR, dataSetSelectResponse.getResult().getResultMajor()); assertEquals(ECardConstants.Minor.SAL.NAMED_ENTITY_NOT_FOUND, dataSetSelectResponse.getResult().getResultMinor()); // test invalid connectionhandle dataSetSelect = new DataSetSelect(); ConnectionHandleType invalidConnectionHandle = result.getConnectionHandle(); invalidConnectionHandle.setIFDName(("invalid")); dataSetSelect.setConnectionHandle(invalidConnectionHandle); dataSetSelect.setDataSetName("EF.C.CH.AUT"); dataSetSelectResponse = instance.dataSetSelect(dataSetSelect); assertEquals(ECardConstants.Major.ERROR, dataSetSelectResponse.getResult().getResultMajor()); assertEquals(ECardConstants.Minor.SAL.UNKNOWN_HANDLE, dataSetSelectResponse.getResult().getResultMinor()); } /** * Test of dataSetDelete method, of class TinySAL. */ @Test(enabled=false) public void testDataSetDelete() { System.out.println("dataSetDelete"); DataSetDelete parameters = new DataSetDelete(); // get path to esign CardApplicationPath cardApplicationPath = new CardApplicationPath(); CardApplicationPathType cardApplicationPathType = new CardApplicationPathType(); cardApplicationPathType.setCardApplication(appIdentifier_ESIGN); cardApplicationPath.setCardAppPathRequest(cardApplicationPathType); CardApplicationPathResponse cardApplicationPathResponse = instance.cardApplicationPath(cardApplicationPath); // connect to esign CardApplicationConnect cardApplicationConnect = new CardApplicationConnect(); cardApplicationConnect.setCardApplicationPath(cardApplicationPathResponse.getCardAppPathResultSet().getCardApplicationPathResult() .get(0)); CardApplicationConnectResponse result = instance.cardApplicationConnect(cardApplicationConnect); assertEquals(ECardConstants.Major.OK, result.getResult().getResultMajor()); parameters.setConnectionHandle(result.getConnectionHandle()); String dataSetName = "DataSetTest"; parameters.setDataSetName(dataSetName); DataSetDeleteResponse resultDataSetDelete = instance.dataSetDelete(parameters); assertEquals(ECardConstants.Major.OK, resultDataSetDelete.getResult().getResultMajor()); // list datasets of esign DataSetList dataSetList = new DataSetList(); dataSetList.setConnectionHandle(result.getConnectionHandle()); DataSetListResponse dataSetListResponse = instance.dataSetList(dataSetList); Iterator<String> it = dataSetListResponse.getDataSetNameList().getDataSetName().iterator(); boolean dataSetFound = false; while (it.hasNext()) { String val = it.next(); if (val.equals(dataSetName)) dataSetFound = true; } assertTrue(!dataSetFound); assertEquals(ECardConstants.Major.OK, dataSetListResponse.getResult().getResultMajor()); } /** * Test of dsiList method, of class TinySAL. */ @Test(enabled=false) public void testDsiList() { System.out.println("dsiList"); // get path to esign CardApplicationPath cardApplicationPath = new CardApplicationPath(); CardApplicationPathType cardApplicationPathType = new CardApplicationPathType(); cardApplicationPathType.setCardApplication(appIdentifier_ESIGN); cardApplicationPath.setCardAppPathRequest(cardApplicationPathType); CardApplicationPathResponse cardApplicationPathResponse = instance.cardApplicationPath(cardApplicationPath); // connect to esign CardApplicationConnect cardApplicationConnect = new CardApplicationConnect(); cardApplicationConnect.setCardApplicationPath(cardApplicationPathResponse.getCardAppPathResultSet().getCardApplicationPathResult() .get(0)); CardApplicationConnectResponse result = instance.cardApplicationConnect(cardApplicationConnect); assertEquals(ECardConstants.Major.OK, result.getResult().getResultMajor()); // list datasets of esign DataSetList dataSetList = new DataSetList(); dataSetList.setConnectionHandle(result.getConnectionHandle()); DataSetListResponse dataSetListResponse = instance.dataSetList(dataSetList); Assert.assertTrue(dataSetListResponse.getDataSetNameList().getDataSetName().size() > 0); assertEquals(ECardConstants.Major.OK, dataSetListResponse.getResult().getResultMajor()); String dataSetName = dataSetListResponse.getDataSetNameList().getDataSetName().get(0); DSIList parameters = new DSIList(); parameters.setDataSetName(dataSetName); parameters.setConnectionHandle(result.getConnectionHandle()); DSIListResponse resultDSIList = instance.dsiList(parameters); assertEquals(ECardConstants.Major.OK, resultDSIList.getResult().getResultMajor()); assertTrue(resultDSIList.getDSINameList().getDSIName().size() == 0); } /** * Test of dsiCreate method, of class TinySAL. */ @Test(enabled = false) public void testDsiCreate() { System.out.println("dsiCreate"); // get path to esign CardApplicationPath cardApplicationPath = new CardApplicationPath(); CardApplicationPathType cardApplicationPathType = new CardApplicationPathType(); cardApplicationPathType.setCardApplication(appIdentifier_ESIGN); cardApplicationPath.setCardAppPathRequest(cardApplicationPathType); CardApplicationPathResponse cardApplicationPathResponse = instance.cardApplicationPath(cardApplicationPath); // connect to esign CardApplicationConnect cardApplicationConnect = new CardApplicationConnect(); cardApplicationConnect.setCardApplicationPath(cardApplicationPathResponse.getCardAppPathResultSet().getCardApplicationPathResult() .get(0)); CardApplicationConnectResponse result = instance.cardApplicationConnect(cardApplicationConnect); assertEquals(ECardConstants.Major.OK, result.getResult().getResultMajor()); // list datasets of esign DataSetList dataSetList = new DataSetList(); dataSetList.setConnectionHandle(result.getConnectionHandle()); DataSetListResponse dataSetListResponse = instance.dataSetList(dataSetList); Assert.assertTrue(dataSetListResponse.getDataSetNameList().getDataSetName().size() > 0); assertEquals(ECardConstants.Major.OK, dataSetListResponse.getResult().getResultMajor()); String dataSetName = dataSetListResponse.getDataSetNameList().getDataSetName().get(0); byte[] dsiContent = {(byte)0x74, (byte)0x65, (byte)0x73, (byte)0x74}; String dsiName = "DsiTest"; PathType dsiPath = new PathType(); byte[] dsiEF = {(byte)0x03, (byte)0x00}; dsiPath.setEfIdOrPath(dsiEF); DSICreate parameters = new DSICreate(); parameters.setConnectionHandle(result.getConnectionHandle()); parameters.setDataSetName(dataSetName); parameters.setDSIContent(dsiContent); parameters.setDSIName(dsiName); parameters.setDSIPath(dsiPath); DSICreateResponse resultDSICreate = instance.dsiCreate(parameters); assertEquals(ECardConstants.Major.OK, resultDSICreate.getResult().getResultMajor()); // list DSIs of DataSetName DSIList parametersDSI = new DSIList(); parametersDSI.setDataSetName(dataSetName); parametersDSI.setConnectionHandle(result.getConnectionHandle()); DSIListResponse resultDSIList = instance.dsiList(parametersDSI); assertEquals(ECardConstants.Major.OK, resultDSIList.getResult().getResultMajor()); // try to find new DSI Iterator<String> it = resultDSIList.getDSINameList().getDSIName().iterator(); boolean dsiFound = false; while (it.hasNext()) { String val = it.next(); if (val.equals(dsiName)) dsiFound = true; } assertTrue(dsiFound); } /** * Test of dsiDelete method, of class TinySAL. */ @Test(enabled = false) public void testDsiDelete() { System.out.println("dsiDelete"); // get path to esign CardApplicationPath cardApplicationPath = new CardApplicationPath(); CardApplicationPathType cardApplicationPathType = new CardApplicationPathType(); cardApplicationPathType.setCardApplication(appIdentifier_ESIGN); cardApplicationPath.setCardAppPathRequest(cardApplicationPathType); CardApplicationPathResponse cardApplicationPathResponse = instance.cardApplicationPath(cardApplicationPath); // connect to esign CardApplicationConnect cardApplicationConnect = new CardApplicationConnect(); cardApplicationConnect.setCardApplicationPath(cardApplicationPathResponse.getCardAppPathResultSet().getCardApplicationPathResult() .get(0)); CardApplicationConnectResponse result = instance.cardApplicationConnect(cardApplicationConnect); assertEquals(ECardConstants.Major.OK, result.getResult().getResultMajor()); // list datasets of esign DataSetList dataSetList = new DataSetList(); dataSetList.setConnectionHandle(result.getConnectionHandle()); DataSetListResponse dataSetListResponse = instance.dataSetList(dataSetList); Assert.assertTrue(dataSetListResponse.getDataSetNameList().getDataSetName().size() > 0); assertEquals(ECardConstants.Major.OK, dataSetListResponse.getResult().getResultMajor()); String dataSetName = dataSetListResponse.getDataSetNameList().getDataSetName().get(0); String dsiName = "dsiTest"; DSIDelete parameters = new DSIDelete(); parameters.setConnectionHandle(result.getConnectionHandle()); parameters.setDataSetName(dataSetName); parameters.setDSIName(dsiName); DSIDeleteResponse resultDSIDelete = instance.dsiDelete(parameters); assertEquals(ECardConstants.Major.OK, resultDSIDelete.getResult().getResultMajor()); // try to find dsiName under dataSetName DSIList parametersDSI = new DSIList(); parametersDSI.setDataSetName("EF.C.ICC.QES"); parametersDSI.setConnectionHandle(result.getConnectionHandle()); DSIListResponse resultDSIList = instance.dsiList(parametersDSI); assertEquals(ECardConstants.Major.OK, resultDSIList.getResult().getResultMajor()); // try to find new DSI Iterator<String> it = resultDSIList.getDSINameList().getDSIName().iterator(); boolean dsiFound = false; while (it.hasNext()) { String val = it.next(); if (val.equals(dsiName)) dsiFound = true; } assertTrue(!dsiFound); } /** * Test of dsiWrite method, of class TinySAL. */ @Test(enabled=false) public void testDsiWrite() { System.out.println("dsiWrite"); DSIWrite parameters = new DSIWrite(); DSIWriteResponse result = instance.dsiWrite(parameters); assertEquals(ECardConstants.Major.ERROR, result.getResult().getResultMajor()); } /** * Test of dsiRead method, of class TinySAL. */ @Test(enabled=false) public void testDsiRead() { System.out.println("dsiRead"); // test normal case // get esign path CardApplicationPath cardApplicationPath = new CardApplicationPath(); CardApplicationPathType cardApplicationPathType = new CardApplicationPathType(); cardApplicationPathType.setCardApplication(appIdentifier_ESIGN); cardApplicationPath.setCardAppPathRequest(cardApplicationPathType); CardApplicationPathResponse cardApplicationPathResponse = instance.cardApplicationPath(cardApplicationPath); // connect to esign CardApplicationConnect cardApplicationConnect = new CardApplicationConnect(); cardApplicationConnect.setCardApplicationPath(cardApplicationPathResponse.getCardAppPathResultSet().getCardApplicationPathResult().get(0)); CardApplicationConnectResponse result = instance.cardApplicationConnect(cardApplicationConnect); assertEquals(ECardConstants.Major.OK, result.getResult().getResultMajor()); assertEquals(appIdentifier_ESIGN, result.getConnectionHandle().getCardApplication()); // read EF.C.CH.AUT DSIRead dsiRead = new DSIRead(); dsiRead.setConnectionHandle(result.getConnectionHandle()); dsiRead.setDSIName("EF.C.CH.AUT"); DSIReadResponse dsiReadResponse = instance.dsiRead(dsiRead); System.out.println(dsiReadResponse.getResult().getResultMinor()); assertEquals(ECardConstants.Major.OK, dsiReadResponse.getResult().getResultMajor()); System.out.println(dsiReadResponse.getResult().getResultMinor()); assertTrue(dsiReadResponse.getDSIContent().length>0); // test connectionhandle == null dsiRead = new DSIRead(); dsiRead.setConnectionHandle(null); dsiRead.setDSIName("EF.C.CH.AUT"); dsiReadResponse = instance.dsiRead(dsiRead); assertEquals(ECardConstants.Major.ERROR, dsiReadResponse.getResult().getResultMajor()); assertEquals(ECardConstants.Minor.App.INCORRECT_PARM, dsiReadResponse.getResult().getResultMinor()); // test dsiName == null dsiRead = new DSIRead(); dsiRead.setConnectionHandle(result.getConnectionHandle()); dsiRead.setDSIName(null); dsiReadResponse = instance.dsiRead(dsiRead); assertEquals(ECardConstants.Major.ERROR, dsiReadResponse.getResult().getResultMajor()); assertEquals(ECardConstants.Minor.App.INCORRECT_PARM, dsiReadResponse.getResult().getResultMinor()); // test dsiName invalid dsiRead = new DSIRead(); dsiRead.setConnectionHandle(result.getConnectionHandle()); dsiRead.setDSIName("INVALID"); dsiReadResponse = instance.dsiRead(dsiRead); assertEquals(ECardConstants.Major.ERROR, dsiReadResponse.getResult().getResultMajor()); assertEquals(ECardConstants.Minor.SAL.NAMED_ENTITY_NOT_FOUND, dsiReadResponse.getResult().getResultMinor()); // test security condition not satisfied dsiRead = new DSIRead(); dsiRead.setConnectionHandle(result.getConnectionHandle()); dsiRead.setDSIName("EF.C.CH.AUTN"); dsiReadResponse = instance.dsiRead(dsiRead); assertEquals(ECardConstants.Major.ERROR, dsiReadResponse.getResult().getResultMajor()); assertEquals(ECardConstants.Minor.SAL.SECURITY_CONDITINON_NOT_SATISFIED, dsiReadResponse.getResult().getResultMinor()); // test invalid connectionhandle dsiRead = new DSIRead(); dsiRead.setConnectionHandle(result.getConnectionHandle()); dsiRead.getConnectionHandle().setIFDName("invalid"); dsiRead.setDSIName(null); dsiReadResponse = instance.dsiRead(dsiRead); assertEquals(ECardConstants.Major.ERROR, dsiReadResponse.getResult().getResultMajor()); assertEquals(ECardConstants.Minor.SAL.UNKNOWN_HANDLE, dsiReadResponse.getResult().getResultMinor()); } /** * Test of encipher method, of class TinySAL. */ @Test(enabled=false) public void testEncipher() { System.out.println("encipher"); Encipher parameters = new Encipher(); EncipherResponse result = instance.encipher(parameters); assertEquals(ECardConstants.Major.ERROR, result.getResult().getResultMajor()); } /** * Test of decipher method, of class TinySAL. */ @Test(enabled=false) public void testDecipher() { System.out.println("decipher"); Decipher parameters = new Decipher(); DecipherResponse result = instance.decipher(parameters); assertEquals(ECardConstants.Major.ERROR, result.getResult().getResultMajor()); } /** * Test of getRandom method, of class TinySAL. */ @Test(enabled=false) public void testGetRandom() { System.out.println("getRandom"); GetRandom parameters = new GetRandom(); GetRandomResponse result = instance.getRandom(parameters); assertEquals(ECardConstants.Major.ERROR, result.getResult().getResultMajor()); } /** * Test of hash method, of class TinySAL. */ @Test(enabled=false) public void testHash() { System.out.println("hash"); Hash parameters = new Hash(); HashResponse result = instance.hash(parameters); assertEquals(ECardConstants.Major.ERROR, result.getResult().getResultMajor()); } /** * Test of sign method, of class TinySAL. */ @Test(enabled=false) public void testSign() { System.out.println("sign"); Sign parameters = new Sign(); SignResponse result = instance.sign(parameters); assertEquals(ECardConstants.Major.ERROR, result.getResult().getResultMajor()); } /** * Test of verifySignature method, of class TinySAL. */ @Test(enabled=false) public void testVerifySignature() { System.out.println("verifySignature"); VerifySignature parameters = new VerifySignature(); VerifySignatureResponse result = instance.verifySignature(parameters); assertEquals(ECardConstants.Major.ERROR, result.getResult().getResultMajor()); } /** * Test of verifyCertificate method, of class TinySAL. */ @Test(enabled=false) public void testVerifyCertificate() { System.out.println("verifyCertificate"); VerifyCertificate parameters = new VerifyCertificate(); VerifyCertificateResponse result = instance.verifyCertificate(parameters); assertEquals(ECardConstants.Major.ERROR, result.getResult().getResultMajor()); } /** * Test of didList method, of class TinySAL. */ @Test(enabled=false) public void testDidList() { System.out.println("didList"); // get path to esign CardApplicationPath cardApplicationPath = new CardApplicationPath(); CardApplicationPathType cardApplicationPathType = new CardApplicationPathType(); cardApplicationPathType.setCardApplication(appIdentifier_ESIGN); cardApplicationPath.setCardAppPathRequest(cardApplicationPathType); CardApplicationPathResponse cardApplicationPathResponse = instance.cardApplicationPath(cardApplicationPath); // connect to esign CardApplicationConnect cardApplicationConnect = new CardApplicationConnect(); cardApplicationConnect.setCardApplicationPath(cardApplicationPathResponse.getCardAppPathResultSet().getCardApplicationPathResult() .get(0)); CardApplicationConnectResponse result = instance.cardApplicationConnect(cardApplicationConnect); assertEquals(ECardConstants.Major.OK, result.getResult().getResultMajor()); DIDList didList = new DIDList(); didList.setConnectionHandle(result.getConnectionHandle()); DIDQualifierType didQualifier = new DIDQualifierType(); didQualifier.setApplicationIdentifier(appIdentifier_ESIGN); didQualifier.setObjectIdentifier("urn:oid:1.3.162.15480.3.0.25"); didQualifier.setApplicationFunction("Compute-signature"); didList.setFilter(didQualifier); DIDListResponse didListResponse = instance.didList(didList); Assert.assertTrue(didListResponse.getDIDNameList().getDIDName().size() > 0); assertEquals(ECardConstants.Major.OK, result.getResult().getResultMajor()); // get path to root cardApplicationPath = new CardApplicationPath(); cardApplicationPathType = new CardApplicationPathType(); cardApplicationPathType.setCardApplication(appIdentifier_ROOT); cardApplicationPath.setCardAppPathRequest(cardApplicationPathType); cardApplicationPathResponse = instance.cardApplicationPath(cardApplicationPath); // connect to root cardApplicationConnect = new CardApplicationConnect(); cardApplicationConnect.setCardApplicationPath(cardApplicationPathResponse.getCardAppPathResultSet().getCardApplicationPathResult() .get(0)); cardApplicationConnect.getCardApplicationPath().setCardApplication(appIdentifier_ROOT); result = instance.cardApplicationConnect(cardApplicationConnect); assertEquals(ECardConstants.Major.OK, result.getResult().getResultMajor()); didList = new DIDList(); didList.setConnectionHandle(result.getConnectionHandle()); didQualifier = new DIDQualifierType(); didQualifier.setApplicationIdentifier(appIdentifier_ROOT); didQualifier.setObjectIdentifier("urn:oid:1.3.162.15480.3.0.25"); didQualifier.setApplicationFunction("Compute-signature"); didList.setFilter(didQualifier); didListResponse = instance.didList(didList); // we expect 0 because of the filter Assert.assertEquals(didListResponse.getDIDNameList().getDIDName().size(), 0); assertEquals(ECardConstants.Major.OK, didListResponse.getResult().getResultMajor()); // test null connectionhandle didList = new DIDList(); didList.setConnectionHandle(null); didListResponse = instance.didList(didList); assertEquals(ECardConstants.Major.ERROR, didListResponse.getResult().getResultMajor()); assertEquals(ECardConstants.Minor.App.INCORRECT_PARM, didListResponse.getResult().getResultMinor()); //test invalid connectionhandle didList = new DIDList(); didList.setConnectionHandle(result.getConnectionHandle()); didList.getConnectionHandle().setIFDName("invalid"); didListResponse = instance.didList(didList); assertEquals(ECardConstants.Major.ERROR, didListResponse.getResult().getResultMajor()); assertEquals(ECardConstants.Minor.SAL.UNKNOWN_HANDLE, didListResponse.getResult().getResultMinor()); } /** * Test of didCreate method, of class TinySAL. */ @Test(enabled=false) public void testDidCreate() { System.out.println("didCreate"); DIDCreate parameters = new DIDCreate(); DIDCreateResponse result = instance.didCreate(parameters); assertEquals(ECardConstants.Major.ERROR, result.getResult().getResultMajor()); } /** * Test of didGet method, of class TinySAL. */ @Test(enabled=false) public void testDidGet() { System.out.println("didGet"); // get path to esign CardApplicationPath cardApplicationPath = new CardApplicationPath(); CardApplicationPathType cardApplicationPathType = new CardApplicationPathType(); cardApplicationPathType.setCardApplication(appIdentifier_ESIGN); cardApplicationPath.setCardAppPathRequest(cardApplicationPathType); CardApplicationPathResponse cardApplicationPathResponse = instance.cardApplicationPath(cardApplicationPath); // connect to esign CardApplicationConnect cardApplicationConnect = new CardApplicationConnect(); cardApplicationConnect.setCardApplicationPath(cardApplicationPathResponse.getCardAppPathResultSet().getCardApplicationPathResult() .get(0)); CardApplicationConnectResponse result = instance.cardApplicationConnect(cardApplicationConnect); assertEquals(ECardConstants.Major.OK, result.getResult().getResultMajor()); DIDList didList = new DIDList(); didList.setConnectionHandle(result.getConnectionHandle()); DIDQualifierType didQualifier = new DIDQualifierType(); didQualifier.setApplicationIdentifier(appIdentifier_ESIGN); didQualifier.setObjectIdentifier("urn:oid:1.3.162.15480.3.0.25"); didQualifier.setApplicationFunction("Compute-signature"); didList.setFilter(didQualifier); DIDListResponse didListResponse = instance.didList(didList); Assert.assertTrue(didListResponse.getDIDNameList().getDIDName().size() > 0); assertEquals(ECardConstants.Major.OK, result.getResult().getResultMajor()); String didName = didListResponse.getDIDNameList().getDIDName().get(0); DIDGet parameters = new DIDGet(); parameters.setDIDName(didName); parameters.setConnectionHandle(result.getConnectionHandle()); DIDGetResponse resultDIDGet = instance.didGet(parameters); assertEquals(ECardConstants.Major.OK, resultDIDGet.getResult().getResultMajor()); assertTrue(resultDIDGet.getDIDStructure() != null); } /** * Test of didUpdate method, of class TinySAL. */ @Test(enabled=false) public void testDidUpdate() { System.out.println("didUpdate"); DIDUpdate parameters = new DIDUpdate(); DIDUpdateResponse result = instance.didUpdate(parameters); assertEquals(ECardConstants.Major.ERROR, result.getResult().getResultMajor()); } /** * Test of didDelete method, of class TinySAL. */ @Test(enabled=false) public void testDidDelete() { System.out.println("didDelete"); DIDDelete parameters = new DIDDelete(); DIDDeleteResponse result = instance.didDelete(parameters); assertEquals(ECardConstants.Major.ERROR, result.getResult().getResultMajor()); } /** * Test of didAuthenticate method, of class TinySAL. * * @throws ParserConfigurationException */ @Test(enabled=false) public void testDidAuthenticate() throws ParserConfigurationException { System.out.println("didAuthenticate"); DIDAuthenticate parameters = new DIDAuthenticate(); DIDAuthenticateResponse result = instance.didAuthenticate(parameters); assertEquals(ECardConstants.Major.ERROR, result.getResult().getResultMajor()); } /** * Test of aclList method, of class TinySAL. */ @Test(enabled=false) public void testAclList() { System.out.println("aclList"); // get path to esign CardApplicationPath cardApplicationPath = new CardApplicationPath(); CardApplicationPathType cardApplicationPathType = new CardApplicationPathType(); cardApplicationPathType.setCardApplication(appIdentifier_ESIGN); cardApplicationPath.setCardAppPathRequest(cardApplicationPathType); CardApplicationPathResponse cardApplicationPathResponse = instance.cardApplicationPath(cardApplicationPath); // connect to esign CardApplicationConnect cardApplicationConnect = new CardApplicationConnect(); cardApplicationConnect.setCardApplicationPath(cardApplicationPathResponse.getCardAppPathResultSet().getCardApplicationPathResult() .get(0)); CardApplicationConnectResponse result = instance.cardApplicationConnect(cardApplicationConnect); assertEquals(ECardConstants.Major.OK, result.getResult().getResultMajor()); ACLList aclList = new ACLList(); aclList.setConnectionHandle(result.getConnectionHandle()); TargetNameType targetName = new TargetNameType(); targetName.setCardApplicationName(appIdentifier_ESIGN); aclList.setTargetName(targetName); ACLListResponse aclListResponse = instance.aclList(aclList); assertEquals(aclListResponse.getResult().getResultMajor(), ECardConstants.Major.OK); assertTrue(aclListResponse.getTargetACL().getAccessRule().size()>0); // test null connectionhandle aclList = new ACLList(); aclList.setConnectionHandle(null); targetName = new TargetNameType(); targetName.setCardApplicationName(appIdentifier_ESIGN); aclList.setTargetName(targetName); aclListResponse = instance.aclList(aclList); assertEquals(ECardConstants.Major.ERROR, aclListResponse.getResult().getResultMajor()); assertEquals(ECardConstants.Minor.App.INCORRECT_PARM, aclListResponse.getResult().getResultMinor()); // test missing targetname aclList = new ACLList(); aclList.setConnectionHandle(null); targetName = new TargetNameType(); aclList.setTargetName(targetName); aclListResponse = instance.aclList(aclList); assertEquals(ECardConstants.Major.ERROR, aclListResponse.getResult().getResultMajor()); assertEquals(ECardConstants.Minor.App.INCORRECT_PARM, aclListResponse.getResult().getResultMinor()); //test invalid applicationIdentifier aclList = new ACLList(); aclList.setConnectionHandle(result.getConnectionHandle()); targetName = new TargetNameType(); targetName.setCardApplicationName(new byte[]{0x0, 0x0, 0x0}); aclList.setTargetName(targetName); aclListResponse = instance.aclList(aclList); assertEquals(ECardConstants.Major.ERROR, aclListResponse.getResult().getResultMajor()); assertEquals(ECardConstants.Minor.SAL.NAMED_ENTITY_NOT_FOUND, aclListResponse.getResult().getResultMinor()); //test invalid connectionhandle aclList = new ACLList(); aclList.setConnectionHandle(result.getConnectionHandle()); aclList.getConnectionHandle().setIFDName("invalid"); targetName = new TargetNameType(); targetName.setCardApplicationName(appIdentifier_ESIGN); aclList.setTargetName(targetName); aclListResponse = instance.aclList(aclList); assertEquals(ECardConstants.Major.ERROR, aclListResponse.getResult().getResultMajor()); assertEquals(ECardConstants.Minor.SAL.UNKNOWN_HANDLE, aclListResponse.getResult().getResultMinor()); } /** * Test of aclModify method, of class TinySAL. */ @Test(enabled=false) public void testAclModify() { System.out.println("aclModify"); // get path to esign CardApplicationPath cardApplicationPath = new CardApplicationPath(); CardApplicationPathType cardApplicationPathType = new CardApplicationPathType(); cardApplicationPathType.setCardApplication(appIdentifier_ESIGN); cardApplicationPath.setCardAppPathRequest(cardApplicationPathType); CardApplicationPathResponse cardApplicationPathResponse = instance.cardApplicationPath(cardApplicationPath); // connect to esign CardApplicationConnect cardApplicationConnect = new CardApplicationConnect(); cardApplicationConnect.setCardApplicationPath(cardApplicationPathResponse.getCardAppPathResultSet().getCardApplicationPathResult() .get(0)); CardApplicationConnectResponse result = instance.cardApplicationConnect(cardApplicationConnect); assertEquals(ECardConstants.Major.OK, result.getResult().getResultMajor()); ACLList aclList = new ACLList(); aclList.setConnectionHandle(result.getConnectionHandle()); TargetNameType targetName = new TargetNameType(); targetName.setCardApplicationName(appIdentifier_ESIGN); aclList.setTargetName(targetName); ACLListResponse aclListResponse = instance.aclList(aclList); assertEquals(aclListResponse.getResult().getResultMajor(), ECardConstants.Major.OK); assertTrue(aclListResponse.getTargetACL().getAccessRule().size()>0); AccessRuleType accessRuleFirst = aclListResponse.getTargetACL().getAccessRule().get(0); String cardApplicationServiceName = accessRuleFirst.getCardApplicationServiceName(); ActionNameType actionName = accessRuleFirst.getAction(); assertEquals(actionName.getAPIAccessEntryPoint(), APIAccessEntryPointName.INITIALIZE); SecurityConditionType securityCondition = accessRuleFirst.getSecurityCondition(); // modify first rule ACLModify parameters = new ACLModify(); parameters.setConnectionHandle(result.getConnectionHandle()); parameters.setTargetName(targetName); parameters.setCardApplicationServiceName(cardApplicationServiceName); actionName.setAPIAccessEntryPoint(APIAccessEntryPointName.TERMINATE); parameters.setActionName(actionName); parameters.setSecurityCondition(securityCondition); ACLModifyResponse resultACLModify = instance.aclModify(parameters); assertEquals(ECardConstants.Major.OK, resultACLModify.getResult().getResultMajor()); // Check modify aclList = new ACLList(); aclList.setConnectionHandle(result.getConnectionHandle()); aclList.setTargetName(targetName); aclListResponse = instance.aclList(aclList); assertEquals(aclListResponse.getResult().getResultMajor(), ECardConstants.Major.OK); assertTrue(aclListResponse.getTargetACL().getAccessRule().size()>0); accessRuleFirst = aclListResponse.getTargetACL().getAccessRule().get(0); assertEquals(actionName.getAPIAccessEntryPoint(), APIAccessEntryPointName.TERMINATE); // Undo modify parameters = new ACLModify(); parameters.setConnectionHandle(result.getConnectionHandle()); parameters.setTargetName(targetName); parameters.setCardApplicationServiceName(cardApplicationServiceName); actionName.setAPIAccessEntryPoint(APIAccessEntryPointName.INITIALIZE); parameters.setActionName(actionName); parameters.setSecurityCondition(securityCondition); resultACLModify = instance.aclModify(parameters); assertEquals(ECardConstants.Major.OK, resultACLModify.getResult().getResultMajor()); // Check modify aclList = new ACLList(); aclList.setConnectionHandle(result.getConnectionHandle()); aclList.setTargetName(targetName); aclListResponse = instance.aclList(aclList); assertEquals(aclListResponse.getResult().getResultMajor(), ECardConstants.Major.OK); assertTrue(aclListResponse.getTargetACL().getAccessRule().size()>0); accessRuleFirst = aclListResponse.getTargetACL().getAccessRule().get(0); assertEquals(actionName.getAPIAccessEntryPoint(), APIAccessEntryPointName.INITIALIZE); } /** * Test of singalEvent method, of class TinySAL. */ @Test(enabled=false) public void testSingalEvent() { System.out.println("singalEvent"); // same as getconnectionhandles, so call this one instead testGetConnectionHandles(); } }
package com.ecyrd.jspwiki.providers; import junit.framework.*; import java.io.*; import java.util.*; import com.ecyrd.jspwiki.*; import com.ecyrd.jspwiki.attachment.*; public class BasicAttachmentProviderTest extends TestCase { public static final String NAME1 = "TestPage"; public static final String NAME2 = "TestPageToo"; Properties props = new Properties(); TestEngine m_engine; BasicAttachmentProvider m_provider; /** * This is the sound of my head hitting the keyboard. */ private static final String c_fileContents = "gy th tgyhgthygyth tgyfgftrfgvtgfgtr"; public BasicAttachmentProviderTest( String s ) { super( s ); } public void setUp() throws Exception { props.load( TestEngine.findTestProperties() ); m_engine = new TestEngine(props); m_provider = new BasicAttachmentProvider(); m_provider.initialize( props ); m_engine.saveText( NAME1, "Foobar" ); m_engine.saveText( NAME2, "Foobar2" ); } private File makeAttachmentFile() throws Exception { File tmpFile = File.createTempFile("test","txt"); tmpFile.deleteOnExit(); FileWriter out = new FileWriter( tmpFile ); FileUtil.copyContents( new StringReader( c_fileContents ), out ); out.close(); return tmpFile; } private File makeExtraFile( File directory, String name ) throws Exception { File tmpFile = new File( directory, name ); FileWriter out = new FileWriter( tmpFile ); FileUtil.copyContents( new StringReader( c_fileContents ), out ); out.close(); return tmpFile; } public void tearDown() { m_engine.deletePage( NAME1 ); m_engine.deletePage( NAME2 ); String tmpfiles = props.getProperty( BasicAttachmentProvider.PROP_STORAGEDIR ); File f = new File( tmpfiles, NAME1+BasicAttachmentProvider.DIR_EXTENSION ); m_engine.deleteAll( f ); f = new File( tmpfiles, NAME2+BasicAttachmentProvider.DIR_EXTENSION ); m_engine.deleteAll( f ); } public void testExtension() { String s = "test.png"; assertEquals( m_provider.getFileExtension(s), "png" ); } public void testExtension2() { String s = ".foo"; assertEquals( "foo", m_provider.getFileExtension(s) ); } public void testExtension3() { String s = "test.png.3"; assertEquals( "3", m_provider.getFileExtension(s) ); } public void testExtension4() { String s = "testpng"; assertEquals( "bin", m_provider.getFileExtension(s) ); } public void testExtension5() { String s = "test."; assertEquals( "bin", m_provider.getFileExtension(s) ); } public void testExtension6() { String s = "test.a"; assertEquals( "a", m_provider.getFileExtension(s) ); } /** * Can we save attachments with names in UTF-8 range? */ public void testPutAttachmentUTF8() throws Exception { File in = makeAttachmentFile(); Attachment att = new Attachment( NAME1, "\u3072\u3048\u308btest.f" ); m_provider.putAttachmentData( att, new FileInputStream(in) ); List res = m_provider.listAllChanged( new Date(0L) ); Attachment a0 = (Attachment) res.get(0); assertEquals( "name", att.getName(), a0.getName() ); } public void testListAll() throws Exception { File in = makeAttachmentFile(); Attachment att = new Attachment( NAME1, "test1.txt" ); m_provider.putAttachmentData( att, new FileInputStream(in) ); Thread.sleep( 2000L ); // So that we get a bit of granularity. Attachment att2 = new Attachment( NAME2, "test2.txt" ); m_provider.putAttachmentData( att2, new FileInputStream(in) ); List res = m_provider.listAllChanged( new Date(0L) ); assertEquals( "list size", 2, res.size() ); Attachment a2 = (Attachment) res.get(0); // Most recently changed Attachment a1 = (Attachment) res.get(1); // Least recently changed assertEquals( "a1 name", att.getName(), a1.getName() ); assertEquals( "a2 name", att2.getName(), a2.getName() ); } /** * Check that the system does not fail if there are extra files in the directory. */ public void testListAllExtrafile() throws Exception { File in = makeAttachmentFile(); File sDir = new File(m_engine.getWikiProperties().getProperty( BasicAttachmentProvider.PROP_STORAGEDIR )); File extrafile = makeExtraFile( sDir, "foobar.blob" ); try { Attachment att = new Attachment( NAME1, "test1.txt" ); m_provider.putAttachmentData( att, new FileInputStream(in) ); Thread.sleep( 2000L ); // So that we get a bit of granularity. Attachment att2 = new Attachment( NAME2, "test2.txt" ); m_provider.putAttachmentData( att2, new FileInputStream(in) ); List res = m_provider.listAllChanged( new Date(0L) ); assertEquals( "list size", 2, res.size() ); Attachment a2 = (Attachment) res.get(0); // Most recently changed Attachment a1 = (Attachment) res.get(1); // Least recently changed assertEquals( "a1 name", att.getName(), a1.getName() ); assertEquals( "a2 name", att2.getName(), a2.getName() ); } finally { extrafile.delete(); } } /** * Check that the system does not fail if there are extra files in the * attachment directory. */ public void testListAllExtrafileInAttachmentDir() throws Exception { File in = makeAttachmentFile(); File sDir = new File(m_engine.getWikiProperties().getProperty( BasicAttachmentProvider.PROP_STORAGEDIR )); File attDir = new File( sDir, NAME1+"-att" ); Attachment att = new Attachment( NAME1, "test1.txt" ); m_provider.putAttachmentData( att, new FileInputStream(in) ); File extrafile = makeExtraFile( attDir, "ping.pong" ); try { Thread.sleep( 2000L ); // So that we get a bit of granularity. Attachment att2 = new Attachment( NAME2, "test2.txt" ); m_provider.putAttachmentData( att2, new FileInputStream(in) ); List res = m_provider.listAllChanged( new Date(0L) ); assertEquals( "list size", 2, res.size() ); Attachment a2 = (Attachment) res.get(0); // Most recently changed Attachment a1 = (Attachment) res.get(1); // Least recently changed assertEquals( "a1 name", att.getName(), a1.getName() ); assertEquals( "a2 name", att2.getName(), a2.getName() ); } finally { extrafile.delete(); } } /** * Check that the system does not fail if there are extra dirs in the * attachment directory. */ public void testListAllExtradirInAttachmentDir() throws Exception { File in = makeAttachmentFile(); File sDir = new File(m_engine.getWikiProperties().getProperty( BasicAttachmentProvider.PROP_STORAGEDIR )); File attDir = new File( sDir, NAME1+"-att" ); Attachment att = new Attachment( NAME1, "test1.txt" ); m_provider.putAttachmentData( att, new FileInputStream(in) ); File extrafile = new File( attDir, "ping.pong" ); extrafile.mkdir(); try { Thread.sleep( 2000L ); // So that we get a bit of granularity. Attachment att2 = new Attachment( NAME2, "test2.txt" ); m_provider.putAttachmentData( att2, new FileInputStream(in) ); List res = m_provider.listAllChanged( new Date(0L) ); assertEquals( "list size", 2, res.size() ); Attachment a2 = (Attachment) res.get(0); // Most recently changed Attachment a1 = (Attachment) res.get(1); // Least recently changed assertEquals( "a1 name", att.getName(), a1.getName() ); assertEquals( "a2 name", att2.getName(), a2.getName() ); } finally { extrafile.delete(); } } public void testListAllNoExtension() throws Exception { File in = makeAttachmentFile(); Attachment att = new Attachment( NAME1, "test1." ); m_provider.putAttachmentData( att, new FileInputStream(in) ); Thread.sleep( 2000L ); // So that we get a bit of granularity. Attachment att2 = new Attachment( NAME2, "test2." ); m_provider.putAttachmentData( att2, new FileInputStream(in) ); List res = m_provider.listAllChanged( new Date(0L) ); assertEquals( "list size", 2, res.size() ); Attachment a2 = (Attachment) res.get(0); // Most recently changed Attachment a1 = (Attachment) res.get(1); // Least recently changed assertEquals( "a1 name", att.getName(), a1.getName() ); assertEquals( "a2 name", att2.getName(), a2.getName() ); } public static Test suite() { return new TestSuite( BasicAttachmentProviderTest.class ); } }
package org.voltdb.regressionsuites; import java.io.IOException; import org.voltdb.BackendTarget; import org.voltdb.VoltTable; import org.voltdb.client.Client; import org.voltdb.client.ProcCallException; import org.voltdb.compiler.VoltProjectBuilder; import org.voltdb.types.GeographyValue; public class TestGeographyValue extends RegressionSuite { public TestGeographyValue(String name) { super(name); } private final String BERMUDA_TRIANGLE_WKT = "POLYGON(" + "(32.305 -64.751, " + "25.244 -80.437, " + "18.476 -66.371, " + "32.305 -64.751))"; // The Bermuda Triangle with a hole inside private final String BERMUDA_TRIANGLE_HOLE_WKT = "POLYGON(" + "(32.305 -64.751, " + "25.244 -80.437, " + "18.476 -66.371, " + "32.305 -64.751), " + "(28.066 -68.874, " + "25.361 -68.855, " + "28.376 -73.381," + " 28.066 -68.874))"; // (Useful for testing comparisons since it has the same number of vertices as // the Bermuda Triangle) private final String BILLERICA_TRIANGLE_WKT = "POLYGON(" + "(42.571 -71.276, " + "42.547 -71.308, " + "42.533 -71.231, " + "42.571 -71.276))"; // The dreaded "Lowell Square". One loop, // five vertices (last is the same as the first) private final String LOWELL_SQUARE_WKT = "POLYGON(" + "(42.641 -71.338, " + "42.619 -71.340, " + "42.617 -71.313, " + "42.639 -71.316, " + "42.641 -71.338))"; private final GeographyValue BERMUDA_TRIANGLE_POLY = new GeographyValue(BERMUDA_TRIANGLE_WKT); private final GeographyValue BERMUDA_TRIANGLE_HOLE_POLY = new GeographyValue(BERMUDA_TRIANGLE_HOLE_WKT); private final GeographyValue BILLERICA_TRIANGLE_POLY = new GeographyValue(BILLERICA_TRIANGLE_WKT); private final GeographyValue LOWELL_SQUARE_POLY = new GeographyValue(LOWELL_SQUARE_WKT); private int fillTable(Client client, String tbl, int startPk) throws Exception { VoltTable vt = client.callProcedure(tbl + ".Insert", startPk, "Bermuda Triangle", BERMUDA_TRIANGLE_POLY).getResults()[0]; validateTableOfScalarLongs(vt, new long[] {1}); ++startPk; vt = client.callProcedure(tbl + ".Insert", startPk, "Bermuda Triangle with a hole", BERMUDA_TRIANGLE_HOLE_POLY).getResults()[0]; validateTableOfScalarLongs(vt, new long[] {1}); ++startPk; vt = client.callProcedure(tbl + ".Insert", startPk, "Billerica Triangle", BILLERICA_TRIANGLE_POLY).getResults()[0]; validateTableOfScalarLongs(vt, new long[] {1}); ++startPk; vt = client.callProcedure(tbl + ".Insert", startPk, "Lowell Square", LOWELL_SQUARE_POLY).getResults()[0]; validateTableOfScalarLongs(vt, new long[] {1}); ++startPk; vt = client.callProcedure(tbl + ".Insert", startPk, "null poly", null).getResults()[0]; ++startPk; return startPk; } public void testNullValues() throws Exception { Client client = getClient(); validateTableOfScalarLongs(client, "select * from t;", new long[] {}); // Insert a null via default value validateTableOfScalarLongs(client, "insert into t (pk) values (0);", new long[] {1}); VoltTable vt = client.callProcedure("@AdHoc", "select poly from t").getResults()[0]; assertTrue(vt.toString().contains("NULL")); assertTrue(vt.advanceRow()); GeographyValue gv = vt.getGeographyValue(0); assertTrue(vt.wasNull()); assertEquals(null, gv); assertFalse(vt.advanceRow()); // This produces a null geography since the function argument is null vt = client.callProcedure("@AdHoc", "select polygonfromtext(null) from t").getResults()[0]; assertTrue(vt.advanceRow()); gv = vt.getGeographyValue(0); assertTrue(vt.wasNull()); assertEquals(null, gv); assertFalse(vt.advanceRow()); // This tests the is null predicate for this type vt = client.callProcedure("@AdHoc", "select poly from t where poly is null").getResults()[0]; assertTrue(vt.advanceRow()); gv = vt.getGeographyValue(0); assertTrue(vt.wasNull()); assertEquals(null, gv); assertFalse(vt.advanceRow()); // Try inserting a SQL literal null, which takes a different code path. validateTableOfScalarLongs(client, "delete from t;", new long[] {1}); validateTableOfScalarLongs(client, "insert into t values (0, 'boo', null);", new long[] {1}); vt = client.callProcedure("@AdHoc", "select poly from t").getResults()[0]; assertTrue(vt.advanceRow()); gv = vt.getGeographyValue(0); assertTrue(vt.wasNull()); assertEquals(null, gv); assertFalse(vt.advanceRow()); // Insert a null by passing a null reference. validateTableOfScalarLongs(client, "delete from t;", new long[] {1}); vt = client.callProcedure("t.Insert", 0, "null geog", null).getResults()[0]; validateTableOfScalarLongs(vt, new long[] {1}); vt = client.callProcedure("@AdHoc", "select poly from t").getResults()[0]; assertTrue(vt.advanceRow()); gv = vt.getGeographyValue(0); assertTrue(vt.wasNull()); assertEquals(null, gv); assertFalse(vt.advanceRow()); } public void testInsertAndSimpleSelect() throws IOException, ProcCallException { Client client = getClient(); String tables[] = {"pt", "t"}; for (String tbl : tables) { // There's no rows in here yet. validateTableOfScalarLongs(client, "select * from " + tbl, new long[] {}); // insert using the polygonfromtext function validateTableOfScalarLongs(client, "insert into " + tbl + " values(0, 'Bermuda Triangle', " + "polygonfromtext('" + BERMUDA_TRIANGLE_WKT + "'));", new long[] {1}); VoltTable vt = client.callProcedure("@AdHoc", "select * from " + tbl).getResults()[0]; assertTrue(vt.advanceRow()); assertEquals(0, vt.getLong(0)); assertEquals("Bermuda Triangle", vt.getString(1)); assertEquals(BERMUDA_TRIANGLE_WKT, vt.getGeographyValue(2).toString()); assertFalse(vt.advanceRow()); vt = client.callProcedure("@AdHoc", "select polygonfromtext('" + BERMUDA_TRIANGLE_WKT + "') from " + tbl).getResults()[0]; assertTrue(vt.advanceRow()); assertEquals(BERMUDA_TRIANGLE_WKT, vt.getGeographyValue(0).toString()); assertFalse(vt.advanceRow()); } } public void testParams() throws IOException, ProcCallException { Client client = getClient(); GeographyValue gv = new GeographyValue(BERMUDA_TRIANGLE_WKT); assertEquals(BERMUDA_TRIANGLE_WKT, gv.toString()); VoltTable vt = client.callProcedure("t.Insert", 0, "Bermuda Triangle", gv).getResults()[0]; validateTableOfScalarLongs(vt, new long[] {1}); vt = client.callProcedure("@AdHoc", "select * from t").getResults()[0]; assertTrue(vt.advanceRow()); assertEquals(0, vt.getLong(0)); assertEquals("Bermuda Triangle", vt.getString(1)); assertEquals(BERMUDA_TRIANGLE_WKT, vt.getGeographyValue(2).toString()); assertFalse(vt.advanceRow()); } public void testComparison() throws Exception { Client client = getClient(); fillTable(client, "t", 0); // equals VoltTable vt = client.callProcedure("@AdHoc", "select pk, name, poly " + "from t as t1, t as t2 " + "where t1.poly = t2.poly " + "order by t1.pk").getResults()[0]; assertContentOfTable(new Object[][] { {0, "Bermuda Triangle", BERMUDA_TRIANGLE_POLY}, {1, "Bermuda Triangle with a hole", BERMUDA_TRIANGLE_HOLE_POLY}, {2, "Billerica Triangle", BILLERICA_TRIANGLE_POLY}, {3, "Lowell Square", LOWELL_SQUARE_POLY}}, vt); // not equals vt = client.callProcedure("@AdHoc", "select t1.pk, t1.name, t2.pk, t2.name " + "from t as t1, t as t2 " + "where t1.poly != t2.poly " + "order by t1.pk, t2.pk").getResults()[0]; assertContentOfTable(new Object[][] { {0, "Bermuda Triangle", 1, "Bermuda Triangle with a hole"}, {0, "Bermuda Triangle", 2, "Billerica Triangle"}, {0, "Bermuda Triangle", 3, "Lowell Square"}, {1, "Bermuda Triangle with a hole", 0, "Bermuda Triangle"}, {1, "Bermuda Triangle with a hole", 2, "Billerica Triangle"}, {1, "Bermuda Triangle with a hole", 3, "Lowell Square"}, {2, "Billerica Triangle", 0, "Bermuda Triangle"}, {2, "Billerica Triangle", 1, "Bermuda Triangle with a hole"}, {2, "Billerica Triangle", 3, "Lowell Square"}, {3, "Lowell Square", 0, "Bermuda Triangle"}, {3, "Lowell Square", 1, "Bermuda Triangle with a hole"}, {3, "Lowell Square", 2, "Billerica Triangle"}}, vt); // less than vt = client.callProcedure("@AdHoc", "select t1.pk, t1.name, t2.pk, t2.name " + "from t as t1, t as t2 " + "where t1.poly < t2.poly " + "order by t1.pk, t2.pk").getResults()[0]; assertContentOfTable(new Object[][] { {0, "Bermuda Triangle" , 1, "Bermuda Triangle with a hole"}, {0, "Bermuda Triangle", 2, "Billerica Triangle"}, {0, "Bermuda Triangle", 3, "Lowell Square"}, {2, "Billerica Triangle", 1, "Bermuda Triangle with a hole"}, {2, "Billerica Triangle" , 3, "Lowell Square"}, {3, "Lowell Square", 1, "Bermuda Triangle with a hole"}}, vt); // less than or equal to vt = client.callProcedure("@AdHoc", "select t1.pk, t1.name, t2.pk, t2.name " + "from t as t1, t as t2 " + "where t1.poly <= t2.poly " + "order by t1.pk, t2.pk").getResults()[0]; assertContentOfTable(new Object[][] { {0, "Bermuda Triangle" , 0, "Bermuda Triangle"}, {0, "Bermuda Triangle" , 1, "Bermuda Triangle with a hole"}, {0, "Bermuda Triangle", 2, "Billerica Triangle"}, {0, "Bermuda Triangle", 3, "Lowell Square"}, {1, "Bermuda Triangle with a hole" , 1, "Bermuda Triangle with a hole"}, {2, "Billerica Triangle", 1, "Bermuda Triangle with a hole"}, {2, "Billerica Triangle", 2, "Billerica Triangle"}, {2, "Billerica Triangle" , 3, "Lowell Square"}, {3, "Lowell Square", 1, "Bermuda Triangle with a hole"}, {3, "Lowell Square", 3, "Lowell Square"}}, vt); // greater than vt = client.callProcedure("@AdHoc", "select t1.pk, t1.name, t2.pk, t2.name " + "from t as t1, t as t2 " + "where t1.poly > t2.poly " + "order by t1.pk, t2.pk").getResults()[0]; assertContentOfTable(new Object[][] { {1, "Bermuda Triangle with a hole", 0, "Bermuda Triangle"}, {1, "Bermuda Triangle with a hole", 2, "Billerica Triangle"}, {1, "Bermuda Triangle with a hole", 3, "Lowell Square"}, {2, "Billerica Triangle",0 ,"Bermuda Triangle"}, {3, "Lowell Square", 0, "Bermuda Triangle"}, {3, "Lowell Square", 2, "Billerica Triangle"}}, vt); // greater than or equal to vt = client.callProcedure("@AdHoc", "select t1.pk, t1.name, t2.pk, t2.name " + "from t as t1, t as t2 " + "where t1.poly >= t2.poly " + "order by t1.pk, t2.pk").getResults()[0]; assertContentOfTable(new Object[][] { {0, "Bermuda Triangle", 0, "Bermuda Triangle"}, {1, "Bermuda Triangle with a hole", 0, "Bermuda Triangle"}, {1, "Bermuda Triangle with a hole", 1, "Bermuda Triangle with a hole"}, {1, "Bermuda Triangle with a hole", 2, "Billerica Triangle"}, {1, "Bermuda Triangle with a hole", 3, "Lowell Square"}, {2, "Billerica Triangle", 0 ,"Bermuda Triangle"}, {2, "Billerica Triangle", 2, "Billerica Triangle"}, {3, "Lowell Square", 0, "Bermuda Triangle"}, {3, "Lowell Square", 2, "Billerica Triangle"}, {3, "Lowell Square", 3, "Lowell Square"}}, vt); // is null vt = client.callProcedure("@AdHoc", "select pk, name " + "from t " + "where poly is null " + "order by pk").getResults()[0]; assertContentOfTable(new Object[][] { {4, "null poly"}}, vt); // is not null vt = client.callProcedure("@AdHoc", "select pk, name " + "from t " + "where poly is not null " + "order by pk").getResults()[0]; assertContentOfTable(new Object[][] { {0, "Bermuda Triangle"}, {1, "Bermuda Triangle with a hole"}, {2, "Billerica Triangle"}, {3, "Lowell Square"}}, vt); } public void testArithmetic() throws Exception { Client client = getClient(); fillTable(client, "t", 0); verifyStmtFails(client, "select pk, poly + poly from t order by pk", "incompatible data type in conversion"); verifyStmtFails(client, "select pk, poly + 1 from t order by pk", "incompatible data type in conversion"); } public void testGroupBy() throws Exception { Client client = getClient(); int pk = 0; pk = fillTable(client, "t", pk); pk = fillTable(client, "t", pk); pk = fillTable(client, "t", pk); VoltTable vt = client.callProcedure("@AdHoc", "select poly, count(*) " + "from t " + "group by poly " + "order by poly asc") .getResults()[0]; assertContentOfTable(new Object[][] { {null, 3}, {BERMUDA_TRIANGLE_POLY, 3}, {BILLERICA_TRIANGLE_POLY, 3}, {LOWELL_SQUARE_POLY, 3}, {BERMUDA_TRIANGLE_HOLE_POLY, 3}}, vt); } public void testUpdate() throws Exception { Client client = getClient(); fillTable(client,"t", 0); String santaCruzWkt = "POLYGON(" + "(36.999 -122.061, " + "36.950 -122.058, " + "36.955 -121.974, " + "36.999 -122.061))"; String southValleyWkt = "POLYGON(" + "(37.367 -122.038, " + "37.232 -121.980, " +" 37.339 -121.887, " + "37.367 -122.038))"; VoltTable vt = client.callProcedure("@AdHoc", "update t set poly = ?, name = ? where pk = ?", new GeographyValue(santaCruzWkt), "Santa Cruz Triangle", 0) .getResults()[0]; validateTableOfScalarLongs(vt, new long[] {1}); vt = client.callProcedure("@AdHoc", "update t set poly = polygonfromtext(?), name = ? where pk = ?", southValleyWkt, "South Valley Triangle", 2) .getResults()[0]; validateTableOfScalarLongs(vt, new long[] {1}); vt = client.callProcedure("@AdHoc", "select * from t order by pk asc") .getResults()[0]; assertContentOfTable(new Object[][] { {0, "Santa Cruz Triangle", new GeographyValue(santaCruzWkt)}, {1, "Bermuda Triangle with a hole", BERMUDA_TRIANGLE_HOLE_POLY}, {2, "South Valley Triangle", new GeographyValue(southValleyWkt)}, {3, "Lowell Square", LOWELL_SQUARE_POLY}, {4, "null poly", null}}, vt); } public void testNotNullConstraint() throws Exception { Client client = getClient(); verifyStmtFails(client, "insert into t_not_null (pk) values (0)", "Column POLY has no default and is not nullable"); verifyStmtFails(client, "insert into t_not_null values (0, 'foo', null)", "Attempted violation of constraint"); verifyStmtFails(client, "insert into t_not_null values (0, 'foo', null)", "Attempted violation of constraint"); validateTableOfScalarLongs(client, "insert into t_not_null values " + "(0, 'foo', polygonfromtext('" + BERMUDA_TRIANGLE_WKT + "'))", new long[] {1}); verifyStmtFails(client, "update t_not_null set poly = null where pk = 0", "Attempted violation of constraint"); } public void testIn() throws Exception { Client client = getClient(); fillTable(client, "t", 0); VoltTable vt = client.callProcedure("select_in", (Object)(new GeographyValue[] {BERMUDA_TRIANGLE_POLY, null, LOWELL_SQUARE_POLY})) .getResults()[0]; assertContentOfTable(new Object[][] { {0}, {3}}, vt); } private String wktRoundTrip(Client client, String wkt) throws Exception { VoltTable vt = client.callProcedure("@AdHoc", "select polygonfromtext(?) from t", wkt) .getResults()[0]; vt.advanceRow(); return vt.getGeographyValue(0).toString(); } public void testPolygonFromTextPositive() throws Exception { Client client = getClient(); validateTableOfScalarLongs(client, "insert into t (pk) values (0)", new long[] {1}); String expected = "POLYGON((32.305 -64.751, 25.244 -80.437, 18.476 -66.371, 32.305 -64.751))"; // Just a simple round trip with reasonable WKT. assertEquals(expected, wktRoundTrip(client, expected)); // polygonfromtext should be case-insensitve. assertEquals(expected, wktRoundTrip(client, "Polygon((32.305 -64.751, 25.244 -80.437, 18.476 -66.371, 32.305 -64.751))")); assertEquals(expected, wktRoundTrip(client, "polygon((32.305 -64.751, 25.244 -80.437, 18.476 -66.371, 32.305 -64.751))")); assertEquals(expected, wktRoundTrip(client, "PoLyGoN((32.305 -64.751, 25.244 -80.437, 18.476 -66.371, 32.305 -64.751))")); assertEquals(expected, wktRoundTrip(client, "\n\nPOLYGON\n(\n(\n32.305\n-64.751\n,\n25.244\n-80.437\n,\n18.476\n-66.371\n,\n32.305\n-64.751\n)\n)\n")); assertEquals(expected, wktRoundTrip(client, "\t\tPOLYGON\t(\t(\t32.305\t-64.751\t,\t25.244\t-80.437\t,\t18.476\t-66.371\t,\t32.305\t-64.751\t)\t)\t")); assertEquals(expected, wktRoundTrip(client, " POLYGON ( ( 32.305 -64.751 , 25.244 -80.437 , 18.476 -66.371 , 32.305 -64.751 ) ) ")); // Parsing with more than one loop should work the same. expected = "POLYGON((32.305 -64.751, 25.244 -80.437, 18.476 -66.371, 32.305 -64.751), " + "(28.066 -68.874, 25.361 -68.855, 28.376 -73.381, 28.066 -68.874))"; assertEquals(expected, wktRoundTrip(client, "PoLyGoN\t( (\n32.305\n-64.751 , 25.244\t-80.437\n,18.476 -66.371,32.305\t\t\t-64.751 ),\t " + "(\n28.066\t-68.874,\t25.361 -68.855\n,28.376 -73.381,28.066\n\n-68.874\t)\n)\t")); } private void assertWktParseError(Client client, String expectedMsg, String wkt) throws Exception { String stmt = "select polygonfromtext('" + wkt + "') from t"; verifyStmtFails(client, stmt, expectedMsg); } public void testPolygonFromTextNegative() throws Exception { Client client = getClient(); validateTableOfScalarLongs(client, "insert into t (pk) values (0)", new long[] {1}); assertWktParseError(client, "does not start with POLYGON keyword", "NOT_A_POLYGON(...)"); assertWktParseError(client, "missing left parenthesis after POLYGON", "POLYGON []"); assertWktParseError(client, "expected left parenthesis to start a loop", "POLYGON(3 3, 4 4, 5 5, 3 3)"); assertWktParseError(client, "expected a number but found ','", "POLYGON ((80 80, 60, 70 70, 90 90))"); assertWktParseError(client, "unexpected token: '60'", "POLYGON ((80 80 60 60, 70 70, 90 90))"); assertWktParseError(client, "unexpected end of input", "POLYGON ((80 80, 60 60, 70 70,"); assertWktParseError(client, "expected a number but found '\\('", "POLYGON ((80 80, 60 60, 70 70, (30 15, 15 30, 15 45)))"); assertWktParseError(client, "unexpected token: 'z'", "POLYGON ((80 80, 60 60, 70 70, 80 80)z)"); assertWktParseError(client, "unrecognized input after WKT: 'blahblah'", "POLYGON ((80 80, 60 60, 70 70, 90 90))blahblah"); // The Java WKT parser (in GeographyValue, which uses Java's StreamTokenizer) can handle coordinates // that are separated only by a minus sign indicating that the second coordinate is negative. // But boost's tokenizer (at least as its currently configured) will consider "32.305-64.571" as a single // token. This seems like an acceptable discrepancy? assertWktParseError(client, "expected a number but found '32.305-64.751'", "POLYGON((32.305-64.751,25.244-80.437,18.476-66.371,32.305-64.751))"); } static public junit.framework.Test suite() { VoltServerConfig config = null; MultiConfigSuiteBuilder builder = new MultiConfigSuiteBuilder(TestGeographyValue.class); boolean success; VoltProjectBuilder project = new VoltProjectBuilder(); String literalSchema = "CREATE TABLE T (\n" + " PK INTEGER NOT NULL PRIMARY KEY,\n" + " NAME VARCHAR(32),\n" + " POLY GEOGRAPHY\n" + ");\n" + "CREATE TABLE PT (\n" + " PK INTEGER NOT NULL PRIMARY KEY,\n" + " NAME VARCHAR(32),\n" + " POLY GEOGRAPHY\n" + ");\n" + "PARTITION TABLE PT ON COLUMN PK;\n" + "CREATE TABLE T_NOT_NULL (\n" + " PK INTEGER NOT NULL PRIMARY KEY,\n" + " NAME VARCHAR(32),\n" + " POLY GEOGRAPHY NOT NULL\n" + ");\n" + "CREATE PROCEDURE select_in AS \n" + " SELECT pk FROM t WHERE poly IN ? ORDER BY pk ASC;\n" + "\n" ; try { project.addLiteralSchema(literalSchema); } catch (Exception e) { fail(); } config = new LocalCluster("geography-value-onesite.jar", 1, 1, 0, BackendTarget.NATIVE_EE_JNI); success = config.compile(project); assertTrue(success); builder.addServerConfig(config); return builder; } }
package io.c0nnector.github.least; import android.content.Context; import android.support.annotation.LayoutRes; import android.support.annotation.Nullable; import android.view.View; import android.view.ViewGroup; import io.c0nnector.github.least.util.UtilList; /** * Binds list objects to viewholders * * @param <Viewholder> * @param <Item> */ public abstract class Binder<Viewholder extends BaseViewHolder, Item> { @Nullable protected Context context; @Nullable BindListener<Viewholder, Item> bindListener; @Nullable ListItemListener<Viewholder, Item> listItemListener; public Binder(Context context) { this.context = context; } public Binder() { } /** * Creates a viewholder given the class and layout * * @param parent * * @return */ public Viewholder getViewHolder(ViewGroup parent) { return UtilList.getViewHolder(parent, getLayoutId(), getViewHolderClass()); } /** * Called when the viewholder for this binder is created * @param viewholder created viewholder */ public void onCreateViewHolder(Viewholder viewholder){} /** * Called when the adapter's onBind matches a viewholder to a list item A callback will be * invoked too, if defined * * @param holder viewholder * @param item list item tied to the viewholder * @param position list position */ public void onBindCallback(final Viewholder holder, final Item item, final int position) { onBindViewHolder(holder, item, position); //bind callback if (bindListener != null) bindListener.onBindViewHolder(holder, item, position); //list item click callback holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if(listItemListener != null) listItemListener.onListItemClick(holder, item, position); } }); } public abstract void onBindViewHolder(Viewholder holder, Item item, int position); /** * Layout id used to create the viewholder * * @return */ @LayoutRes public abstract int getLayoutId(); /** * Class of the viewholder * * @return */ public abstract Class<Viewholder> getViewHolderClass(); /** * Class of the object that is binded to this view * * @return */ public abstract Class<Item> getItemClass(); /** * Override to set a custom view type. By default we use the item class to identify the type * @return */ public int getViewType(){ return -1; } public boolean isViewTypeCustom(){ return getViewType() != -1; } /** * OnBind listener * * @return */ public Binder setBindListener(BindListener<Viewholder, Item> bindListener) { this.bindListener = bindListener; return this; } /** * List item click listener * * @return */ public Binder setListItemClickListener(ListItemListener<Viewholder, Item> listener) { this.listItemListener = listener; return this; } }
package org.voltdb.regressionsuites; import java.io.IOException; import org.voltdb.BackendTarget; import org.voltdb.VoltTable; import org.voltdb.client.Client; import org.voltdb.client.ProcCallException; import org.voltdb.compiler.VoltProjectBuilder; import org.voltdb_testprocs.regressionsuites.fixedsql.Insert; /** * System tests for UPDATE, mainly focusing on the correctness of the WHERE * clause */ public class TestSqlUpdateSuite extends RegressionSuite { /** Procedures used by this suite */ static final Class<?>[] PROCEDURES = { Insert.class }; static final int ROWS = 10; private void executeAndTestUpdate(Client client, String table, String update, int expectedRowsChanged) throws IOException, ProcCallException { for (int i = 0; i < ROWS; ++i) { client.callProcedure("Insert", table, i, "desc", i, 14.5); } VoltTable[] results = client.callProcedure("@AdHoc", update).getResults(); // ADHOC update still returns number of modified rows * number of partitions // Comment this out until it's fixed; the select count should be good enough, though //assertEquals(expectedRowsChanged, results[0].asScalarLong()); String query = String.format("select count(%s.NUM) from %s where %s.NUM = -1", table, table, table); results = client.callProcedure("@AdHoc", query).getResults(); assertEquals(String.format("Failing SQL: %s",query), expectedRowsChanged, results[0].asScalarLong()); client.callProcedure("@AdHoc",String.format("truncate table %s;",table)); } public void testUpdate() throws IOException, ProcCallException { Client client = getClient(); String[] tables = {"P1", "R1"}; System.out.println("testUpdate"); for (String table : tables) { String update = String.format("update %s set %s.NUM = -1", table, table); // Expect all rows to change executeAndTestUpdate(client, table, update, ROWS); } System.out.println("testUpdateWithEqualToIndexPredicate"); for (String table : tables) { String update = String.format("update %s set %s.NUM = -1 where %s.ID = 5", table, table, table); // Only row with ID = 5 should change executeAndTestUpdate(client, table, update, 1); } System.out.println("testUpdateWithEqualToNonIndexPredicate"); for (String table : tables) { String update = String.format("update %s set %s.NUM = -1 where %s.NUM = 5", table, table, table); // Only row with NUM = 5 should change executeAndTestUpdate(client, table, update, 1); } // This tests a bug found by the SQL coverage tool. The code in HSQL // which generates the XML eaten by the planner didn't generate // anything in the <condition> element output for > or >= on an index System.out.println("testUpdateWithGreaterThanIndexPredicate"); for (String table : tables) { String update = String.format("update %s set %s.NUM = -1 where %s.ID > 5", table, table, table); // Rows 6-9 should change executeAndTestUpdate(client, table, update, 4); } System.out.println("testUpdateWithGreaterThanNonIndexPredicate"); for (String table : tables) { String update = String.format("update %s set %s.NUM = -1 where %s.NUM > 5", table, table, table); // rows 6-9 should change executeAndTestUpdate(client, table, update, 4); } System.out.println("testUpdateWithLessThanIndexPredicate"); for (String table : tables) { String update = String.format("update %s set %s.NUM = -1 where %s.ID < 5", table, table, table); // Rows 0-4 should change executeAndTestUpdate(client, table, update, 5); } // This tests a bug found by the SQL coverage tool. The code in HSQL // which generates the XML eaten by the planner wouldn't combine // the various index and non-index join and where conditions, so the planner // would end up only seeing the first subnode written to the <condition> // element System.out.println("testUpdateWithOnePredicateAgainstIndexAndOneFalse"); for (String table : tables) { String update = "update " + table + " set " + table + ".NUM = 100" + " where " + table + ".NUM = 1000 and " + table + ".ID = 4"; executeAndTestUpdate(client, table, update, 0); } // This tests a bug found by the SQL coverage tool. The code in HSQL // which generates the XML eaten by the planner wouldn't combine (AND) // the index begin and end conditions, so the planner would only see the // begin condition in the <condition> element. System.out.println("testUpdateWithRangeAgainstIndex"); for (String table : tables) { String update = String.format("update %s set %s.NUM = -1 where %s.ID < 8 and %s.ID > 5", table, table, table, table); executeAndTestUpdate(client, table, update, 2); } System.out.println("testUpdateWithRangeAgainstNonIndex"); for (String table : tables) { String update = String.format("update %s set %s.NUM = -1 where %s.NUM < 8 and %s.NUM > 5", table, table, table, table); executeAndTestUpdate(client, table, update, 2); } // This is a regression test for ENG-6799 System.out.println("testUpdateFromInlineVarchar"); client.callProcedure("STRINGPART.insert", "aa", 1, 1, 0, "a potentially (but not really) very long string)"); // NAME is inlined varchar, DESC is not. String update = "update STRINGPART set desc = name, num = -1 where val1 = 1"; executeAndTestUpdate(client, "STRINGPART", update, 1); System.out.println("testInvalidUpdate"); verifyStmtFails(client, "UPDATE P1_VIEW SET NUM_SUM = 5", "Illegal to modify a materialized view."); } // JUnit / RegressionSuite boilerplate public TestSqlUpdateSuite(String name) { super(name); } static public junit.framework.Test suite() { VoltServerConfig config = null; MultiConfigSuiteBuilder builder = new MultiConfigSuiteBuilder(TestSqlUpdateSuite.class); VoltProjectBuilder project = new VoltProjectBuilder(); project.addSchema(Insert.class.getResource("sql-update-ddl.sql")); project.addProcedures(PROCEDURES); config = new LocalCluster("sqlupdate-onesite.jar", 1, 1, 0, BackendTarget.NATIVE_EE_JNI); if (!config.compile(project)) fail(); builder.addServerConfig(config); config = new LocalCluster("sqlupdate-hsql.jar", 1, 1, 0, BackendTarget.HSQLDB_BACKEND); if (!config.compile(project)) fail(); builder.addServerConfig(config); // Cluster config = new LocalCluster("sqlupdate-cluster.jar", 2, 3, 1, BackendTarget.NATIVE_EE_JNI); if (!config.compile(project)) fail(); builder.addServerConfig(config); return builder; } }
package txnIdSelfCheck; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import java.io.FileWriter; import java.io.IOException; import org.voltcore.logging.VoltLogger; import org.voltdb.CLIConfig; import org.voltdb.ClientResponseImpl; import org.voltdb.VoltTable; import org.voltdb.client.Client; import org.voltdb.client.ClientConfig; import org.voltdb.client.ClientFactory; import org.voltdb.client.ClientImpl; import org.voltdb.client.ClientResponse; import org.voltdb.client.ClientStatusListenerExt; import org.voltdb.client.ProcCallException; import org.voltdb.utils.MiscUtils; public class Benchmark { static VoltLogger log = new VoltLogger("HOST"); // handy, rather than typing this out several times static final String HORIZONTAL_RULE = " " // validated command line configuration final Config config; // create a client for each server node Client client; // Timer for periodic stats printing Timer timer; // Benchmark start time long benchmarkStartTS; // Timer for writing the checkpoint count for apprunner Timer checkpointTimer; final TxnId2PayloadProcessor processor; final AtomicInteger activeConnections = new AtomicInteger(0); final AtomicBoolean shutdown = new AtomicBoolean(false); // for reporting and detecting progress private final AtomicLong txnCount = new AtomicLong(); private long txnCountAtLastCheck; private long lastProgressTimestamp = System.currentTimeMillis(); // For retry connections private final ExecutorService es = Executors.newCachedThreadPool(new ThreadFactory() { @Override public Thread newThread(Runnable arg0) { Thread thread = new Thread(arg0, "Retry Connection"); thread.setDaemon(true); return thread; } }); /** * Uses included {@link CLIConfig} class to * declaratively state command line options with defaults * and validation. */ private static class Config extends CLIConfig { @Option(desc = "Interval for performance feedback, in seconds.") long displayinterval = 5; @Option(desc = "Benchmark duration, in seconds.") int duration = 20; @Option(desc = "Comma separated list of the form server[:port] to connect to.") String servers = "localhost"; String[] parsedServers = null; @Option(desc = "Number of parallel syncrhonous threads.") int threads = 100; @Option(desc = "Id of the first thread (useful for running multiple clients).") int threadoffset = 0; @Option(desc = "Minimum value size in bytes.") int minvaluesize = 1024; @Option(desc = "Maximum value size in bytes.") int maxvaluesize = 1024; @Option(desc = "Number of values considered for each value byte.") int entropy = 127; @Option(desc = "Compress values on the client side.") boolean usecompression = false; @Option(desc = "Filler table blob size.") int fillerrowsize = 5128; @Option(desc = "Target data size for the filler replicated table (at each site).") int replfillerrowmb = 32; @Option(desc = "Target data size for the partitioned filler table.") int partfillerrowmb = 128; @Option(desc = "Timeout that kills the client if progress is not made.") int progresstimeout = 120; @Option(desc = "Filename to write raw summary statistics to.") String statsfile = ""; @Override public void validate() { if (duration <= 0) exitWithMessageAndUsage("duration must be > 0"); if (displayinterval <= 0) exitWithMessageAndUsage("displayinterval must be > 0"); if (threadoffset < 0) exitWithMessageAndUsage("threadoffset must be >= 0"); if (threads <= 0) exitWithMessageAndUsage("threads must be > 0"); if (threadoffset > 127) exitWithMessageAndUsage("threadoffset must be within [0, 127]"); if (threadoffset + threads > 128) exitWithMessageAndUsage("max thread offset must be <= 127"); if (minvaluesize <= 0) exitWithMessageAndUsage("minvaluesize must be > 0"); if (maxvaluesize <= 0) exitWithMessageAndUsage("maxvaluesize must be > 0"); if (entropy <= 0) exitWithMessageAndUsage("entropy must be > 0"); if (entropy > 127) exitWithMessageAndUsage("entropy must be <= 127"); } @Override public void parse(String cmdName, String[] args) { super.parse(cmdName, args); // parse servers parsedServers = servers.split(","); } } /** * Fake an internal jstack to the log */ static public void printJStack() { log.info(new Date().toString() + " Full thread dump"); Map<String, List<String>> deduped = new HashMap<String, List<String>>(); // collect all the output, but dedup the identical stack traces for (Entry<Thread, StackTraceElement[]> e : Thread.getAllStackTraces().entrySet()) { Thread t = e.getKey(); String header = String.format("\"%s\" %sprio=%d tid=%d %s", t.getName(), t.isDaemon() ? "daemon " : "", t.getPriority(), t.getId(), t.getState().toString()); String stack = ""; for (StackTraceElement ste : e.getValue()) { stack += " at " + ste.toString() + "\n"; } if (deduped.containsKey(stack)) { deduped.get(stack).add(header); } else { ArrayList<String> headers = new ArrayList<String>(); headers.add(header); deduped.put(stack, headers); } } for (Entry<String, List<String>> e : deduped.entrySet()) { String logline = ""; for (String header : e.getValue()) { logline += header + "\n"; } logline += e.getKey(); log.info(logline); } } /** * Remove the client from the list if connection is broken. */ private class StatusListener extends ClientStatusListenerExt { @Override public void connectionLost(String hostname, int port, int connectionsLeft, DisconnectCause cause) { if (shutdown.get()) { return; } activeConnections.decrementAndGet(); // reset the connection id so the client will connect to a recovered cluster // this is a bit of a hack if (connectionsLeft == 0) { ((ClientImpl) client).resetInstanceId(); } // if the benchmark is still active if ((System.currentTimeMillis() - benchmarkStartTS) < (config.duration * 1000)) { log.warn(String.format("Connection to %s:%d was lost.", hostname, port)); } // setup for retry final String server = MiscUtils.getHostnameColonPortString(hostname, port); es.execute(new Runnable() { @Override public void run() { connectToOneServerWithRetry(server); } }); } } /** * Constructor for benchmark instance. * Configures VoltDB client and prints configuration. * * @param config Parsed & validated CLI options. */ Benchmark(Config config) { this.config = config; processor = new TxnId2PayloadProcessor(4, config.minvaluesize, config.maxvaluesize, config.entropy, Integer.MAX_VALUE, config.usecompression); log.info(HORIZONTAL_RULE); log.info(" Command Line Configuration"); log.info(HORIZONTAL_RULE); log.info(config.getConfigDumpString()); StatusListener statusListener = new StatusListener(); ClientConfig clientConfig = new ClientConfig("", "", statusListener); client = ClientFactory.createClient(clientConfig); } /** * Connect to a single server with retry. Limited exponential backoff. * No timeout. This will run until the process is killed if it's not * able to connect. * * @param server hostname:port or just hostname (hostname can be ip). */ private void connectToOneServerWithRetry(String server) { int sleep = 1000; while (!shutdown.get()) { try { client.createConnection(server); activeConnections.incrementAndGet(); log.info(String.format("Connected to VoltDB node at: %s.", server)); break; } catch (Exception e) { log.warn(String.format("Connection to " + server + " failed - retrying in %d second(s).", sleep / 1000)); try { Thread.sleep(sleep); } catch (Exception interruted) {} if (sleep < 8000) sleep += sleep; } } } /** * Connect to a set of servers in parallel. Each will retry until * connection. This call will block until all have connected. * * @throws InterruptedException if anything bad happens with the threads. */ private void connect() throws InterruptedException { log.info("Connecting to VoltDB..."); final CountDownLatch connections = new CountDownLatch(config.parsedServers.length); // use a new thread to connect to each server for (final String server : config.parsedServers) { new Thread(new Runnable() { @Override public void run() { connectToOneServerWithRetry(server); connections.countDown(); } }).start(); } // block until all have connected connections.await(); } /** * Create a Timer task to write the value of the txnCount to * disk to make it available to apprunner */ private void schedulePeriodicCheckpoint() throws IOException { checkpointTimer = new Timer(); TimerTask checkpointTask = new TimerTask() { @Override public void run() { String count = String.valueOf(txnCount.get()) + "\n"; try { FileWriter writer = new FileWriter(".checkpoint", false); writer.write(count); writer.close(); } catch (Exception e) { System.err.println("Caught exception writing checkpoint file."); } } }; checkpointTimer.scheduleAtFixedRate(checkpointTask, 1 * 1000, 1 * 1000); } /** * Create a Timer task to display performance data on the Vote procedure * It calls printStatistics() every displayInterval seconds */ private void schedulePeriodicStats() { timer = new Timer(); TimerTask statsPrinting = new TimerTask() { @Override public void run() { printStatistics(); } }; timer.scheduleAtFixedRate(statsPrinting, config.displayinterval * 1000, config.displayinterval * 1000); } /** * Prints a one line update on performance that can be printed * periodically during a benchmark. */ private synchronized void printStatistics() { long txnCountNow = txnCount.get(); long now = System.currentTimeMillis(); boolean madeProgress = txnCountNow > txnCountAtLastCheck; if (madeProgress) { lastProgressTimestamp = now; } txnCountAtLastCheck = txnCountNow; long diffInSeconds = (now - lastProgressTimestamp) / 1000; log.info(String.format("Executed %d%s", txnCount.get(), madeProgress ? "" : " (no progress made in " + diffInSeconds + " seconds)")); if (diffInSeconds > config.progresstimeout) { log.error("No progress was made in over " + diffInSeconds + " seconds while connected to a cluster. Exiting."); printJStack(); System.exit(-1); } } /** * Core benchmark code. * Connect. Initialize. Run the loop. Cleanup. Print Results. * * @throws Exception if anything unexpected happens. */ public void runBenchmark() throws Exception { log.info(HORIZONTAL_RULE); log.info(" Setup & Initialization"); log.info(HORIZONTAL_RULE); final int cidCount = 128; final long[] lastRid = new long[cidCount]; for (int i = 0; i < lastRid.length; i++) { lastRid[i] = 0; } // connect to one or more servers, loop until success connect(); // get stats try { ClientResponse cr = client.callProcedure("Summarize"); if (cr.getStatus() != ClientResponse.SUCCESS) { log.error("Failed to call Summarize proc at startup. Exiting."); log.error(((ClientResponseImpl) cr).toJSONString()); printJStack(); System.exit(-1); } // successfully called summarize VoltTable t = cr.getResults()[0]; long ts = t.fetchRow(0).getLong("ts"); String tsStr = ts == 0 ? "NO TIMESTAMPS" : String.valueOf(ts) + " / " + new Date(ts).toString(); long count = t.fetchRow(0).getLong("count"); log.info("STARTUP TIMESTAMP OF LAST UPDATE (GMT): " + tsStr); log.info("UPDATES RUN AGAINST THIS DB TO DATE: " + count); } catch (ProcCallException e) { log.error("Failed to call Summarize proc at startup. Exiting.", e); log.error(((ClientResponseImpl) e.getClientResponse()).toJSONString()); printJStack(); System.exit(-1); } log.info(HORIZONTAL_RULE); log.info("Starting Benchmark"); log.info(HORIZONTAL_RULE); // print periodic statistics to the console benchmarkStartTS = System.currentTimeMillis(); // reset progress tracker lastProgressTimestamp = System.currentTimeMillis(); schedulePeriodicStats(); schedulePeriodicCheckpoint(); // Run the benchmark loop for the requested duration // The throughput may be throttled depending on client configuration log.info("Running benchmark..."); BigTableLoader partitionedLoader = new BigTableLoader(client, "bigp", (config.partfillerrowmb * 1024 * 1024) / config.fillerrowsize, config.fillerrowsize); partitionedLoader.start(); BigTableLoader replicatedLoader = new BigTableLoader(client, "bigr", (config.replfillerrowmb * 1024 * 1024) / config.fillerrowsize, config.fillerrowsize); replicatedLoader.start(); ReadThread readThread = new ReadThread(client, config.threads, config.threadoffset); readThread.start(); AdHocMayhemThread adHocMayhemThread = new AdHocMayhemThread(client); adHocMayhemThread.start(); List<ClientThread> clientThreads = new ArrayList<ClientThread>(); for (byte cid = (byte) config.threadoffset; cid < config.threadoffset + config.threads; cid++) { ClientThread clientThread = new ClientThread(cid, txnCount, client, processor); clientThread.start(); clientThreads.add(clientThread); } final long benchmarkEndTime = System.currentTimeMillis() + (1000l * config.duration); while (benchmarkEndTime > System.currentTimeMillis()) { Thread.yield(); } replicatedLoader.shutdown(); partitionedLoader.shutdown(); readThread.shutdown(); adHocMayhemThread.shutdown(); for (ClientThread clientThread : clientThreads) { clientThread.shutdown(); } replicatedLoader.join(); partitionedLoader.join(); readThread.join(); adHocMayhemThread.join(); for (ClientThread clientThread : clientThreads) { clientThread.join(); } // cancel periodic stats printing timer.cancel(); checkpointTimer.cancel(); shutdown.set(true); es.shutdownNow(); // block until all outstanding txns return client.drain(); client.close(); log.info(HORIZONTAL_RULE); log.info("Benchmark Complete"); } /** * Main routine creates a benchmark instance and kicks off the run method. * * @param args Command line arguments. * @throws Exception if anything goes wrong. * @see {@link Config} */ public static void main(String[] args) throws Exception { // create a configuration from the arguments Config config = new Config(); config.parse(Benchmark.class.getName(), args); Benchmark benchmark = new Benchmark(config); benchmark.runBenchmark(); } }
// LIFReader.java package loci.formats.in; import java.io.ByteArrayInputStream; import java.io.IOException; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Stack; import java.util.StringTokenizer; import java.util.Vector; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import loci.common.DataTools; import loci.common.DateTools; import loci.common.RandomAccessInputStream; import loci.common.services.DependencyException; import loci.common.services.ServiceException; import loci.common.services.ServiceFactory; import loci.common.xml.XMLTools; import loci.formats.CoreMetadata; import loci.formats.FormatException; import loci.formats.FormatReader; import loci.formats.FormatTools; import loci.formats.ImageTools; import loci.formats.MetadataTools; import loci.formats.meta.IMetadata; import loci.formats.meta.MetadataStore; import loci.formats.services.OMEXMLService; import ome.xml.model.enums.DetectorType; import ome.xml.model.enums.LaserMedium; import ome.xml.model.enums.LaserType; import ome.xml.model.primitives.NonNegativeInteger; import ome.xml.model.primitives.PercentFraction; import ome.xml.model.primitives.PositiveFloat; import ome.xml.model.primitives.PositiveInteger; import org.xml.sax.SAXException; import org.w3c.dom.Attr; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class LIFReader extends FormatReader { // -- Constants -- public static final byte LIF_MAGIC_BYTE = 0x70; public static final byte LIF_MEMORY_BYTE = 0x2a; private static final HashMap<String, Integer> CHANNEL_PRIORITIES = createChannelPriorities(); private static HashMap<String, Integer> createChannelPriorities() { HashMap<String, Integer> h = new HashMap<String, Integer>(); h.put("red", new Integer(0)); h.put("green", new Integer(1)); h.put("blue", new Integer(2)); h.put("cyan", new Integer(3)); h.put("magenta", new Integer(4)); h.put("yellow", new Integer(5)); h.put("black", new Integer(6)); h.put("gray", new Integer(7)); h.put("", new Integer(8)); return h; } // -- Fields -- /** Offsets to memory blocks, paired with their corresponding description. */ private Vector<Long> offsets; private int[][] realChannel; private int lastChannel = 0; private Vector<String> lutNames = new Vector<String>(); private Vector<Double> physicalSizeXs = new Vector<Double>(); private Vector<Double> physicalSizeYs = new Vector<Double>(); private String[] descriptions, microscopeModels, serialNumber; private Double[] pinholes, zooms, zSteps, tSteps, lensNA; private Double[][] expTimes, gains, detectorOffsets; private String[][] channelNames; private Vector[] detectorModels, voltages; private Integer[][] exWaves; private Vector[] activeDetector; private HashMap[] detectorIndexes; private String[] immersions, corrections, objectiveModels; private Integer[] magnification; private Double[] posX, posY, posZ; private Double[] refractiveIndex; private Vector[] cutIns, cutOuts, filterModels; private double[][] timestamps; private Vector[] laserWavelength, laserIntensity; private ROI[][] imageROIs; private boolean alternateCenter = false; private String[] imageNames; private double[] acquiredDate; // -- Constructor -- /** Constructs a new Leica LIF reader. */ public LIFReader() { super("Leica Image File Format", "lif"); suffixNecessary = false; domains = new String[] {FormatTools.LM_DOMAIN}; } // -- IFormatReader API methods -- /* @see loci.formats.IFormatReader#getOptimalTileHeight() */ public int getOptimalTileHeight() { FormatTools.assertId(currentId, true, 1); return getSizeY(); } /* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */ public boolean isThisType(RandomAccessInputStream stream) throws IOException { final int blockLen = 1; if (!FormatTools.validStream(stream, blockLen, true)) return false; return stream.read() == LIF_MAGIC_BYTE; } /* @see loci.formats.IFormatReader#get8BitLookupTable() */ public byte[][] get8BitLookupTable() { FormatTools.assertId(currentId, true, 1); if (getPixelType() != FormatTools.UINT8 || !isIndexed()) return null; if (lastChannel < 0 || lastChannel >= 9) { return null; } byte[][] lut = new byte[3][256]; for (int i=0; i<256; i++) { switch (lastChannel) { case 0: // red lut[0][i] = (byte) (i & 0xff); break; case 1: // green lut[1][i] = (byte) (i & 0xff); break; case 2: // blue lut[2][i] = (byte) (i & 0xff); break; case 3: // cyan lut[1][i] = (byte) (i & 0xff); lut[2][i] = (byte) (i & 0xff); break; case 4: // magenta lut[0][i] = (byte) (i & 0xff); lut[2][i] = (byte) (i & 0xff); break; case 5: // yellow lut[0][i] = (byte) (i & 0xff); lut[1][i] = (byte) (i & 0xff); break; default: // gray lut[0][i] = (byte) (i & 0xff); lut[1][i] = (byte) (i & 0xff); lut[2][i] = (byte) (i & 0xff); } } return lut; } /* @see loci.formats.IFormatReader#get16BitLookupTable() */ public short[][] get16BitLookupTable() { FormatTools.assertId(currentId, true, 1); if (getPixelType() != FormatTools.UINT16 || !isIndexed()) return null; if (lastChannel < 0 || lastChannel >= 9) { return null; } short[][] lut = new short[3][65536]; for (int i=0; i<65536; i++) { switch (lastChannel) { case 0: // red lut[0][i] = (short) (i & 0xffff); break; case 1: // green lut[1][i] = (short) (i & 0xffff); break; case 2: // blue lut[2][i] = (short) (i & 0xffff); break; case 3: // cyan lut[1][i] = (short) (i & 0xffff); lut[2][i] = (short) (i & 0xffff); break; case 4: // magenta lut[0][i] = (short) (i & 0xffff); lut[2][i] = (short) (i & 0xffff); break; case 5: // yellow lut[0][i] = (short) (i & 0xffff); lut[1][i] = (short) (i & 0xffff); break; default: // gray lut[0][i] = (short) (i & 0xffff); lut[1][i] = (short) (i & 0xffff); lut[2][i] = (short) (i & 0xffff); } } return lut; } /** * @see loci.formats.IFormatReader#openBytes(int, byte[], int, int, int, int) */ public byte[] openBytes(int no, byte[] buf, int x, int y, int w, int h) throws FormatException, IOException { FormatTools.checkPlaneParameters(this, no, buf.length, x, y, w, h); if (!isRGB()) { int[] pos = getZCTCoords(no); lastChannel = realChannel[series][pos[1]]; } if (series >= offsets.size()) { // truncated file; imitate LAS AF and return black planes Arrays.fill(buf, (byte) 0); return buf; } long offset = offsets.get(series).longValue(); int bytes = FormatTools.getBytesPerPixel(getPixelType()); int bpp = bytes * getRGBChannelCount(); long planeSize = (long) getSizeX() * getSizeY() * bpp; long nextOffset = series + 1 < offsets.size() ? offsets.get(series + 1).longValue() : in.length(); int bytesToSkip = (int) (nextOffset - offset - planeSize * getImageCount()); bytesToSkip /= getSizeY(); if ((getSizeX() % 4) == 0) bytesToSkip = 0; if (offset + (planeSize + bytesToSkip * getSizeY()) * no >= in.length()) { // truncated file; imitate LAS AF and return black planes Arrays.fill(buf, (byte) 0); return buf; } in.seek(offset + planeSize * no); in.skipBytes(bytesToSkip * getSizeY() * no); if (bytesToSkip == 0) { readPlane(in, x, y, w, h, buf); } else { in.skipBytes(y * (getSizeX() * bpp + bytesToSkip)); for (int row=0; row<h; row++) { in.skipBytes(x * bpp); in.read(buf, row * w * bpp, w * bpp); in.skipBytes(bpp * (getSizeX() - w - x) + bytesToSkip); } } // color planes are stored in BGR order if (getRGBChannelCount() == 3) { ImageTools.bgrToRgb(buf, isInterleaved(), bytes, getRGBChannelCount()); } return buf; } /* @see loci.formats.IFormatReader#close(boolean) */ public void close(boolean fileOnly) throws IOException { super.close(fileOnly); if (!fileOnly) { offsets = null; realChannel = null; lastChannel = 0; lutNames.clear(); physicalSizeXs.clear(); physicalSizeYs.clear(); descriptions = microscopeModels = serialNumber = null; pinholes = zooms = lensNA = null; zSteps = tSteps = null; expTimes = gains = null; detectorOffsets = null; channelNames = null; detectorModels = voltages = null; exWaves = null; activeDetector = null; immersions = corrections = null; magnification = null; objectiveModels = null; posX = posY = posZ = null; refractiveIndex = null; cutIns = cutOuts = filterModels = null; timestamps = null; laserWavelength = laserIntensity = null; imageROIs = null; alternateCenter = false; imageNames = null; acquiredDate = null; detectorIndexes = null; } } // -- Internal FormatReader API methods -- /* @see loci.formats.FormatReader#initFile(String) */ protected void initFile(String id) throws FormatException, IOException { super.initFile(id); in = new RandomAccessInputStream(id); offsets = new Vector<Long>(); in.order(true); // read the header LOGGER.info("Reading header"); byte checkOne = in.readByte(); in.skipBytes(2); byte checkTwo = in.readByte(); if (checkOne != LIF_MAGIC_BYTE && checkTwo != LIF_MAGIC_BYTE) { throw new FormatException(id + " is not a valid Leica LIF file"); } in.skipBytes(4); // read and parse the XML description if (in.read() != LIF_MEMORY_BYTE) { throw new FormatException("Invalid XML description"); } // number of Unicode characters in the XML block int nc = in.readInt(); String xml = DataTools.stripString(in.readString(nc * 2)); LOGGER.info("Finding image offsets"); while (in.getFilePointer() < in.length()) { LOGGER.debug("Looking for a block at {}; {} blocks read", in.getFilePointer(), offsets.size()); int check = in.readInt(); if (check != LIF_MAGIC_BYTE) { throw new FormatException("Invalid Memory Block: found magic bytes " + check + ", expected " + LIF_MAGIC_BYTE); } in.skipBytes(4); check = in.read(); if (check != LIF_MEMORY_BYTE) { throw new FormatException("Invalid Memory Description: found magic " + "byte " + check + ", expected " + LIF_MEMORY_BYTE); } long blockLength = in.readInt(); if (in.read() != LIF_MEMORY_BYTE) { in.seek(in.getFilePointer() - 5); blockLength = in.readLong(); check = in.read(); if (check != LIF_MEMORY_BYTE) { throw new FormatException("Invalid Memory Description: found magic " + "byte " + check + ", expected " + LIF_MEMORY_BYTE); } } int descrLength = in.readInt() * 2; if (blockLength > 0) { offsets.add(new Long(in.getFilePointer() + descrLength)); } in.seek(in.getFilePointer() + descrLength + blockLength); } initMetadata(xml); xml = null; // correct offsets, if necessary if (offsets.size() > getSeriesCount()) { Long[] storedOffsets = offsets.toArray(new Long[offsets.size()]); offsets.clear(); int index = 0; for (int i=0; i<getSeriesCount(); i++) { setSeries(i); long nBytes = (long) FormatTools.getPlaneSize(this) * getImageCount(); long start = storedOffsets[index]; long end = index == storedOffsets.length - 1 ? in.length() : storedOffsets[index + 1]; while (end - start < nBytes && ((end - start) / nBytes) != 1) { index++; start = storedOffsets[index]; end = index == storedOffsets.length - 1 ? in.length() : storedOffsets[index + 1]; } offsets.add(storedOffsets[index]); index++; } setSeries(0); } } // -- Helper methods -- /** Parses a string of XML and puts the values in a Hashtable. */ private void initMetadata(String xml) throws FormatException, IOException { IMetadata omexml = null; try { ServiceFactory factory = new ServiceFactory(); OMEXMLService service = factory.getInstance(OMEXMLService.class); omexml = service.createOMEXMLMetadata(); } catch (DependencyException exc) { throw new FormatException("Could not create OME-XML store.", exc); } catch (ServiceException exc) { throw new FormatException("Could not create OME-XML store.", exc); } MetadataStore store = makeFilterMetadata(); MetadataLevel level = getMetadataOptions().getMetadataLevel(); // the XML blocks stored in a LIF file are invalid, // because they don't have a root node xml = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?><LEICA>" + xml + "</LEICA>"; xml = XMLTools.sanitizeXML(xml); translateMetadata(getMetadataRoot(xml)); for (int i=0; i<imageNames.length; i++) { setSeries(i); addSeriesMeta("Image name", imageNames[i]); } setSeries(0); // set up mapping to rearrange channels // for instance, the green channel may be #0, and the red channel may be #1 realChannel = new int[getSeriesCount()][]; int nextLut = 0; for (int i=0; i<getSeriesCount(); i++) { realChannel[i] = new int[core[i].sizeC]; for (int q=0; q<core[i].sizeC; q++) { String lut = lutNames.get(nextLut++).toLowerCase(); if (!CHANNEL_PRIORITIES.containsKey(lut)) lut = ""; realChannel[i][q] = CHANNEL_PRIORITIES.get(lut).intValue(); } int[] sorted = new int[core[i].sizeC]; Arrays.fill(sorted, -1); for (int q=0; q<sorted.length; q++) { int min = Integer.MAX_VALUE; int minIndex = -1; for (int n=0; n<core[i].sizeC; n++) { if (realChannel[i][n] < min && !DataTools.containsValue(sorted, n)) { min = realChannel[i][n]; minIndex = n; } } sorted[q] = minIndex; } } MetadataTools.populatePixels(store, this, true, false); for (int i=0; i<getSeriesCount(); i++) { setSeries(i); String instrumentID = MetadataTools.createLSID("Instrument", i); store.setInstrumentID(instrumentID, i); store.setMicroscopeModel(microscopeModels[i], i); store.setMicroscopeType(getMicroscopeType("Other"), i); String objectiveID = MetadataTools.createLSID("Objective", i, 0); store.setObjectiveID(objectiveID, i, 0); store.setObjectiveLensNA(lensNA[i], i, 0); store.setObjectiveSerialNumber(serialNumber[i], i, 0); if (magnification[i] != null && magnification[i] > 0) { store.setObjectiveNominalMagnification( new PositiveInteger(magnification[i]), i, 0); } else { LOGGER.warn("Expected positive value for NominalMagnification; got {}", magnification[i]); } store.setObjectiveImmersion(getImmersion(immersions[i]), i, 0); store.setObjectiveCorrection(getCorrection(corrections[i]), i, 0); store.setObjectiveModel(objectiveModels[i], i, 0); if (cutIns[i] != null) { for (int filter=0; filter<cutIns[i].size(); filter++) { String filterID = MetadataTools.createLSID("Filter", i, filter); store.setFilterID(filterID, i, filter); if (filter < filterModels[i].size()) { store.setFilterModel( (String) filterModels[i].get(filter), i, filter); } int channel = filter - (cutIns[i].size() - getEffectiveSizeC()); if (channel >= 0 && channel < getEffectiveSizeC()) { //store.setLightPathEmissionFilterRef(filterID, i, channel, 0); } store.setTransmittanceRangeCutIn( (PositiveInteger) cutIns[i].get(filter), i, filter); store.setTransmittanceRangeCutOut( (PositiveInteger) cutOuts[i].get(filter), i, filter); } } Vector lasers = laserWavelength[i]; Vector laserIntensities = laserIntensity[i]; int nextChannel = 0; if (lasers != null) { int laserIndex = 0; while (laserIndex < lasers.size()) { if ((Integer) lasers.get(laserIndex) == 0) { lasers.removeElementAt(laserIndex); } else { laserIndex++; } } for (int laser=0; laser<lasers.size(); laser++) { String id = MetadataTools.createLSID("LightSource", i, laser); store.setLaserID(id, i, laser); store.setLaserType(LaserType.OTHER, i, laser); store.setLaserLaserMedium(LaserMedium.OTHER, i, laser); Integer wavelength = (Integer) lasers.get(laser); if (wavelength > 0) { store.setLaserWavelength(new PositiveInteger(wavelength), i, laser); } else { LOGGER.warn("Expected positive value for Wavelength; got {}", wavelength); } } Vector<Integer> validIntensities = new Vector<Integer>(); for (int laser=0; laser<laserIntensities.size(); laser++) { double intensity = (Double) laserIntensities.get(laser); if (intensity < 100) { validIntensities.add(laser); } } int start = validIntensities.size() - getEffectiveSizeC(); if (start < 0) { start = 0; } boolean noNames = true; for (String name : channelNames[i]) { if (name != null && !name.equals("")) { noNames = false; break; } } for (int k=start; k<validIntensities.size(); k++, nextChannel++) { int index = validIntensities.get(k); double intensity = (Double) laserIntensities.get(index); int laser = index % lasers.size(); Integer wavelength = (Integer) lasers.get(laser); if (wavelength != 0) { while (channelNames != null && nextChannel < getEffectiveSizeC() && ((channelNames[i][nextChannel] == null || channelNames[i][nextChannel].equals("")) && !noNames)) { nextChannel++; } if (nextChannel < getEffectiveSizeC()) { String id = MetadataTools.createLSID("LightSource", i, laser); store.setChannelLightSourceSettingsID(id, i, nextChannel); store.setChannelLightSourceSettingsAttenuation( new PercentFraction((float) intensity / 100f), i, nextChannel); if (wavelength > 0) { store.setChannelExcitationWavelength( new PositiveInteger(wavelength), i, nextChannel); } else { LOGGER.warn( "Expected positive value for ExcitationWavelength; got {}", wavelength); } } } } } store.setImageInstrumentRef(instrumentID, i); store.setImageObjectiveSettingsID(objectiveID, i); store.setImageObjectiveSettingsRefractiveIndex(refractiveIndex[i], i); store.setImageDescription(descriptions[i], i); if (acquiredDate[i] > 0) { store.setImageAcquiredDate(DateTools.convertDate( (long) (acquiredDate[i] * 1000), DateTools.COBOL), i); } store.setImageName(imageNames[i].trim(), i); if (physicalSizeXs.get(i) > 0) { store.setPixelsPhysicalSizeX( new PositiveFloat(physicalSizeXs.get(i)), i); } else { LOGGER.warn("Expected positive value for PhysicalSizeX; got {}", physicalSizeXs.get(i)); } if (physicalSizeYs.get(i) > 0) { store.setPixelsPhysicalSizeY( new PositiveFloat(physicalSizeYs.get(i)), i); } else { LOGGER.warn("Expected positive value for PhysicalSizeY; got {}", physicalSizeYs.get(i)); } if (zSteps[i] != null && zSteps[i] > 0) { store.setPixelsPhysicalSizeZ(new PositiveFloat(zSteps[i]), i); } else { LOGGER.warn("Expected positive value for PhysicalSizeZ; got {}", zSteps[i]); } store.setPixelsTimeIncrement(tSteps[i], i); Vector detectors = detectorModels[i]; if (detectors != null) { nextChannel = 0; for (int detector=0; detector<detectors.size(); detector++) { String detectorID = MetadataTools.createLSID("Detector", i, detector); store.setDetectorID(detectorID, i, detector); store.setDetectorModel((String) detectors.get(detector), i, detector); store.setDetectorZoom(zooms[i], i, detector); store.setDetectorType(DetectorType.PMT, i, detector); if (voltages[i] != null && detector < voltages[i].size()) { store.setDetectorVoltage( (Double) voltages[i].get(detector), i, detector); } if (activeDetector[i] != null) { if (detector < activeDetector[i].size() && (Boolean) activeDetector[i].get(detector) && detectorOffsets[i] != null && nextChannel < detectorOffsets[i].length) { store.setDetectorOffset( detectorOffsets[i][nextChannel++], i, detector); } } } } Vector activeDetectors = activeDetector[i]; int firstDetector = activeDetectors == null ? 0 : activeDetectors.size() - getEffectiveSizeC(); int nextDetector = firstDetector; for (int c=0; c<getEffectiveSizeC(); c++) { if (activeDetectors != null) { while (nextDetector >= 0 && nextDetector < activeDetectors.size() && !(Boolean) activeDetectors.get(nextDetector)) { nextDetector++; } if (nextDetector < activeDetectors.size() && detectors != null && nextDetector - firstDetector < detectors.size()) { String detectorID = MetadataTools.createLSID( "Detector", i, nextDetector - firstDetector); store.setDetectorSettingsID(detectorID, i, c); nextDetector++; if (detectorOffsets[i] != null && c < detectorOffsets[i].length) { store.setDetectorSettingsOffset(detectorOffsets[i][c], i, c); } if (gains[i] != null) { store.setDetectorSettingsGain(gains[i][c], i, c); } } } if (channelNames[i] != null) { store.setChannelName(channelNames[i][c], i, c); } store.setChannelPinholeSize(pinholes[i], i, c); if (exWaves[i] != null) { if (exWaves[i][c] != null && exWaves[i][c] > 1) { store.setChannelExcitationWavelength( new PositiveInteger(exWaves[i][c]), i, c); } else { LOGGER.warn( "Expected positive value for ExcitationWavelength; got {}", exWaves[i][c]); } } if (expTimes[i] != null) { store.setPlaneExposureTime(expTimes[i][c], i, c); } int channelColor = getChannelColor(realChannel[i][c]); store.setChannelColor(channelColor, i, c); } for (int image=0; image<getImageCount(); image++) { store.setPlanePositionX(posX[i], i, image); store.setPlanePositionY(posY[i], i, image); store.setPlanePositionZ(posZ[i], i, image); if (timestamps[i] != null) { double timestamp = timestamps[i][image]; if (timestamps[i][0] == acquiredDate[i]) { timestamp -= acquiredDate[i]; } else if (timestamp == acquiredDate[i] && image > 0) { timestamp = timestamps[i][0]; } store.setPlaneDeltaT(timestamp, i, image); } } if (imageROIs[i] != null) { for (int roi=0; roi<imageROIs[i].length; roi++) { if (imageROIs[i][roi] != null) { imageROIs[i][roi].storeROI(store, i, roi); } } } } } private Element getMetadataRoot(String xml) throws FormatException, IOException { try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder parser = factory.newDocumentBuilder(); ByteArrayInputStream s = new ByteArrayInputStream(xml.getBytes()); Element root = parser.parse(s).getDocumentElement(); s.close(); return root; } catch (ParserConfigurationException e) { throw new FormatException(e); } catch (SAXException e) { throw new FormatException(e); } } private void translateMetadata(Element root) throws FormatException { Element realRoot = (Element) root.getChildNodes().item(0); NodeList toPrune = getNodes(realRoot, "LDM_Block_Sequential_Master"); if (toPrune != null) { for (int i=0; i<toPrune.getLength(); i++) { Element prune = (Element) toPrune.item(i); Element parent = (Element) prune.getParentNode(); parent.removeChild(prune); } } NodeList imageNodes = getNodes(realRoot, "Image"); core = new CoreMetadata[imageNodes.getLength()]; acquiredDate = new double[imageNodes.getLength()]; descriptions = new String[imageNodes.getLength()]; laserWavelength = new Vector[imageNodes.getLength()]; laserIntensity = new Vector[imageNodes.getLength()]; timestamps = new double[imageNodes.getLength()][]; activeDetector = new Vector[imageNodes.getLength()]; voltages = new Vector[imageNodes.getLength()]; serialNumber = new String[imageNodes.getLength()]; lensNA = new Double[imageNodes.getLength()]; magnification = new Integer[imageNodes.getLength()]; immersions = new String[imageNodes.getLength()]; corrections = new String[imageNodes.getLength()]; objectiveModels = new String[imageNodes.getLength()]; posX = new Double[imageNodes.getLength()]; posY = new Double[imageNodes.getLength()]; posZ = new Double[imageNodes.getLength()]; refractiveIndex = new Double[imageNodes.getLength()]; cutIns = new Vector[imageNodes.getLength()]; cutOuts = new Vector[imageNodes.getLength()]; filterModels = new Vector[imageNodes.getLength()]; microscopeModels = new String[imageNodes.getLength()]; detectorModels = new Vector[imageNodes.getLength()]; detectorIndexes = new HashMap[imageNodes.getLength()]; zSteps = new Double[imageNodes.getLength()]; tSteps = new Double[imageNodes.getLength()]; pinholes = new Double[imageNodes.getLength()]; zooms = new Double[imageNodes.getLength()]; expTimes = new Double[imageNodes.getLength()][]; gains = new Double[imageNodes.getLength()][]; detectorOffsets = new Double[imageNodes.getLength()][]; channelNames = new String[imageNodes.getLength()][]; exWaves = new Integer[imageNodes.getLength()][]; imageROIs = new ROI[imageNodes.getLength()][]; imageNames = new String[imageNodes.getLength()]; for (int i=0; i<imageNodes.getLength(); i++) { Element image = (Element) imageNodes.item(i); setSeries(i); translateImageNames(image, i); translateImageNodes(image, i); translateAttachmentNodes(image, i); translateScannerSettings(image, i); translateFilterSettings(image, i); translateTimestamps(image, i); translateLaserLines(image, i); translateROIs(image, i); translateSingleROIs(image, i); translateDetectors(image, i); Stack<String> nameStack = new Stack<String>(); HashMap<String, Integer> indexes = new HashMap<String, Integer>(); populateOriginalMetadata(image, nameStack, indexes); indexes.clear(); } setSeries(0); } private void populateOriginalMetadata(Element root, Stack<String> nameStack, HashMap<String, Integer> indexes) { String name = root.getNodeName(); if (root.hasAttributes() && !name.equals("Element") && !name.equals("Attachment") && !name.equals("LMSDataContainerHeader")) { nameStack.push(name); String suffix = root.getAttribute("Identifier"); String value = root.getAttribute("Variant"); if (suffix == null || suffix.trim().length() == 0) { suffix = root.getAttribute("Description"); } StringBuffer key = new StringBuffer(); for (String k : nameStack) { key.append(k); key.append("|"); } if (suffix != null && value != null && suffix.length() > 0 && value.length() > 0 && !suffix.equals("HighInteger") && !suffix.equals("LowInteger")) { Integer i = indexes.get(key.toString() + suffix); String storedKey = key.toString() + suffix + " " + (i == null ? 0 : i); indexes.put(key.toString() + suffix, i == null ? 1 : i + 1); addSeriesMeta(storedKey, value); } else { NamedNodeMap attributes = root.getAttributes(); for (int i=0; i<attributes.getLength(); i++) { Attr attr = (Attr) attributes.item(i); if (!attr.getName().equals("HighInteger") && !attr.getName().equals("LowInteger")) { Integer index = indexes.get(key.toString() + attr.getName()); if (index == null) { index = 0; } String storedKey = key.toString() + attr.getName() + " " + index; indexes.put(key.toString() + attr.getName(), index + 1); addSeriesMeta(storedKey, attr.getValue()); } } } } NodeList children = root.getChildNodes(); for (int i=0; i<children.getLength(); i++) { Object child = children.item(i); if (child instanceof Element) { populateOriginalMetadata((Element) child, nameStack, indexes); } } if (root.hasAttributes() && !name.equals("Element") && !name.equals("Attachment") && !name.equals("LMSDataContainerHeader")) { nameStack.pop(); } } private void translateImageNames(Element imageNode, int image) { Vector<String> names = new Vector<String>(); Element parent = imageNode; while (true) { parent = (Element) parent.getParentNode(); if (parent == null || parent.getNodeName().equals("LEICA")) { break; } if (parent.getNodeName().equals("Element")) { names.add(parent.getAttribute("Name")); } } imageNames[image] = ""; for (int i=names.size() - 2; i>=0; i imageNames[image] += names.get(i); if (i > 0) imageNames[image] += "/"; } } private void translateDetectors(Element imageNode, int image) throws FormatException { NodeList definitions = getNodes(imageNode, "ATLConfocalSettingDefinition"); if (definitions == null) return; Vector<String> channels = new Vector<String>(); int nextChannel = 0; for (int definition=0; definition<definitions.getLength(); definition++) { Element definitionNode = (Element) definitions.item(definition); NodeList detectors = getNodes(definitionNode, "Detector"); if (detectors == null) return; for (int d=0; d<detectors.getLength(); d++) { Element detector = (Element) detectors.item(d); NodeList multibands = getNodes(definitionNode, "MultiBand"); String v = detector.getAttribute("Gain"); Double gain = v == null || v.trim().length() == 0 ? null : new Double(v); v = detector.getAttribute("Offset"); Double offset = v == null || v.trim().length() == 0 ? null : new Double(v); boolean active = "1".equals(detector.getAttribute("IsActive")); if (active) { String c = detector.getAttribute("Channel"); int channel = c == null ? 0 : Integer.parseInt(c); detectorModels[image].add(detectorIndexes[image].get(channel)); Element multiband = null; if (multibands != null) { for (int i=0; i<multibands.getLength(); i++) { Element mb = (Element) multibands.item(i); if (channel == Integer.parseInt(mb.getAttribute("Channel"))) { multiband = mb; break; } } } if (multiband != null) { channels.add(multiband.getAttribute("DyeName")); double cutIn = new Double(multiband.getAttribute("LeftWorld")); double cutOut = new Double(multiband.getAttribute("RightWorld")); if ((int) cutIn > 0) { cutIns[image].add(new PositiveInteger((int) Math.round(cutIn))); } else { LOGGER.warn("Expected positive value for CutIn; got {}", cutIn); } if ((int) cutOut > 0) { cutOuts[image].add(new PositiveInteger((int) Math.round(cutOut))); } else { LOGGER.warn("Expected positive value for CutOut; got {}", cutOut); } } else { channels.add(""); } if (nextChannel < getEffectiveSizeC()) { gains[image][nextChannel] = gain; detectorOffsets[image][nextChannel] = offset; } nextChannel++; } if (active) { activeDetector[image].add(active); } } } for (int i=0; i<getEffectiveSizeC(); i++) { int index = i + channels.size() - getEffectiveSizeC(); if (index >= 0 && index < channels.size()) { channelNames[image][i] = channels.get(index); } } } private void translateROIs(Element imageNode, int image) throws FormatException { NodeList rois = getNodes(imageNode, "Annotation"); if (rois == null) return; imageROIs[image] = new ROI[rois.getLength()]; for (int r=0; r<rois.getLength(); r++) { Element roiNode = (Element) rois.item(r); ROI roi = new ROI(); String type = roiNode.getAttribute("type"); if (type != null) { roi.type = Integer.parseInt(type); } String color = roiNode.getAttribute("color"); if (color != null) { roi.color = Long.parseLong(color); } roi.name = roiNode.getAttribute("name"); roi.fontName = roiNode.getAttribute("fontName"); roi.fontSize = roiNode.getAttribute("fontSize"); roi.transX = parseDouble(roiNode.getAttribute("transTransX")); roi.transY = parseDouble(roiNode.getAttribute("transTransY")); roi.scaleX = parseDouble(roiNode.getAttribute("transScalingX")); roi.scaleY = parseDouble(roiNode.getAttribute("transScalingY")); roi.rotation = parseDouble(roiNode.getAttribute("transRotation")); String linewidth = roiNode.getAttribute("linewidth"); if (linewidth != null) { try { roi.linewidth = Integer.parseInt(linewidth); } catch (NumberFormatException e) { } } roi.text = roiNode.getAttribute("text"); NodeList vertices = getNodes(roiNode, "Vertex"); if (vertices == null) { continue; } for (int v=0; v<vertices.getLength(); v++) { Element vertex = (Element) vertices.item(v); String xx = vertex.getAttribute("x"); String yy = vertex.getAttribute("y"); if (xx != null) { roi.x.add(parseDouble(xx)); } if (yy != null) { roi.y.add(parseDouble(yy)); } } imageROIs[image][r] = roi; if (getNodes(imageNode, "ROI") != null) { alternateCenter = true; } } } private void translateSingleROIs(Element imageNode, int image) throws FormatException { if (imageROIs[image] != null) return; NodeList children = getNodes(imageNode, "ROI"); if (children == null) return; children = getNodes((Element) children.item(0), "Children"); if (children == null) return; children = getNodes((Element) children.item(0), "Element"); if (children == null) return; imageROIs[image] = new ROI[children.getLength()]; for (int r=0; r<children.getLength(); r++) { NodeList rois = getNodes((Element) children.item(r), "ROISingle"); Element roiNode = (Element) rois.item(0); ROI roi = new ROI(); String type = roiNode.getAttribute("RoiType"); if (type != null) { roi.type = Integer.parseInt(type); } String color = roiNode.getAttribute("Color"); if (color != null) { roi.color = Long.parseLong(color); } Element parent = (Element) roiNode.getParentNode(); parent = (Element) parent.getParentNode(); roi.name = parent.getAttribute("Name"); NodeList vertices = getNodes(roiNode, "P"); double sizeX = physicalSizeXs.get(image); double sizeY = physicalSizeYs.get(image); for (int v=0; v<vertices.getLength(); v++) { Element vertex = (Element) vertices.item(v); String xx = vertex.getAttribute("X"); String yy = vertex.getAttribute("Y"); if (xx != null) { roi.x.add(parseDouble(xx) / sizeX); } if (yy != null) { roi.y.add(parseDouble(yy) / sizeY); } } Element transform = (Element) getNodes(roiNode, "Transformation").item(0); roi.rotation = parseDouble(transform.getAttribute("Rotation")); Element scaling = (Element) getNodes(transform, "Scaling").item(0); roi.scaleX = parseDouble(scaling.getAttribute("XScale")); roi.scaleY = parseDouble(scaling.getAttribute("YScale")); Element translation = (Element) getNodes(transform, "Translation").item(0); roi.transX = parseDouble(translation.getAttribute("X")) / sizeX; roi.transY = parseDouble(translation.getAttribute("Y")) / sizeY; imageROIs[image][r] = roi; } } private void translateLaserLines(Element imageNode, int image) throws FormatException { NodeList aotfLists = getNodes(imageNode, "AotfList"); if (aotfLists == null) return; laserWavelength[image] = new Vector<Integer>(); laserIntensity[image] = new Vector<Double>(); int baseIntensityIndex = 0; for (int channel=0; channel<aotfLists.getLength(); channel++) { Element aotf = (Element) aotfLists.item(channel); NodeList laserLines = getNodes(aotf, "LaserLineSetting"); if (laserLines == null) return; for (int laser=0; laser<laserLines.getLength(); laser++) { Element laserLine = (Element) laserLines.item(laser); String lineIndex = laserLine.getAttribute("LineIndex"); String qual = laserLine.getAttribute("Qualifier"); int index = lineIndex == null ? 0 : Integer.parseInt(lineIndex); int qualifier = qual == null ? 0: Integer.parseInt(qual); index += (2 - (qualifier / 10)); if (index < 0) index = 0; Integer wavelength = new Integer(laserLine.getAttribute("LaserLine")); if (index < laserWavelength[image].size()) { laserWavelength[image].setElementAt(wavelength, index); } else { for (int i=laserWavelength[image].size(); i<index; i++) { laserWavelength[image].add(new Integer(0)); } laserWavelength[image].add(wavelength); } String intensity = laserLine.getAttribute("IntensityDev"); double realIntensity = intensity == null ? 0d : new Double(intensity); realIntensity = 100d - realIntensity; int realIndex = baseIntensityIndex + index; if (realIndex < laserIntensity[image].size()) { laserIntensity[image].setElementAt(realIntensity, realIndex); } else { while (realIndex < laserIntensity[image].size()) { laserIntensity[image].add(100d); } laserIntensity[image].add(realIntensity); } } baseIntensityIndex += laserWavelength[image].size(); } } private void translateTimestamps(Element imageNode, int image) throws FormatException { NodeList timestampNodes = getNodes(imageNode, "TimeStamp"); if (timestampNodes == null) return; timestamps[image] = new double[getImageCount()]; if (timestampNodes != null) { for (int stamp=0; stamp<timestampNodes.getLength(); stamp++) { if (stamp < getImageCount()) { Element timestamp = (Element) timestampNodes.item(stamp); String stampHigh = timestamp.getAttribute("HighInteger"); String stampLow = timestamp.getAttribute("LowInteger"); long high = stampHigh == null ? 0 : Long.parseLong(stampHigh); long low = stampLow == null ? 0 : Long.parseLong(stampLow); long ms = DateTools.getMillisFromTicks(high, low); timestamps[image][stamp] = ms / 1000.0; } } } acquiredDate[image] = timestamps[image][0]; NodeList relTimestampNodes = getNodes(imageNode, "RelTimeStamp"); if (relTimestampNodes != null) { for (int stamp=0; stamp<relTimestampNodes.getLength(); stamp++) { if (stamp < getImageCount()) { Element timestamp = (Element) relTimestampNodes.item(stamp); timestamps[image][stamp] = new Double(timestamp.getAttribute("Time")); } } } } private void translateFilterSettings(Element imageNode, int image) throws FormatException { NodeList filterSettings = getNodes(imageNode, "FilterSettingRecord"); if (filterSettings == null) return; activeDetector[image] = new Vector<Boolean>(); voltages[image] = new Vector<Double>(); cutIns[image] = new Vector<PositiveInteger>(); cutOuts[image] = new Vector<PositiveInteger>(); filterModels[image] = new Vector<String>(); detectorIndexes[image] = new HashMap<Integer, String>(); for (int i=0; i<filterSettings.getLength(); i++) { Element filterSetting = (Element) filterSettings.item(i); String object = filterSetting.getAttribute("ObjectName"); String attribute = filterSetting.getAttribute("Attribute"); String objectClass = filterSetting.getAttribute("ClassName"); String variant = filterSetting.getAttribute("Variant"); String data = filterSetting.getAttribute("Data"); if (attribute.equals("NumericalAperture")) { lensNA[image] = new Double(variant); } else if (attribute.equals("OrderNumber")) { serialNumber[image] = variant; } else if (objectClass.equals("CDetectionUnit")) { if (attribute.equals("State")) { int channel = getChannelIndex(filterSetting); if (channel < 0) continue; detectorIndexes[image].put(new Integer(data), object); activeDetector[image].add(variant.equals("Active")); } else if (attribute.equals("HighVoltage")) { int channel = getChannelIndex(filterSetting); if (channel < 0) continue; if (channel < voltages[image].size()) { voltages[image].setElementAt(new Double(variant), channel); } else { while (channel > voltages[image].size()) { voltages[image].add(new Double(0)); } voltages[image].add(new Double(variant)); } } } else if (attribute.equals("Objective")) { StringTokenizer tokens = new StringTokenizer(variant, " "); boolean foundMag = false; StringBuffer model = new StringBuffer(); while (!foundMag) { String token = tokens.nextToken(); int x = token.indexOf("x"); if (x != -1) { foundMag = true; int mag = (int) Double.parseDouble(token.substring(0, x)); String na = token.substring(x + 1); magnification[image] = mag; lensNA[image] = new Double(na); } else { model.append(token); model.append(" "); } } String immersion = "Other"; if (tokens.hasMoreTokens()) { immersion = tokens.nextToken(); if (immersion == null || immersion.trim().equals("")) { immersion = "Other"; } } immersions[image] = immersion; String correction = "Other"; if (tokens.hasMoreTokens()) { correction = tokens.nextToken(); if (correction == null || correction.trim().equals("")) { correction = "Other"; } } corrections[image] = correction; objectiveModels[image] = model.toString().trim(); } else if (attribute.equals("RefractionIndex")) { refractiveIndex[image] = new Double(variant); } else if (attribute.equals("XPos")) { posX[image] = new Double(variant); } else if (attribute.equals("YPos")) { posY[image] = new Double(variant); } else if (attribute.equals("ZPos")) { posZ[image] = new Double(variant); } else if (objectClass.equals("CSpectrophotometerUnit")) { Integer v = null; try { v = new Integer((int) Double.parseDouble(variant)); } catch (NumberFormatException e) { } String description = filterSetting.getAttribute("Description"); if (description.endsWith("(left)")) { filterModels[image].add(object); if (v != null && v > 0) { cutIns[image].add(new PositiveInteger(v)); } else { LOGGER.warn("Expected positive value for CutIn; got {}", v); } } else if (description.endsWith("(right)")) { if (v != null && v > 0) { cutOuts[image].add(new PositiveInteger(v)); } else { LOGGER.warn("Expected positive value for CutOut; got {}", v); } } } } } private void translateScannerSettings(Element imageNode, int image) throws FormatException { NodeList scannerSettings = getNodes(imageNode, "ScannerSettingRecord"); if (scannerSettings == null) return; expTimes[image] = new Double[getEffectiveSizeC()]; gains[image] = new Double[getEffectiveSizeC()]; detectorOffsets[image] = new Double[getEffectiveSizeC()]; channelNames[image] = new String[getEffectiveSizeC()]; exWaves[image] = new Integer[getEffectiveSizeC()]; detectorModels[image] = new Vector<String>(); for (int i=0; i<scannerSettings.getLength(); i++) { Element scannerSetting = (Element) scannerSettings.item(i); String id = scannerSetting.getAttribute("Identifier"); if (id == null) id = ""; String suffix = scannerSetting.getAttribute("Identifier"); String value = scannerSetting.getAttribute("Variant"); if (id.equals("SystemType")) { microscopeModels[image] = value; } else if (id.equals("dblPinhole")) { pinholes[image] = Double.parseDouble(value) * 1000000; } else if (id.equals("dblZoom")) { zooms[image] = new Double(value); } else if (id.equals("dblStepSize")) { zSteps[image] = Double.parseDouble(value) * 1000000; } else if (id.equals("nDelayTime_s")) { tSteps[image] = new Double(value); } else if (id.equals("CameraName")) { detectorModels[image].add(value); } else if (id.equals("eDirectional")) { addSeriesMeta("Reverse X orientation", value.equals("1")); } else if (id.equals("eDirectionalY")) { addSeriesMeta("Reverse Y orientation", value.equals("1")); } else if (id.indexOf("WFC") == 1) { int c = 0; try { c = Integer.parseInt(id.replaceAll("\\D", "")); } catch (NumberFormatException e) { } if (c < 0 || c >= getEffectiveSizeC()) { continue; } if (id.endsWith("ExposureTime")) { expTimes[image][c] = new Double(value); } else if (id.endsWith("Gain")) { gains[image][c] = new Double(value); } else if (id.endsWith("WaveLength")) { Integer exWave = new Integer(value); if (exWave > 0) { exWaves[image][c] = exWave; } } // NB: "UesrDefName" is not a typo. else if (id.endsWith("UesrDefName") && !value.equals("None")) { channelNames[image][c] = value; } } } } private void translateAttachmentNodes(Element imageNode, int image) throws FormatException { NodeList attachmentNodes = getNodes(imageNode, "Attachment"); if (attachmentNodes == null) return; for (int i=0; i<attachmentNodes.getLength(); i++) { Element attachment = (Element) attachmentNodes.item(i); if ("ContextDescription".equals(attachment.getAttribute("Name"))) { descriptions[image] = attachment.getAttribute("Content"); } } } private void translateImageNodes(Element imageNode, int i) throws FormatException { core[i] = new CoreMetadata(); core[i].orderCertain = true; core[i].metadataComplete = true; core[i].littleEndian = true; core[i].falseColor = true; NodeList channels = getChannelDescriptionNodes(imageNode); NodeList dimensions = getDimensionDescriptionNodes(imageNode); HashMap<Long, String> bytesPerAxis = new HashMap<Long, String>(); Double physicalSizeX = null; Double physicalSizeY = null; core[i].sizeC = channels.getLength(); for (int ch=0; ch<channels.getLength(); ch++) { Element channel = (Element) channels.item(ch); lutNames.add(channel.getAttribute("LUTName")); String bytesInc = channel.getAttribute("BytesInc"); long bytes = bytesInc == null ? 0 : Long.parseLong(bytesInc); if (bytes > 0) { bytesPerAxis.put(bytes, "C"); } } int extras = 1; for (int dim=0; dim<dimensions.getLength(); dim++) { Element dimension = (Element) dimensions.item(dim); int id = Integer.parseInt(dimension.getAttribute("DimID")); int len = Integer.parseInt(dimension.getAttribute("NumberOfElements")); long nBytes = Long.parseLong(dimension.getAttribute("BytesInc")); Double physicalLen = new Double(dimension.getAttribute("Length")); String unit = dimension.getAttribute("Unit"); physicalLen /= len; if (unit.equals("Ks")) { physicalLen /= 1000; } else if (unit.equals("m")) { physicalLen *= 1000000; } switch (id) { case 1: // X axis core[i].sizeX = len; core[i].rgb = (nBytes % 3) == 0; if (core[i].rgb) nBytes /= 3; core[i].pixelType = FormatTools.pixelTypeFromBytes((int) nBytes, false, true); physicalSizeX = physicalLen; break; case 2: // Y axis if (core[i].sizeY != 0) { if (core[i].sizeZ == 1) { core[i].sizeZ = len; bytesPerAxis.put(nBytes, "Z"); } else if (core[i].sizeT == 1) { core[i].sizeT = len; bytesPerAxis.put(nBytes, "T"); } } else { core[i].sizeY = len; physicalSizeY = physicalLen; } break; case 3: // Z axis if (core[i].sizeY == 0) { // XZ scan - swap Y and Z core[i].sizeY = len; core[i].sizeZ = 1; bytesPerAxis.put(nBytes, "Y"); physicalSizeY = physicalLen; } else { core[i].sizeZ = len; bytesPerAxis.put(nBytes, "Z"); } break; case 4: // T axis if (core[i].sizeY == 0) { // XT scan - swap Y and T core[i].sizeY = len; core[i].sizeT = 1; bytesPerAxis.put(nBytes, "Y"); physicalSizeY = physicalLen; } else { core[i].sizeT = len; bytesPerAxis.put(nBytes, "T"); } break; default: extras *= len; } } physicalSizeXs.add(physicalSizeX); physicalSizeYs.add(physicalSizeY); if (extras > 1) { if (core[i].sizeZ == 1) core[i].sizeZ = extras; else { if (core[i].sizeT == 0) core[i].sizeT = extras; else core[i].sizeT *= extras; } } if (core[i].sizeC == 0) core[i].sizeC = 1; if (core[i].sizeZ == 0) core[i].sizeZ = 1; if (core[i].sizeT == 0) core[i].sizeT = 1; core[i].interleaved = core[i].rgb; core[i].indexed = !core[i].rgb; core[i].imageCount = core[i].sizeZ * core[i].sizeT; if (!core[i].rgb) core[i].imageCount *= core[i].sizeC; Long[] bytes = bytesPerAxis.keySet().toArray(new Long[0]); Arrays.sort(bytes); core[i].dimensionOrder = "XY"; for (Long nBytes : bytes) { String axis = bytesPerAxis.get(nBytes); if (core[i].dimensionOrder.indexOf(axis) == -1) { core[i].dimensionOrder += axis; } } if (core[i].dimensionOrder.indexOf("Z") == -1) { core[i].dimensionOrder += "Z"; } if (core[i].dimensionOrder.indexOf("C") == -1) { core[i].dimensionOrder += "C"; } if (core[i].dimensionOrder.indexOf("T") == -1) { core[i].dimensionOrder += "T"; } } private NodeList getNodes(Element root, String nodeName) { NodeList nodes = root.getElementsByTagName(nodeName); if (nodes.getLength() == 0) { NodeList children = root.getChildNodes(); for (int i=0; i<children.getLength(); i++) { Object child = children.item(i); if (child instanceof Element) { NodeList childNodes = getNodes((Element) child, nodeName); if (childNodes != null) { return childNodes; } } } return null; } else return nodes; } private Element getImageDescription(Element root) { return (Element) root.getElementsByTagName("ImageDescription").item(0); } private NodeList getChannelDescriptionNodes(Element root) { Element imageDescription = getImageDescription(root); Element channels = (Element) imageDescription.getElementsByTagName("Channels").item(0); return channels.getElementsByTagName("ChannelDescription"); } private NodeList getDimensionDescriptionNodes(Element root) { Element imageDescription = getImageDescription(root); Element channels = (Element) imageDescription.getElementsByTagName("Dimensions").item(0); return channels.getElementsByTagName("DimensionDescription"); } private int getChannelIndex(Element filterSetting) { String data = filterSetting.getAttribute("data"); if (data == null || data.equals("")) { data = filterSetting.getAttribute("Data"); } int channel = data == null || data.equals("") ? 0 : Integer.parseInt(data); if (channel < 0) return -1; return channel - 1; } // -- Helper class -- class ROI { // -- Constants -- public static final int TEXT = 512; public static final int SCALE_BAR = 8192; public static final int POLYGON = 32; public static final int RECTANGLE = 16; public static final int LINE = 256; public static final int ARROW = 2; // -- Fields -- public int type; public Vector<Double> x = new Vector<Double>(); public Vector<Double> y = new Vector<Double>(); // center point of the ROI public double transX, transY; // transformation parameters public double scaleX, scaleY; public double rotation; public long color; public int linewidth; public String text; public String fontName; public String fontSize; public String name; private boolean normalized = false; // -- ROI API methods -- public void storeROI(MetadataStore store, int series, int roi) { MetadataLevel level = getMetadataOptions().getMetadataLevel(); if (level == MetadataLevel.NO_OVERLAYS || level == MetadataLevel.MINIMUM) { return; } // keep in mind that vertices are given relative to the center // point of the ROI and the transX/transY values are relative to // the center point of the image String roiID = MetadataTools.createLSID("ROI", roi); store.setImageROIRef(roiID, series, roi); store.setROIID(roiID, roi); store.setTextID(MetadataTools.createLSID("Shape", roi, 0), roi, 0); if (text == null) { text = name; } store.setTextValue(text, roi, 0); if (fontSize != null) { try { int size = (int) Double.parseDouble(fontSize); if (size > 0) { store.setTextFontSize(new NonNegativeInteger(size), roi, 0); } else { LOGGER.warn("Expected non-negative value for FontSize; got {}", size); } } catch (NumberFormatException e) { } } store.setTextStrokeWidth(new Double(linewidth), roi, 0); if (!normalized) normalize(); double cornerX = x.get(0).doubleValue(); double cornerY = y.get(0).doubleValue(); store.setTextX(cornerX, roi, 0); store.setTextY(cornerY, roi, 0); int centerX = (core[series].sizeX / 2) - 1; int centerY = (core[series].sizeY / 2) - 1; double roiX = centerX + transX; double roiY = centerY + transY; if (alternateCenter) { roiX = transX - 2 * cornerX; roiY = transY - 2 * cornerY; } // TODO : rotation/scaling not populated String shapeID = MetadataTools.createLSID("Shape", roi, 1); switch (type) { case POLYGON: StringBuffer points = new StringBuffer(); for (int i=0; i<x.size(); i++) { points.append(x.get(i).doubleValue() + roiX); points.append(","); points.append(y.get(i).doubleValue() + roiY); if (i < x.size() - 1) points.append(" "); } store.setPolylineID(shapeID, roi, 1); store.setPolylinePoints(points.toString(), roi, 1); store.setPolylineClosed(Boolean.TRUE, roi, 1); break; case TEXT: case RECTANGLE: store.setRectangleID(shapeID, roi, 1); store.setRectangleX(roiX - Math.abs(cornerX), roi, 1); store.setRectangleY(roiY - Math.abs(cornerY), roi, 1); double width = 2 * Math.abs(cornerX); double height = 2 * Math.abs(cornerY); store.setRectangleWidth(width, roi, 1); store.setRectangleHeight(height, roi, 1); break; case SCALE_BAR: case ARROW: case LINE: store.setLineID(shapeID, roi, 1); store.setLineX1(roiX + x.get(0), roi, 1); store.setLineY1(roiY + y.get(0), roi, 1); store.setLineX2(roiX + x.get(1), roi, 1); store.setLineY2(roiY + y.get(1), roi, 1); break; } } // -- Helper methods -- /** * Vertices and transformation values are not stored in pixel coordinates. * We need to convert them from physical coordinates to pixel coordinates * so that they can be stored in a MetadataStore. */ private void normalize() { if (normalized) return; // coordinates are in meters transX *= 1000000; transY *= 1000000; transX *= 1; transY *= 1; for (int i=0; i<x.size(); i++) { double coordinate = x.get(i).doubleValue() * 1000000; coordinate *= 1; x.setElementAt(coordinate, i); } for (int i=0; i<y.size(); i++) { double coordinate = y.get(i).doubleValue() * 1000000; coordinate *= 1; y.setElementAt(coordinate, i); } normalized = true; } } private double parseDouble(String number) { if (number != null) { number = number.replaceAll(",", "."); try { return Double.parseDouble(number); } catch (NumberFormatException e) { } } return 0; } private int getChannelColor(int colorCode) { switch (colorCode) { case 0: return 0xff0000; case 1: return 0xff00; case 2: return 0xff; case 3: return 0xffff; case 4: return 0xff00ff; case 5: return 0xffff00; } return 0xffffff; } }
package com.blstream.studybox.model.database; import com.activeandroid.Model; import com.activeandroid.annotation.Column; import com.activeandroid.annotation.Table; import com.activeandroid.query.Select; import com.google.gson.annotations.Expose; import java.text.Collator; import java.util.List; import java.util.Locale; @Table(name = "Decks") public class Deck extends Model implements Comparable<Deck> { @Expose @Column(name = "deckId", unique = true, onUniqueConflict = Column.ConflictAction.REPLACE) private String id; @Expose @Column(name = "name") private String name; @Expose @Column(name = "isPublic") private Boolean isPublic; @Expose @Column(name = "creatorEmail") private String creatorEmail; @Expose @Column(name = "flashcardsCount") private int flashcardsCount; private static final Collator collator = Collator.getInstance(Locale.getDefault()); public Deck() { super(); } public Deck(String id, String name, Boolean isPublic) { this.id = id; this.name = name; this.isPublic = isPublic; } public static List<Deck> getAll() { return new Select() .from(Deck.class) .execute(); } public String getDeckId() { return id; } public void setDeckId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Boolean getIsPublic() { return isPublic; } public void setIsPublic(Boolean isPublic) { this.isPublic = isPublic; } public String getCreatorEmail() { return creatorEmail; } public void setCreatorEmail(String creatorEmail) { this.creatorEmail = creatorEmail; } public int getFlashcardsCount() { return flashcardsCount; } public void setFlashcardsCount(int flashcardsCount) { this.flashcardsCount = flashcardsCount; } @Override public int compareTo(Deck another) { return collator.compare(name, another.getName()); } }
package com.example.lit.activity; import android.app.Activity; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.MenuItem; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.ImageView; import com.example.lit.Utilities.MultiSelectionSpinner; import com.example.lit.R; import com.example.lit.habit.Habit; import com.example.lit.habit.NormalHabit; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; public class AddHabitActivity extends AppCompatActivity { private static final String CLASS_KEY = "com.example.lit.activity.AddHabitActivity"; private EditText habitName; private EditText habitComment; //private EditText habitFrequency; private ImageView habitImage; private Button editImage; private Button saveHabit; private Button cancelHabit; private CheckBox locationCheck; //This should not be a button, its currently a placeholder private MultiSelectionSpinner weekday_spinner; //TODO: Implement location feature private Date habitStartDate; private String habitNameString; private String commentString; private List<String> weekdays; private EditText hour_view; private EditText minute_view; private int hour; private int minute; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_habit); setTitle("Adding A New Habit"); // Activity components habitName = (EditText) findViewById(R.id.Habit_EditText); habitComment = (EditText) findViewById(R.id.Comment_EditText); habitComment.setLines(3); //Maximum lines our comment should be able to show at once. saveHabit = (Button) findViewById(R.id.SaveHabit); cancelHabit = (Button) findViewById(R.id.discard_button); hour_view = (EditText) findViewById(R.id.hour); minute_view = (EditText)findViewById(R.id.minute); weekday_spinner = (MultiSelectionSpinner) findViewById(R.id.weekday_spinner); locationCheck = (CheckBox) findViewById(R.id.locationCheckBox); // Set up weekday selection weekday_spinner.setItems(createWeekdayList()); saveHabit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Log.i("AddHabitActivity", "Save Button pressed."); returnNewHabit(view); } }); cancelHabit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Log.i("AddHabitActivity", "Cancel button pressed. Habit creation cancelled."); setResult(Activity.RESULT_CANCELED); finish(); } }); } public void returnNewHabit(View saveNewHabitButton){ habitNameString = habitName.getText().toString(); commentString = habitComment.getText().toString(); habitStartDate = Calendar.getInstance().getTime(); hour = Integer.parseInt(hour_view.getText().toString()); minute = Integer.parseInt(minute_view.getText().toString()); weekdays = weekday_spinner.getSelectedStrings(); //TODO: missing location parameter. Currently null pointer. //TODO: What if the habit throws an exception. Intent newHabitIntent = new Intent(); Habit newHabit = new NormalHabit(habitNameString, habitStartDate, null, commentString); newHabitIntent.putExtra(CLASS_KEY, newHabit); //Habit needs serializable. setResult(Activity.RESULT_OK, newHabitIntent); finish(); } @Override public boolean onOptionsItemSelected(MenuItem selection){ switch (selection.getItemId()){ case android.R.id.home: //Up button pressed Log.i("AddHabitActivity", "Up button pressed. Habit creation cancelled."); setResult(Activity.RESULT_CANCELED); finish(); } return true; } private ArrayList<String> createWeekdayList(){ ArrayList<String> weekdayList = new ArrayList<String>(); weekdayList.add("None"); weekdayList.add("Monday"); weekdayList.add("Tuesday"); weekdayList.add("Wednesday"); weekdayList.add("Thursday"); weekdayList.add("Friday"); weekdayList.add("Saturday"); weekdayList.add("Sunday"); return weekdayList; } /** * Returns an array list of numbers in a string format. This list is from low to high * inclusively. Each number is seperated by each other as defined by the interval. * Should low > high then the list returned is empty. * * @param low The beginning of the range of numbers to be added to the list. * @param high The end of the range of numbers to be added to the list. * @param interval The interval in between numbers. * @return A list of numbers in ascending order. */ private ArrayList<String> createNumberList(int low, int high, int interval){ ArrayList<String> numberList = new ArrayList<>(); for(int i = low; i <= high; i += interval){ numberList.add(String.valueOf(i)); } return numberList; } }
package com.liangmayong.superandroid; import android.os.Bundle; import android.os.Handler; import android.view.View; import com.liangmayong.base.BaseActivity; import com.liangmayong.base.bind.annotations.ColorId; import com.liangmayong.base.bind.annotations.Layout; import com.liangmayong.base.bind.annotations.Title; import com.liangmayong.base.widget.iconfont.Icon; import com.liangmayong.base.widget.pullrefresh.PullRefreshLayout; import com.liangmayong.base.widget.pullrefresh.drawables.PictureDrawable; import com.liangmayong.loading.Loading; import com.liangmayong.preferences.annotations.PreferenceValue; @Layout(R.layout.activity_main) @Title("AndroidBase") public class MainActivity extends BaseActivity { @PreferenceValue("key") String app_name; @ColorId int colorPrimary; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setThemeColor(colorPrimary); // getDefualtToolbar().setTitle(app_name); getDefualtToolbar().leftOne().iconToLeft(Icon.icon_back).clicked(new View.OnClickListener() { @Override public void onClick(View v) { finish(); } }); getDefualtToolbar().leftTwo().iconToRight(Icon.icon_filter); getDefualtToolbar().leftThree().iconToRight(Icon.icon_message); getDefualtToolbar().rightOne().iconToRight(Icon.icon_menu); getDefualtToolbar().rightTwo().iconToRight(Icon.icon_edit); getDefualtToolbar().rightThree().iconToRight(Icon.icon_location); final PullRefreshLayout pullRefreshLayout = (PullRefreshLayout) findViewById(R.id.pull); PictureDrawable pictureDrawable = new PictureDrawable(pullRefreshLayout, R.mipmap.loading_bee, R.mipmap.loading_bee1, R.mipmap.loading_bee2, R.mipmap.loading_bee3, R.mipmap.loading_bee4, R.mipmap.loading_bee5, R.mipmap.loading_bee6); pullRefreshLayout.setRefreshDrawable(pictureDrawable); pullRefreshLayout.setOnRefreshListener(new PullRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { Loading.showLoading(MainActivity.this, ""); new Handler().postDelayed(new Runnable() { @Override public void run() { pullRefreshLayout.setRefreshing(false); Loading.cancelLoading(MainActivity.this); } }, 5000); } }); } }
package com.pr0gramm.app.services; import android.annotation.SuppressLint; import android.content.Context; import android.os.Build; import com.google.common.base.Charsets; import com.google.common.collect.Ordering; import com.google.common.io.CharStreams; import com.pr0gramm.app.BuildConfig; import com.pr0gramm.app.Settings; import com.pr0gramm.app.feed.Nothing; import com.pr0gramm.app.util.AndroidUtility; import com.pr0gramm.app.util.BackgroundScheduler; import java.io.IOException; import java.io.InputStreamReader; import java.io.Writer; import java.lang.reflect.Modifier; import java.util.Map; import java.util.Set; import javax.inject.Inject; import javax.inject.Singleton; import okhttp3.OkHttpClient; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; import retrofit2.http.Field; import retrofit2.http.FormUrlEncoded; import retrofit2.http.POST; import rx.Observable; import static java.util.Arrays.asList; /** * A simple service to generate and send a feedback to the feedback server. */ @Singleton public class FeedbackService { private final Api api; private final Context context; @Inject public FeedbackService(OkHttpClient okHttpClient, Context context) { this.context = context; this.api = new Retrofit.Builder() .client(okHttpClient) .baseUrl("https://pr0.wibbly-wobbly.de/api/feedback/v1/") .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build().create(Api.class); } public Observable<Nothing> post(String name, String feedback) { String version = String.valueOf(AndroidUtility.getPackageVersionCode(context)); return Observable.fromCallable(this::payload) .flatMap(logcat -> api.post(name, feedback, version, logcat)) .subscribeOn(BackgroundScheduler.instance()); } private String payload() { try { StringBuilder result = new StringBuilder(); appendDeviceInfo(result); result.append("\n\n"); appendMemoryInfo(result); result.append("\n\n"); appendPreferences(result); result.append("\n\n"); appendLogcat(result); // convert result to a string return result.toString(); } catch (Exception err) { return "Could not generate logcat: " + err; } } private void appendPreferences(StringBuilder result) { //noinspection unchecked Iterable<Map.Entry<String, Object>> entries = Ordering.natural() .<Map.Entry<String, Object>>onResultOf(Map.Entry::getKey) .sortedCopy((Set) Settings.of(context).raw().getAll().entrySet()); for (Map.Entry<String, Object> entry : entries) { if (entry.getKey().startsWith("pref_")) { result.append(entry.getKey()).append(": ").append(entry.getValue()).append("\n"); } } } @SuppressLint("NewApi") private static void appendLogcat(StringBuilder result) throws IOException { Process process = Runtime.getRuntime().exec("logcat -d -v threadtime"); try (Writer writer = CharStreams.asWriter(result)) { InputStreamReader reader = new InputStreamReader(process.getInputStream(), Charsets.UTF_8); CharStreams.copy(reader, writer); } finally { try { process.destroy(); } catch (Exception ignored) { } } } private static void appendDeviceInfo(StringBuilder result) { result.append("Android: ").append(Build.VERSION.RELEASE).append('\n'); result.append("Flavor: ").append(BuildConfig.FLAVOR) .append("(").append(BuildConfig.APPLICATION_ID).append(")\n"); for (java.lang.reflect.Field field : Build.class.getFields()) { if (Modifier.isStatic(field.getModifiers())) { try { String name = field.getName().toLowerCase().replace('_', ' '); Object value = formatValue(field.get(null)); result.append(name).append(" = ").append(value).append("\n"); } catch (Exception ignored) { } } } } private static String formatValue(Object value) { if (value instanceof String[]) { return asList((String[]) value).toString(); } else { return String.valueOf(value); } } private static void appendMemoryInfo(StringBuilder result) { Runtime rt = Runtime.getRuntime(); result.append("Memory used: ").append(rt.totalMemory() / 1024 / 1024).append("mb\n"); result.append("MaxMemory for this app: ").append(rt.maxMemory() / 1024 / 1024).append("mb\n"); } private interface Api { @FormUrlEncoded @POST("post") Observable<Nothing> post(@Field("name") String name, @Field("feedback") String feedback, @Field("version") String version, @Field("logcat") String logcat); } }
package com.uti.sensors.bleshow; import android.content.Context; import android.support.annotation.NonNull; import android.support.annotation.StringDef; import android.util.Log; import android.view.View; import android.widget.TableLayout; import android.widget.TableRow; import com.polidea.rxandroidble.RxBleConnection; import com.uti.Utils.GenericTabRow; import java.util.UUID; import rx.Observable; import static java.lang.StrictMath.pow; public class TempertureProfile extends GenericProfile { private final boolean DBG = false; private final String TAG = "TempertureProfile"; private final static String GattServ = "F000AA00-0451-4000-B000-0000000000000"; private final static String GattData = "F000AA01-0451-4000-B000-0000000000000"; private final static String GattConf = "F000AA02-0451-4000-B000-0000000000000"; private final static String GattPeri = "F000AA03-0451-4000-B000-0000000000000"; private final static byte[] Bconf = new byte[] {(byte)0x01 }; private double ambient; private double target; protected GenericTabRow tr; protected GenericTabRow am; protected Context context; public TempertureProfile(@NonNull Observable<RxBleConnection> conn) { super(conn, UUID.fromString(GattServ), UUID.fromString(GattConf), UUID.fromString(GattData), UUID.fromString(GattPeri), Bconf); } @Override public boolean registerNotification(Context con, View parenet, TableLayout tabLayout) { am = new GenericTabRow(con); am.sl1.autoScale = true; am.sl1.autoScale = true; am.sl1.autoScaleBounceBack = true; am.setIcon("sensortag2", "temperature"); am.title.setText("Ambient Temperature Data"); am.uuidLabel.setText(GattData); am.value.setText("0.0'C"); am.periodMinVal = 200; am.periodBar.setMax(255 - (am.periodMinVal/10)); am.periodBar.setProgress(100); am.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT)); tr = new GenericTabRow(con); tr.sl1.autoScale = true; tr.sl1.autoScaleBounceBack = true; tr.setIcon("sensortag2", "irtemperature"); tr.title.setText("IR Temperature Data"); tr.uuidLabel.setText(GattData); tr.value.setText("0.0'C"); tr.periodMinVal = 200; tr.periodBar.setMax(255 - (tr.periodMinVal/10)); tr.periodBar.setProgress(100); tr.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT)); tabLayout.addView(am, new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT)); tabLayout.addView(tr, new TableLayout.LayoutParams(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT)); super.registerNotificationImp(bytes -> { convertRaw(bytes); if (DBG) Log.d(TAG, "Ambient value:" + ambient + ", Target:" + target); am.value.setText(String.format("%.1fC", ambient)); tr.value.setText(String.format("%.1fC", target)); }); return true; } @Override public boolean configuration() { super.configurationImp(bytes -> { if (DBG) Log.d(TAG, "configuration complete"); }); return true; } @Override protected void convertRaw(byte[] bytes) { final double SCALE_LSB = (0.03125f); // TI -- TMP007 sensor algorithm target = (int16AtOffset(bytes, 0)>>2)*SCALE_LSB; ambient = (int16AtOffset(bytes, 2)>>2)*SCALE_LSB; } }
package com.william.mangoreader; import android.app.Activity; import android.database.sqlite.SQLiteConstraintException; import android.support.design.widget.Snackbar; import android.text.TextUtils; import android.util.Log; import android.view.View; import com.william.mangoreader.activity.MangoReaderActivity; import com.william.mangoreader.daogen.UserLibraryManga; import com.william.mangoreader.daogen.UserLibraryMangaDao; import com.william.mangoreader.model.MangaEdenMangaListItem; import java.util.List; import de.greenrobot.dao.query.QueryBuilder; public class UserLibraryHelper { private static String added; private static String removed; public static List findMangaInLibrary(final MangaEdenMangaListItem m) { QueryBuilder qb = MangoReaderActivity.userLibraryMangaDao.queryBuilder(); qb.where(UserLibraryMangaDao.Properties.MangaEdenId.eq(m.id)); return qb.list(); } /** * Creates dialog for user to select library category to add to. * * @param m */ public static boolean addToLibrary(final MangaEdenMangaListItem m, final View button, final Activity activity) { String genres = TextUtils.join("\t", m.genres); added = "\"" + m.title + "\" added to your library under \"Plan to Read\""; removed = "\"" + m.title + "\" removed from your library."; final UserLibraryManga mangaItem = new UserLibraryManga( m.id, activity.getResources().getStringArray(R.array.library_categories)[0], m.title, m.imageUrl, genres, m.status, m.lastChapterDate, m.hits); try { // insert and show snackbar with undo, return true if successful, false otherwise MangoReaderActivity.userLibraryMangaDao.insert(mangaItem); Snackbar .make(activity.findViewById(R.id.parent_layout), added, Snackbar.LENGTH_LONG) .setAction("UNDO", new View.OnClickListener() { @Override public void onClick(View v) { removeFromLibrary(m, button, activity, false); button.setSelected(false); } }) .show(); button.setSelected(true); return true; } catch (SQLiteConstraintException e) { String duplicate = "\"" + m.title + "\" is already in your library."; Snackbar .make(activity.findViewById(R.id.parent_layout), duplicate, Snackbar.LENGTH_SHORT) .show(); Log.d("LIBRARY", "Entry already exists"); return false; } } /** * @param m * @param button * @param activity * @param showUndo */ public static void removeFromLibrary(final MangaEdenMangaListItem m, final View button, final Activity activity, boolean showUndo) { final List l = findMangaInLibrary(m); added = "\"" + m.title + "\" added to your library under \"Plan to Read\""; removed = "\"" + m.title + "\" removed from your library."; // don't do anything if not found in library if (l.size() == 0) { Log.e("MangoReader", "No manga found in user library."); return; } UserLibraryManga mangaItem = (UserLibraryManga) l.get(0); MangoReaderActivity.userLibraryMangaDao.delete(mangaItem); removed = "\"" + m.title + "\" removed from your library."; // show undo option only if not called from add undo if (showUndo) { button.setSelected(false); Snackbar .make(activity.findViewById(R.id.parent_layout), removed, Snackbar.LENGTH_LONG) .setAction("UNDO", new View.OnClickListener() { @Override public void onClick(View v) { MangoReaderActivity.userLibraryMangaDao.insert((UserLibraryManga) l.get(0)); Snackbar.make(activity.findViewById(R.id.parent_layout), removed, Snackbar.LENGTH_LONG); button.setSelected(true); } }) .show(); } else { button.setSelected(false); Snackbar .make(activity.findViewById(R.id.parent_layout), removed, Snackbar.LENGTH_LONG) .show(); } } }
package com.xuncl.selfimproveproject; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Locale; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.content.DialogInterface; import android.content.Intent; import android.database.sqlite.SQLiteDatabase; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.Window; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ImageView; import android.widget.ListView; import android.widget.PopupMenu; import android.widget.ProgressBar; import android.widget.TextView; import android.widget.Toast; import com.umeng.analytics.MobclickAgent; import com.xuncl.selfimproveproject.activities.ActivityCollector; import com.xuncl.selfimproveproject.activities.BaseActivity; import com.xuncl.selfimproveproject.activities.TargetActivity; import com.xuncl.selfimproveproject.activities.TargetAdapter; import com.xuncl.selfimproveproject.database.DataDeleter; import com.xuncl.selfimproveproject.database.DataFetcher; import com.xuncl.selfimproveproject.database.DataUpdater; import com.xuncl.selfimproveproject.database.MyDatabaseHelper; import com.xuncl.selfimproveproject.service.Agenda; import com.xuncl.selfimproveproject.service.Backlog; import com.xuncl.selfimproveproject.service.Scheme; import com.xuncl.selfimproveproject.service.Target; import com.xuncl.selfimproveproject.utils.FileUtils; import com.xuncl.selfimproveproject.utils.HttpUtils; import com.xuncl.selfimproveproject.utils.LogUtils; import com.xuncl.selfimproveproject.utils.Tools; public class MainActivity extends BaseActivity implements OnClickListener { private PopupMenu popupMenu; private Scheme scheme = new Scheme(); private static Date today = new Date(); private MyDatabaseHelper dbHelper; private String path = Environment.getExternalStorageDirectory().getPath()+"/scheme"; // ProgressBar int progressStatus = 0; TextView titleText; ProgressBar bar; /** * today */ static { initToday(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.activity_main); initTitle(); initTargets(); MobclickAgent.UMAnalyticsConfig config = new MobclickAgent.UMAnalyticsConfig(this, Constant.UMENG_APPKEY, Constant.UMENG_CHANNELID); MobclickAgent.startWithConfigure(config); } /** * today2359 */ private static void initToday() { SimpleDateFormat sdf = new SimpleDateFormat(Constant.DATE_FORMAT_PATTERN, Locale.CHINA); SimpleDateFormat sdf2 = new SimpleDateFormat(Constant.DATE_FORMAT_PATTERN +" HH:mm", Locale.CHINA); String timeStr = sdf.format(today); timeStr = timeStr + " 23:59"; try { today = sdf2.parse(timeStr); } catch (ParseException e) { e.printStackTrace(); } } private void initTitle() { ImageView titleBack = (ImageView) findViewById(R.id.title_back); titleBack.setOnClickListener(this); ImageView titleMore = (ImageView) findViewById(R.id.title_more); titleMore.setOnClickListener(this); ImageView titleRefresh = (ImageView) findViewById(R.id.title_refresh); titleRefresh.setOnClickListener(this); titleText = (TextView) findViewById(R.id.title_text); titleText.setOnClickListener(this); initPopupMenu(titleMore); initBar(); } private void initPopupMenu(ImageView titleMore) { popupMenu = new PopupMenu(this, titleMore); Menu menu = popupMenu.getMenu(); // XML MenuInflater menuInflater = getMenuInflater(); menuInflater.inflate(R.menu.popup_menu, menu); popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { @Override public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.upload_btn: Toast.makeText(MainActivity.this, "upload", Toast.LENGTH_LONG).show(); startUpdate(); break; case R.id.download_btn: Toast.makeText(MainActivity.this, "download", Toast.LENGTH_LONG).show(); // startDownload(); break; case R.id.add_target: onAddTarget(); break; default: break; } return false; } }); } private void initBar(){ bar = (ProgressBar) findViewById(R.id.bar); } private void initTargets() { dbHelper = new MyDatabaseHelper(this, Constant.DB_NAME, null, 2); refreshTargets(); } private void refreshTargets() { Date today = scheme.getDate(); setHomeSchemeByDate(today); } /** * * @param today */ private void setHomeSchemeByDate(Date today) { SQLiteDatabase db = dbHelper.getWritableDatabase(); scheme = DataFetcher.fetchScheme(db, today); titleText.setText(scheme.toShortString()); initList(); db.close(); } private void initList() { TargetAdapter adapter = new TargetAdapter(MainActivity.this, R.layout.target_item, scheme.getTargets()); ListView listView = (ListView) findViewById(R.id.target_list_view); listView.setAdapter(adapter); listView.setOnItemClickListener(new OnItemClickListener() { @SuppressWarnings("deprecation") @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // Because of existence of image button, event will not focus on // parents. Target target = scheme.getTargets().get(position); // deleteDialog(target); MainActivity.this.showDialog(scheme.getTargets().indexOf(target)); } }); } private void saveTodayTargets() { SQLiteDatabase db = dbHelper.getWritableDatabase(); DataUpdater.updateScheme(db, scheme); db.close(); } private void saveScheme(Scheme s){ SQLiteDatabase db = dbHelper.getWritableDatabase(); DataUpdater.updateScheme(db, s); db.close(); } /** * * @param target */ private void addNewTarget(Target target) { SQLiteDatabase db = dbHelper.getWritableDatabase(); scheme.getTargets().add(target); DataUpdater.insertTarget(db, scheme, target); db.close(); } @Override public void onPause() { saveAll(); super.onPause(); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.title_back: // will saveFile data at life cycle ActivityCollector.finishAll(); break; case R.id.title_refresh: saveAll(); fetchAll(); break; case R.id.title_more: popupMenu.show(); break; case R.id.title_text: showSchemeDetail(); break; default: break; } } /** * scheme */ private void startUpdate(){ // TODO // Handler final Handler handler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == 0x111) { bar.setProgress(progressStatus); } } }; new Thread() { public void run() { String fromDate = FileUtils.read(MainActivity.this,Constant.UPLOAD_FILE_NAME); LogUtils.e("UPDATE","form date is "+fromDate); Date veryFirstDay = Tools.parseTimeByDate(fromDate,Constant.DEFAULT_TIME); Date thisDay = Tools.parseTimeByDate(today,Constant.DEFAULT_TIME_AFTER); int intervalDays = Tools.daysBetween(veryFirstDay, thisDay); SQLiteDatabase db = dbHelper.getWritableDatabase(); SimpleDateFormat sdf = new SimpleDateFormat(Constant.DATE_FORMAT_PATTERN,Locale.CHINA); while (thisDay.after(veryFirstDay)) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } int interval = Tools.daysBetween(veryFirstDay, thisDay); if (interval<0) break; if (interval==0){ progressStatus = 100; }else{ progressStatus = 100*(intervalDays-interval)/intervalDays; } Scheme thisScheme = DataFetcher.fetchScheme(db,thisDay); boolean isEmpty = false; if (thisScheme!=null){ if (thisScheme.getTargets().size()<1){ // LogUtils.e("update", ""+sdf.format(thisDay)+"'s target's is EMPTY!"); isEmpty = true; } }else{ LogUtils.e("update", ""+sdf.format(thisDay)+"'s target's is NULL!"); } HttpUtils.postSchemeJson(thisScheme); final String showing = ""+interval+"/"+intervalDays+" "+sdf.format(thisDay) +(isEmpty?" EMPTY":" updating"); runOnUiThread(new Runnable() { @Override public void run() { titleText.setText(showing); } }); thisDay=Tools.prevDay(thisDay); Message m = new Message(); m.what = 0x111; // Handler handler.sendMessage(m); } FileUtils.write(MainActivity.this, sdf.format(today), Constant.UPLOAD_FILE_NAME); db.close(); // bar.setProgress(0);// progressStatus = 0; Message m = new Message(); m.what = 0x111; // Handler handler.sendMessage(m); runOnUiThread(new Runnable() { @Override public void run() { titleText.setText(scheme.toShortString()); Toast.makeText(MainActivity.this,"Upload success.",Toast.LENGTH_SHORT).show(); } }); } }.start(); } private void startDownload() { // TODO // Handler final Handler handler = new Handler() { @Override public void handleMessage(Message msg) { if (msg.what == 0x111) { bar.setProgress(progressStatus); } } }; new Thread() { public void run() { String fromDate = FileUtils.read(MainActivity.this,Constant.DOWNLOAD_FILE_NAME); SQLiteDatabase db = dbHelper.getWritableDatabase(); for (int i=1; i<5496;i++){ try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } progressStatus = 100*(i)/5495; HttpUtils.getTargetJson(db, i); final String showing = "download "+i+"/5495"; runOnUiThread(new Runnable() { @Override public void run() { titleText.setText(showing); } }); Message m = new Message(); m.what = 0x111; // Handler handler.sendMessage(m); } db.close(); } }.start(); } int lastX; int lastY; @Override public boolean onTouchEvent(MotionEvent event) { int x = (int) event.getX(); int y = (int) event.getY(); switch (event.getAction()) { case MotionEvent.ACTION_DOWN: lastX = x; lastY = y; break; case MotionEvent.ACTION_MOVE: int offX = x - lastX; int offY = y - lastY; //layout if (offX>200){ lastX = x; setHomeSchemeByDate(Tools.prevDay(scheme.getDate())); }else if (offX<-200){ if (!(Tools.nextDay(scheme.getDate()).after(today))){ lastX = x; setHomeSchemeByDate(Tools.nextDay(scheme.getDate())); } } break; } return true; } /** * * @param requestCode * @param resultCode * @param data intent */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { String name = data.getStringExtra(Constant.NAME_PARA); String des = data.getStringExtra(Constant.DESCRIPTION_PARA); String start = data.getStringExtra(Constant.START_PARA); String end = data.getStringExtra(Constant.END_PARA); int value = data.getIntExtra(Constant.VALUE_PARA, Constant.BASED_VALUE); boolean isdone = data.getBooleanExtra(Constant.ISDONE_PARA, false); boolean isagenda = data.getBooleanExtra(Constant.ISAGENDA_PARA, false); int interval = data.getIntExtra(Constant.INTERVAL_PARA, Constant.BASED_INTERVAL); int maxvalue = data.getIntExtra(Constant.MAXVALUE_PARA, Constant.BASED_VALUE); switch (requestCode) { case Constant.RESULT_ADD_TAG: if (resultCode == RESULT_OK) { if (!isagenda) { Backlog backlog = new Backlog(scheme.getDate(), name, start, end, des, value, isdone); addNewTarget(backlog); } else { Agenda agenda = new Agenda(scheme.getDate(), name, start, end, des, value, interval, maxvalue, isdone); addNewTarget(agenda); } fetchAll(); } break; case Constant.RESULT_MOD_TAG: if (resultCode == RESULT_OK) { Target target = Tools.getTargetByScheme(scheme, name); target.setDescription(des); target.setValue(value); target.setTime(Tools.parseTimeByDate(new Date(), start)); target.setEndTime(Tools.parseTimeByDate(new Date(), end)); saveAll(); fetchAll(); } break; } } private void showSchemeDetail() { Toast.makeText(MainActivity.this, scheme.toLongString(), Toast.LENGTH_LONG).show(); } /** * * @return */ private boolean fetchAll() { // Toast.makeText(MainActivity.this, "fetching...", Toast.LENGTH_SHORT).show(); refreshTargets(); return false; } private void onAddTarget() { LogUtils.d(Constant.SERVICE_TAG, "into onAddTarget()"); TargetActivity.actionStart(MainActivity.this, null, null, null, null, 0, false, false, 0, 0, Constant.RESULT_ADD_TAG); } /** * * @param target */ private void deleteTarget(Target target) { // Toast.makeText(MainActivity.this, "deleting...", Toast.LENGTH_SHORT).show(); SQLiteDatabase db = dbHelper.getWritableDatabase(); DataDeleter.deleteTarget(db, target); scheme.getTargets().remove(target); scheme.check(); db.close(); fetchAll(); } /** * * @return */ private boolean saveAll() { // Toast.makeText(MainActivity.this, "saving...", Toast.LENGTH_SHORT).show(); saveTodayTargets(); return false; } /** * * @param target */ private void deleteDialog(final Target target) { AlertDialog.Builder builder = new Builder(MainActivity.this); builder.setMessage("" + target.getName() + ""); builder.setTitle(""); builder.setPositiveButton("", new android.content.DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); deleteTarget(target); } }); builder.setNegativeButton("", new android.content.DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.create().show(); } /** * * @param id * @return */ @Override protected Dialog onCreateDialog(int id) { final int index = id; Dialog dialog = null; Builder builder = new android.app.AlertDialog.Builder(this); builder.setTitle(""); // android.content.DialogInterface.OnClickListener.OnClickListener builder.setItems(R.array.dialog_actions, new android.content.DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { String action = getResources().getStringArray(R.array.dialog_actions)[which]; if (action.equals("")) { dialog.dismiss(); deleteDialog(scheme.getTargets().get(index)); } else if (action.equals("")) { dialog.dismiss(); Target target = scheme.getTargets().get(index); if (target instanceof Agenda) { Agenda agenda = (Agenda) target; TargetActivity.actionStart(MainActivity.this, agenda.getName(), agenda.getDescription(), Tools.formatTime(agenda.getTime()), Tools.formatTime(agenda.getEndTime()), agenda.getValue(), agenda.isDone(), true, agenda.getInterval(), agenda.getMaxValue(), Constant.RESULT_MOD_TAG); } else { TargetActivity.actionStart(MainActivity.this, target.getName(), target.getDescription(), Tools.formatTime(target.getTime()), Tools.formatTime(target.getEndTime()), target.getValue(), target.isDone(), false, 0, 0, Constant.RESULT_MOD_TAG); } } else { dialog.dismiss(); } } }); dialog = builder.create(); return dialog; } /** * * @param object */ public void saveFile(Serializable object) { FileOutputStream out = null; ObjectOutputStream oos = null; ArrayList<Scheme> arrayList = (ArrayList<Scheme>)object; LogUtils.e("savefile",""+arrayList.size()); try { // sdcard // out = openFileOutput(path, Context.MODE_PRIVATE); out = new FileOutputStream(path); oos = new ObjectOutputStream(out); oos.writeObject(object); } catch (IOException e) { e.printStackTrace(); } finally { if (oos != null) { try { oos.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * * @param fileDir */ public Object loadFile(String fileDir) { FileInputStream in = null; ObjectInputStream ois = null; Object obj = null; try { // sdcard // in = openFileInput(fileDir); in = new FileInputStream(fileDir); ois = new ObjectInputStream(in); obj = ois.readObject(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { if (ois != null) { try { ois.close(); } catch (IOException e) { e.printStackTrace(); } } } return obj; } }
package de.htwdd.htwdresden; import android.app.Activity; import android.app.AlertDialog; import android.app.Fragment; import android.app.TimePickerDialog; import android.content.Context; import android.content.DialogInterface; import android.content.res.Resources; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.Snackbar; import android.support.design.widget.TextInputEditText; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.EditText; import android.widget.Spinner; import android.widget.TimePicker; import android.widget.Toast; import java.text.DateFormat; import java.text.DateFormatSymbols; import java.util.Arrays; import java.util.GregorianCalendar; import java.util.Locale; import java.util.UUID; import java.util.concurrent.TimeUnit; import de.htwdd.htwdresden.classes.Const; import de.htwdd.htwdresden.classes.TimetableHelper; import de.htwdd.htwdresden.interfaces.INavigation; import de.htwdd.htwdresden.types.LessonUser; import de.htwdd.htwdresden.types.LessonWeek; import de.htwdd.htwdresden.types.Room; import io.realm.Realm; import io.realm.RealmList; public class TimetableEditFragment extends Fragment { private static final DateFormat dateFormat = DateFormat.getTimeInstance(DateFormat.SHORT); private static final String[] nameOfDays = Arrays.copyOfRange(DateFormatSymbols.getInstance().getWeekdays(), 2, 8); private static final String[] listOfDs = new String[Const.Timetable.beginDS.length + 1]; private Realm realm; private View mLayout; private TextInputEditText lesson_name; private TextInputEditText lesson_tag; private TextInputEditText lesson_prof; private Spinner lesson_type; private TextInputEditText lesson_rooms; private Spinner lesson_week; private Spinner lesson_day; private Spinner lesson_ds; private EditText lesson_beginTime; private EditText lesson_endTime; private TextInputEditText lesson_weeksOnly; private LessonUser lesson = null; private int startTime; private int endTime; private boolean[] selectedKws = new boolean[53]; public TimetableEditFragment() { // Required empty public constructor } @Override public View onCreateView(@NonNull final LayoutInflater inflater, final ViewGroup container, @Nullable final Bundle savedInstanceState) { final Activity activity = getActivity(); final Bundle bundle = getArguments(); // Inflate the layout for this fragment mLayout = inflater.inflate(R.layout.fragment_timetable_edit, container, false); realm = Realm.getDefaultInstance(); if (activity instanceof INavigation) ((INavigation) activity).setTitle(getResources().getString(R.string.timetable_edit_activity_titel)); // Alten Zustand wiederherstellen if (savedInstanceState != null) { startTime = savedInstanceState.getInt("startTime", 0); endTime = savedInstanceState.getInt("endTime", 0); selectedKws = savedInstanceState.getBooleanArray("selectedKws"); } createLocalResources(bundle); createListener(); if (!bundle.containsKey(Const.BundleParams.TIMETABLE_LESSON_ID)) return mLayout; lesson = realm.where(LessonUser.class).endsWith(Const.database.Lesson.ID, bundle.getString(Const.BundleParams.TIMETABLE_LESSON_ID, "")).findFirst(); if (lesson != null) { fillForms(lesson); final Button buttonDelete = mLayout.findViewById(R.id.timetable_edit_LessonDelete); buttonDelete.setEnabled(true); if (lesson.isCreatedByUser()) { buttonDelete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View view) { realm.beginTransaction(); lesson.deleteFromRealm(); realm.commitTransaction(); Toast.makeText(activity, R.string.timetable_edit_lessonDeleteSuccess, Toast.LENGTH_SHORT).show(); activity.finish(); } }); } // Lehrveranstaltung nur ausblenden else { buttonDelete.setText(lesson.isHideLesson() ? R.string.timetable_edit_show : R.string.timetable_edit_hide); buttonDelete.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View view) { realm.beginTransaction(); lesson.setHideLesson(!lesson.isHideLesson()); realm.commitTransaction(); Toast.makeText(activity, R.string.timetable_edit_lessonSaveSuccess, Toast.LENGTH_SHORT).show(); activity.finish(); } }); } } return mLayout; } @Override public void onSaveInstanceState(final Bundle outState) { super.onSaveInstanceState(outState); outState.putInt("startTime", startTime); outState.putInt("endTime", endTime); outState.putBooleanArray("selectedKws", selectedKws); } @Override public void onDestroyView() { super.onDestroyView(); realm.close(); } /** * Holt alle Views aus dem Layout */ private void createLocalResources(@NonNull final Bundle arguments) { final int count = listOfDs.length; final Resources resources = getResources(); final Context context = getActivity(); // Views finden lesson_name = mLayout.findViewById(R.id.timetable_edit_lessonName); lesson_tag = mLayout.findViewById(R.id.timetable_edit_lessonTag); lesson_prof = mLayout.findViewById(R.id.timetable_edit_lessonProf); lesson_type = mLayout.findViewById(R.id.timetable_edit_lessonType); lesson_rooms = mLayout.findViewById(R.id.timetable_edit_lessonRooms); lesson_week = mLayout.findViewById(R.id.timetable_edit_lessonWeek); lesson_day = mLayout.findViewById(R.id.timetable_edit_lessonDay); lesson_ds = mLayout.findViewById(R.id.timetable_edit_lessonDS); lesson_weeksOnly = mLayout.findViewById(R.id.timetable_edit_lessonWeeksOnly); lesson_beginTime = mLayout.findViewById(R.id.timetable_edit_startTime); lesson_endTime = mLayout.findViewById(R.id.timetable_edit_endTime); setTimeAndUpdateView(getMinutes(true), getMinutes(false)); listOfDs[0] = getString(R.string.timetable_edit_lessonDS_value); for (int i = 1; i < count; i++) { listOfDs[i] = resources.getString( R.string.timetable_ds_list, i, dateFormat.format(Const.Timetable.getDate(Const.Timetable.beginDS[i - 1])), dateFormat.format(Const.Timetable.getDate(Const.Timetable.endDS[i - 1])) ); } lesson_day.setAdapter(new ArrayAdapter<>(context, android.R.layout.simple_spinner_dropdown_item, nameOfDays)); lesson_day.setSelection(arguments.getInt(Const.BundleParams.TIMETABLE_DAY, 1) - 1); lesson_ds.setAdapter(new ArrayAdapter<>(context, android.R.layout.simple_spinner_dropdown_item, listOfDs)); lesson_ds.setSelection(arguments.getInt(Const.BundleParams.TIMETABLE_DS, 0)); } private void createListener() { lesson_ds.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(final AdapterView<?> adapterView, final View view, final int i, final long l) { mLayout.findViewById(R.id.timetable_edit_row_individualTime).setVisibility(i == 0 ? View.VISIBLE : View.GONE); if (i != 0) { setTimeAndUpdateView(Const.Timetable.beginDS[i - 1], Const.Timetable.endDS[i - 1]); } } @Override public void onNothingSelected(final AdapterView<?> adapterView) { } }); lesson_beginTime.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View view) { final long minutes = getMinutes(true); final int hour = (int) minutes / 60; final int minute = (int) minutes % 60; final TimePickerDialog timePickerDialog = new TimePickerDialog(getActivity(), new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(final TimePicker timePicker, final int hourOfDay, final int minute) { setTimeAndUpdateView((int) TimeUnit.MINUTES.convert(hourOfDay, TimeUnit.HOURS) + minute, endTime); } }, hour, minute, true); timePickerDialog.show(); } }); lesson_endTime.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View view) { final long minutes = getMinutes(false); final int hour = (int) minutes / 60; final int minute = (int) minutes % 60; final TimePickerDialog timePickerDialog = new TimePickerDialog(getActivity(), new TimePickerDialog.OnTimeSetListener() { @Override public void onTimeSet(final TimePicker timePicker, final int hourOfDay, final int minute) { setTimeAndUpdateView(startTime, (int) TimeUnit.MINUTES.convert(hourOfDay, TimeUnit.HOURS) + minute); } }, hour, minute, true); timePickerDialog.show(); } }); lesson_weeksOnly.setOnClickListener(new View.OnClickListener() { @Override public void onClick(final View view) { final int increment = lesson_week.getSelectedItemPosition() == 0 ? 1 : 2; final int startWeek = lesson_week.getSelectedItemPosition() == 2 ? 2 : 1; final String[] kws = new String[53 / increment]; final boolean[] selectedKwsMinimal = new boolean[53 / increment]; for (int kw = 0; kw < 53 / increment; kw++) { kws[kw] = view.getResources().getString(R.string.timetable_calendar_week, kw * increment + startWeek); selectedKwsMinimal[kw] = selectedKws[kw * increment]; } new AlertDialog.Builder(getActivity()) .setMultiChoiceItems(kws, selectedKwsMinimal, new DialogInterface.OnMultiChoiceClickListener() { @Override public void onClick(final DialogInterface dialog, final int which, final boolean isChecked) { selectedKws[which * increment] = isChecked; // Auswahl in Textbox neu anzeigen String listOfWeeks = ""; for (int i = 0; i < selectedKws.length; i++) { if (selectedKws[i]) { listOfWeeks += i + 1 + "; "; } } lesson_weeksOnly.setText(listOfWeeks); } }) .setPositiveButton("OK", null) .setTitle(R.string.timetable_edit_lessonWeeks_title) .create() .show(); } }); // Speichern mLayout.findViewById(R.id.timetable_edit_lessonSave).setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { final Activity activity = getActivity(); if (saveLesson()) { Toast.makeText(activity, R.string.timetable_edit_lessonSaveSuccess, Toast.LENGTH_SHORT).show(); activity.finish(); } else Snackbar.make(view, R.string.info_error_save, Snackbar.LENGTH_LONG).show(); } }); } private void fillForms(@NonNull final LessonUser lesson) { lesson_name.setText(lesson.getName()); lesson_tag.setText(lesson.getLessonTag()); lesson_prof.setText(lesson.getProfessor()); lesson_type.setSelection(TimetableHelper.getIntegerTypOfLesson(lesson)); lesson_week.setSelection(lesson.getWeek()); lesson_rooms.setText(TimetableHelper.getStringOfRooms(lesson)); lesson_day.setSelection(lesson.getDay() - 1); // Lehrveranstaltung in ein Zeitraster einordnen final int count = listOfDs.length; for (int i = 0; i < count - 1; i++) { if (Const.Timetable.beginDS[i] == lesson.getBeginTime() && Const.Timetable.endDS[i] == lesson.getEndTime()) { lesson_ds.setSelection(i + 1); break; } } if (lesson_ds.getSelectedItemPosition() == 0) { setTimeAndUpdateView(lesson.getBeginTime(), lesson.getEndTime()); mLayout.findViewById(R.id.timetable_edit_row_individualTime).setVisibility(View.VISIBLE); } // Auswahl der einzelnen Wochen final RealmList<LessonWeek> lessonWeeks = lesson.getWeeksOnly(); for (final LessonWeek lessonWeek : lessonWeeks) { selectedKws[lessonWeek.getWeekOfYear() - 1] = true; } lesson_weeksOnly.setText(TimetableHelper.getStringOfKws(lesson)); } private int getMinutes(final boolean startTime) { final int currentDS = TimetableHelper.getCurrentDS(TimetableHelper.getMinutesSinceMidnight(GregorianCalendar.getInstance(Locale.GERMANY))) - 1; if (currentDS >= 0) { return startTime ? Const.Timetable.beginDS[currentDS] : Const.Timetable.endDS[currentDS]; } else { return startTime ? Const.Timetable.beginDS[0] : Const.Timetable.endDS[0]; } } private void setTimeAndUpdateView(final int startTime, final int endTime) { this.startTime = startTime; this.endTime = endTime; lesson_beginTime.setText(dateFormat.format(Const.Timetable.getDate(startTime))); lesson_endTime.setText(dateFormat.format(Const.Timetable.getDate(endTime))); } /** * Holt sich Daten aus dem View und speichert diese in die Datenbank * * @return true beim erfolgreichen speichern sonst false */ private boolean saveLesson() { try { realm.beginTransaction(); if (lesson == null) { lesson = realm.createObject(LessonUser.class, "user_" + UUID.randomUUID().toString()); lesson.setCreatedByUser(true); } lesson.setName(lesson_name.getText().toString()); lesson.setLessonTag(lesson_tag.getText().toString()); lesson.setProfessor(lesson_prof.getText().toString()); lesson.setType(lesson_type.getSelectedItem().toString()); lesson.setWeek(lesson_week.getSelectedItemPosition()); lesson.setDay(lesson_day.getSelectedItemPosition() + 1); lesson.setBeginTime(startTime); lesson.setEndTime(endTime); lesson.setEditedByUser(true); // Wenn keine Kurzform gesetzt ist, diese automatisch erzeugen if (lesson.getLessonTag() == null || lesson.getLessonTag().isEmpty()) { lesson.setLessonTag(lesson.getName().substring(0, Math.min(lesson.getName().length(), 5))); } final RealmList<LessonWeek> lessonWeeks = new RealmList<>(); LessonWeek lessonWeek; for (int i = 0; i < 53; i++) { if (selectedKws[i]) { lessonWeek = realm.where(LessonWeek.class).equalTo("weekOfYear", i + 1).findFirst(); if (lessonWeek == null) { lessonWeek = realm.createObject(LessonWeek.class, i + 1); } lessonWeeks.add(lessonWeek); } } lesson.setWeeksOnly(lessonWeeks); String[] rooms = lesson_rooms.getText().toString().split(";"); Room room; final RealmList<Room> roomsList = new RealmList<>(); for (final String roomName : rooms) { room = realm.where(Room.class).equalTo("roomName", roomName).findFirst(); if (room == null) { room = realm.createObject(Room.class, roomName); } roomsList.add(room); } lesson.setRooms(roomsList); realm.commitTransaction(); } catch (final Exception e) { return false; } return true; } }
package iecs.fcu_navigate.helper; import android.graphics.Color; import android.net.Uri; import android.os.AsyncTask; import android.util.Log; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.LatLngBounds; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.Polyline; import com.google.android.gms.maps.model.PolylineOptions; import com.google.common.collect.Lists; import com.google.gson.Gson; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.ArrayList; import java.util.List; import java.util.Map; import iecs.fcu_navigate.database.MarkerContract; /** * Google Dictionary Api Helper */ public class DictionaryHelper { private static String generateURL(MarkerContract.Item origin, MarkerContract.Item destination) { return new Uri.Builder() .scheme("https") .authority("maps.googleapis.com") .appendPath("maps") .appendPath("api") .appendPath("directions") .appendPath("json") .appendQueryParameter("origin", origin.getLatitude() + "," + origin.getLongitude()) .appendQueryParameter("destination", destination.getLatitude() + "," + destination.getLongitude()) .appendQueryParameter("mode", "walking") .build().toString(); } public static void startNavigate(GoogleMap mMap, MarkerContract.Item origin, MarkerContract.Item destination) { new DownLoadDataTask(mMap).execute(generateURL(origin, destination)); } private static class DownLoadDataTask extends AsyncTask<String, Void, String> { private static ArrayList<Polyline> mPolylines = new ArrayList<>(); private GoogleMap mMap; public DownLoadDataTask(GoogleMap mMap) { this.mMap = mMap; } @Override protected String doInBackground(String... params) { return getData(params[0]); } private String getData(String uri) { try { URL url = new URL(uri); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout(10000 /* milliseconds */); conn.setConnectTimeout(15000 /* milliseconds */); conn.setRequestMethod("GET"); conn.setDoInput(true); // Starts the query conn.connect(); Log.d("Google Directions API", "The response is: " + conn.getResponseCode()); InputStream is = conn.getInputStream(); // Convert the InputStream into a string BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8")); StringBuffer sb = new StringBuffer(); String line = ""; while ((line = br.readLine()) != null) { sb.append(line); } return sb.toString(); } catch (Exception e) { Log.e("Google Directions API", e.getMessage()); Log.e("Google Directions API", Log.getStackTraceString(e)); } return "{}"; } @Override protected void onPostExecute(String result) { Map<String, Object> data = new Gson().fromJson(result, Map.class); if (data.get("status").equals("OK")) { String overview_polyline = (String) ((Map)((Map)((List)data.get("routes")).get(0)).get("overview_polyline")).get("points"); List<LatLng> points = decodePolylines(overview_polyline); PolylineOptions lineOptions = new PolylineOptions(); lineOptions.addAll(points); lineOptions.width(10); lineOptions.color(Color.BLUE); for (Polyline polyline : mPolylines) { polyline.remove(); } mPolylines.add(mMap.addPolyline(lineOptions)); Map<String, Double> northeast = (Map<String, Double>) ((Map) ((Map) ((List) data.get("routes")).get(0)).get("bounds")).get("northeast"); Map<String, Double> southwest = (Map<String, Double>) ((Map) ((Map) ((List) data.get("routes")).get(0)).get("bounds")).get("southwest"); LatLngBounds bounds = new LatLngBounds( new LatLng(southwest.get("lat"), southwest.get("lng")), new LatLng(northeast.get("lat"), northeast.get("lng")) ); mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 100)); } } private List<LatLng> decodePolylines(String poly) { List<LatLng> point = Lists.newArrayList(); int len = poly.length(); int index = 0; int lat = 0; int lng = 0; while (index < len) { int b, shift = 0, result = 0; do { b = poly.charAt(index++) - 63; result |= (b & 0x1f) << shift; shift += 5; } while (b >= 0x20); int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1)); lat += dlat; shift = 0; result = 0; do { b = poly.charAt(index++) - 63; result |= (b & 0x1f) << shift; shift += 5; } while (b >= 0x20); int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1)); lng += dlng; point.add(new LatLng((((double) lat / 1E5)),(((double) lng / 1E5)))); } return point; } } }
package io.keen.client.android.example; import android.app.Activity; import android.app.AlertDialog; import android.os.AsyncTask; import android.os.Bundle; import android.util.Log; import android.view.View; import java.io.IOException; import java.util.HashMap; import java.util.Map; import io.keen.client.android.AndroidKeenClientBuilder; import io.keen.client.java.KeenClient; import io.keen.client.java.KeenLogging; import io.keen.client.java.KeenProject; import io.keen.client.java.KeenQueryClient; import io.keen.client.java.RelativeTimeframe; public class MyActivity extends Activity { private static int clickNumber = 0; private KeenQueryClient queryClient; private KeenProject project; protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_my); // If the Keen Client isn't already initialized, initialize it. if (!KeenClient.isInitialized()) { // Create a new instance of the client. KeenClient client = new AndroidKeenClientBuilder(this).build(); client.setDefaultProject(getProject()); // During testing, enable logging and debug mode. // NOTE: REMOVE THESE LINES BEFORE SHIPPING YOUR APPLICATION! KeenLogging.enableLogging(); client.setDebugMode(true); // Initialize the KeenClient singleton with the created client. KeenClient.initialize(client); } // Also create a query client (if it doesn't exist). if (queryClient == null) { queryClient = new KeenQueryClient.Builder(getProject()).build(); } } @Override protected void onPause() { // Send all queued events to Keen. Use the asynchronous method to // avoid network activity on the main thread. KeenClient.client().sendQueuedEventsAsync(); super.onPause(); } public void handleClick(View view) { Log.i(this.getLocalClassName(), "handling click on view " + view.getId()); switch (view.getId()) { case R.id.send_event_button: // Create an event to upload to Keen. Map<String, Object> event = new HashMap<>(); event.put("click-number", clickNumber++); // Add it to the "purchases" collection in your Keen Project. KeenClient.client().queueEvent(getCollection(), event); break; case R.id.query_button: new KeenQueryAsyncTask().execute(); break; } } private KeenProject getProject() { if (project == null) { // Get the project ID and write key from string resources, then create a project and set // it as the default for the client. String projectId = getString(R.string.keen_project_id); String readKey = getString(R.string.keen_read_key); String writeKey = getString(R.string.keen_write_key); project = new KeenProject(projectId, writeKey, readKey); } return project; } private String getCollection() { return getString(R.string.keen_collection); } private long getCount() { try { Log.i(this.getLocalClassName(), "executing count query"); long result = queryClient.count(getCollection(), new RelativeTimeframe("this_24_hours")); Log.i(this.getLocalClassName(), "finished count query"); return result; } catch (IOException e) { Log.w(this.getLocalClassName(), "count failed", e); return -1; } } private class KeenQueryAsyncTask extends AsyncTask<Void, Void, Long> { @Override protected Long doInBackground(Void[] params) { return getCount(); } @Override protected void onPostExecute(Long result) { new AlertDialog.Builder(MyActivity.this) .setTitle("Count succeeded") .setMessage("Count = " + result) .show(); } } }
package com.mercadopago; import android.content.Intent; import android.net.Uri; import android.support.design.widget.Snackbar; import android.text.Html; import android.text.Spanned; import android.util.TypedValue; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import com.mercadopago.callbacks.Callback; import com.mercadopago.callbacks.FailureRecovery; import com.mercadopago.core.MercadoPago; import com.mercadopago.model.ApiException; import com.mercadopago.model.Instruction; import com.mercadopago.model.InstructionActionInfo; import com.mercadopago.model.InstructionReference; import com.mercadopago.model.Payment; import com.mercadopago.model.PaymentMethod; import com.mercadopago.model.PaymentResult; import com.mercadopago.mptracker.MPTracker; import com.mercadopago.util.ApiUtil; import com.mercadopago.util.CurrenciesUtil; import com.mercadopago.util.ErrorUtil; import com.mercadopago.util.JsonUtil; import com.mercadopago.util.LayoutUtil; import com.mercadopago.util.MercadoPagoUtil; import com.mercadopago.util.ScaleUtil; import com.mercadopago.views.MPButton; import com.mercadopago.views.MPTextView; import java.util.ArrayList; import java.util.List; public class InstructionsActivity extends MercadoPagoActivity { //Const private static final String INSTRUCTIONS_NOT_FOUND_FOR_TYPE = "instruction not found for type"; //Values protected MercadoPago mMercadoPago; protected Boolean mBackPressedOnce; //Controls protected LinearLayout mReferencesLayout; protected MPTextView mTitle; protected MPTextView mPrimaryInfo; protected MPTextView mSecondaryInfo; protected MPTextView mTertiaryInfo; protected MPTextView mAccreditationMessage; protected MPButton mActionButton; protected MPTextView mExitTextView; //Params protected Payment mPayment; protected PaymentMethod mPaymentMethod; protected String mMerchantPublicKey; @Override protected void getActivityParameters() { mMerchantPublicKey = getIntent().getStringExtra("merchantPublicKey"); mPayment = JsonUtil.getInstance().fromJson(getIntent().getStringExtra("payment"), Payment.class); mPaymentMethod = JsonUtil.getInstance().fromJson(getIntent().getStringExtra("paymentMethod"), PaymentMethod.class); } @Override protected void validateActivityParameters() throws IllegalStateException { if(mMerchantPublicKey == null) { throw new IllegalStateException("merchant public key not set"); } if(mPayment == null) { throw new IllegalStateException("payment not set"); } if(mPaymentMethod == null) { throw new IllegalStateException("payment method not set"); } if(MercadoPagoUtil.isCard(mPaymentMethod.getPaymentTypeId())) { throw new IllegalStateException("payment method cannot be card"); } } @Override protected void setContentView() { setContentView(R.layout.mpsdk_activity_instructions); } @Override protected void initializeControls() { mReferencesLayout = (LinearLayout) findViewById(R.id.mpsdkReferencesLayout); mTitle = (MPTextView) findViewById(R.id.mpsdkTitle); mPrimaryInfo = (MPTextView) findViewById(R.id.mpsdkPrimaryInfo); mSecondaryInfo = (MPTextView) findViewById(R.id.mpsdkSecondaryInfo); mTertiaryInfo = (MPTextView) findViewById(R.id.mpsdkTertiaryInfo); mAccreditationMessage = (MPTextView) findViewById(R.id.mpsdkAccreditationMessage); mActionButton = (MPButton) findViewById(R.id.mpsdkActionButton); mExitTextView = (MPTextView) findViewById(R.id.mpsdkExitInstructions); mExitTextView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { finish(); animateOut(); } }); } @Override protected void onInvalidStart(String message) { ErrorUtil.startErrorActivity(this, message, false); } @Override protected void onValidStart() { mBackPressedOnce = false; mMercadoPago = new MercadoPago.Builder() .setContext(this) .setPublicKey(mMerchantPublicKey) .build(); getInstructionsAsync(); } protected void getInstructionsAsync() { LayoutUtil.showProgressLayout(this); mMercadoPago.getPaymentResult(mPayment.getId(), mPaymentMethod.getPaymentTypeId(), new Callback<PaymentResult>() { @Override public void success(PaymentResult paymentResult) { List<Instruction> instructions = paymentResult.getInstructions() == null ? new ArrayList<Instruction>() : paymentResult.getInstructions(); if(instructions.isEmpty()) { ErrorUtil.startErrorActivity(getActivity(), getActivity().getString(R.string.mpsdk_standard_error_message), INSTRUCTIONS_NOT_FOUND_FOR_TYPE + mPaymentMethod.getPaymentTypeId(), false); } else { resolveInstructionsFound(instructions); } } @Override public void failure(ApiException apiException) { if (isActivityActive()) { ApiUtil.showApiExceptionError(getActivity(), apiException); setFailureRecovery(new FailureRecovery() { @Override public void recover() { getInstructionsAsync(); } }); } } }); } private void resolveInstructionsFound(List<Instruction> instructions) { Instruction instruction = getInstruction(instructions); if(instruction == null) { ErrorUtil.startErrorActivity(this, this.getString(R.string.mpsdk_standard_error_message), "instruction not found for type " + mPaymentMethod.getPaymentTypeId(), false); } else { showInstructions(instruction); } LayoutUtil.showRegularLayout(this); } private Instruction getInstruction(List<Instruction> instructions) { Instruction instruction; if(instructions.size() == 1) { instruction = instructions.get(0); } else { instruction = getInstructionForType(instructions, mPaymentMethod.getPaymentTypeId()); } return instruction; } private Instruction getInstructionForType(List<Instruction> instructions, String paymentTypeId) { Instruction instructionForType = null; for(Instruction instruction : instructions) { if(instruction.getType().equals(paymentTypeId)) { instructionForType = instruction; break; } } return instructionForType; } protected void showInstructions(Instruction instruction) { MPTracker.getInstance().trackScreen( "INSTRUCTIONS", 2, mMerchantPublicKey, BuildConfig.VERSION_NAME, this); setTitle(instruction.getTitle()); setInformationMessages(instruction); setReferencesInformation(instruction); mAccreditationMessage.setText(instruction.getAcreditationMessage()); setActions(instruction); } protected void setTitle(String title) { Spanned formattedTitle = CurrenciesUtil.formatCurrencyInText(mPayment.getTransactionAmount(), mPayment.getCurrencyId(), title, true, true); mTitle.setText(formattedTitle); } protected void setActions(Instruction instruction) { if(instruction.getActions() != null && !instruction.getActions().isEmpty()) { final InstructionActionInfo actionInfo = instruction.getActions().get(0); if(actionInfo.getTag().equals(InstructionActionInfo.Tags.LINK) && actionInfo.getUrl() != null && !actionInfo.getUrl().isEmpty()) { mActionButton.setVisibility(View.VISIBLE); mActionButton.setText(actionInfo.getLabel()); mActionButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(actionInfo.getUrl())); startActivity(browserIntent); } }); } } } protected void setReferencesInformation(Instruction instruction) { LinearLayout.LayoutParams marginParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); int marginTop = ScaleUtil.getPxFromDp(3, this); int marginBottom = ScaleUtil.getPxFromDp(15, this); for(InstructionReference reference : instruction.getReferences()) { MPTextView currentTitleTextView = new MPTextView(this); MPTextView currentValueTextView = new MPTextView(this); if(reference.hasValue()) { if (reference.hasLabel()) { currentTitleTextView.setText(reference.getLabel().toUpperCase()); currentTitleTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimensionPixelSize(R.dimen.mpsdk_smaller_text)); mReferencesLayout.addView(currentTitleTextView); } String formattedReference = reference.getFormattedReference(); int referenceSize = getTextSizeForReference(); currentValueTextView.setText(formattedReference); currentValueTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, referenceSize); marginParams.setMargins(0, marginTop, 0, marginBottom); currentValueTextView.setLayoutParams(marginParams); mReferencesLayout.addView(currentValueTextView); } } } private int getTextSizeForReference() { return getResources().getDimensionPixelSize(R.dimen.mpsdk_large_text); } private void setInformationMessages(Instruction instruction) { if(instruction.getInfo() != null && !instruction.getInfo().isEmpty()) { mPrimaryInfo.setText(Html.fromHtml(getInfoHtmlText(instruction.getInfo()))); } else { mPrimaryInfo.setVisibility(View.GONE); } if(instruction.getSecondaryInfo() != null && !instruction.getSecondaryInfo().isEmpty()) { mSecondaryInfo.setText(Html.fromHtml(getInfoHtmlText(instruction.getSecondaryInfo()))); } else { mSecondaryInfo.setVisibility(View.GONE); } if(instruction.getTertiaryInfo() != null && !instruction.getTertiaryInfo().isEmpty()) { mTertiaryInfo.setText(Html.fromHtml(getInfoHtmlText(instruction.getTertiaryInfo()))); } else { mTertiaryInfo.setVisibility(View.GONE); } } protected String getInfoHtmlText(List<String> info) { StringBuilder stringBuilder = new StringBuilder(); for(String line : info) { stringBuilder.append(line); if(!line.equals(info.get(info.size() - 1))) { stringBuilder.append("<br/>"); } } return stringBuilder.toString(); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if(requestCode == ErrorUtil.ERROR_REQUEST_CODE) { if(resultCode == RESULT_OK) { recoverFromFailure(); } else { setResult(RESULT_CANCELED, data); finish(); } } } private void animateOut() { overridePendingTransition(R.anim.mpsdk_slide_right_to_left_in, R.anim.mpsdk_slide_right_to_left_out); } @Override public void onBackPressed() { MPTracker.getInstance().trackScreen( "INSTRUCTIONS", 2, mMerchantPublicKey, BuildConfig.VERSION_NAME, this); if(mBackPressedOnce) { super.onBackPressed(); } else { Snackbar.make(mTertiaryInfo, getString(R.string.mpsdk_press_again_to_leave), Snackbar.LENGTH_LONG).show(); mBackPressedOnce = true; resetBackPressedOnceIn(4000); } } private void resetBackPressedOnceIn(final int mills) { new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(mills); mBackPressedOnce = false; } catch (InterruptedException e) { //Do nothing } } }).start(); } }
package de.avgl.dmp.controller; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.util.Properties; import javax.ws.rs.core.UriBuilder; import org.glassfish.grizzly.http.server.HttpServer; import org.glassfish.jersey.grizzly2.httpserver.GrizzlyHttpServerFactory; import org.glassfish.jersey.media.multipart.MultiPartFeature; import org.glassfish.jersey.server.ResourceConfig; /** * Main class. */ public class Main { private static final org.apache.log4j.Logger log = org.apache.log4j.Logger.getLogger(Main.class); // Base URI the Grizzly HTTP server will listen on public final String BASE_URI; public Main(Properties properties) { final String host = properties.getProperty("backend_http_server_host"); final int port = Integer.valueOf(properties.getProperty("backend_http_server_port")); final URI baseUri = UriBuilder.fromUri("http://" + host).port(port).path("dmp/").build(); BASE_URI = baseUri.toString(); } public String getBaseUri() { return BASE_URI; } private static Properties loadProperties(String propertiesPath) { final InputStream inStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(propertiesPath); final Properties properties = new Properties(); try { properties.load(inStream); } catch (IOException e) { log.debug("could not load properties"); } return properties; } private static Properties loadProperties() { return loadProperties("dmp.properties"); } /** * Starts Grizzly HTTP server exposing JAX-RS resources defined in this application. * * @return Grizzly HTTP server. */ public HttpServer startServer() { // create a resource config that scans for JAX-RS resources and // providers // in de.avgl.dmp.controller.resources package final ResourceConfig rc = new ResourceConfig() // .register(JacksonJaxbJsonProvider.class) .packages("de.avgl.dmp.controller.resources") .register(MultiPartFeature.class) .register(de.avgl.dmp.controller.providers.ExceptionHandler.class); // create and start a new instance of grizzly http server // exposing the Jersey application at BASE_URI final HttpServer httpServer = GrizzlyHttpServerFactory.createHttpServer(URI.create(BASE_URI), rc); httpServer.getListener("grizzly").setMaxFormPostSize(Integer.MAX_VALUE); return httpServer; } public static Main create(int port) { final Properties properties = loadProperties(); properties.setProperty("backend_http_server_port", Integer.valueOf(port).toString()); return new Main(properties); } public static Main create() { final Properties properties = loadProperties(); return new Main(properties); } /** * Main method. * * @param args * @throws IOException */ public static void main(String[] args) throws IOException { final Main main = Main.create(); final HttpServer server = main.startServer(); System.out.println(String.format("Jersey app started with WADL available at " + "%sapplication.wadl\nHit enter to stop it...", main.getBaseUri())); System.in.read(); server.stop(); } }
package com.intellij.psi.impl.source; import com.intellij.lang.ASTNode; import com.intellij.navigation.ItemPresentation; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.module.Module; import com.intellij.openapi.roots.OrderEntry; import com.intellij.openapi.roots.ProjectFileIndex; import com.intellij.openapi.roots.ProjectRootManager; import com.intellij.openapi.util.Pair; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.pom.java.PomMemberOwner; import com.intellij.psi.*; import com.intellij.psi.impl.*; import com.intellij.psi.impl.cache.ClassView; import com.intellij.psi.impl.cache.RepositoryElementType; import com.intellij.psi.impl.cache.RepositoryManager; import com.intellij.psi.impl.light.LightMethod; import com.intellij.psi.impl.meta.MetaRegistry; import com.intellij.psi.impl.source.tree.ChildRole; import com.intellij.psi.impl.source.tree.JavaElementType; import com.intellij.psi.impl.source.tree.RepositoryTreeElement; import com.intellij.psi.impl.source.tree.java.ClassElement; import com.intellij.psi.impl.source.tree.java.PsiTypeParameterListImpl; import com.intellij.psi.javadoc.PsiDocComment; import com.intellij.psi.meta.PsiMetaData; import com.intellij.psi.presentation.java.ClassPresentationUtil; import com.intellij.psi.scope.NameHint; import com.intellij.psi.scope.PsiScopeProcessor; import com.intellij.psi.search.GlobalSearchScope; import com.intellij.util.IncorrectOperationException; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; public class PsiClassImpl extends NonSlaveRepositoryPsiElement implements PsiClass { private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.source.PsiClassImpl"); private PsiModifierListImpl myRepositoryModifierList = null; private PsiReferenceListImpl myRepositoryExtendsList = null; private PsiReferenceListImpl myRepositoryImplementsList = null; private PsiTypeParameterListImpl myRepositoryParameterList = null; private String myCachedName = null; private String myCachedQName = null; private Map<String, PsiField> myCachedFieldsMap = null; private Map<String, PsiMethod[]> myCachedMethodsMap = null; private Map<String, PsiClass> myCachedInnersMap = null; private PsiField[] myCachedFields = null; private PsiMethod[] myCachedMethods = null; private PsiMethod[] myCachedConstructors = null; private PsiClass[] myCachedInners = null; private Boolean myCachedIsDeprecated = null; private Boolean myCachedIsInterface = null; private Boolean myCachedIsAnnotationType = null; private Boolean myCachedIsEnum = null; private PsiMethod myValuesMethod = null; private PsiMethod myValueOfMethod = null; private String myCachedForLongName = null; private static final @NonNls String VALUES_METHOD = "values"; private static final @NonNls String VALUE_OF_METHOD = "valueOf"; public PsiClassImpl(PsiManagerImpl manager, long repositoryId) { super(manager, repositoryId); } public PsiClassImpl(PsiManagerImpl manager, RepositoryTreeElement treeElement) { super(manager, treeElement); } public void subtreeChanged() { dropCaches(); super.subtreeChanged(); } private void dropCaches() { myCachedName = null; myCachedFields = null; myCachedMethods = null; myCachedConstructors = null; myCachedInners = null; myCachedFieldsMap = null; myCachedMethodsMap = null; myCachedInnersMap = null; myCachedIsDeprecated = null; myCachedIsInterface = null; myCachedIsAnnotationType = null; myCachedIsEnum = null; myCachedQName = null; myCachedForLongName = null; } protected Object clone() { PsiClassImpl clone = (PsiClassImpl)super.clone(); clone.myRepositoryModifierList = null; clone.myRepositoryExtendsList = null; clone.myRepositoryImplementsList = null; clone.myRepositoryParameterList = null; clone.dropCaches(); return clone; } public void setRepositoryId(long repositoryId) { super.setRepositoryId(repositoryId); if (repositoryId < 0){ if (myRepositoryModifierList != null){ myRepositoryModifierList.setOwner(this); myRepositoryModifierList = null; } if (myRepositoryExtendsList != null){ myRepositoryExtendsList.setOwner(this); myRepositoryExtendsList = null; } if (myRepositoryImplementsList != null){ myRepositoryImplementsList.setOwner(this); myRepositoryImplementsList = null; } if (myRepositoryParameterList != null) { myRepositoryParameterList.setOwner(this); myRepositoryParameterList = null; } } else{ myRepositoryModifierList = (PsiModifierListImpl)bindSlave(ChildRole.MODIFIER_LIST); myRepositoryExtendsList = (PsiReferenceListImpl)bindSlave(ChildRole.EXTENDS_LIST); myRepositoryImplementsList = (PsiReferenceListImpl)bindSlave(ChildRole.IMPLEMENTS_LIST); myRepositoryParameterList = (PsiTypeParameterListImpl)bindSlave(ChildRole.TYPE_PARAMETER_LIST); } dropCaches(); } public PsiElement getParent() { PsiElement parent = getDefaultParentByRepository(); if (parent instanceof PsiMethod || parent instanceof PsiField || parent instanceof PsiClassInitializer){ return SourceTreeToPsiMap.treeElementToPsi(calcTreeElement().getTreeParent()); // anonymous or local } return parent; } public PsiElement getOriginalElement() { PsiFile psiFile = getContainingFile(); VirtualFile vFile = psiFile.getVirtualFile(); final ProjectFileIndex idx = ProjectRootManager.getInstance(myManager.getProject()).getFileIndex(); if (!idx.isInLibrarySource(vFile)) return this; final Set<OrderEntry> orderEntries = new HashSet<OrderEntry>(idx.getOrderEntriesForFile(vFile)); PsiClass original = myManager.findClass(getQualifiedName(), new GlobalSearchScope() { public int compare(VirtualFile file1, VirtualFile file2) { return 0; } public boolean contains(VirtualFile file) { // order for file and vFile has non empty intersection. Set<OrderEntry> entries = new HashSet<OrderEntry>(idx.getOrderEntriesForFile(file)); int size = entries.size(); entries.addAll(orderEntries); return size + orderEntries.size() > entries.size(); } public boolean isSearchInModuleContent(Module aModule) { return false; } public boolean isSearchInLibraries() { return true; } }); return original != null ? original : this; } public PsiIdentifier getNameIdentifier() { return (PsiIdentifier)calcTreeElement().findChildByRoleAsPsiElement(ChildRole.NAME); } public PsiElement getScope() { ASTNode treeElement = getTreeElement(); if (treeElement != null){ ASTNode parent = treeElement.getTreeParent(); while(true){ if (parent instanceof RepositoryTreeElement){ return SourceTreeToPsiMap.treeElementToPsi(parent); } parent = parent.getTreeParent(); } } else{ return getRepositoryElementsManager().findOrCreatePsiElementById(getParentId()); } } public String getName() { if (myCachedName == null){ if (getTreeElement() != null){ PsiIdentifier identifier = getNameIdentifier(); myCachedName = identifier != null ? identifier.getText() : null; } else{ myCachedName = getRepositoryManager().getClassView().getName(getRepositoryId()); } } return myCachedName; } public String getQualifiedName() { String qName = myCachedQName; if (qName == null) { if (getTreeElement() != null) { PsiElement parent = getParent(); if (parent instanceof PsiJavaFile) { String packageName = ((PsiJavaFile)parent).getPackageName(); if (packageName.length() > 0) { qName = packageName + "." + getName(); } else { qName = getName(); } } else if (parent instanceof PsiClass) { String parentQName = ((PsiClass)parent).getQualifiedName(); if (parentQName == null) return null; qName = parentQName + "." + getName(); } } else { qName = getRepositoryManager().getClassView().getQualifiedName(getRepositoryId()); } //if (getRepositoryId() >= 0) { myCachedQName = qName; } return qName; } public PsiModifierList getModifierList(){ long repositoryId = getRepositoryId(); if (repositoryId >= 0){ if (myRepositoryModifierList == null){ myRepositoryModifierList = new PsiModifierListImpl(myManager, this); } return myRepositoryModifierList; } else{ return (PsiModifierList)calcTreeElement().findChildByRoleAsPsiElement(ChildRole.MODIFIER_LIST); } } public boolean hasModifierProperty(@NotNull String name) { return getModifierList().hasModifierProperty(name); } public PsiReferenceList getExtendsList() { if (isEnum() || isAnnotationType()) return null; long repositoryId = getRepositoryId(); if (repositoryId >= 0){ if (myRepositoryExtendsList == null){ myRepositoryExtendsList = new PsiReferenceListImpl(myManager, this, JavaElementType.EXTENDS_LIST); } return myRepositoryExtendsList; } else{ return (PsiReferenceList)calcTreeElement().findChildByRoleAsPsiElement(ChildRole.EXTENDS_LIST); } } public PsiReferenceList getImplementsList() { long repositoryId = getRepositoryId(); if (repositoryId >= 0){ if (myRepositoryImplementsList == null){ myRepositoryImplementsList = new PsiReferenceListImpl(myManager, this, JavaElementType.IMPLEMENTS_LIST); } return myRepositoryImplementsList; } else{ return (PsiReferenceList)calcTreeElement().findChildByRoleAsPsiElement(ChildRole.IMPLEMENTS_LIST); } } @NotNull public PsiClassType[] getExtendsListTypes() { return PsiClassImplUtil.getExtendsListTypes(this); } @NotNull public PsiClassType[] getImplementsListTypes() { return PsiClassImplUtil.getImplementsListTypes(this); } public PsiClass getSuperClass() { return PsiClassImplUtil.getSuperClass(this); } public PsiClass[] getInterfaces() { return PsiClassImplUtil.getInterfaces(this); } @NotNull public PsiClass[] getSupers() { return PsiClassImplUtil.getSupers(this); } @NotNull public PsiClassType[] getSuperTypes() { return PsiClassImplUtil.getSuperTypes(this); } @Nullable public PsiClass getContainingClass() { PsiElement parent = getDefaultParentByRepository(); return parent instanceof PsiClass ? (PsiClass)parent : null; } @NotNull public Collection<HierarchicalMethodSignature> getVisibleSignatures() { return PsiSuperMethodImplUtil.getVisibleSignatures(this); } @NotNull public PsiField[] getFields() { PsiField[] cachedFields = myCachedFields; if (cachedFields == null){ if (getTreeElement() != null){ cachedFields = calcTreeElement().getChildrenAsPsiElements(FIELD_BIT_SET, PSI_FIELD_ARRAY_CONSTRUCTOR); } else{ long[] fieldIds = getRepositoryManager().getClassView().getFields(getRepositoryId()); PsiField[] fields = fieldIds.length > 0 ? new PsiField[fieldIds.length] : PsiField.EMPTY_ARRAY; for(int i = 0; i < fieldIds.length; i++){ long id = fieldIds[i]; fields[i] = (PsiField)getRepositoryElementsManager().findOrCreatePsiElementById(id); } cachedFields = fields; } myCachedFields = cachedFields; } return cachedFields; } @NotNull public PsiMethod[] getMethods() { if (myCachedMethods == null){ if (getTreeElement() != null){ myCachedMethods = calcTreeElement().getChildrenAsPsiElements(METHOD_BIT_SET, PSI_METHOD_ARRAY_CONSTRUCTOR); } else{ long[] methodIds = getRepositoryManager().getClassView().getMethods(getRepositoryId()); PsiMethod[] methods = methodIds.length > 0 ? new PsiMethod[methodIds.length] : PsiMethod.EMPTY_ARRAY; for(int i = 0; i < methodIds.length; i++){ long id = methodIds[i]; methods[i] = (PsiMethod)getRepositoryElementsManager().findOrCreatePsiElementById(id); } myCachedMethods = methods; } } return myCachedMethods; } @NotNull public PsiMethod[] getConstructors() { if (myCachedConstructors == null) { myCachedConstructors = PsiImplUtil.getConstructors(this); } return myCachedConstructors; } @NotNull public PsiClass[] getInnerClasses() { PsiClass[] cachedInners = myCachedInners; if (cachedInners == null) { if (getTreeElement() != null) { cachedInners = calcTreeElement().getChildrenAsPsiElements(CLASS_BIT_SET, PSI_CLASS_ARRAY_CONSTRUCTOR); } else { long[] classIds = getRepositoryManager().getClassView().getInnerClasses(getRepositoryId()); PsiClass[] classes = classIds.length > 0 ? new PsiClass[classIds.length] : PsiClass.EMPTY_ARRAY; for (int i = 0; i < classIds.length; i++) { long id = classIds[i]; classes[i] = (PsiClass)getRepositoryElementsManager().findOrCreatePsiElementById(id); } cachedInners = classes; } myCachedInners = cachedInners; } return cachedInners; } @NotNull public PsiClassInitializer[] getInitializers() { if (getTreeElement() != null) { return calcTreeElement().getChildrenAsPsiElements(CLASS_INITIALIZER_BIT_SET, PSI_CLASS_INITIALIZER_ARRAY_CONSTRUCTOR); } else { long[] initializerIds = getRepositoryManager().getClassView().getInitializers(getRepositoryId()); PsiClassInitializer[] initializers = initializerIds.length > 0 ? new PsiClassInitializer[initializerIds.length] : PsiClassInitializer.EMPTY_ARRAY; for (int i = 0; i < initializerIds.length; i++) { long id = initializerIds[i]; initializers[i] = (PsiClassInitializer)getRepositoryElementsManager().findOrCreatePsiElementById(id); } return initializers; } } @NotNull public PsiTypeParameter[] getTypeParameters() { return PsiImplUtil.getTypeParameters(this); } @NotNull public PsiField[] getAllFields() { return PsiClassImplUtil.getAllFields(this); } @NotNull public PsiMethod[] getAllMethods() { return PsiClassImplUtil.getAllMethods(this); } @NotNull public PsiClass[] getAllInnerClasses() { return PsiClassImplUtil.getAllInnerClasses(this); } public PsiField findFieldByName(String name, boolean checkBases) { if(!checkBases){ Map<String, PsiField> cachedFields = myCachedFieldsMap; if(cachedFields == null){ final PsiField[] fields = getFields(); cachedFields = new HashMap<String, PsiField>(); for (final PsiField field : fields) { cachedFields.put(field.getName(), field); } myCachedFieldsMap = cachedFields; } return cachedFields.get(name); } return PsiClassImplUtil.findFieldByName(this, name, checkBases); } public PsiMethod findMethodBySignature(PsiMethod patternMethod, boolean checkBases) { return PsiClassImplUtil.findMethodBySignature(this, patternMethod, checkBases); } @NotNull public PsiMethod[] findMethodsBySignature(PsiMethod patternMethod, boolean checkBases) { return PsiClassImplUtil.findMethodsBySignature(this, patternMethod, checkBases); } @NotNull public PsiMethod[] findMethodsByName(String name, boolean checkBases) { if(!checkBases){ Map<String, PsiMethod[]> cachedMethods = myCachedMethodsMap; if(cachedMethods == null){ cachedMethods = new HashMap<String,PsiMethod[]>(); Map<String, List<PsiMethod>> cachedMethodsMap = new HashMap<String,List<PsiMethod>>(); final PsiMethod[] methods = getMethods(); for (final PsiMethod method : methods) { List<PsiMethod> list = cachedMethodsMap.get(method.getName()); if (list == null) { list = new ArrayList<PsiMethod>(1); cachedMethodsMap.put(method.getName(), list); } list.add(method); } for (final String methodName : cachedMethodsMap.keySet()) { cachedMethods.put(methodName, cachedMethodsMap.get(methodName).toArray(PsiMethod.EMPTY_ARRAY)); } myCachedMethodsMap = cachedMethods; } final PsiMethod[] psiMethods = cachedMethods.get(name); return psiMethods != null ? psiMethods : PsiMethod.EMPTY_ARRAY; } return PsiClassImplUtil.findMethodsByName(this, name, checkBases); } @NotNull public List<Pair<PsiMethod, PsiSubstitutor>> findMethodsAndTheirSubstitutorsByName(String name, boolean checkBases) { return PsiClassImplUtil.findMethodsAndTheirSubstitutorsByName(this, name, checkBases); } @NotNull public List<Pair<PsiMethod, PsiSubstitutor>> getAllMethodsAndTheirSubstitutors() { return PsiClassImplUtil.getAllWithSubstitutorsByMap(this, PsiMethod.class); } public PsiClass findInnerClassByName(String name, boolean checkBases) { if(!checkBases){ Map<String, PsiClass> inners = myCachedInnersMap; if(inners == null){ final PsiClass[] classes = getInnerClasses(); inners = new HashMap<String,PsiClass>(); for (final PsiClass psiClass : classes) { inners.put(psiClass.getName(), psiClass); } myCachedInnersMap = inners; } return inners.get(name); } return PsiClassImplUtil.findInnerByName(this, name, checkBases); } public PsiTypeParameterList getTypeParameterList() { long repositoryId = getRepositoryId(); if (repositoryId >= 0){ if (myRepositoryParameterList == null){ myRepositoryParameterList = new PsiTypeParameterListImpl(myManager, this); } return myRepositoryParameterList; } return (PsiTypeParameterList) calcTreeElement().findChildByRoleAsPsiElement(ChildRole.TYPE_PARAMETER_LIST); } public boolean hasTypeParameters() { final PsiTypeParameterList typeParameterList = getTypeParameterList(); return typeParameterList != null && typeParameterList.getTypeParameters().length != 0; } public boolean isDeprecated() { Boolean cachedIsDeprecated = myCachedIsDeprecated; if (cachedIsDeprecated == null) { boolean deprecated; if (getTreeElement() != null) { PsiDocComment docComment = getDocComment(); deprecated = docComment != null && docComment.findTagByName("deprecated") != null; if (!deprecated) { PsiModifierList modifierList = getModifierList(); if (modifierList != null) { deprecated = modifierList.findAnnotation("java.lang.Deprecated") != null; } } } else { ClassView classView = getRepositoryManager().getClassView(); deprecated = classView.isDeprecated(getRepositoryId()); if (!deprecated && classView.mayBeDeprecatedByAnnotation(getRepositoryId())) { deprecated = getModifierList().findAnnotation("java.lang.Deprecated") != null; } } cachedIsDeprecated = myCachedIsDeprecated = deprecated ? Boolean.TRUE : Boolean.FALSE; } return cachedIsDeprecated.booleanValue(); } public PsiDocComment getDocComment(){ return (PsiDocComment)calcTreeElement().findChildByRoleAsPsiElement(ChildRole.DOC_COMMENT); } public PsiJavaToken getLBrace() { return (PsiJavaToken)calcTreeElement().findChildByRoleAsPsiElement(ChildRole.LBRACE); } public PsiJavaToken getRBrace() { return (PsiJavaToken)calcTreeElement().findChildByRoleAsPsiElement(ChildRole.RBRACE); } public boolean isInterface() { Boolean cachedIsInterface = myCachedIsInterface; if (cachedIsInterface == null) { boolean isInterface; if (getTreeElement() != null) { ASTNode keyword = calcTreeElement().findChildByRole(ChildRole.CLASS_OR_INTERFACE_KEYWORD); if (keyword.getElementType() == CLASS_KEYWORD) { isInterface = false; } else if (keyword.getElementType() == INTERFACE_KEYWORD) { isInterface = true; } else if (keyword.getElementType() == ENUM_KEYWORD) { isInterface = false; } else { LOG.assertTrue(false); isInterface = false; } } else { isInterface = getRepositoryManager().getClassView().isInterface(getRepositoryId()); } cachedIsInterface = myCachedIsInterface = isInterface ? Boolean.TRUE : Boolean.FALSE; } return cachedIsInterface.booleanValue(); } public boolean isAnnotationType() { Boolean cachedIsAnnotationType = myCachedIsAnnotationType; if (cachedIsAnnotationType == null) { boolean isAnnotationType = false; if (isInterface()) { if (getTreeElement() != null) { isAnnotationType = calcTreeElement().findChildByRole(ChildRole.AT) != null; } else { isAnnotationType = getRepositoryManager().getClassView().isAnnotationType(getRepositoryId()); } } cachedIsAnnotationType = myCachedIsAnnotationType = isAnnotationType ? Boolean.TRUE : Boolean.FALSE; } return cachedIsAnnotationType.booleanValue(); } public boolean isEnum() { Boolean cachedIsEnum = myCachedIsEnum; if (cachedIsEnum == null) { final boolean isEnum; if (getTreeElement() != null) { isEnum = ((ClassElement)getTreeElement()).isEnum(); } else { isEnum = getRepositoryManager().getClassView().isEnum(getRepositoryId()); } cachedIsEnum = myCachedIsEnum = Boolean.valueOf(isEnum); } return cachedIsEnum.booleanValue(); } public void accept(@NotNull PsiElementVisitor visitor){ visitor.visitClass(this); } public String toString(){ return "PsiClass:" + getName(); } public boolean processDeclarations(PsiScopeProcessor processor, PsiSubstitutor substitutor, PsiElement lastParent, PsiElement place) { if (isEnum()) { String name = getName(); if (name != null) { try { if (myValuesMethod == null || myValueOfMethod == null || !name.equals(myCachedForLongName)) { myCachedForLongName = name; final PsiMethod valuesMethod = getManager().getElementFactory().createMethodFromText("public static " + name + "[] values() {}", this); myValuesMethod = new LightMethod(getManager(), valuesMethod, this); final PsiMethod valueOfMethod = getManager().getElementFactory().createMethodFromText("public static " + name + " valueOf(String name) throws IllegalArgumentException {}", this); myValueOfMethod = new LightMethod(getManager(), valueOfMethod, this); } final NameHint hint = processor.getHint(NameHint.class); if (hint == null || VALUES_METHOD.equals(hint.getName())) { if (!processor.execute(myValuesMethod, PsiSubstitutor.EMPTY)) return false; } if (hint == null || VALUE_OF_METHOD.equals(hint.getName())) { if (!processor.execute(myValueOfMethod, PsiSubstitutor.EMPTY)) return false; } } catch (IncorrectOperationException e) { LOG.error(e); } } } return PsiClassImplUtil.processDeclarationsInClass(this, processor, substitutor, new HashSet<PsiClass>(), lastParent, place, false); } public PsiElement setName(@NotNull String newName) throws IncorrectOperationException{ String oldName = getName(); boolean isRenameFile = isRenameFileOnRenaming(); SharedPsiElementImplUtil.setName(getNameIdentifier(), newName); if (isRenameFile) { PsiFile file = (PsiFile)getParent(); String fileName = file.getName(); int dotIndex = fileName.lastIndexOf('.'); file.setName(dotIndex >= 0 ? newName + "." + fileName.substring(dotIndex + 1) : newName); } // rename constructors PsiMethod[] methods = getMethods(); for (PsiMethod method : methods) { if (method.isConstructor() && method.getName().equals(oldName)) { method.setName(newName); } } return this; } private boolean isRenameFileOnRenaming() { final PsiElement parent = getParent(); if (parent instanceof PsiFile) { PsiFile file = (PsiFile)parent; String fileName = file.getName(); if (fileName == null) return false; int dotIndex = fileName.lastIndexOf('.'); String name = dotIndex >= 0 ? fileName.substring(0, dotIndex) : fileName; String oldName = getName(); return name.equals(oldName); } else { return false; } } public PsiMetaData getMetaData(){ return MetaRegistry.getMeta(this); } public boolean isMetaEnough(){ return false; } // optimization to not load tree when resolving bases of anonymous and locals // if there is no local classes with such name in scope it's possible to use outer scope as context @Nullable protected PsiElement calcBasesResolveContext(String baseClassName, final PsiElement defaultResolveContext) { return calcBasesResolveContext(this, baseClassName, true, defaultResolveContext); } @Nullable private PsiElement calcBasesResolveContext(PsiClass aClass, String className, boolean isInitialClass, final PsiElement defaultResolveContext) { boolean isAnonOrLocal = false; if (aClass instanceof PsiAnonymousClass){ isAnonOrLocal = true; } else { long scopeId = ((PsiClassImpl)aClass).getParentId(); RepositoryElementType scopeType = myManager.getRepositoryManager().getElementType(scopeId); boolean isLocalClass = scopeType == RepositoryElementType.METHOD || scopeType == RepositoryElementType.FIELD || scopeType == RepositoryElementType.CLASS_INITIALIZER; if (isLocalClass){ isAnonOrLocal = true; } } if (!isAnonOrLocal) { return isInitialClass ? defaultResolveContext : aClass; } if (!isInitialClass){ if (aClass.findInnerClassByName(className, true) != null) return aClass; } long classId = ((RepositoryPsiElement)aClass).getRepositoryId(); RepositoryManager repositoryManager = myManager.getRepositoryManager(); long scopeId = repositoryManager.getClassView().getParent(classId); long[] classesInScope = repositoryManager.getItemView(scopeId).getChildren(scopeId, RepositoryElementType.CLASS); boolean needPreciseContext = false; if (classesInScope.length > 1){ for (long id : classesInScope) { if (id == classId) continue; String className1 = repositoryManager.getClassView().getName(id); if (className.equals(className1)) { needPreciseContext = true; break; } } } else{ LOG.assertTrue(classesInScope.length == 1); LOG.assertTrue(classesInScope[0] == classId); } if (needPreciseContext){ return aClass.getParent(); } else{ PsiElement context = myManager.getRepositoryElementsManager().findOrCreatePsiElementById(scopeId); if (context instanceof PsiClass){ return calcBasesResolveContext((PsiClass)context, className, false, defaultResolveContext); } else if (context instanceof PsiMember){ return calcBasesResolveContext(((PsiMember)context).getContainingClass(), className, false, defaultResolveContext); } else{ LOG.assertTrue(false); return context; } } } public boolean isInheritor(PsiClass baseClass, boolean checkDeep) { return InheritanceImplUtil.isInheritor(this, baseClass, checkDeep); } public boolean isInheritorDeep(PsiClass baseClass, PsiClass classToByPass) { return InheritanceImplUtil.isInheritorDeep(this, baseClass, classToByPass); } @Nullable public PomMemberOwner getPom() { //TODO: return null; } public ItemPresentation getPresentation() { return ClassPresentationUtil.getPresentation(this); } }
package imagej.script; import static org.junit.Assert.assertEquals; import java.io.StringReader; import org.junit.Test; import org.scijava.Context; import org.scijava.service.ServiceHelper; /** * Verifies that the Javascript support works as expected. * * @author Johannes Schindelin */ public class JavascriptTest { @Test public void testBasic() throws Exception { final Context context = new Context(ScriptService.class); final ScriptService scriptService = context.getService(ScriptService.class); new ServiceHelper(context).createExactService(DummyService.class); String script = "dummy = IJ.getService('imagej.script.DummyService');\n" + "dummy.context = IJ;\n" + "dummy.value = 1234;\n"; scriptService.eval("hello.js", new StringReader(script)); final DummyService dummy = context.getService(DummyService.class); assertEquals(context, dummy.context); assertEquals(1234, dummy.value); } }
package org.eigenbase.runtime; import java.io.InputStream; import java.io.Reader; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.math.BigDecimal; import java.net.URL; import java.sql.*; import java.sql.Date; import java.util.*; import org.eigenbase.util.Util; /** * A <code>IteratorResultSet</code> is an adapter which converts a {@link * java.util.Iterator} into a {@link java.sql.ResultSet}. * * <p> * See also its converse adapter, {@link ResultSetIterator} * </p> */ public class IteratorResultSet implements ResultSet { private final ColumnGetter columnGetter; private final Iterator iterator; private Object current; private int row; // 1-based (starts on 0 to represent before first row) private TimeoutQueueIterator timeoutIter; protected boolean wasNull; private long timeoutMillis; /** * Creates a result set based upon an iterator. The column-getter accesses * columns based upon their ordinal. * * @pre iterator != null */ public IteratorResultSet( Iterator iterator, ColumnGetter columnGetter) { Util.pre(iterator != null, "iterator != null"); this.iterator = iterator; String [] columnNames = columnGetter.getColumnNames(); this.columnGetter = columnGetter; } private String [] getColumnNames() { String [] columnNames = columnGetter.getColumnNames(); if (columnNames == null) { return Util.emptyStringArray; } else { return columnNames; } } /** * Sets the timeout that this IteratorResultSet will wait for a row from * the underlying iterator. * * @param timeoutMillis Timeout in milliseconds. Must be greater than zero. * @pre timeoutMillis > 0 * @pre this.timeoutMillis == 0 */ public void setTimeout(long timeoutMillis) { Util.pre(timeoutMillis > 0, "timeoutMillis > 0"); Util.pre(this.timeoutMillis == 0, "this.timeoutMillis == 0"); assert timeoutIter == null; // we create a new semaphore for each executeQuery call // and then pass ownership to the result set returned // the query timeout used is the last set via JDBC. this.timeoutMillis = timeoutMillis; timeoutIter = new TimeoutQueueIterator(iterator); timeoutIter.start(); } public boolean isAfterLast() throws SQLException { // TODO jvs 25-June-2005: make this return true after // next() returns false return false; } public Array getArray(int i) throws SQLException { throw new UnsupportedOperationException(); } public Array getArray(String colName) throws SQLException { throw new UnsupportedOperationException(); } public InputStream getAsciiStream(int columnIndex) throws SQLException { throw new UnsupportedOperationException(); } public InputStream getAsciiStream(String columnName) throws SQLException { throw new UnsupportedOperationException(); } public boolean isBeforeFirst() throws SQLException { // REVIEW jvs 25-June-2005: make this return false if there are // no rows? return row == 0; } public BigDecimal getBigDecimal( int columnIndex, int scale) throws SQLException { throw new UnsupportedOperationException(); } public BigDecimal getBigDecimal( String columnName, int scale) throws SQLException { throw new UnsupportedOperationException(); } public BigDecimal getBigDecimal(int columnIndex) throws SQLException { return BigDecimal.valueOf(toLong(getRaw(columnIndex))); } public BigDecimal getBigDecimal(String columnName) throws SQLException { return BigDecimal.valueOf(toLong(getRaw(columnName))); } public InputStream getBinaryStream(int columnIndex) throws SQLException { throw new UnsupportedOperationException(); } public InputStream getBinaryStream(String columnName) throws SQLException { throw new UnsupportedOperationException(); } public Blob getBlob(int i) throws SQLException { return null; } public Blob getBlob(String colName) throws SQLException { throw new UnsupportedOperationException(); } public boolean getBoolean(int columnIndex) throws SQLException { return toBoolean(getRaw(columnIndex)); } public boolean getBoolean(String columnName) throws SQLException { return toBoolean(getRaw(columnName)); } public byte getByte(int columnIndex) throws SQLException { return toByte(getRaw(columnIndex)); } public byte getByte(String columnName) throws SQLException { return toByte(getRaw(columnName)); } public byte [] getBytes(int columnIndex) throws SQLException { return (byte []) getRaw(columnIndex); } public byte [] getBytes(String columnName) throws SQLException { return (byte []) getRaw(columnName); } public Reader getCharacterStream(int columnIndex) throws SQLException { throw new UnsupportedOperationException(); } public Reader getCharacterStream(String columnName) throws SQLException { throw new UnsupportedOperationException(); } public Clob getClob(int i) throws SQLException { throw new UnsupportedOperationException(); } public Clob getClob(String colName) throws SQLException { throw new UnsupportedOperationException(); } public int getConcurrency() throws SQLException { return CONCUR_READ_ONLY; } public String getCursorName() throws SQLException { throw new UnsupportedOperationException(); } public Date getDate(int columnIndex) throws SQLException { return toDate(getRaw(columnIndex)); } public Date getDate(String columnName) throws SQLException { return toDate(getRaw(columnName)); } public Date getDate( int columnIndex, Calendar cal) throws SQLException { throw new UnsupportedOperationException(); } public Date getDate( String columnName, Calendar cal) throws SQLException { throw new UnsupportedOperationException(); } public double getDouble(int columnIndex) throws SQLException { return toDouble(getRaw(columnIndex)); } public double getDouble(String columnName) throws SQLException { return toDouble(getRaw(columnName)); } public void setFetchDirection(int direction) throws SQLException { if (direction != FETCH_FORWARD) { throw newDirectionError(); } } public int getFetchDirection() throws SQLException { return FETCH_FORWARD; } public void setFetchSize(int rows) throws SQLException { } public int getFetchSize() throws SQLException { return 0; } public boolean isFirst() throws SQLException { return row == 1; } public float getFloat(int columnIndex) throws SQLException { return toFloat(getRaw(columnIndex)); } public float getFloat(String columnName) throws SQLException { return toFloat(getRaw(columnName)); } public int getInt(int columnIndex) throws SQLException { return toInt(getRaw(columnIndex)); } public int getInt(String columnName) throws SQLException { return toInt(getRaw(columnName)); } public boolean isLast() throws SQLException { return false; } public long getLong(int columnIndex) throws SQLException { return toLong(getRaw(columnIndex)); } public long getLong(String columnName) throws SQLException { return toLong(getRaw(columnName)); } public ResultSetMetaData getMetaData() throws SQLException { return new MetaData(); } public Object getObject(int columnIndex) throws SQLException { Object o = getRaw(columnIndex); if (o == null) { wasNull = true; } else { wasNull = false; } return o; } public Object getObject(String columnName) throws SQLException { return getObject(findColumn(columnName)); } public Object getObject( int i, Map map) throws SQLException { throw new UnsupportedOperationException(); } public Object getObject( String colName, Map map) throws SQLException { throw new UnsupportedOperationException(); } public Ref getRef(int i) throws SQLException { throw new UnsupportedOperationException(); } public Ref getRef(String colName) throws SQLException { throw new UnsupportedOperationException(); } public int getRow() throws SQLException { return row; } public short getShort(int columnIndex) throws SQLException { return toShort(getRaw(columnIndex)); } public short getShort(String columnName) throws SQLException { return toShort(getRaw(columnName)); } public Statement getStatement() throws SQLException { return null; } public String getString(int columnIndex) throws SQLException { return toString(getRaw(columnIndex)); } public String getString(String columnName) throws SQLException { return toString(getRaw(columnName)); } public Time getTime(int columnIndex) throws SQLException { return toTime(getRaw(columnIndex)); } public Time getTime(String columnName) throws SQLException { return toTime(getRaw(columnName)); } public Time getTime( int columnIndex, Calendar cal) throws SQLException { throw new UnsupportedOperationException(); } public Time getTime( String columnName, Calendar cal) throws SQLException { throw new UnsupportedOperationException(); } public Timestamp getTimestamp(int columnIndex) throws SQLException { return toTimestamp(getRaw(columnIndex)); } public Timestamp getTimestamp(String columnName) throws SQLException { return toTimestamp(getRaw(columnName)); } public Timestamp getTimestamp( int columnIndex, Calendar cal) throws SQLException { throw new UnsupportedOperationException(); } public Timestamp getTimestamp( String columnName, Calendar cal) throws SQLException { throw new UnsupportedOperationException(); } public int getType() throws SQLException { return TYPE_FORWARD_ONLY; } public URL getURL(int columnIndex) throws SQLException { throw new UnsupportedOperationException(); } public URL getURL(String columnName) throws SQLException { throw new UnsupportedOperationException(); } public InputStream getUnicodeStream(int columnIndex) throws SQLException { throw new UnsupportedOperationException(); } public InputStream getUnicodeStream(String columnName) throws SQLException { throw new UnsupportedOperationException(); } public SQLWarning getWarnings() throws SQLException { return null; } public boolean absolute(int row) throws SQLException { if ((row < 1) || (getType() == TYPE_FORWARD_ONLY)) { throw newDirectionError(); } return relative(row - getRow()); } public void afterLast() throws SQLException { throw newDirectionError(); } public void beforeFirst() throws SQLException { throw newDirectionError(); } public void cancelRowUpdates() throws SQLException { throw newUpdatabilityError(); } public void clearWarnings() throws SQLException { } public void close() throws SQLException { if (timeoutIter != null) { final long noTimeout = 0; timeoutIter.close(noTimeout); timeoutIter = null; } } public void deleteRow() throws SQLException { throw newUpdatabilityError(); } public int findColumn(String columnName) throws SQLException { ResultSetMetaData metaData = getMetaData(); int n = metaData.getColumnCount(); for (int i = 1; i <= n; i++) { if (columnName.equals(metaData.getColumnName(i))) { return i; } } throw new SQLException("column '" + columnName + "' not found"); } public boolean first() throws SQLException { throw newDirectionError(); } public void insertRow() throws SQLException { throw newUpdatabilityError(); } public boolean last() throws SQLException { throw newDirectionError(); } public void moveToCurrentRow() throws SQLException { throw newUpdatabilityError(); } public void moveToInsertRow() throws SQLException { throw newUpdatabilityError(); } // the remaining methods implement ResultSet public boolean next() throws SQLException { if (timeoutIter != null) { try { long endTime = System.currentTimeMillis() + timeoutMillis; if (timeoutIter.hasNext(timeoutMillis)) { long remainingTimeout = endTime - System.currentTimeMillis(); if (remainingTimeout <= 0) { // The call to hasNext() took longer than we // expected -- we're out of time. throw new SqlTimeoutException(); } this.current = timeoutIter.next(remainingTimeout); this.row++; return true; } else { return false; } } catch (QueueIterator.TimeoutException e) { throw new SqlTimeoutException(); } catch (Throwable e) { throw newFetchError(e); } } else { try { if (iterator.hasNext()) { this.current = iterator.next(); this.row++; return true; } else { return false; } } catch (Throwable e) { throw newFetchError(e); } } } public boolean previous() throws SQLException { throw newDirectionError(); } public void refreshRow() throws SQLException { throw newUpdatabilityError(); } public boolean relative(int rows) throws SQLException { if ((rows < 0) || (getType() == TYPE_FORWARD_ONLY)) { throw newDirectionError(); } while (rows if (!next()) { return false; } } return true; } public boolean rowDeleted() throws SQLException { return false; } public boolean rowInserted() throws SQLException { return false; } public boolean rowUpdated() throws SQLException { return false; } public void updateArray( int columnIndex, Array x) throws SQLException { throw newUpdatabilityError(); } public void updateArray( String columnName, Array x) throws SQLException { throw newUpdatabilityError(); } public void updateAsciiStream( int columnIndex, InputStream x, int length) throws SQLException { throw newUpdatabilityError(); } public void updateAsciiStream( String columnName, InputStream x, int length) throws SQLException { throw newUpdatabilityError(); } public void updateBigDecimal( int columnIndex, BigDecimal x) throws SQLException { throw newUpdatabilityError(); } public void updateBigDecimal( String columnName, BigDecimal x) throws SQLException { throw newUpdatabilityError(); } public void updateBinaryStream( int columnIndex, InputStream x, int length) throws SQLException { throw newUpdatabilityError(); } public void updateBinaryStream( String columnName, InputStream x, int length) throws SQLException { throw newUpdatabilityError(); } public void updateBlob( int columnIndex, Blob x) throws SQLException { throw newUpdatabilityError(); } public void updateBlob( String columnName, Blob x) throws SQLException { throw newUpdatabilityError(); } public void updateBoolean( int columnIndex, boolean x) throws SQLException { throw newUpdatabilityError(); } public void updateBoolean( String columnName, boolean x) throws SQLException { throw newUpdatabilityError(); } public void updateByte( int columnIndex, byte x) throws SQLException { throw newUpdatabilityError(); } public void updateByte( String columnName, byte x) throws SQLException { throw newUpdatabilityError(); } public void updateBytes( int columnIndex, byte [] x) throws SQLException { throw newUpdatabilityError(); } public void updateBytes( String columnName, byte [] x) throws SQLException { throw newUpdatabilityError(); } public void updateCharacterStream( int columnIndex, Reader x, int length) throws SQLException { throw newUpdatabilityError(); } public void updateCharacterStream( String columnName, Reader reader, int length) throws SQLException { throw newUpdatabilityError(); } public void updateClob( int columnIndex, Clob x) throws SQLException { throw newUpdatabilityError(); } public void updateClob( String columnName, Clob x) throws SQLException { throw newUpdatabilityError(); } public void updateDate( int columnIndex, Date x) throws SQLException { throw newUpdatabilityError(); } public void updateDate( String columnName, Date x) throws SQLException { throw newUpdatabilityError(); } public void updateDouble( int columnIndex, double x) throws SQLException { throw newUpdatabilityError(); } public void updateDouble( String columnName, double x) throws SQLException { throw newUpdatabilityError(); } public void updateFloat( int columnIndex, float x) throws SQLException { throw newUpdatabilityError(); } public void updateFloat( String columnName, float x) throws SQLException { throw newUpdatabilityError(); } public void updateInt( int columnIndex, int x) throws SQLException { throw newUpdatabilityError(); } public void updateInt( String columnName, int x) throws SQLException { throw newUpdatabilityError(); } public void updateLong( int columnIndex, long x) throws SQLException { throw newUpdatabilityError(); } public void updateLong( String columnName, long x) throws SQLException { throw newUpdatabilityError(); } public void updateNull(int columnIndex) throws SQLException { throw newUpdatabilityError(); } public void updateNull(String columnName) throws SQLException { throw newUpdatabilityError(); } public void updateObject( int columnIndex, Object x, int scale) throws SQLException { throw newUpdatabilityError(); } public void updateObject( int columnIndex, Object x) throws SQLException { throw newUpdatabilityError(); } public void updateObject( String columnName, Object x, int scale) throws SQLException { throw newUpdatabilityError(); } public void updateObject( String columnName, Object x) throws SQLException { throw newUpdatabilityError(); } public void updateRef( int columnIndex, Ref x) throws SQLException { throw newUpdatabilityError(); } public void updateRef( String columnName, Ref x) throws SQLException { throw newUpdatabilityError(); } public void updateRow() throws SQLException { throw newUpdatabilityError(); } public void updateShort( int columnIndex, short x) throws SQLException { throw newUpdatabilityError(); } public void updateShort( String columnName, short x) throws SQLException { throw newUpdatabilityError(); } public void updateString( int columnIndex, String x) throws SQLException { throw newUpdatabilityError(); } public void updateString( String columnName, String x) throws SQLException { throw newUpdatabilityError(); } public void updateTime( int columnIndex, Time x) throws SQLException { throw newUpdatabilityError(); } public void updateTime( String columnName, Time x) throws SQLException { throw newUpdatabilityError(); } public void updateTimestamp( int columnIndex, Timestamp x) throws SQLException { throw newUpdatabilityError(); } public void updateTimestamp( String columnName, Timestamp x) throws SQLException { throw newUpdatabilityError(); } public boolean wasNull() throws SQLException { return wasNull; } /** * Returns the raw value of a column as an object. */ protected Object getRaw(int columnIndex) { return columnGetter.get(current, columnIndex); } protected Object getRaw(String columnName) throws SQLException { return getRaw(findColumn(columnName)); } private SQLException newConversionError( Object o, Class clazz) { return new SQLException("cannot convert " + o.getClass() + "(" + o + ") to " + clazz); } private SQLException newDirectionError() { return new SQLException("ResultSet is TYPE_FORWARD_ONLY"); } private SQLException newUpdatabilityError() { return new SQLException("ResultSet is CONCUR_READ_ONLY"); } private SQLException newFetchError(Throwable e) { final SQLException sqlEx = new SQLException("error while fetching from cursor"); if (e != null) { sqlEx.initCause(e); } return sqlEx; } private boolean toBoolean(Object o) throws SQLException { if (o == null) { wasNull = true; return false; } else { wasNull = false; } if (o instanceof Boolean) { return ((Boolean) o).booleanValue(); } else { long value = toLong(o); if (value > 0) { return true; } return false; //throw newConversionError(o,boolean.class); } } private byte toByte(Object o) throws SQLException { if (o == null) { wasNull = true; return 0; } else { wasNull = false; } if (o instanceof Byte) { return ((Byte) o).byteValue(); } else { return (byte) toLong_(o); } } private java.sql.Date toDate(Object o) throws SQLException { if (o == null) { wasNull = true; return null; } else { wasNull = false; } if (o instanceof java.sql.Date) { return (java.sql.Date) o; } else if (o instanceof java.util.Date) { return new java.sql.Date(((java.util.Date) o).getTime()); } else { throw newConversionError(o, java.sql.Date.class); } } private double toDouble(Object o) throws SQLException { if (o == null) { wasNull = true; return 0.0; } else { wasNull = false; } if (o instanceof Double) { return ((Double) o).doubleValue(); } else if (o instanceof Float) { return ((Float) o).doubleValue(); } else if (o instanceof String) { try { return Double.parseDouble(((String) o).trim()); } catch (NumberFormatException e) { throw new SQLException( "Fail to convert to internal representation"); } } else { return (double) toLong_(o); } } private float toFloat(Object o) throws SQLException { if (o == null) { wasNull = true; return (float) 0; } else { wasNull = false; } if (o instanceof Float) { return ((Float) o).floatValue(); } else if (o instanceof Double) { return ((Double) o).floatValue(); } else if (o instanceof String) { try { return Float.parseFloat(((String) o).trim()); } catch (NumberFormatException e) { throw new SQLException( "Fail to convert to internal representation"); } } else { return (float) toLong_(o); } } private int toInt(Object o) throws SQLException { if (o == null) { wasNull = true; return 0; } else { wasNull = false; } if (o instanceof Integer) { return ((Integer) o).intValue(); } else { return (int) toLong_(o); } } private long toLong(Object o) throws SQLException { if (o == null) { wasNull = true; return 0; } else { wasNull = false; } return toLong_(o); } private long toLong_(Object o) throws SQLException { if (o instanceof Long) { return ((Long) o).longValue(); } else if (o instanceof Integer) { return ((Integer) o).longValue(); } else if (o instanceof Short) { return ((Short) o).longValue(); } else if (o instanceof Character) { return ((Character) o).charValue(); } else if (o instanceof Byte) { return ((Byte) o).longValue(); } else if (o instanceof Double) { return ((Double) o).longValue(); } else if (o instanceof Float) { return ((Float) o).longValue(); } else if (o instanceof Boolean) { if (((Boolean) o).booleanValue()) { return 1; } else { return 0; } } else if (o instanceof String) { try { return Long.parseLong(((String) o).trim()); } catch (NumberFormatException e) { throw newConversionError(o, long.class); } } else { throw newConversionError(o, long.class); } } private short toShort(Object o) throws SQLException { if (o == null) { wasNull = true; return 0; } else { wasNull = false; } if (o instanceof Short) { return ((Short) o).shortValue(); } else { return (short) toLong_(o); } } private String toString(Object o) { if (o == null) { wasNull = true; return null; } else if (o instanceof byte []) { // convert to hex string return Util.toStringFromByteArray((byte []) o, 16); } else { wasNull = false; return o.toString(); } } private Time toTime(Object o) throws SQLException { if (o == null) { wasNull = true; return null; } else { wasNull = false; } if (o instanceof Time) { return (Time) o; } else { throw newConversionError(o, Time.class); } } private Timestamp toTimestamp(Object o) throws SQLException { if (o == null) { wasNull = true; return null; } else { wasNull = false; } if (o instanceof Timestamp) { return (Timestamp) o; } else { throw newConversionError(o, Timestamp.class); } } /** * A <code>ColumnGetter</code> retrieves a column from an input row based * upon its 1-based ordinal. */ public interface ColumnGetter { String [] getColumnNames(); Object get( Object o, int columnIndex); } /** * A <code>FieldGetter</code> retrieves each public field as a separate * column. */ public static class FieldGetter implements ColumnGetter { private static final Field [] emptyFieldArray = new Field[0]; private final Class clazz; private final Field [] fields; public FieldGetter(Class clazz) { this.clazz = clazz; this.fields = getFields(); } public String [] getColumnNames() { String [] columnNames = new String[fields.length]; for (int i = 0; i < fields.length; i++) { columnNames[i] = fields[i].getName(); } return columnNames; } public Object get( Object o, int columnIndex) { try { return fields[columnIndex - 1].get(o); } catch (IllegalArgumentException e) { throw Util.newInternal(e, "Error while retrieving field " + fields[columnIndex - 1]); } catch (IllegalAccessException e) { throw Util.newInternal(e, "Error while retrieving field " + fields[columnIndex - 1]); } } private Field [] getFields() { List list = new ArrayList(); final Field [] fields = clazz.getFields(); for (int i = 0; i < fields.length; i++) { Field field = fields[i]; if (Modifier.isPublic(field.getModifiers()) && !Modifier.isStatic(field.getModifiers())) { list.add(field); } } return (Field []) list.toArray(emptyFieldArray); } } // NOTE jvs 30-May-2003: I made this public because iSQL wanted it that // way for reflection. public class MetaData implements ResultSetMetaData { public boolean isAutoIncrement(int column) throws SQLException { return false; } public boolean isCaseSensitive(int column) throws SQLException { return false; } public String getCatalogName(int column) throws SQLException { return null; } public String getColumnClassName(int column) throws SQLException { return null; } public int getColumnCount() throws SQLException { return getColumnNames().length; } public int getColumnDisplaySize(int column) throws SQLException { return 0; } public String getColumnLabel(int column) throws SQLException { return getColumnName(column); } public String getColumnName(int column) throws SQLException { return getColumnNames()[column - 1]; } public int getColumnType(int column) throws SQLException { return 0; } public String getColumnTypeName(int column) throws SQLException { return null; } public boolean isCurrency(int column) throws SQLException { return false; } public boolean isDefinitelyWritable(int column) throws SQLException { return false; } public int isNullable(int column) throws SQLException { return 0; } public int getPrecision(int column) throws SQLException { return 0; } public boolean isReadOnly(int column) throws SQLException { return false; } public int getScale(int column) throws SQLException { return 0; } public String getSchemaName(int column) throws SQLException { return null; } public boolean isSearchable(int column) throws SQLException { return false; } public boolean isSigned(int column) throws SQLException { return false; } public String getTableName(int column) throws SQLException { return null; } public boolean isWritable(int column) throws SQLException { return false; } } /** * A <code>SingletonColumnGetter</code> retrieves the object itself. */ public static class SingletonColumnGetter implements ColumnGetter { public SingletonColumnGetter() { } public String [] getColumnNames() { return new String [] { "column0" }; } public Object get( Object o, int columnIndex) { assert (columnIndex == 1); return o; } } /** * A <code>SyntheticColumnGetter</code> retrieves columns from a synthetic * object. */ public static class SyntheticColumnGetter implements ColumnGetter { String [] columnNames; Field [] fields; public SyntheticColumnGetter(Class clazz) { assert (SyntheticObject.class.isAssignableFrom(clazz)); this.fields = clazz.getFields(); this.columnNames = new String[fields.length]; for (int i = 0; i < fields.length; i++) { columnNames[i] = fields[i].getName(); } } public String [] getColumnNames() { return columnNames; } public Object get( Object o, int columnIndex) { try { return fields[columnIndex - 1].get(o); } catch (IllegalArgumentException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } } } /** * Indicates that an operation timed out. This is not an error; you can * retry the operation. */ public static class SqlTimeoutException extends SQLException { SqlTimeoutException() { // SQLException(reason, SQLState, vendorCode) // REVIEW mb 19-Jul-05 Is there a standard SQLState? super("timeout", null, 0); } } } // End IteratorResultSet.java
package com.intellij.util.xml.impl; import com.intellij.openapi.components.ProjectComponent; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Key; import com.intellij.pom.PomModel; import com.intellij.pom.PomModelAspect; import com.intellij.pom.event.PomModelEvent; import com.intellij.pom.event.PomModelListener; import com.intellij.pom.xml.XmlAspect; import com.intellij.pom.xml.XmlChangeSet; import com.intellij.psi.PsiLock; import com.intellij.psi.PsiElement; import com.intellij.psi.xml.XmlElement; import com.intellij.psi.xml.XmlFile; import com.intellij.psi.xml.XmlTag; import com.intellij.util.xml.*; import com.intellij.util.xml.events.DomEvent; import com.intellij.util.xml.reflect.DomChildrenDescription; import com.intellij.util.Function; import net.sf.cglib.core.CodeGenerationException; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.*; /** * @author peter */ public class DomManagerImpl extends DomManager implements ProjectComponent { private static final Key<DomNameStrategy> NAME_STRATEGY_KEY = Key.create("NameStrategy"); private static final Key<DomInvocationHandler> CACHED_HANDLER = Key.create("CachedInvocationHandler"); private static final Key<DomFileElementImpl> CACHED_FILE_ELEMENT = Key.create("CachedFileElement"); private final List<DomEventListener> myListeners = new ArrayList<DomEventListener>(); private final ConverterManagerImpl myConverterManager = new ConverterManagerImpl(); private final Map<Type, GenericInfoImpl> myMethodsMaps = new HashMap<Type, GenericInfoImpl>(); private final Map<Type, InvocationCache> myInvocationCaches = new HashMap<Type, InvocationCache>(); private final Map<Class<? extends DomElement>, Class<? extends DomElement>> myImplementationClasses = new HashMap<Class<? extends DomElement>, Class<? extends DomElement>>(); private final List<Function<DomElement, Collection<PsiElement>>> myPsiElementProviders = new ArrayList<Function<DomElement, Collection<PsiElement>>>(); private DomEventListener[] myCachedListeners; private PomModelListener myXmlListener; private Project myProject; private PomModel myPomModel; private boolean myChanging; public DomManagerImpl(final PomModel pomModel, final Project project) { myPomModel = pomModel; myProject = project; final XmlAspect xmlAspect = myPomModel.getModelAspect(XmlAspect.class); assert xmlAspect != null; myXmlListener = new PomModelListener() { public synchronized void modelChanged(PomModelEvent event) { if (myChanging) return; final XmlChangeSet changeSet = (XmlChangeSet)event.getChangeSet(xmlAspect); if (changeSet != null) { new ExternalChangeProcessor(changeSet).processChanges(); } } public boolean isAspectChangeInteresting(PomModelAspect aspect) { return xmlAspect.equals(aspect); } }; } public final void addDomEventListener(DomEventListener listener) { myCachedListeners = null; myListeners.add(listener); } public final void removeDomEventListener(DomEventListener listener) { myCachedListeners = null; myListeners.remove(listener); } public final ConverterManagerImpl getConverterManager() { return myConverterManager; } protected final void fireEvent(DomEvent event) { DomEventListener[] listeners = myCachedListeners; if (listeners == null) { listeners = myCachedListeners = myListeners.toArray(new DomEventListener[myListeners.size()]); } for (DomEventListener listener : listeners) { listener.eventOccured(event); } } public final GenericInfoImpl getGenericInfo(final Type type) { GenericInfoImpl genericInfoImpl = myMethodsMaps.get(type); if (genericInfoImpl == null) { if (type instanceof Class) { genericInfoImpl = new GenericInfoImpl((Class<? extends DomElement>)type, this); myMethodsMaps.put(type, genericInfoImpl); } else if (type instanceof ParameterizedType) { ParameterizedType parameterizedType = (ParameterizedType)type; genericInfoImpl = new GenericInfoImpl((Class<? extends DomElement>)parameterizedType.getRawType(), this); myMethodsMaps.put(type, genericInfoImpl); } else { assert false : "Type not supported " + type; } } return genericInfoImpl; } final InvocationCache getInvocationCache(final Type type) { InvocationCache invocationCache = myInvocationCaches.get(type); if (invocationCache == null) { invocationCache = new InvocationCache(); myInvocationCaches.put(type, invocationCache); } return invocationCache; } public static DomInvocationHandler getDomInvocationHandler(DomElement proxy) { return (DomInvocationHandler)AdvancedProxy.getInvocationHandler(proxy); } final DomElement createDomElement(final DomInvocationHandler handler) { synchronized (PsiLock.LOCK) { try { XmlTag tag = handler.getXmlTag(); final Class abstractInterface = DomUtil.getRawType(handler.getDomElementType()); final ClassChooser<? extends DomElement> classChooser = ClassChooserManager.getClassChooser(abstractInterface); final Class<? extends DomElement> concreteInterface = classChooser.chooseClass(tag); final DomElement element = doCreateDomElement(concreteInterface, handler); if (concreteInterface != abstractInterface) { handler.setType(concreteInterface); } handler.setProxy(element); handler.attach(tag); return element; } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new CodeGenerationException(e); } } } private DomElement doCreateDomElement(final Class<? extends DomElement> concreteInterface, final DomInvocationHandler handler) { final Class<? extends DomElement> aClass = getImplementation(concreteInterface); if (aClass != null) { return AdvancedProxy.createProxy(aClass, new Class[]{concreteInterface}, handler, Collections.<JavaMethodSignature>emptySet()); } return AdvancedProxy.createProxy(handler, concreteInterface); } @Nullable Class<? extends DomElement> getImplementation(final Class<? extends DomElement> concreteInterface) { final Class<? extends DomElement> registeredImplementation = findImplementationClassDFS(concreteInterface); if (registeredImplementation != null) { return registeredImplementation; } final Implementation implementation = DomUtil.findAnnotationDFS(concreteInterface, Implementation.class); return implementation == null ? null : implementation.value(); } private Class<? extends DomElement> findImplementationClassDFS(final Class<? extends DomElement> concreteInterface) { Class<? extends DomElement> aClass = myImplementationClasses.get(concreteInterface); if (aClass != null) { return aClass; } for (final Class aClass1 : concreteInterface.getInterfaces()) { aClass = findImplementationClassDFS(aClass1); if (aClass != null) { return aClass; } } return null; } public final Project getProject() { return myProject; } public static void setNameStrategy(final XmlFile file, final DomNameStrategy strategy) { file.putUserData(NAME_STRATEGY_KEY, strategy); } @NotNull public final <T extends DomElement> DomFileElementImpl<T> getFileElement(final XmlFile file, final Class<T> aClass, String rootTagName) { synchronized (PsiLock.LOCK) { DomFileElementImpl<T> element = getCachedElement(file); if (element == null) { element = new DomFileElementImpl<T>(file, aClass, rootTagName, this); setCachedElement(file, element); } return element; } } protected static void setCachedElement(final XmlFile file, final DomFileElementImpl element) { file.putUserData(CACHED_FILE_ELEMENT, element); } protected static void setCachedElement(final XmlTag tag, final DomInvocationHandler element) { if (tag != null) { tag.putUserData(CACHED_HANDLER, element); } } @Nullable public static DomFileElementImpl getCachedElement(final XmlFile file) { return file != null ? file.getUserData(CACHED_FILE_ELEMENT) : null; } @Nullable public static DomInvocationHandler getCachedElement(final XmlElement xmlElement) { return xmlElement.getUserData(CACHED_HANDLER); } @NonNls public final String getComponentName() { return getClass().getName(); } public final synchronized boolean setChanging(final boolean changing) { boolean oldChanging = myChanging; myChanging = changing; return oldChanging; } public final boolean isChanging() { return myChanging; } public final void initComponent() { } public final void disposeComponent() { } public final void projectOpened() { myPomModel.addModelListener(myXmlListener); } public final void projectClosed() { myPomModel.removeModelListener(myXmlListener); } public <T extends DomElement> void registerImplementation(Class<T> domElementClass, Class<? extends T> implementationClass) { assert domElementClass.isAssignableFrom(implementationClass); myImplementationClasses.put(domElementClass, implementationClass); } public DomElement getDomElement(final XmlTag tag) { final DomInvocationHandler handler = _getDomElement(tag); return handler != null ? handler.getProxy() : null; } public void registerPsiElementProvider(Function<DomElement, Collection<PsiElement>> provider) { myPsiElementProviders.add(provider); } public void unregisterPsiElementProvider(Function<DomElement, Collection<PsiElement>> provider) { myPsiElementProviders.remove(provider); } @Nullable private static DomInvocationHandler _getDomElement(final XmlTag tag) { if (tag == null) return null; DomInvocationHandler invocationHandler = getCachedElement(tag); if (invocationHandler != null && invocationHandler.isValid()) { return invocationHandler; } final XmlTag parentTag = tag.getParentTag(); if (parentTag == null) { final XmlFile xmlFile = (XmlFile)tag.getContainingFile(); if (xmlFile != null) { final DomFileElementImpl element = getCachedElement(xmlFile); if (element != null) { return element.getRootHandler(); } } return null; } DomInvocationHandler parent = _getDomElement(parentTag); if (parent == null) return null; final GenericInfoImpl info = parent.getGenericInfo(); final String tagName = tag.getName(); final DomChildrenDescription childDescription = info.getChildDescription(tagName); if (childDescription == null) return null; childDescription.getValues(parent.getProxy()); return getCachedElement(tag); } }
package com.smeanox.games.sg002.world; import com.badlogic.gdx.graphics.Texture; import java.util.Collection; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * @author Fabian Lyck */ public class MapObjectType { private static Map<String, MapObjectType> idmap = new HashMap<String, MapObjectType>(); private static MapObjectType defaultMapObjectType; // field without anything special(i.e. gold) private Texture texture; private String textureName; private Set<GameObjectType> allowedGameObjectTypes; public final String id; /** * Create a new instance * * @param textureName the name of the texture to use * @param id id of this type * @param allowedGameObjectTypes Set of all allowed GameObjectTypes on this typo of MapObject */ public MapObjectType(String textureName, String id, Set<GameObjectType> allowedGameObjectTypes) { this.id = id; this.textureName = textureName; this.allowedGameObjectTypes = allowedGameObjectTypes; idmap.put(id, this); } public String getTextureName() { System.out.println(textureName); return textureName; } public void setTexture(Texture texture) { this.texture = texture; } public Texture getTexture() { return texture; } /** * Checks whether a gameObjectType is allowed to be placed on this map tile * * @param gameObjectType the GameObjectType to check * @return true if it is allowed */ public boolean isGameObjectTypeAllowed(GameObjectType gameObjectType) { return allowedGameObjectTypes.contains(gameObjectType); } /** * Returns all gameObjectTypes which are allowed to be placed on this map tile * * @return collection of allowed gameObjectTypes, direct reference - DO NOT MODIFY */ public Collection<GameObjectType> getAllowedGameObjectTypes() { return allowedGameObjectTypes; } /** * Get a specific MapObjectType identified by their Id * * @param id id of the MapObjectType * @return the MapObjectType or null if it doesn't exist */ public static MapObjectType getMapObjectTypeById(String id) { return idmap.get(id); } /** * get all loaded mapObjectTypes * * @return Collection of mapObjectTypes */ public static Collection<MapObjectType> getMapObjectTypes() { return idmap.values(); } /** * set the mapobjecttype which will be used for all fields which are non-special(i.e. no gold) * @param mot */ public static void setDefaultMapObjectType(MapObjectType mot) { defaultMapObjectType = mot; } /** * get the mapobjecttype which will be used for all fields which are non-special(i.e. no gold) */ public static MapObjectType getDefaultMapObjectType() { return defaultMapObjectType; } }