answer
stringlengths
17
10.2M
package de.thischwa.pmcms.tool; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; import de.thischwa.pmcms.Constants; import de.thischwa.pmcms.configuration.BasicConfigurator; import de.thischwa.pmcms.configuration.InitializationManager; import de.thischwa.pmcms.tool.DESCryptor; import static org.junit.Assert.*; public class TestDESCryptor { private static DESCryptor cryptor; @BeforeClass public static void init() { InitializationManager.start(new BasicConfigurator(Constants.APPLICATION_DIR), false); cryptor = new DESCryptor(InitializationManager.getProperty("pmcms.crypt.key")); } @AfterClass public static void shutDown() { InitializationManager.end(); } @Test public final void testCrypt() throws Exception { String plain = "some text"; String encrypted = cryptor.encrypt(plain); String actual = cryptor.decrypt(encrypted); assertEquals(plain, actual); } }
package application; import java.util.ArrayList; import javafx.scene.paint.Color; public class AntCell extends Cell { private boolean hasFoodItem = false; private int homePheromones; private int foodPheromones; private AntCell ; private AntCell foodPile; @Override public void updateCell(int i, int j, Cell[][] cellMatrix) { xPos = i; yPos = j; Matrix = cellMatrix; } private void antForage() { if (currentState == Color.RED) { updatedState = Color.RED; } else if (currentState == Color.GREEN) { updatedState = Color.GREEN; } else if (hasFoodItem) { returnToNest(); } else { findFoodSource(); } } private void returnToNest() { AntCell foodCell = findParticularCell(Color.GREEN); if (foodCell == null) { } } private void findFoodSource() { AntCell foodCell = findParticularCell(Color.GREEN); if (foodCell == null) { } } private Cell findNeighbors (Color color){ ArrayList<AntCell> list = new ArrayList<AntCell>(); for(int i = xPos-1; i <= xPos+1; i++){ for(int j = yPos-1; j <= yPos+1; j++){ if (Matrix[i][j].currentState == color) { return Matrix[i][j]; } } } return null; } private AntCell findParticularCell(Color color) { } private boolean checkBounds(int i, int j){ return (i < ApplicationConstants.NUM_OF_COLUMNS && i >= 0 && j < ApplicationConstants.NUM_OF_ROWS && j >= 0); } @Override void setCurrentState(String s) { // TODO Auto-generated method stub } }
package bio.terra.integration; import bio.terra.category.Integration; import bio.terra.model.DatasetSummaryModel; import bio.terra.model.IngestResponseModel; import bio.terra.model.StudySummaryModel; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringRunner; import java.util.ArrayList; import java.util.List; import static org.hamcrest.Matchers.equalTo; import static org.junit.Assert.assertThat; @RunWith(SpringRunner.class) @SpringBootTest @ActiveProfiles({"google", "integrationtest"}) @Category(Integration.class) public class IngestTest extends UsersBase { @Autowired private DataRepoFixtures dataRepoFixtures; private StudySummaryModel studySummaryModel; private String studyId; private List<String> createdDatasetIds = new ArrayList<>(); @Before public void setup() throws Exception { super.setup(); studySummaryModel = dataRepoFixtures.createStudy(steward(), "ingest-test-study.json"); studyId = studySummaryModel.getId(); } @After public void teardown() throws Exception { for (String datasetId : createdDatasetIds) { dataRepoFixtures.deleteDataset(custodian(), datasetId); } if (studyId != null) { dataRepoFixtures.deleteStudy(steward(), studyId); } } @Ignore // subset of the dataset test; not worth running everytime, but useful for debugging @Test public void ingestParticipants() throws Exception { IngestResponseModel ingestResponse = dataRepoFixtures.ingestJsonData( steward(), studyId, "participant", "ingest-test/ingest-test-participant.json"); assertThat("correct participant row count", ingestResponse.getRowCount(), equalTo(5L)); } @Test public void ingestBuildDataset() throws Exception { IngestResponseModel ingestResponse = dataRepoFixtures.ingestJsonData( steward(), studyId, "participant", "ingest-test/ingest-test-participant.json"); assertThat("correct participant row count", ingestResponse.getRowCount(), equalTo(5L)); ingestResponse = dataRepoFixtures.ingestJsonData( steward(), studyId, "sample", "ingest-test/ingest-test-sample.json"); assertThat("correct sample row count", ingestResponse.getRowCount(), equalTo(7L)); ingestResponse = dataRepoFixtures.ingestJsonData( steward(), studyId, "file", "ingest-test/ingest-test-file.json"); assertThat("correct file row count", ingestResponse.getRowCount(), equalTo(1L)); DatasetSummaryModel datasetSummary = dataRepoFixtures.createDataset(custodian(), studySummaryModel, "ingest-test-dataset.json"); createdDatasetIds.add(datasetSummary.getId()); } }
package net.tomp2p.p2p.builder; import java.util.Collection; import java.util.concurrent.atomic.AtomicReferenceArray; import net.tomp2p.connection.DefaultConnectionConfiguration; import net.tomp2p.futures.FutureResponse; import net.tomp2p.futures.FutureRouting; import net.tomp2p.p2p.RoutingMechanism; import net.tomp2p.peers.Number160; import net.tomp2p.peers.Number640; import net.tomp2p.peers.PeerFilter; import net.tomp2p.rpc.NeighborRPC.SearchValues; import net.tomp2p.rpc.SimpleBloomFilter; public class RoutingBuilder extends DefaultConnectionConfiguration { private Number160 locationKey; private Number160 domainKey; private Number160 contentKey; private SimpleBloomFilter<Number160> keyBloomFilter; private SimpleBloomFilter<Number160> contentBloomFilter; private Number640 from; private Number640 to; private Collection<PeerFilter> peerFilters; private int maxDirectHits; private int maxNoNewInfo; private int maxFailures; private int maxSuccess; private int parallel; private boolean isBootstrap; private boolean isForceRoutingOnlyToSelf; private boolean isRoutingToOthers; public Number160 locationKey() { return locationKey; } public Number160 domainKey() { return domainKey; } /** * number of direct hits to stop at * * @return */ public int maxDirectHits() { return maxDirectHits; } public void setMaxDirectHits(int maxDirectHits) { this.maxDirectHits = maxDirectHits; } public int maxNoNewInfo() { return maxNoNewInfo; } public void setMaxNoNewInfo(int maxNoNewInfo) { this.maxNoNewInfo = maxNoNewInfo; } public int maxFailures() { return maxFailures; } public void setMaxFailures(int maxFailures) { this.maxFailures = maxFailures; } public int maxSuccess() { return maxSuccess; } public void setMaxSuccess(int maxSuccess) { this.maxSuccess = maxSuccess; } public int parallel() { return parallel; } public void setParallel(int parallel) { this.parallel = parallel; } public boolean isBootstrap() { return isBootstrap; } public void setBootstrap(boolean isBootstrap) { this.isBootstrap = isBootstrap; } public boolean isForceRoutingOnlyToSelf() { return isForceRoutingOnlyToSelf; } public void setIsForceRoutingOnlyToSelf(boolean isForceRoutingOnlyToSelf) { this.isForceRoutingOnlyToSelf = isForceRoutingOnlyToSelf; } public void setLocationKey(Number160 locationKey) { this.locationKey = locationKey; } public void setDomainKey(Number160 domainKey) { this.domainKey = domainKey; } public RoutingBuilder peerFilters(Collection<PeerFilter> peerFilters) { this.peerFilters = peerFilters; return this; } public Collection<PeerFilter> peerFilters() { return peerFilters; } /** * @return The search values for the neighbor request, or null if no content key is specified */ public SearchValues searchValues() { if (contentKey() != null) { return new SearchValues(locationKey, domainKey, contentKey()); } if(from !=null && to!=null) { return new SearchValues(locationKey, domainKey, from, to); } if (contentBloomFilter() == null && keyBloomFilter() != null) { return new SearchValues(locationKey, domainKey, keyBloomFilter()); } if (contentBloomFilter() != null && keyBloomFilter() != null) { return new SearchValues(locationKey, domainKey, keyBloomFilter(), contentBloomFilter()); } return new SearchValues(locationKey, domainKey); } public RoutingBuilder routingOnlyToSelf(boolean isRoutingOnlyToSelf) { this.isRoutingToOthers = !isRoutingOnlyToSelf; return this; } public boolean isRoutingToOthers() { return isRoutingToOthers; } public Number160 contentKey() { return contentKey; } public void setContentKey(Number160 contentKey) { this.contentKey = contentKey; } public SimpleBloomFilter<Number160> contentBloomFilter() { return contentBloomFilter; } public void setContentBloomFilter(SimpleBloomFilter<Number160> contentBloomFilter) { this.contentBloomFilter = contentBloomFilter; } public SimpleBloomFilter<Number160> keyBloomFilter() { return keyBloomFilter; } public void setKeyBloomFilter(SimpleBloomFilter<Number160> keyBloomFilter) { this.keyBloomFilter = keyBloomFilter; } public RoutingMechanism createRoutingMechanism(FutureRouting futureRouting) { final FutureResponse[] futureResponses = new FutureResponse[parallel()]; RoutingMechanism routingMechanism = new RoutingMechanism( new AtomicReferenceArray<FutureResponse>(futureResponses), futureRouting, peerFilters); routingMechanism.maxDirectHits(maxDirectHits()); routingMechanism.maxFailures(maxFailures()); routingMechanism.maxNoNewInfo(maxNoNewInfo()); routingMechanism.maxSucess(maxSuccess()); return routingMechanism; } public void setRange(Number640 from, Number640 to) { this.from = from; this.to = to; } public Number640 from() { return from; } public Number640 to() { return to; } }
package ch.bind.philib.io; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertTrue; import static junit.framework.Assert.fail; import java.util.Arrays; import java.util.LinkedList; import java.util.List; import java.util.Random; import org.junit.Test; public class RingBufferTest { private final Random rand = new Random(); private static final int MB = 1024 * 1024; private static final long GB = 1024 * MB; private static final int TEST_BUF_SIZE = 1 * MB; private static final int RANDOM_TEST_SIZE = 16 * MB; private static final int RANDOM_TEST_MAX_BUF_SIZE = 4 * MB; private static final int RANDOM_TEST_MAX_CHUNK_SIZE = 256; private static final long PERF_SIZE = 4 * GB; private static final int PERF_CHUNKSIZE = 4096; private static final int PERF_MAX_BUFSIZE = 64 * MB; @Test public void frontAndBack() { LinkedList<byte[]> bufExp = new LinkedList<byte[]>(); RingBuffer buf = new RingBuffer(); assertEquals(0, buf.available()); final int chunkSize = 16; int chunkIdx = 0; int size = 0; while (size < TEST_BUF_SIZE) { byte[] d = genData(chunkSize); if (chunkIdx % 2 == 0) { buf.write(d); bufExp.addLast(d); } else { buf.writeFront(d); bufExp.addFirst(d); } size += chunkSize; assertEquals(size, buf.available()); chunkIdx++; } verifyBuf(bufExp, buf); } @Test public void randomAccess() { LinkedList<Byte> bufExp = new LinkedList<Byte>(); RingBuffer ringBuf = new RingBuffer(); int size = 0; long performed = 0; while (performed < RANDOM_TEST_SIZE) { int len = rand.nextInt(RANDOM_TEST_MAX_CHUNK_SIZE) + 1; byte[] buf = new byte[len]; int a = ringBuf.available(); boolean doRead = a >= len ? rand.nextBoolean() : false; if (!doRead && a + len > RANDOM_TEST_MAX_BUF_SIZE) { doRead = true; } boolean doFront = rand.nextBoolean(); if (doRead) { if (doFront) { ringBuf.read(buf); verifyRead(buf, bufExp); } else { ringBuf.readBack(buf); verifyReadBack(buf, bufExp); } size -= len; } else { rand.nextBytes(buf); if (doFront) { ringBuf.writeFront(buf); prepend(buf, bufExp); } else { ringBuf.write(buf); append(buf, bufExp); } size += len; } assertEquals(size, ringBuf.available()); assertEquals(size, bufExp.size()); performed += len; } } @Test public void perfTest() { final long start = System.currentTimeMillis(); RingBuffer ringBuf = new RingBuffer(); byte[] buf = new byte[PERF_CHUNKSIZE]; rand.nextBytes(buf); long performed = 0; while (performed < PERF_SIZE) { ringBuf.write(buf); ringBuf.writeFront(buf); ringBuf.read(buf); ringBuf.writeFront(buf); ringBuf.readBack(buf); ringBuf.write(buf); ringBuf.read(buf); ringBuf.writeFront(buf); ringBuf.readBack(buf); ringBuf.read(buf); performed += (PERF_CHUNKSIZE * 10); assertEquals(0, ringBuf.available()); } final long time = System.currentTimeMillis() - start; double mb = (double) (performed / MB); double mbPerSec = mb / (time / 1000f); System.out.printf("%s - %d MB in %dms = %.1fMB/s%n", getClass().getSimpleName(), performed / MB, time, mbPerSec); } private void verifyReadBack(byte[] bs, LinkedList<Byte> bufExp) { for (int i = bs.length - 1; i >= 0; i byte b = bs[i]; byte e = bufExp.removeLast(); assertEquals(e, b); } } private void verifyRead(byte[] bs, LinkedList<Byte> bufExp) { for (byte b : bs) { byte e = bufExp.removeFirst(); assertEquals(e, b); } } private void prepend(byte[] bs, LinkedList<Byte> bufExp) { for (int i = bs.length - 1; i >= 0; i bufExp.addFirst(bs[i]); } } private void append(byte[] bs, LinkedList<Byte> bufExp) { for (byte b : bs) { bufExp.add(b); } } @Test(expected = IllegalArgumentException.class) public void notNullRead() { RingBuffer buf = new RingBuffer(); buf.read(null); } @Test(expected = IllegalArgumentException.class) public void notNullReadOffLen() { RingBuffer buf = new RingBuffer(); buf.read(null, 0, 0); } @Test(expected = IllegalArgumentException.class) public void notNegativeOffsetRead() { RingBuffer buf = new RingBuffer(); byte[] b = new byte[16]; buf.write(b); buf.read(b, -1, 16); } @Test(expected = IllegalArgumentException.class) public void notNegativeLengthRead() { RingBuffer buf = new RingBuffer(); byte[] b = new byte[16]; buf.write(b); buf.read(b, 0, -1); } @Test(expected = IllegalArgumentException.class) public void tooBigReadForInbuf() { RingBuffer buf = new RingBuffer(); byte[] b = new byte[16]; buf.write(b); buf.write(b); assertEquals(32, buf.available()); buf.read(b, 0, 17); // too big read } @Test(expected = IllegalArgumentException.class) public void tooBigWriteForOutbuf() { RingBuffer buf = new RingBuffer(); byte[] b = new byte[16]; buf.write(b, 0, 17); // too big write } @Test public void tooBigReadForBuf() { RingBuffer buf = new RingBuffer(); byte[] b = new byte[16]; buf.write(b, 0, 8); // 8 bytes in buffer try { buf.read(b, 0, 9); // try to read too much fail("should have thrown an illegal-argument-exc"); } catch (IllegalArgumentException e) { // expected } } @Test public void clear() { RingBuffer buf = new RingBuffer(); byte[] a = { 0, 1, 2, 3 }; buf.write(a); assertEquals(a.length, buf.available()); buf.clear(); assertEquals(0, buf.available()); } private void verifyBuf(List<byte[]> expected, RingBuffer buf) { byte[] a = null; int expSize = buf.available(); for (byte[] e : expected) { if (a == null || a.length != e.length) { a = new byte[e.length]; } assertEquals(expSize, buf.available()); buf.read(a); expSize -= a.length; assertTrue(Arrays.equals(e, a)); assertEquals(expSize, buf.available()); } assertEquals(0, buf.available()); } private byte[] genData(int num) { byte[] d = new byte[num]; rand.nextBytes(d); return d; } }
package edu.wustl.common.security; import java.util.Vector; import edu.wustl.common.security.exceptions.SMException; import edu.wustl.common.security.exceptions.SMTransactionException; import edu.wustl.common.util.logger.Logger; import gov.nih.nci.security.AuthenticationManager; import gov.nih.nci.security.AuthorizationManager; import gov.nih.nci.security.SecurityServiceProvider; import gov.nih.nci.security.UserProvisioningManager; import gov.nih.nci.security.authorization.domainobjects.User; import gov.nih.nci.security.exceptions.CSException; import gov.nih.nci.security.exceptions.CSTransactionException; public class SecurityManager { private static AuthenticationManager authenticationManager = null; private static AuthorizationManager authorizationManager = null; private Class requestingClass=null; private static final String CATISSUE_CORE_CONTEXT_NAME = "catissuecore"; private static final String ADMINISTRATOR_ROLE="1"; private static final String SUPERVISOR_ROLE="2"; private static final String TECHNICIAN_ROLE="3"; private static final String ADMINISTRATOR_GROUP="ADMINISTRATOR_GROUP"; private static final String SUPERVISOR_GROUP="SUPERVISOR_GROUP"; private static final String TECHNICIAN_GROUP="TECHNICIAN_GROUP"; /** * @param class1 */ public SecurityManager(Class class1) { requestingClass = class1; } /** * @param class1 * @return */ public static SecurityManager getInstance(Class class1) { return new SecurityManager(class1); } /** * Returns the AuthenticationManager for the caTISSUE Core. This method follows the * singleton pattern so that only one AuthenticationManager is created for * the caTISSUE Core. * * @return * @throws CSException */ protected AuthenticationManager getAuthenticationManager() throws CSException { if (authenticationManager == null) { synchronized (requestingClass) { if (authenticationManager == null) { authenticationManager = SecurityServiceProvider .getAuthenticationManager(CATISSUE_CORE_CONTEXT_NAME); } } } return authenticationManager; } /** * Returns the Authorization Manager for the caTISSUE Core. * This method follows the singleton pattern so that * only one AuthorizationManager is created. * * @return * @throws CSException */ protected AuthorizationManager getAuthorizationManager() throws CSException { if (authorizationManager == null) { synchronized (requestingClass) { if (authorizationManager == null) { authorizationManager = SecurityServiceProvider .getAuthorizationManager(CATISSUE_CORE_CONTEXT_NAME); } } } return authorizationManager; } /** * Returns the UserProvisioningManager singleton object. * * @return * @throws CSException */ protected UserProvisioningManager getUserProvisioningManager() throws CSException { return (UserProvisioningManager) getAuthorizationManager(); } /** * Returns true or false depending on the person gets authenticated or not. * @param requestingClass * @param loginName login name * @param password password * @return * @throws CSException */ public boolean login(String loginName, String password) throws SMException { boolean loginSuccess = false; try { Logger.out.debug("login name: "+loginName+" passowrd: "+password); AuthenticationManager authMngr=getAuthenticationManager(); loginSuccess =authMngr.login( loginName, password); } catch (CSException ex) { Logger.out.debug("Authentication|"+requestingClass+"|"+loginName+"|login|Success| Authentication is not successful for user "+loginName+"|" + ex.getMessage()); throw new SMException (ex.getMessage(), ex); } return loginSuccess; } public void createUser(User user) throws SMTransactionException { try { getUserProvisioningManager().createUser(user); } catch (CSTransactionException e) { Logger.out.debug("Unable to create user: Exception: "+e.getMessage()); throw new SMTransactionException (e.getMessage(), e); } catch (CSException e) { Logger.out.debug("Unable to create user: Exception: "+e); } } public Vector getRoles()throws SMException { Vector roles=new Vector(); UserProvisioningManager userProvisioningManager=null; try { userProvisioningManager=getUserProvisioningManager(); roles.add(userProvisioningManager.getRoleById(ADMINISTRATOR_ROLE)); roles.add(userProvisioningManager.getRoleById(SUPERVISOR_ROLE)); roles.add(userProvisioningManager.getRoleById(TECHNICIAN_ROLE)); } catch (CSException e) { Logger.out.debug("Unable to get roles: Exception: "+e.getMessage()); throw new SMException (e.getMessage(), e); } return roles; } public void assignRoleToUser(String userName, String roleID) throws SMException { UserProvisioningManager userProvisioningManager=null; try { userProvisioningManager=getUserProvisioningManager(); if(roleID.equals(ADMINISTRATOR_ROLE)) { userProvisioningManager.assignUserToGroup(userName,ADMINISTRATOR_GROUP); } else if(roleID.equals(SUPERVISOR_ROLE)) { userProvisioningManager.assignUserToGroup(userName,SUPERVISOR_GROUP); } else if(roleID.equals(TECHNICIAN_ROLE)) { userProvisioningManager.assignUserToGroup(userName,TECHNICIAN_GROUP); } } catch (CSException e) { Logger.out.debug("UNABLE TO ASSIGN ROLE TO USER: Exception: "+e.getMessage()); throw new SMException (e.getMessage(), e); } } }
package com.thaiopensource.xml.dtd.parse; import java.util.Vector; import com.thaiopensource.xml.tok.Tokenizer; class AtomParser { private final DtdBuilder db; private final AtomStream as; private final PrologParser pp; private final Vector v; private Particle group; AtomParser(DtdBuilder db, AtomStream as, PrologParser pp, Vector v) { this.db = db; this.as = as; this.pp = pp; this.v = v; } AtomParser(DtdBuilder db, AtomStream as, PrologParser pp, Particle group) { this.db = db; this.as = as; this.pp = pp; this.v = group.particles; this.group = group; } void parse() { try { parseDecls(); pp.end(); } catch (PrologSyntaxException e) { throw new Error("syntax error on reparse at end of file"); } } private void parseDecls() throws PrologSyntaxException { while (as.advance()) { Decl d = null; if (as.entity != null) { d = new Decl(Decl.REFERENCE); d.entity = as.entity; v.addElement(d); int start = v.size(); new AtomParser(db, new AtomStream(as.entity.atoms), pp, v).parseDecls(); d.entity.setParsed(Entity.DECL_LEVEL, v, start, v.size()); d = new Decl(Decl.REFERENCE_END); } else { doAction(); switch (as.tokenType) { case Tokenizer.TOK_COMMENT: d = new Decl(Decl.COMMENT); d.value = as.token.substring(4, as.token.length() - 3); break; case Tokenizer.TOK_PI: d = new Decl(Decl.PROCESSING_INSTRUCTION); d.value = as.token.substring(2, as.token.length() - 2); break; case Tokenizer.TOK_PROLOG_S: case Tokenizer.TOK_XML_DECL: break; case Tokenizer.TOK_DECL_OPEN: { int type; if (as.token.equals("<!ENTITY")) type = Decl.ENTITY; else if (as.token.equals("<!ATTLIST")) type = Decl.ATTLIST; else if (as.token.equals("<!ELEMENT")) type = Decl.ELEMENT; else if (as.token.equals("<!NOTATION")) type = Decl.NOTATION; else throw new Error("unexpected decl type"); // should have been caught d = new Decl(type); d.params = new Vector(); new AtomParser(db, as, pp, d.params).parseParams(); } break; case Tokenizer.TOK_COND_SECT_OPEN: { Vector params = new Vector(); // current token should be "[" if (new AtomParser(db, as, pp, params).parseParams()) { d = new Decl(Decl.IGNORE_SECTION); as.advance(); d.value = as.token.substring(0, as.token.length() - 3); } else { d = new Decl(Decl.INCLUDE_SECTION); d.decls = new Vector(); new AtomParser(db, as, pp, d.decls).parseDecls(); } d.params = params; } break; case Tokenizer.TOK_COND_SECT_CLOSE: return; default: throw new Error("unexpected decl on reparse"); } } if (d != null) v.addElement(d); } } // Return true for IGNORE status keyword spec private boolean parseParams() throws PrologSyntaxException { while (as.advance()) { Param p = null; if (as.entity != null) { p = new Param(Param.REFERENCE); p.entity = as.entity; PrologParser ppSaved; if (p.entity.overrides != null) ppSaved = (PrologParser)pp.clone(); else ppSaved = null; v.addElement(p); int start = v.size(); new AtomParser(db, new AtomStream(as.entity.atoms), pp, v).parseParams(); if (v.size() == start && pp.expectingAttributeName()) v.addElement(new Param(Param.EMPTY_ATTRIBUTE_GROUP)); p.entity.setParsed(Entity.PARAM_LEVEL, v, start, v.size()); for (Entity overridden = p.entity.overrides; overridden != null; overridden = overridden.overrides) { if (overridden.atoms != null) { Vector tem = new Vector(); AtomParser ap = new AtomParser(db, new AtomStream(overridden.atoms), (PrologParser)ppSaved.clone(), tem); try { ap.parseParams(); if (tem.size() == 0 && ap.pp.expectingAttributeName()) tem.addElement(new Param(Param.EMPTY_ATTRIBUTE_GROUP)); if (ap.pp.isCompatible(pp)) overridden.setParsed(Entity.PARAM_LEVEL, tem, 0, tem.size()); else overridden.inconsistentParse(); } catch (PrologSyntaxException e) { overridden.inconsistentParse(); } } } p = new Param(Param.REFERENCE_END); } else { int action = doAction(); switch (as.tokenType) { case Tokenizer.TOK_OPEN_BRACKET: return action == PrologParser.ACTION_IGNORE_SECT; case Tokenizer.TOK_DECL_CLOSE: return false; case Tokenizer.TOK_OPEN_PAREN: switch (action) { case PrologParser.ACTION_GROUP_OPEN: p = new Param(Param.MODEL_GROUP); break; case PrologParser.ACTION_ENUM_GROUP_OPEN: p = new Param(Param.ATTRIBUTE_VALUE_GROUP); break; case PrologParser.ACTION_NOTATION_GROUP_OPEN: p = new Param(Param.NOTATION_GROUP); break; } p.group = parseGroup(); break; case Tokenizer.TOK_LITERAL: switch (action) { case PrologParser.ACTION_DEFAULT_ATTRIBUTE_VALUE: p = new Param(Param.DEFAULT_ATTRIBUTE_VALUE); p.value = db.getNormalized(as.token.substring(1, as.token.length() - 1)); break; default: p = new Param(Param.LITERAL); p.value = as.token.substring(1, as.token.length() - 1); break; } break; case Tokenizer.TOK_PERCENT: p = new Param(Param.PERCENT); break; case Tokenizer.TOK_NAME: case Tokenizer.TOK_PREFIXED_NAME: switch (action) { case PrologParser.ACTION_CONTENT_ANY: p = new Param(Param.ANY); break; case PrologParser.ACTION_CONTENT_EMPTY: p = new Param(Param.EMPTY); break; case PrologParser.ACTION_ELEMENT_NAME: case PrologParser.ACTION_ATTLIST_ELEMENT_NAME: p = new Param(Param.ELEMENT_NAME); p.value = as.token; break; case PrologParser.ACTION_ATTRIBUTE_NAME: p = new Param(Param.ATTRIBUTE_NAME); p.value = as.token; break; case PrologParser.ACTION_ATTRIBUTE_TYPE_CDATA: case PrologParser.ACTION_ATTRIBUTE_TYPE_ID: case PrologParser.ACTION_ATTRIBUTE_TYPE_IDREF: case PrologParser.ACTION_ATTRIBUTE_TYPE_IDREFS: case PrologParser.ACTION_ATTRIBUTE_TYPE_ENTITY: case PrologParser.ACTION_ATTRIBUTE_TYPE_ENTITIES: case PrologParser.ACTION_ATTRIBUTE_TYPE_NMTOKEN: case PrologParser.ACTION_ATTRIBUTE_TYPE_NMTOKENS: p = new Param(Param.ATTRIBUTE_TYPE); p.value = as.token; break; case PrologParser.ACTION_ATTRIBUTE_TYPE_NOTATION: p = new Param(Param.ATTRIBUTE_TYPE_NOTATION); break; case PrologParser.ACTION_SECTION_STATUS_IGNORE: p = new Param(Param.IGNORE); break; case PrologParser.ACTION_SECTION_STATUS_INCLUDE: p = new Param(Param.INCLUDE); break; default: p = new Param(Param.OTHER); p.value = as.token; } break; case Tokenizer.TOK_POUND_NAME: switch (action) { case PrologParser.ACTION_IMPLIED_ATTRIBUTE_VALUE: p = new Param(Param.IMPLIED); break; case PrologParser.ACTION_REQUIRED_ATTRIBUTE_VALUE: p = new Param(Param.REQUIRED); break; case PrologParser.ACTION_FIXED_ATTRIBUTE_VALUE: p = new Param(Param.FIXED); break; default: throw new Error("unexpected name after } break; case Tokenizer.TOK_PROLOG_S: break; default: throw new Error("unexpected parameter on reparse"); } } if (p != null) v.addElement(p); } return false; } private Particle parseGroup() throws PrologSyntaxException { Particle g = new Particle(Particle.GROUP); g.particles = new Vector(); new AtomParser(db, as, pp, g).parseParticles(); int n = g.particles.size(); int flags = 0; for (int i = 0; i < n; i++) { switch (((Particle)g.particles.elementAt(i)).type) { case Particle.GROUP: flags |= Entity.GROUP_CONTAINS_GROUP; break; case Particle.CONNECT_OR: flags |= Entity.GROUP_CONTAINS_OR; break; case Particle.CONNECT_SEQ: flags |= Entity.GROUP_CONTAINS_SEQ; break; case Particle.PCDATA: flags |= Entity.GROUP_CONTAINS_PCDATA; break; case Particle.ELEMENT_NAME: flags |= Entity.GROUP_CONTAINS_ELEMENT_NAME; break; case Particle.NMTOKEN: flags |= Entity.GROUP_CONTAINS_NMTOKEN; break; } } for (int i = 0; i < n; i++) { Particle p = (Particle)g.particles.elementAt(i); if (p.type == Particle.REFERENCE) p.entity.groupFlags |= flags; } return g; } private void parseParticles() throws PrologSyntaxException { while (as.advance()) { Particle p = null; if (as.entity != null) { p = new Particle(Particle.REFERENCE); p.entity = as.entity; PrologParser ppSaved; if (p.entity.overrides != null) ppSaved = (PrologParser)pp.clone(); else ppSaved = null; v.addElement(p); int start = v.size(); new AtomParser(db, new AtomStream(as.entity.atoms), pp, group).parseParticles(); p.entity.setParsed(Entity.PARTICLE_LEVEL, v, start, v.size()); for (Entity overridden = p.entity.overrides; overridden != null; overridden = overridden.overrides) { if (overridden.atoms != null) { Particle g = new Particle(Particle.GROUP); g.particles = new Vector(); AtomParser ap = new AtomParser(db, new AtomStream(overridden.atoms), (PrologParser)ppSaved.clone(), g); try { ap.parseParticles(); if (ap.pp.isCompatible(pp)) overridden.setParsed(Entity.PARTICLE_LEVEL, g.particles, 0, g.particles.size()); else overridden.inconsistentParse(); } catch (PrologSyntaxException e) { overridden.inconsistentParse(); } } } p = new Particle(Particle.REFERENCE_END); } else { int action = doAction(); switch (as.tokenType) { case Tokenizer.TOK_POUND_NAME: p = new Particle(Particle.PCDATA); break; case Tokenizer.TOK_NAME: case Tokenizer.TOK_PREFIXED_NAME: p = new Particle(action == PrologParser.ACTION_CONTENT_ELEMENT ? Particle.ELEMENT_NAME : Particle.NMTOKEN); p.value = as.token; break; case Tokenizer.TOK_NMTOKEN: p = new Particle(Particle.NMTOKEN); p.value = as.token; break; case Tokenizer.TOK_NAME_QUESTION: p = new Particle(Particle.ELEMENT_NAME); p.value = as.token.substring(0, as.token.length() - 1); p.occur = '?'; break; case Tokenizer.TOK_NAME_ASTERISK: p = new Particle(Particle.ELEMENT_NAME); p.value = as.token.substring(0, as.token.length() - 1); p.occur = '*'; break; case Tokenizer.TOK_NAME_PLUS: p = new Particle(Particle.ELEMENT_NAME); p.value = as.token.substring(0, as.token.length() - 1); p.occur = '+'; break; case Tokenizer.TOK_OPEN_PAREN: p = parseGroup(); break; case Tokenizer.TOK_CLOSE_PAREN: return; case Tokenizer.TOK_CLOSE_PAREN_QUESTION: group.occur = '?'; return; case Tokenizer.TOK_CLOSE_PAREN_ASTERISK: group.occur = '*'; return; case Tokenizer.TOK_CLOSE_PAREN_PLUS: group.occur = '+'; return; case Tokenizer.TOK_OR: p = new Particle(Particle.CONNECT_OR); break; case Tokenizer.TOK_COMMA: p = new Particle(Particle.CONNECT_SEQ); break; case Tokenizer.TOK_PROLOG_S: break; default: throw new Error("unexpected particle on reparse"); } } if (p != null) v.addElement(p); } } private int doAction() throws PrologSyntaxException { return pp.action(as.tokenType, as.token); } }
package org.opendaylight.controller.md.statistics.manager; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.TimeUnit; import org.opendaylight.controller.sal.binding.api.data.DataModificationTransaction; import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNode; import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.FlowCapableNodeConnector; import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.Meter; import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.meters.MeterKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.Table; import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.TableKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.inventory.rev130819.tables.table.Flow; import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.statistics.rev130819.FlowStatisticsData; import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.queues.Queue; import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.port.rev130925.queues.QueueKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.flow.types.queue.rev130925.QueueId; import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.NodeGroupDescStats; import org.opendaylight.yang.gen.v1.urn.opendaylight.group.statistics.rev131111.NodeGroupStatistics; import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.group.desc.stats.reply.GroupDescStats; import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.Group; import org.opendaylight.yang.gen.v1.urn.opendaylight.group.types.rev131018.groups.GroupKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.NodeConnectorId; import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.Nodes; import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnector; import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.node.NodeConnectorKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.Node; import org.opendaylight.yang.gen.v1.urn.opendaylight.inventory.rev130819.nodes.NodeKey; import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.NodeMeterConfigStats; import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.statistics.rev131111.NodeMeterStatistics; import org.opendaylight.yang.gen.v1.urn.opendaylight.meter.types.rev130918.meter.config.stats.reply.MeterConfigStats; import org.opendaylight.yang.gen.v1.urn.opendaylight.queue.statistics.rev131216.FlowCapableNodeConnectorQueueStatisticsData; import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; import org.opendaylight.yangtools.yang.binding.InstanceIdentifier.InstanceIdentifierBuilder; import com.google.common.base.Preconditions; /** * Main responsibility of this class to clean up all the stale statistics data * associated to Flow,Meter,Group,Queue. * @author avishnoi@in.ibm.com * */ public class NodeStatisticsAger { private static final int NUMBER_OF_WAIT_CYCLES = 2; private final Map<GroupDescStats,Long> groupDescStatsUpdate = new HashMap<>(); private final Map<MeterConfigStats,Long> meterConfigStatsUpdate = new HashMap<>(); private final Map<FlowEntry,Long> flowStatsUpdate = new HashMap<>(); private final Map<QueueEntry,Long> queuesStatsUpdate = new HashMap<>(); private final StatisticsProvider statisticsProvider; private final NodeKey targetNodeKey; public NodeStatisticsAger(StatisticsProvider statisticsProvider, NodeKey nodeKey){ this.statisticsProvider = Preconditions.checkNotNull(statisticsProvider); this.targetNodeKey = Preconditions.checkNotNull(nodeKey); } public class FlowEntry { private final Short tableId; private final Flow flow; public FlowEntry(Short tableId, Flow flow){ this.tableId = tableId; this.flow = flow; } public Short getTableId() { return tableId; } public Flow getFlow() { return flow; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + getOuterType().hashCode(); result = prime * result + ((flow == null) ? 0 : flow.hashCode()); result = prime * result + ((tableId == null) ? 0 : tableId.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; FlowEntry other = (FlowEntry) obj; if (!getOuterType().equals(other.getOuterType())) return false; if (flow == null) { if (other.flow != null) return false; } else if (!flow.equals(other.flow)) return false; if (tableId == null) { if (other.tableId != null) return false; } else if (!tableId.equals(other.tableId)) return false; return true; } private NodeStatisticsAger getOuterType() { return NodeStatisticsAger.this; } } public class QueueEntry{ private final NodeConnectorId nodeConnectorId; private final QueueId queueId; public QueueEntry(NodeConnectorId ncId, QueueId queueId){ this.nodeConnectorId = ncId; this.queueId = queueId; } public NodeConnectorId getNodeConnectorId() { return nodeConnectorId; } public QueueId getQueueId() { return queueId; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + getOuterType().hashCode(); result = prime * result + ((nodeConnectorId == null) ? 0 : nodeConnectorId.hashCode()); result = prime * result + ((queueId == null) ? 0 : queueId.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof QueueEntry)) { return false; } QueueEntry other = (QueueEntry) obj; if (!getOuterType().equals(other.getOuterType())) { return false; } if (nodeConnectorId == null) { if (other.nodeConnectorId != null) { return false; } } else if (!nodeConnectorId.equals(other.nodeConnectorId)) { return false; } if (queueId == null) { if (other.queueId != null) { return false; } } else if (!queueId.equals(other.queueId)) { return false; } return true; } private NodeStatisticsAger getOuterType() { return NodeStatisticsAger.this; } } public NodeKey getTargetNodeKey() { return targetNodeKey; } public synchronized void updateGroupDescStats(List<GroupDescStats> list){ Long expiryTime = getExpiryTime(); for(GroupDescStats groupDescStats : list) this.groupDescStatsUpdate.put(groupDescStats, expiryTime); } public synchronized void updateMeterConfigStats(List<MeterConfigStats> list){ Long expiryTime = getExpiryTime(); for(MeterConfigStats meterConfigStats: list) this.meterConfigStatsUpdate.put(meterConfigStats, expiryTime); } public synchronized void updateFlowStats(FlowEntry flowEntry){ this.flowStatsUpdate.put(flowEntry, getExpiryTime()); } public synchronized void updateQueueStats(QueueEntry queueEntry){ this.queuesStatsUpdate.put(queueEntry, getExpiryTime()); } private static Long getExpiryTime(){ final long now = System.nanoTime(); return now + TimeUnit.MILLISECONDS.toNanos(StatisticsProvider.STATS_THREAD_EXECUTION_TIME * NUMBER_OF_WAIT_CYCLES); } public synchronized void cleanStaleStatistics(){ final DataModificationTransaction trans = this.statisticsProvider.startChange(); final long now = System.nanoTime(); //Clean stale statistics related to group for (Iterator<Entry<GroupDescStats, Long>> it = this.groupDescStatsUpdate.entrySet().iterator();it.hasNext();){ Entry<GroupDescStats, Long> e = it.next(); if (now > e.getValue()) { cleanGroupStatsFromDataStore(trans, e.getKey()); it.remove(); } } //Clean stale statistics related to meter for (Iterator<Entry<MeterConfigStats, Long>> it = this.meterConfigStatsUpdate.entrySet().iterator();it.hasNext();){ Entry<MeterConfigStats, Long> e = it.next(); if (now > e.getValue()) { cleanMeterStatsFromDataStore(trans, e.getKey()); it.remove(); } } //Clean stale statistics related to flow for (Iterator<Entry<FlowEntry, Long>> it = this.flowStatsUpdate.entrySet().iterator();it.hasNext();){ Entry<FlowEntry, Long> e = it.next(); if (now > e.getValue()) { cleanFlowStatsFromDataStore(trans, e.getKey()); it.remove(); } } //Clean stale statistics related to queue for (Iterator<Entry<QueueEntry, Long>> it = this.queuesStatsUpdate.entrySet().iterator();it.hasNext();){ Entry<QueueEntry, Long> e = it.next(); if (now > e.getValue()) { cleanQueueStatsFromDataStore(trans, e.getKey()); it.remove(); } } trans.commit(); } private void cleanQueueStatsFromDataStore(DataModificationTransaction trans, QueueEntry queueEntry) { InstanceIdentifier<?> queueRef = InstanceIdentifier.builder(Nodes.class) .child(Node.class, this.targetNodeKey) .child(NodeConnector.class, new NodeConnectorKey(queueEntry.getNodeConnectorId())) .augmentation(FlowCapableNodeConnector.class) .child(Queue.class, new QueueKey(queueEntry.getQueueId())) .augmentation(FlowCapableNodeConnectorQueueStatisticsData.class).toInstance(); trans.removeOperationalData(queueRef); } private void cleanFlowStatsFromDataStore(DataModificationTransaction trans, FlowEntry flowEntry) { InstanceIdentifier<?> flowRef = InstanceIdentifier.builder(Nodes.class).child(Node.class, this.targetNodeKey) .augmentation(FlowCapableNode.class) .child(Table.class, new TableKey(flowEntry.getTableId())) .child(Flow.class,flowEntry.getFlow().getKey()) .augmentation(FlowStatisticsData.class).toInstance(); trans.removeOperationalData(flowRef); } private void cleanMeterStatsFromDataStore(DataModificationTransaction trans, MeterConfigStats meterConfigStats) { InstanceIdentifierBuilder<Meter> meterRef = InstanceIdentifier.builder(Nodes.class).child(Node.class,this.targetNodeKey) .augmentation(FlowCapableNode.class) .child(Meter.class,new MeterKey(meterConfigStats.getMeterId())); InstanceIdentifier<?> nodeMeterConfigStatsAugmentation = meterRef.augmentation(NodeMeterConfigStats.class).toInstance(); trans.removeOperationalData(nodeMeterConfigStatsAugmentation); InstanceIdentifier<?> nodeMeterStatisticsAugmentation = meterRef.augmentation(NodeMeterStatistics.class).toInstance(); trans.removeOperationalData(nodeMeterStatisticsAugmentation); } private void cleanGroupStatsFromDataStore(DataModificationTransaction trans, GroupDescStats groupDescStats) { InstanceIdentifierBuilder<Group> groupRef = InstanceIdentifier.builder(Nodes.class).child(Node.class,this.targetNodeKey) .augmentation(FlowCapableNode.class) .child(Group.class,new GroupKey(groupDescStats.getGroupId())); InstanceIdentifier<?> nodeGroupDescStatsAugmentation = groupRef.augmentation(NodeGroupDescStats.class).toInstance(); trans.removeOperationalData(nodeGroupDescStatsAugmentation); InstanceIdentifier<?> nodeGroupStatisticsAugmentation = groupRef.augmentation(NodeGroupStatistics.class).toInstance(); trans.removeOperationalData(nodeGroupStatisticsAugmentation); } }
package com.athaydes.sparkws; import com.google.common.util.concurrent.SettableFuture; import org.glassfish.tyrus.client.ClientManager; import org.junit.After; import org.junit.Test; import javax.websocket.ClientEndpointConfig; import javax.websocket.Endpoint; import javax.websocket.EndpointConfig; import javax.websocket.MessageHandler; import javax.websocket.Session; import java.io.IOException; import java.net.URI; import java.util.concurrent.TimeUnit; import static com.athaydes.sparkws.SparkWS.runServer; import static com.athaydes.sparkws.SparkWS.stopServer; import static com.athaydes.sparkws.SparkWS.wsEndpoint; import static org.junit.Assert.assertEquals; public class SparkWSTest { private final ClientEndpointConfig cec = ClientEndpointConfig.Builder.create().build(); private final ClientManager client = ClientManager.createClient(); @After public void cleanup() { stopServer(); } @Test public void simplestStart() throws Exception { wsEndpoint( "hello", ( session, message ) -> { session.getBasicRemote().sendText( "Hello " + message ); } ); runServer(); assertMessageReceived( "hello", "Hello SparkWS" ); } @Test public void simplestStartAgainToEnsureServerCanBeRestarted() throws Exception { wsEndpoint( "ola", ( session, message ) -> { session.getBasicRemote().sendText( "Ola " + message ); } ); runServer(); assertMessageReceived( "ola", "Ola SparkWS" ); } @Test public void twoDifferentSimpleEndpoints() throws Exception { wsEndpoint( "ep1", ( session, message ) -> { session.getBasicRemote().sendText( "EP1" ); } ); wsEndpoint( "ep2", ( session, message ) -> { session.getBasicRemote().sendText( "EP2" ); } ); runServer(); assertMessageReceived( "ep1", "EP1" ); assertMessageReceived( "ep2", "EP2" ); } @Test public void multiPathEndpoints() throws Exception { wsEndpoint( "part1/part2", ( session, message ) -> { session.getBasicRemote().sendText( "P1P2" ); } ); wsEndpoint( "part1/part3", ( session, message ) -> { session.getBasicRemote().sendText( "P1P3" ); } ); wsEndpoint( "part2/part3", ( session, message ) -> { session.getBasicRemote().sendText( "P2P3" ); } ); runServer(); assertMessageReceived( "part1/part2", "P1P2" ); assertMessageReceived( "part1/part3", "P1P3" ); assertMessageReceived( "part2/part3", "P2P3" ); } @Test public void mostSpecificPathIsSelected() throws Exception { wsEndpoint( "part1/part2/part3", ( session, message ) -> { session.getBasicRemote().sendText( "P1P2P3" ); } ); wsEndpoint( "part1", ( session, message ) -> { session.getBasicRemote().sendText( "P1" ); } ); wsEndpoint( "part1/part2", ( session, message ) -> { session.getBasicRemote().sendText( "P1P2" ); } ); wsEndpoint( "part1/part2/part3/part4", ( session, message ) -> { session.getBasicRemote().sendText( "P1P2P3P4" ); } ); runServer(); assertMessageReceived( "part1", "P1" ); assertMessageReceived( "part1/part2", "P1P2" ); assertMessageReceived( "part1/part2/part3", "P1P2P3" ); assertMessageReceived( "part1/part2/part3/part4", "P1P2P3P4" ); } private void assertMessageReceived( String endpoint, String expectedMessage ) throws Exception { final SettableFuture<String> futureMessage = SettableFuture.create(); client.connectToServer( new Endpoint() { @Override public void onOpen( Session session, EndpointConfig config ) { try { session.addMessageHandler( new MessageHandler.Whole<String>() { @Override public void onMessage( String message ) { System.out.println( "Received message: " + message ); futureMessage.set( message ); } } ); session.getBasicRemote().sendText( "SparkWS" ); } catch ( IOException e ) { e.printStackTrace(); } } }, cec, new URI( "ws://localhost:8025/" + endpoint ) ); assertEquals( expectedMessage, futureMessage.get( 2, TimeUnit.SECONDS ) ); } }
package com.documents; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.mockito.Matchers.any; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.List; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.mockito.runners.MockitoJUnitRunner; import com.documents.models.Student; import com.documents.repositories.StudentRepository; import com.documents.services.StudentServiceImpl; @RunWith(MockitoJUnitRunner.class) public class StudentServiceTest { //Arrange @Mock private StudentRepository studentRepository; @InjectMocks private StudentServiceImpl studentServiceImpl = new StudentServiceImpl(); @Before public void initializeMockito() { MockitoAnnotations.initMocks(this); } public void setup(Student student) { student.setId((long) 3); student.setMantricolNumber("123412123123"); student.setFirstName("FirstName"); student.setLastName("LastName"); student.setCnp((long) 91781379); student.setIdentityCardId("MX687632"); student.setFatherInitial("F.I."); student.setAddress("The whole Address"); student.setWebmail("FirstName.LastName@info.uaic.ro"); student.setBirthDate("12-June-2015"); student.setPassword("pass"); } @Test public void behavioural_student_save_should_return_true() throws Exception { //Act Student studentAfterSave = new Student(); Student studentToSave = new Student(); setup(studentToSave); when(studentRepository.save(any(Student.class))).thenReturn(studentAfterSave); studentAfterSave = studentServiceImpl.save(studentToSave); //Assert assertNotNull(studentAfterSave); } @Test public void functionality_student_save_should_return_student() throws Exception { //Act Student studentAfterSave = new Student(); setup(studentAfterSave); when(studentRepository.save(any(Student.class))).thenReturn(studentAfterSave); Student savedStudent = studentServiceImpl.save(studentAfterSave); //Assert assertEquals(Long.valueOf(3), savedStudent.getId()); assertEquals("123412123123", savedStudent.getMantricolNumber()); assertEquals("FirstName", savedStudent.getFirstName()); assertEquals("LastName", savedStudent.getLastName()); assertEquals(Long.valueOf(91781379), savedStudent.getCnp()); assertEquals("MX687632", savedStudent.getIdentityCardId()); assertEquals("F.I.", savedStudent.getFatherInitial()); assertEquals("The whole Address", savedStudent.getAddress()); assertEquals("FirstName.LastName@info.uaic.ro", savedStudent.getWebmail()); assertEquals("12-June-2015", savedStudent.getBirthDate()); assertEquals("pass", savedStudent.getPassword()); } @Test public void behavioural_student_findById_should_return_true() throws Exception { //Act Student studentToFind = new Student(); when(studentRepository.findOne(any(long.class))).thenReturn(studentToFind); studentToFind = studentServiceImpl.findById((long) 123); //Assert assertNotNull(studentToFind); } @Test public void functionality_student_findById_should_return_student() throws Exception { //Act Student studentToFind = new Student(); setup(studentToFind); when(studentRepository.findOne(any(long.class))).thenReturn(studentToFind); Student foundStudent = studentServiceImpl.findById((long) 3); //Assert assertEquals(Long.valueOf(3), foundStudent.getId()); assertEquals("123412123123", foundStudent.getMantricolNumber()); assertEquals("FirstName", foundStudent.getFirstName()); assertEquals("LastName", foundStudent.getLastName()); assertEquals(Long.valueOf(91781379), foundStudent.getCnp()); assertEquals("MX687632", foundStudent.getIdentityCardId()); assertEquals("F.I.", foundStudent.getFatherInitial()); assertEquals("The whole Address", foundStudent.getAddress()); assertEquals("FirstName.LastName@info.uaic.ro", foundStudent.getWebmail()); assertEquals("12-June-2015", foundStudent.getBirthDate()); assertEquals("pass", foundStudent.getPassword()); } @Test public void behavioural_student_deleteById_should_return_true() throws Exception { //Act Student student = new Student(); student.setId((long) 3); studentServiceImpl.delete(student.getId()); Student foundStudentToDelete = studentServiceImpl.findById((long) 3); //Assert assertNull(foundStudentToDelete); } @Test public void functionality_student_deleteById_should_delete_student() throws Exception { //Act Student student = new Student(); studentServiceImpl.delete(student.getId()); //Assert verify(studentRepository).delete(student.getId()); } @Test public void behavioural_licenseRequest_findAll_should_return_true() throws Exception { //Act List<Student> students = new ArrayList<>(); Student student = new Student(); setup(student); when(studentRepository.findAll()).thenReturn(students); students.add(student); List<Student> foundStudents; foundStudents = studentServiceImpl.findAll(); //Assert assertNotNull(foundStudents); } @Test public void functionality_licenseRequest_findAll_should_return_list_of_licenseRequest() throws Exception { //Act List<Student> students = new ArrayList<>(); Student student = new Student(); setup(student); when(studentRepository.findAll()).thenReturn(students); students.add(student); List<Student> foundStudents; foundStudents = studentServiceImpl.findAll(); //Assert assertEquals(students.get(0).getId(), foundStudents.get(0).getId()); assertEquals(students.get(0).getMantricolNumber(), foundStudents.get(0).getMantricolNumber()); assertEquals(students.get(0).getFirstName(), foundStudents.get(0).getFirstName()); assertEquals(students.get(0).getLastName(), foundStudents.get(0).getLastName()); assertEquals(students.get(0).getCnp(), foundStudents.get(0).getCnp()); assertEquals(students.get(0).getIdentityCardId(), foundStudents.get(0).getIdentityCardId()); assertEquals(students.get(0).getFatherInitial(), foundStudents.get(0).getFatherInitial()); assertEquals(students.get(0).getAddress(), foundStudents.get(0).getAddress()); assertEquals(students.get(0).getWebmail(), foundStudents.get(0).getWebmail()); assertEquals(students.get(0).getBirthDate(), foundStudents.get(0).getBirthDate()); assertEquals(students.get(0).getPassword(), foundStudents.get(0).getPassword()); } }
package net.bytebuddy; import net.bytebuddy.asm.ClassVisitorWrapper; import net.bytebuddy.description.annotation.AnnotationDescription; import net.bytebuddy.description.annotation.AnnotationList; import net.bytebuddy.description.field.FieldDescription; import net.bytebuddy.description.method.MethodDescription; import net.bytebuddy.description.modifier.*; import net.bytebuddy.description.type.TypeDescription; import net.bytebuddy.description.type.TypeList; import net.bytebuddy.dynamic.ClassFileLocator; import net.bytebuddy.dynamic.DynamicType; import net.bytebuddy.dynamic.TargetType; import net.bytebuddy.dynamic.scaffold.*; import net.bytebuddy.dynamic.scaffold.inline.MethodRebaseResolver; import net.bytebuddy.dynamic.scaffold.inline.RebaseDynamicTypeBuilder; import net.bytebuddy.dynamic.scaffold.inline.RedefinitionDynamicTypeBuilder; import net.bytebuddy.dynamic.scaffold.subclass.ConstructorStrategy; import net.bytebuddy.dynamic.scaffold.subclass.SubclassDynamicTypeBuilder; import net.bytebuddy.implementation.Implementation; import net.bytebuddy.implementation.MethodCall; import net.bytebuddy.implementation.attribute.FieldAttributeAppender; import net.bytebuddy.implementation.attribute.MethodAttributeAppender; import net.bytebuddy.implementation.attribute.TypeAttributeAppender; import net.bytebuddy.implementation.auxiliary.AuxiliaryType; import net.bytebuddy.implementation.bytecode.ByteCodeAppender; import net.bytebuddy.implementation.bytecode.Duplication; import net.bytebuddy.implementation.bytecode.StackManipulation; import net.bytebuddy.implementation.bytecode.TypeCreation; import net.bytebuddy.implementation.bytecode.assign.Assigner; import net.bytebuddy.implementation.bytecode.assign.TypeCasting; import net.bytebuddy.implementation.bytecode.collection.ArrayFactory; import net.bytebuddy.implementation.bytecode.constant.IntegerConstant; import net.bytebuddy.implementation.bytecode.constant.TextConstant; import net.bytebuddy.implementation.bytecode.member.FieldAccess; import net.bytebuddy.implementation.bytecode.member.MethodInvocation; import net.bytebuddy.implementation.bytecode.member.MethodReturn; import net.bytebuddy.matcher.ElementMatcher; import net.bytebuddy.matcher.LatentMethodMatcher; import org.objectweb.asm.MethodVisitor; import org.objectweb.asm.Opcodes; import java.lang.annotation.Annotation; import java.util.*; import static net.bytebuddy.matcher.ElementMatchers.*; import static net.bytebuddy.utility.ByteBuddyCommons.*; /** * {@code ByteBuddy} instances are configurable factories for creating new Java types at a JVM's runtime. * Such types are represented by {@link net.bytebuddy.dynamic.DynamicType}s which can be saved to disk or loaded into * the Java virtual machine. Each instance of {@code ByteBuddy} is immutable where any of the factory methods returns * a new instance that represents the altered configuration. * <p>&nbsp;</p> * Note that any configuration defines not to implement any synthetic methods or the default finalizer method * {@link Object#finalize()}. This behavior can be altered by * {@link net.bytebuddy.ByteBuddy#withIgnoredMethods(net.bytebuddy.matcher.ElementMatcher)}. */ public class ByteBuddy { /** * The default prefix for the default {@link net.bytebuddy.NamingStrategy}. */ public static final String BYTE_BUDDY_DEFAULT_PREFIX = "ByteBuddy"; /** * The default suffix when defining a naming strategy for auxiliary types. */ public static final String BYTE_BUDDY_DEFAULT_SUFFIX = "auxiliary"; /** * The class file version of the current configuration. */ protected final ClassFileVersion classFileVersion; /** * The naming strategy of the current configuration. */ protected final NamingStrategy.Unbound namingStrategy; /** * The naming strategy for auxiliary types of the current configuation. */ protected final AuxiliaryType.NamingStrategy auxiliaryTypeNamingStrategy; /** * A list of interface types to be implemented by any class that is implemented by the current configuration. */ protected final List<TypeDescription> interfaceTypes; /** * A matcher for identifying methods that should never be intercepted. */ protected final ElementMatcher<? super MethodDescription> ignoredMethods; /** * The factory for generating a bridge method resolver for the current configuration. */ protected final BridgeMethodResolver.Factory bridgeMethodResolverFactory; /** * The class visitor wrapper chain for the current configuration. */ protected final ClassVisitorWrapper.Chain classVisitorWrapperChain; /** * The method registry for the current configuration. */ protected final MethodRegistry methodRegistry; /** * The modifiers to apply to any type that is generated by this configuration. */ protected final Definable<Integer> modifiers; /** * The method lookup engine factory to apply to any type that is generated by this configuration. */ protected final MethodLookupEngine.Factory methodLookupEngineFactory; /** * The type attribute appender factory to apply to any type that is generated by this configuration. */ protected final TypeAttributeAppender typeAttributeAppender; /** * The default field attribute appender factory which is applied to any field that is defined * for implementations that are applied by this configuration. */ protected final FieldAttributeAppender.Factory defaultFieldAttributeAppenderFactory; /** * The default method attribute appender factory which is applied to any method that is defined * or intercepted for implementations that are applied by this configuration. */ protected final MethodAttributeAppender.Factory defaultMethodAttributeAppenderFactory; /** * Defines a new {@code ByteBuddy} default configuration for the current Java virtual machine's * class file version. */ public ByteBuddy() { this(ClassFileVersion.forCurrentJavaVersion()); } /** * Defines a new {@code ByteBuddy} default configuration for the given class file version. * * @param classFileVersion The class file version to apply. */ public ByteBuddy(ClassFileVersion classFileVersion) { this(nonNull(classFileVersion), new NamingStrategy.Unbound.Default(BYTE_BUDDY_DEFAULT_PREFIX), new AuxiliaryType.NamingStrategy.SuffixingRandom(BYTE_BUDDY_DEFAULT_SUFFIX), new TypeList.Empty(), isDefaultFinalizer().or(isSynthetic().and(not(isVisibilityBridge()))), BridgeMethodResolver.Simple.Factory.FAIL_ON_REQUEST, new ClassVisitorWrapper.Chain(), new MethodRegistry.Default(), new Definable.Undefined<Integer>(), TypeAttributeAppender.NoOp.INSTANCE, MethodLookupEngine.Default.Factory.INSTANCE, FieldAttributeAppender.NoOp.INSTANCE, MethodAttributeAppender.NoOp.INSTANCE); } /** * Defines a new {@code ByteBuddy} configuration. * * @param classFileVersion The currently defined class file version. * @param namingStrategy The currently defined naming strategy. * @param auxiliaryTypeNamingStrategy The currently defined naming strategy for auxiliary types. * @param interfaceTypes The currently defined collection of interfaces to be implemented * by any dynamically created type. * @param ignoredMethods The methods to always be ignored. * @param bridgeMethodResolverFactory The bridge method resolver factory to be applied to any implementation * process. * @param classVisitorWrapperChain The class visitor wrapper chain to be applied to any implementation * process. * @param methodRegistry The currently valid method registry. * @param modifiers The modifiers to define for any implementation process. * @param typeAttributeAppender The type attribute appender to apply to any implementation process. * @param methodLookupEngineFactory The method lookup engine factory to apply to this configuration. * @param defaultFieldAttributeAppenderFactory The field attribute appender to apply as a default for any field * definition. * @param defaultMethodAttributeAppenderFactory The method attribute appender to apply as a default for any * method definition or implementation. */ protected ByteBuddy(ClassFileVersion classFileVersion, NamingStrategy.Unbound namingStrategy, AuxiliaryType.NamingStrategy auxiliaryTypeNamingStrategy, List<TypeDescription> interfaceTypes, ElementMatcher<? super MethodDescription> ignoredMethods, BridgeMethodResolver.Factory bridgeMethodResolverFactory, ClassVisitorWrapper.Chain classVisitorWrapperChain, MethodRegistry methodRegistry, Definable<Integer> modifiers, TypeAttributeAppender typeAttributeAppender, MethodLookupEngine.Factory methodLookupEngineFactory, FieldAttributeAppender.Factory defaultFieldAttributeAppenderFactory, MethodAttributeAppender.Factory defaultMethodAttributeAppenderFactory) { this.classFileVersion = classFileVersion; this.namingStrategy = namingStrategy; this.auxiliaryTypeNamingStrategy = auxiliaryTypeNamingStrategy; this.interfaceTypes = interfaceTypes; this.ignoredMethods = ignoredMethods; this.bridgeMethodResolverFactory = bridgeMethodResolverFactory; this.classVisitorWrapperChain = classVisitorWrapperChain; this.methodRegistry = methodRegistry; this.modifiers = modifiers; this.typeAttributeAppender = typeAttributeAppender; this.methodLookupEngineFactory = methodLookupEngineFactory; this.defaultFieldAttributeAppenderFactory = defaultFieldAttributeAppenderFactory; this.defaultMethodAttributeAppenderFactory = defaultMethodAttributeAppenderFactory; } /** * Returns the class file version that is defined for the current configuration. * * @return The class file version that is defined for this configuration. */ public ClassFileVersion getClassFileVersion() { return classFileVersion; } /** * Returns the naming strategy for the current configuration. * * @return The naming strategy for the current configuration. */ public NamingStrategy.Unbound getNamingStrategy() { return namingStrategy; } /** * Returns the naming strategy for the current configuration. * * @return The naming strategy for the current configuration. */ public List<TypeDescription> getInterfaceTypes() { return Collections.unmodifiableList(interfaceTypes); } /** * Returns the matcher for the ignored methods for the current configuration. * * @return The matcher for the ignored methods for the current configuration. */ public ElementMatcher<? super MethodDescription> getIgnoredMethods() { return ignoredMethods; } /** * Returns the factory for the bridge method resolver for the current configuration. * * @return The factory for the bridge method resolver for the current configuration. */ public BridgeMethodResolver.Factory getBridgeMethodResolverFactory() { return bridgeMethodResolverFactory; } /** * Returns the class visitor wrapper chain for the current configuration. * * @return The class visitor wrapper chain for the current configuration. */ public ClassVisitorWrapper.Chain getClassVisitorWrapperChain() { return classVisitorWrapperChain; } /** * Returns the method registry for the current configuration. * * @return The method registry for the current configuration. */ public MethodRegistry getMethodRegistry() { return methodRegistry; } /** * Returns the modifiers to apply to any type that is generated by this configuration. * * @return The modifiers to apply to any type that is generated by this configuration. */ public Definable<Integer> getModifiers() { return modifiers; } /** * Returns the method lookup engine factory to apply to any type that is generated by this configuration. * * @return The method lookup engine factory to apply to any type that is generated by this configuration. */ public MethodLookupEngine.Factory getMethodLookupEngineFactory() { return methodLookupEngineFactory; } /** * Returns the type attribute appender factory to apply to any type that is generated by this configuration. * * @return The type attribute appender factory to apply to any type that is generated by this configuration. */ public TypeAttributeAppender getTypeAttributeAppender() { return typeAttributeAppender; } /** * Returns the default field attribute appender factory which is applied to any field that is defined * for implementations that are applied by this configuration. * * @return The default field attribute appender factory which is applied to any field that is defined * for implementations that are applied by this configuration. */ public FieldAttributeAppender.Factory getDefaultFieldAttributeAppenderFactory() { return defaultFieldAttributeAppenderFactory; } /** * Returns the default method attribute appender factory which is applied to any method that is defined * or intercepted for implementations that are applied by this configuration. * * @return The default method attribute appender factory which is applied to any method that is defined * or intercepted for implementations that are applied by this configuration. */ public MethodAttributeAppender.Factory getDefaultMethodAttributeAppenderFactory() { return defaultMethodAttributeAppenderFactory; } /** * Returns the used naming strategy for auxiliary types. * * @return The used naming strategy for auxiliary types. */ public AuxiliaryType.NamingStrategy getAuxiliaryTypeNamingStrategy() { return auxiliaryTypeNamingStrategy; } public <T> DynamicType.Builder<T> subclass(Class<T> superType) { return subclass(new TypeDescription.ForLoadedType(nonNull(superType))); } /** * Creates a dynamic type builder that creates a subclass of a given loaded type. * * @param superType The type or interface to be extended or implemented by the dynamic type. * @param constructorStrategy The constructor strategy to apply. * @param <T> The most specific known type that the created dynamic type represents. * @return A dynamic type builder for this configuration that extends or implements the given loaded type. */ public <T> DynamicType.Builder<T> subclass(Class<T> superType, ConstructorStrategy constructorStrategy) { return subclass(new TypeDescription.ForLoadedType(nonNull(superType)), constructorStrategy); } public <T> DynamicType.Builder<T> subclass(TypeDescription superType) { return subclass(superType, ConstructorStrategy.Default.IMITATE_SUPER_TYPE); } /** * Creates a dynamic type builder that creates a subclass of a given type description. * * @param superType The type or interface to be extended or implemented by the dynamic type. * @param constructorStrategy The constructor strategy to apply. * @param <T> The most specific known type that the created dynamic type represents. * @return A dynamic type builder for this configuration that extends or implements the given type description. */ public <T> DynamicType.Builder<T> subclass(TypeDescription superType, ConstructorStrategy constructorStrategy) { TypeDescription actualSuperType = isExtendable(superType); List<TypeDescription> interfaceTypes = this.interfaceTypes; if (nonNull(superType).isInterface()) { actualSuperType = TypeDescription.OBJECT; interfaceTypes = joinUnique(superType, interfaceTypes); } return new SubclassDynamicTypeBuilder<T>(classFileVersion, nonNull(namingStrategy.subclass(superType)), auxiliaryTypeNamingStrategy, actualSuperType, interfaceTypes, modifiers.resolve(superType.getModifiers() & ~TypeManifestation.ANNOTATION.getMask()), typeAttributeAppender, ignoredMethods, bridgeMethodResolverFactory, classVisitorWrapperChain, new FieldRegistry.Default(), methodRegistry, methodLookupEngineFactory, defaultFieldAttributeAppenderFactory, defaultMethodAttributeAppenderFactory, nonNull(constructorStrategy)); } /** * Creates a dynamic type builder for an interface that extends the given interface. * * @param type The interface to extend. * @param <T> The most specific known type that the created dynamic type represents. * @return A dynamic type builder for this configuration that defines an interface that extends the specified * interface. */ @SuppressWarnings("unchecked") public <T> DynamicType.Builder<T> makeInterface(Class<T> type) { return (DynamicType.Builder<T>) makeInterface(Collections.<TypeDescription>singletonList(new TypeDescription.ForLoadedType(nonNull(type)))); } /** * Creates a dynamic type builder for an interface that extends a number of given interfaces. * * @param type The interface types to extend. * @return A dynamic type builder for this configuration that defines an interface that extends the specified * interfaces. */ public DynamicType.Builder<?> makeInterface(Class<?>... type) { return makeInterface(new TypeList.ForLoadedType(nonNull(type))); } /** * Creates a dynamic type builder for an interface that extends a number of given interfaces. * * @param types The interface types to extend. * @return A dynamic type builder for this configuration that defines an interface that extends the specified * interfaces. */ public DynamicType.Builder<?> makeInterface(Iterable<? extends Class<?>> types) { return makeInterface(new TypeList.ForLoadedType(toList(types))); } /** * Creates a dynamic type builder for an interface that extends a number of given interfaces. * * @param typeDescriptions The interface types to extend. * @return A dynamic type builder for this configuration that defines an interface that extends the specified * interfaces. */ public DynamicType.Builder<?> makeInterface(Collection<? extends TypeDescription> typeDescriptions) { return new SubclassDynamicTypeBuilder<Object>(classFileVersion, namingStrategy.create(), auxiliaryTypeNamingStrategy, TypeDescription.OBJECT, join(interfaceTypes, toList(nonNull(typeDescriptions))), modifiers.resolve(Opcodes.ACC_PUBLIC) | TypeManifestation.INTERFACE.getMask(), typeAttributeAppender, ignoredMethods, bridgeMethodResolverFactory, classVisitorWrapperChain, new FieldRegistry.Default(), methodRegistry, methodLookupEngineFactory, defaultFieldAttributeAppenderFactory, defaultMethodAttributeAppenderFactory, ConstructorStrategy.Default.NO_CONSTRUCTORS); } /** * Creates a dynamic type builder for a new annotation type. * * @return A builder for a new annotation type. */ @SuppressWarnings("unchecked") public DynamicType.Builder<? extends Annotation> makeAnnotation() { return (DynamicType.Builder<? extends Annotation>) (Object) new SubclassDynamicTypeBuilder<Object>(classFileVersion, namingStrategy.create(), auxiliaryTypeNamingStrategy, TypeDescription.OBJECT, Collections.<TypeDescription>singletonList(new TypeDescription.ForLoadedType(Annotation.class)), modifiers.resolve(Opcodes.ACC_PUBLIC) | TypeManifestation.ANNOTATION.getMask(), typeAttributeAppender, ignoredMethods, bridgeMethodResolverFactory, classVisitorWrapperChain, new FieldRegistry.Default(), methodRegistry, methodLookupEngineFactory, defaultFieldAttributeAppenderFactory, defaultMethodAttributeAppenderFactory, ConstructorStrategy.Default.NO_CONSTRUCTORS); } /** * Creates a new enumeration type. * * @param value The enumeration values to define. * @return A builder for a new enumeration type with the given values. */ public DynamicType.Builder<? extends Enum<?>> makeEnumeration(String... value) { return makeEnumeration(Arrays.asList(value)); } /** * Creates a new enumeration type. * * @param values The enumeration values to define. * @return A builder for a new enumeration type with the given values. */ @SuppressWarnings("unchecked") public DynamicType.Builder<? extends Enum<?>> makeEnumeration(Collection<String> values) { if (unique(nonNull(values)).size() == 0) { throw new IllegalArgumentException("Require at least one enumeration constant"); } return new SubclassDynamicTypeBuilder<Enum<?>>(classFileVersion, nonNull(namingStrategy.subclass(TypeDescription.ENUM)), auxiliaryTypeNamingStrategy, TypeDescription.ENUM, interfaceTypes, Visibility.PUBLIC.getMask() | TypeManifestation.FINAL.getMask() | EnumerationState.ENUMERATION.getMask(), typeAttributeAppender, ignoredMethods, bridgeMethodResolverFactory, classVisitorWrapperChain, new FieldRegistry.Default(), methodRegistry, methodLookupEngineFactory, defaultFieldAttributeAppenderFactory, defaultMethodAttributeAppenderFactory, ConstructorStrategy.Default.NO_CONSTRUCTORS) .defineConstructor(Arrays.<Class<?>>asList(String.class, int.class), Visibility.PRIVATE) .intercept(MethodCall.invoke(TypeDescription.ENUM.getDeclaredMethods() .filter(isConstructor().and(takesArguments(String.class, int.class))).getOnly()) .withArgument(0, 1)) .defineMethod(EnumerationImplementation.ENUM_VALUE_OF_METHOD_NAME, TargetType.class, Collections.<Class<?>>singletonList(String.class), Visibility.PUBLIC, Ownership.STATIC) .intercept(MethodCall.invoke(TypeDescription.ENUM.getDeclaredMethods() .filter(named(EnumerationImplementation.ENUM_VALUE_OF_METHOD_NAME).and(takesArguments(Class.class, String.class))).getOnly()) .withOwnType().withArgument(0) .withAssigner(Assigner.DEFAULT, Assigner.DYNAMICALLY_TYPED)) .defineMethod(EnumerationImplementation.ENUM_VALUES_METHOD_NAME, TargetType[].class, Collections.<Class<?>>emptyList(), Visibility.PUBLIC, Ownership.STATIC) .intercept(new EnumerationImplementation(new ArrayList<String>(values))); } /** * <p> * Creates a dynamic type builder for redefining of the given type. The given class must be found on the * class path or by the class's {@link java.lang.ClassLoader}. Otherwise, the class file to the redefined class * must be located explicitly by providing a locator by * {@link net.bytebuddy.ByteBuddy#redefine(Class, net.bytebuddy.dynamic.ClassFileLocator)}. * </p> * <p> * <b>Note</b>: It is possible to experience unexpected errors in case that the provided {@code levelType} and the * corresponding class file get out of sync, i.e. a type is redefined several times without providing an updated * version of the class file. * </p> * * @param levelType The type to redefine. * @param <T> The most specific known type that the created dynamic type represents. * @return A dynamic type builder for this configuration that redefines the given type description. */ public <T> DynamicType.Builder<T> redefine(Class<T> levelType) { return redefine(levelType, ClassFileLocator.ForClassLoader.of(levelType.getClassLoader())); } /** * <p> * Creates a dynamic type builder for redefining of the given type. * </p> * <p> * <b>Note</b>: It is possible to experience unexpected errors in case that the provided {@code levelType} and the * corresponding class file get out of sync, i.e. a type is redefined several times without providing an updated * version of the class file. * </p> * * @param levelType The type to redefine. * @param classFileLocator A locator for finding a class file that represents a type. * @param <T> The most specific known type that the created dynamic type represents. * @return A dynamic type builder for this configuration that redefines the given type description. */ public <T> DynamicType.Builder<T> redefine(Class<T> levelType, ClassFileLocator classFileLocator) { return redefine(new TypeDescription.ForLoadedType(nonNull(levelType)), classFileLocator); } /** * <p> * Creates a dynamic type builder for redefining of the given type. * </p> * <p> * <b>Note</b>: It is possible to experience unexpected errors in case that the provided {@code levelType} and the * corresponding class file get out of sync, i.e. a type is redefined several times without providing an updated * version of the class file. * </p> * * @param levelType The type to redefine. * @param classFileLocator A locator for finding a class file that represents a type. * @param <T> The most specific known type that the created dynamic type represents. * @return A dynamic type builder for this configuration that redefines the given type description. */ public <T> DynamicType.Builder<T> redefine(TypeDescription levelType, ClassFileLocator classFileLocator) { return new RedefinitionDynamicTypeBuilder<T>(classFileVersion, nonNull(namingStrategy.redefine(levelType)), auxiliaryTypeNamingStrategy, nonNull(levelType), interfaceTypes, modifiers.resolve(levelType.getModifiers()), typeAttributeAppender, ignoredMethods, bridgeMethodResolverFactory, classVisitorWrapperChain, new FieldRegistry.Default(), methodRegistry, methodLookupEngineFactory, defaultFieldAttributeAppenderFactory, defaultMethodAttributeAppenderFactory, nonNull(classFileLocator)); } public <T> DynamicType.Builder<T> rebase(Class<T> levelType) { return rebase(levelType, ClassFileLocator.ForClassLoader.of(levelType.getClassLoader())); } public <T> DynamicType.Builder<T> rebase(Class<T> levelType, ClassFileLocator classFileLocator) { return rebase(new TypeDescription.ForLoadedType(nonNull(levelType)), classFileLocator); } public <T> DynamicType.Builder<T> rebase(Class<T> levelType, ClassFileLocator classFileLocator, MethodRebaseResolver.MethodNameTransformer methodNameTransformer) { return rebase(new TypeDescription.ForLoadedType(nonNull(levelType)), classFileLocator, methodNameTransformer); } public <T> DynamicType.Builder<T> rebase(TypeDescription levelType, ClassFileLocator classFileLocator) { return rebase(levelType, classFileLocator, new MethodRebaseResolver.MethodNameTransformer.Suffixing()); } public <T> DynamicType.Builder<T> rebase(TypeDescription levelType, ClassFileLocator classFileLocator, MethodRebaseResolver.MethodNameTransformer methodNameTransformer) { return new RebaseDynamicTypeBuilder<T>(classFileVersion, nonNull(namingStrategy.rebase(levelType)), auxiliaryTypeNamingStrategy, levelType, interfaceTypes, modifiers.resolve(levelType.getModifiers()), TypeAttributeAppender.NoOp.INSTANCE, ignoredMethods, bridgeMethodResolverFactory, classVisitorWrapperChain, new FieldRegistry.Default(), methodRegistry, methodLookupEngineFactory, defaultFieldAttributeAppenderFactory, defaultMethodAttributeAppenderFactory, nonNull(classFileLocator), nonNull(methodNameTransformer)); } /** * Defines a new class file version for this configuration. * * @param classFileVersion The class file version to define for this configuration. * @return A new configuration that represents this configuration with the given class file version. */ public ByteBuddy withClassFileVersion(ClassFileVersion classFileVersion) { return new ByteBuddy(nonNull(classFileVersion), namingStrategy, auxiliaryTypeNamingStrategy, interfaceTypes, ignoredMethods, bridgeMethodResolverFactory, classVisitorWrapperChain, methodRegistry, modifiers, typeAttributeAppender, methodLookupEngineFactory, defaultFieldAttributeAppenderFactory, defaultMethodAttributeAppenderFactory); } /** * Defines a new naming strategy for this configuration. * * @param namingStrategy The unbound naming strategy to apply to the current configuration. * @return A new configuration that represents this configuration with the given unbound naming strategy. */ public ByteBuddy withNamingStrategy(NamingStrategy.Unbound namingStrategy) { return new ByteBuddy(classFileVersion, nonNull(namingStrategy), auxiliaryTypeNamingStrategy, interfaceTypes, ignoredMethods, bridgeMethodResolverFactory, classVisitorWrapperChain, methodRegistry, modifiers, typeAttributeAppender, methodLookupEngineFactory, defaultFieldAttributeAppenderFactory, defaultMethodAttributeAppenderFactory); } /** * Defines a new naming strategy for this configuration. * * @param namingStrategy The naming strategy to apply to the current configuration. * @return A new configuration that represents this configuration with the given naming strategy. */ public ByteBuddy withNamingStrategy(NamingStrategy namingStrategy) { return withNamingStrategy(new NamingStrategy.Unbound.Unified(nonNull(namingStrategy))); } /** * Defines a naming strategy for auxiliary types. * * @param auxiliaryTypeNamingStrategy The naming strategy to use. * @return This configuration with the defined naming strategy for auxiliary types. */ public ByteBuddy withNamingStrategy(AuxiliaryType.NamingStrategy auxiliaryTypeNamingStrategy) { return new ByteBuddy(classFileVersion, namingStrategy, nonNull(auxiliaryTypeNamingStrategy), interfaceTypes, ignoredMethods, bridgeMethodResolverFactory, classVisitorWrapperChain, methodRegistry, modifiers, typeAttributeAppender, methodLookupEngineFactory, defaultFieldAttributeAppenderFactory, defaultMethodAttributeAppenderFactory); } /** * Defines a new modifier contributors for this configuration that replaces the currently defined modifier * contributes which might currently be implicit. * * @param modifierContributor The modifier contributors to define explicitly for this configuration. * @return A new configuration that represents this configuration with the given modifier contributors. */ public ByteBuddy withModifiers(ModifierContributor.ForType... modifierContributor) { return new ByteBuddy(classFileVersion, namingStrategy, auxiliaryTypeNamingStrategy, interfaceTypes, ignoredMethods, bridgeMethodResolverFactory, classVisitorWrapperChain, methodRegistry, new Definable.Defined<Integer>(resolveModifierContributors(TYPE_MODIFIER_MASK, nonNull(modifierContributor))), typeAttributeAppender, methodLookupEngineFactory, defaultFieldAttributeAppenderFactory, defaultMethodAttributeAppenderFactory); } /** * Defines a new type attribute appender for this configuration that replaces the currently defined type * attribute appender. * * @param typeAttributeAppender The type attribute appender to define for this configuration. * @return A new configuration that represents this configuration with the given type attribute appender. */ public ByteBuddy withAttribute(TypeAttributeAppender typeAttributeAppender) { return new ByteBuddy(classFileVersion, namingStrategy, auxiliaryTypeNamingStrategy, interfaceTypes, ignoredMethods, bridgeMethodResolverFactory, classVisitorWrapperChain, methodRegistry, modifiers, nonNull(typeAttributeAppender), methodLookupEngineFactory, defaultFieldAttributeAppenderFactory, defaultMethodAttributeAppenderFactory); } /** * Defines a new type annotation for this configuration that replaces the currently defined type * attribute appender. * * @param annotation The type annotations to define for this configuration. * @return A new configuration that represents this configuration with the given annotations as its new * type attribute appender. */ public ByteBuddy withTypeAnnotation(Annotation... annotation) { return withTypeAnnotation(new AnnotationList.ForLoadedAnnotation(nonNull(annotation))); } /** * Defines a new type annotation for this configuration that replaces the currently defined type * attribute appender. * * @param annotations The type annotations to define for this configuration. * @return A new configuration that represents this configuration with the given annotations as its new * type attribute appender. */ public ByteBuddy withTypeAnnotation(Iterable<? extends Annotation> annotations) { return withTypeAnnotation(new AnnotationList.ForLoadedAnnotation(toList(annotations))); } /** * Defines a new type annotation for this configuration that replaces the currently defined type * attribute appender. * * @param annotation The type annotations to define for this configuration. * @return A new configuration that represents this configuration with the given annotations as its new * type attribute appender. */ public ByteBuddy withTypeAnnotation(AnnotationDescription... annotation) { return withTypeAnnotation(Arrays.asList(annotation)); } /** * Defines a new type annotation for this configuration that replaces the currently defined type * attribute appender. * * @param annotations The type annotations to define for this configuration. * @return A new configuration that represents this configuration with the given annotations as its new * type attribute appender. */ public ByteBuddy withTypeAnnotation(Collection<? extends AnnotationDescription> annotations) { return new ByteBuddy(classFileVersion, namingStrategy, auxiliaryTypeNamingStrategy, interfaceTypes, ignoredMethods, bridgeMethodResolverFactory, classVisitorWrapperChain, methodRegistry, modifiers, new TypeAttributeAppender.ForAnnotation(new ArrayList<AnnotationDescription>(nonNull(annotations))), methodLookupEngineFactory, defaultFieldAttributeAppenderFactory, defaultMethodAttributeAppenderFactory); } public OptionalMethodInterception withImplementing(Class<?>... type) { return withImplementing(new TypeList.ForLoadedType(nonNull(type))); } public OptionalMethodInterception withImplementing(Iterable<? extends Class<?>> types) { return withImplementing(new TypeList.ForLoadedType(toList(types))); } public OptionalMethodInterception withImplementing(TypeDescription... type) { return withImplementing(Arrays.asList(nonNull(type))); } public OptionalMethodInterception withImplementing(Collection<? extends TypeDescription> types) { return new OptionalMethodInterception(classFileVersion, namingStrategy, auxiliaryTypeNamingStrategy, joinUnique(interfaceTypes, toList(isInterface(types))), ignoredMethods, bridgeMethodResolverFactory, classVisitorWrapperChain, methodRegistry, modifiers, typeAttributeAppender, methodLookupEngineFactory, defaultFieldAttributeAppenderFactory, defaultMethodAttributeAppenderFactory, new LatentMethodMatcher.Resolved(isDeclaredBy(anyOf(new ArrayList<TypeDescription>(types))))); } public ByteBuddy withIgnoredMethods(ElementMatcher<? super MethodDescription> ignoredMethods) { return new ByteBuddy(classFileVersion, namingStrategy, auxiliaryTypeNamingStrategy, interfaceTypes, nonNull(ignoredMethods), bridgeMethodResolverFactory, classVisitorWrapperChain, methodRegistry, modifiers, typeAttributeAppender, methodLookupEngineFactory, defaultFieldAttributeAppenderFactory, defaultMethodAttributeAppenderFactory); } /** * Defines a bridge method resolver factory to be applied to this configuration. A bridge method resolver is * responsible for determining the target method that is invoked by a bridge method. This way, a super method * invocation is resolved by invoking the actual super method instead of the bridge method which would in turn * resolve the actual method virtually. * * @param bridgeMethodResolverFactory The bridge method resolver factory to be applied to any implementation * process. * @return A new configuration that represents this configuration with the given bridge method resolver factory * to be applied on any configuration. */ public ByteBuddy withBridgeMethodResolver(BridgeMethodResolver.Factory bridgeMethodResolverFactory) { return new ByteBuddy(classFileVersion, namingStrategy, auxiliaryTypeNamingStrategy, interfaceTypes, ignoredMethods, nonNull(bridgeMethodResolverFactory), classVisitorWrapperChain, methodRegistry, modifiers, typeAttributeAppender, methodLookupEngineFactory, defaultFieldAttributeAppenderFactory, defaultMethodAttributeAppenderFactory); } /** * Defines a new class visitor to be appended to the current collection of {@link org.objectweb.asm.ClassVisitor}s * that are to be applied onto any creation process of a dynamic type. * * @param classVisitorWrapper The class visitor wrapper to ba appended to the current chain of class visitor wrappers. * @return The same configuration with the given class visitor wrapper to be applied onto any creation process of a dynamic * type. */ public ByteBuddy withClassVisitor(ClassVisitorWrapper classVisitorWrapper) { return new ByteBuddy(classFileVersion, namingStrategy, auxiliaryTypeNamingStrategy, interfaceTypes, ignoredMethods, bridgeMethodResolverFactory, classVisitorWrapperChain.append(nonNull(classVisitorWrapper)), methodRegistry, modifiers, typeAttributeAppender, methodLookupEngineFactory, defaultFieldAttributeAppenderFactory, defaultMethodAttributeAppenderFactory); } /** * Defines a new {@link MethodLookupEngine.Factory} to be used for creating * {@link MethodLookupEngine}s for type creations based on this configuration. * The default lookup engine queries any class or interface type that is represented by the created type. These * queries might however be costly such that this factory can be configured to save lookup time, for example * by providing additional caching or by providing precomputed results. * * @param methodLookupEngineFactory The method lookup engine factory to apply to this configuration. * @return The same configuration with the method lookup engine factory. */ public ByteBuddy withMethodLookupEngine(MethodLookupEngine.Factory methodLookupEngineFactory) { return new ByteBuddy(classFileVersion, namingStrategy, auxiliaryTypeNamingStrategy, interfaceTypes, ignoredMethods, bridgeMethodResolverFactory, classVisitorWrapperChain, methodRegistry, modifiers, typeAttributeAppender, nonNull(methodLookupEngineFactory), defaultFieldAttributeAppenderFactory, defaultMethodAttributeAppenderFactory); } public ByteBuddy withDefaultFieldAttributeAppender(FieldAttributeAppender.Factory attributeAppenderFactory) { return new ByteBuddy(classFileVersion, namingStrategy, auxiliaryTypeNamingStrategy, interfaceTypes, ignoredMethods, bridgeMethodResolverFactory, classVisitorWrapperChain, methodRegistry, modifiers, typeAttributeAppender, methodLookupEngineFactory, nonNull(attributeAppenderFactory), defaultMethodAttributeAppenderFactory); } /** * Defines a new default method attribute appender factory that is applied onto any method. * * @param attributeAppenderFactory The attribute appender factory that is applied as a default on any * method that is created or intercepted by a dynamic type that is created * with this configuration. * @return The same configuration with the given method attribute appender factory to be applied as a default to * the creation or interception process of any method of a dynamic type. */ public ByteBuddy withDefaultMethodAttributeAppender(MethodAttributeAppender.Factory attributeAppenderFactory) { return new ByteBuddy(classFileVersion, namingStrategy, auxiliaryTypeNamingStrategy, interfaceTypes, ignoredMethods, bridgeMethodResolverFactory, classVisitorWrapperChain, methodRegistry, modifiers, typeAttributeAppender, methodLookupEngineFactory, defaultFieldAttributeAppenderFactory, nonNull(attributeAppenderFactory)); } /** * Intercepts a given selection of byte code level methods, i.e. a method, a constructor or the type initializer. * * @param methodMatcher The method matcher representing all byte code methods to intercept. * @return A matched method interception for the given selection. */ public MatchedMethodInterception invokable(ElementMatcher<? super MethodDescription> methodMatcher) { return invokeable(new LatentMethodMatcher.Resolved(nonNull(methodMatcher))); } /** * Intercepts a given selection of byte code level methods, i.e. a method, a constructor or the type initializer. * * @param methodMatcher The latent method matcher representing all byte code methods to intercept. * @return A matched method interception for the given selection. */ public MatchedMethodInterception invokeable(LatentMethodMatcher methodMatcher) { return new MatchedMethodInterception(nonNull(methodMatcher)); } /** * Intercepts a given method selection. * * @param methodMatcher The method matcher representing all methods to intercept. * @return A matched method interception for the given selection. */ public MatchedMethodInterception method(ElementMatcher<? super MethodDescription> methodMatcher) { return invokable(isMethod().and(nonNull(methodMatcher))); } /** * Intercepts a given constructor selection. * * @param methodMatcher The method matcher representing all constructors to intercept. * @return A matched method interception for the given selection. */ public MatchedMethodInterception constructor(ElementMatcher<? super MethodDescription> methodMatcher) { return invokable(isConstructor().and(nonNull(methodMatcher))); } @Override public boolean equals(Object other) { if (this == other) return true; if (other == null || getClass() != other.getClass()) return false; ByteBuddy byteBuddy = (ByteBuddy) other; return bridgeMethodResolverFactory.equals(byteBuddy.bridgeMethodResolverFactory) && classFileVersion.equals(byteBuddy.classFileVersion) && classVisitorWrapperChain.equals(byteBuddy.classVisitorWrapperChain) && defaultFieldAttributeAppenderFactory.equals(byteBuddy.defaultFieldAttributeAppenderFactory) && defaultMethodAttributeAppenderFactory.equals(byteBuddy.defaultMethodAttributeAppenderFactory) && ignoredMethods.equals(byteBuddy.ignoredMethods) && interfaceTypes.equals(byteBuddy.interfaceTypes) && methodLookupEngineFactory.equals(byteBuddy.methodLookupEngineFactory) && methodRegistry.equals(byteBuddy.methodRegistry) && modifiers.equals(byteBuddy.modifiers) && namingStrategy.equals(byteBuddy.namingStrategy) && auxiliaryTypeNamingStrategy.equals(byteBuddy.auxiliaryTypeNamingStrategy) && typeAttributeAppender.equals(byteBuddy.typeAttributeAppender); } @Override public int hashCode() { int result = classFileVersion.hashCode(); result = 31 * result + namingStrategy.hashCode(); result = 31 * result + auxiliaryTypeNamingStrategy.hashCode(); result = 31 * result + interfaceTypes.hashCode(); result = 31 * result + ignoredMethods.hashCode(); result = 31 * result + bridgeMethodResolverFactory.hashCode(); result = 31 * result + classVisitorWrapperChain.hashCode(); result = 31 * result + methodRegistry.hashCode(); result = 31 * result + modifiers.hashCode(); result = 31 * result + methodLookupEngineFactory.hashCode(); result = 31 * result + typeAttributeAppender.hashCode(); result = 31 * result + defaultFieldAttributeAppenderFactory.hashCode(); result = 31 * result + defaultMethodAttributeAppenderFactory.hashCode(); return result; } @Override public String toString() { return "ByteBuddy{" + "classFileVersion=" + classFileVersion + ", namingStrategy=" + namingStrategy + ", auxiliaryTypeNamingStrategy=" + auxiliaryTypeNamingStrategy + ", interfaceTypes=" + interfaceTypes + ", ignoredMethods=" + ignoredMethods + ", bridgeMethodResolverFactory=" + bridgeMethodResolverFactory + ", classVisitorWrapperChain=" + classVisitorWrapperChain + ", methodRegistry=" + methodRegistry + ", modifiers=" + modifiers + ", methodLookupEngineFactory=" + methodLookupEngineFactory + ", typeAttributeAppender=" + typeAttributeAppender + ", defaultFieldAttributeAppenderFactory=" + defaultFieldAttributeAppenderFactory + ", defaultMethodAttributeAppenderFactory=" + defaultMethodAttributeAppenderFactory + '}'; } /** * Any definable instance is either {@link net.bytebuddy.ByteBuddy.Definable.Defined} when a value is provided * or {@link net.bytebuddy.ByteBuddy.Definable.Undefined} if a value is not provided. A defined definable will * return its defined value on request while an undefined definable will return the provided default. * * @param <T> The type of the definable object. */ protected interface Definable<T> { /** * Returns the value of this instance or the provided default value for an undefined definable. * * @param defaultValue The default value that is returned for an {@link net.bytebuddy.ByteBuddy.Definable.Undefined} * definable. * @return The value that is represented by this instance. */ T resolve(T defaultValue); /** * Checks if this value is explicitly defined. * * @return {@code true} if this value is defined. */ boolean isDefined(); /** * A representation of an undefined {@link net.bytebuddy.ByteBuddy.Definable}. * * @param <T> The type of the definable object. */ class Undefined<T> implements Definable<T> { @Override public T resolve(T defaultValue) { return defaultValue; } @Override public boolean isDefined() { return false; } @Override public boolean equals(Object other) { return other != null && other.getClass() == Undefined.class; } @Override public int hashCode() { return 31; } @Override public String toString() { return "ByteBuddy.Definable.Undefined{}"; } } /** * A representation of a defined {@link net.bytebuddy.ByteBuddy.Definable} for a given value. * * @param <T> The type of the definable object. */ class Defined<T> implements Definable<T> { /** * The value that is represented by this defined definable. */ private final T value; /** * Creates a new defined instance for the given value. * * @param value The defined value. */ public Defined(T value) { this.value = value; } @Override public T resolve(T defaultValue) { return value; } @Override public boolean isDefined() { return true; } @Override public boolean equals(Object o) { return this == o || !(o == null || getClass() != o.getClass()) && value.equals(((Defined) o).value); } @Override public int hashCode() { return value.hashCode(); } @Override public String toString() { return "ByteBuddy.Definable.Defined{value=" + value + '}'; } } } /** * Implementations of this interface are capable of defining a method interception for a given set of methods. */ public interface MethodInterceptable { /** * Intercepts the given method with the given implementations. * * @param implementation The implementation to apply to the selected methods. * @return A method annotation target for this instance with the given implementation applied to the * current selection. */ MethodAnnotationTarget intercept(Implementation implementation); /** * Defines the currently selected methods as {@code abstract}. * * @return A method annotation target for this instance with implementing the currently selected methods * as {@code abstract}. */ MethodAnnotationTarget withoutCode(); /** * Defines a default annotation value to set for any matched method. * * @param value The value that the annotation property should set as a default. * @param type The type of the annotation property. * @return A builder which defines the given default value for all matched methods. */ MethodAnnotationTarget withDefaultValue(Object value, Class<?> type); /** * Defines a default annotation value to set for any matched method. The value is to be represented in a wrapper format, * {@code enum} values should be handed as {@link net.bytebuddy.description.enumeration.EnumerationDescription} * instances, annotations as {@link AnnotationDescription} instances and * {@link Class} values as {@link TypeDescription} instances. Other values are handed in their raw format or as their wrapper types. * * @param value A non-loaded value that the annotation property should set as a default. * @return A builder which defines the given default value for all matched methods. */ MethodAnnotationTarget withDefaultValue(Object value); } /** * A {@link net.bytebuddy.ByteBuddy} configuration with a selected set of methods for which annotations can * be defined. */ public static class MethodAnnotationTarget extends Proxy { /** * The method matcher representing the current method selection. */ protected final LatentMethodMatcher methodMatcher; /** * The handler for the entry that is to be registered. */ protected final MethodRegistry.Handler handler; /** * The method attribute appender factory that was defined for the current method selection. */ protected final MethodAttributeAppender.Factory attributeAppenderFactory; /** * Creates a new method annotation target. * * @param classFileVersion The currently defined class file version. * @param namingStrategy The currently defined naming strategy. * @param auxiliaryTypeNamingStrategy The currently defined naming strategy for auxiliary types. * @param interfaceTypes The currently defined collection of interfaces to be implemented * by any dynamically created type. * @param ignoredMethods The methods to always be ignored. * @param bridgeMethodResolverFactory The bridge method resolver factory to be applied to any implementation * process. * @param classVisitorWrapperChain The class visitor wrapper chain to be applied to any implementation * process. * @param methodRegistry The currently valid method registry. * @param modifiers The modifiers to define for any implementation process. * @param typeAttributeAppender The type attribute appender to apply to any implementation process. * @param methodLookupEngineFactory The method lookup engine factory to apply to this configuration. * @param defaultFieldAttributeAppenderFactory The field attribute appender to apply as a default for any field * definition. * @param defaultMethodAttributeAppenderFactory The method attribute appender to apply as a default for any * method definition or implementation. * @param methodMatcher The method matcher representing the current method selection. * @param handler The handler for the entry that is to be registered. * @param attributeAppenderFactory The method attribute appender factory that was defined for the current method selection. */ protected MethodAnnotationTarget(ClassFileVersion classFileVersion, NamingStrategy.Unbound namingStrategy, AuxiliaryType.NamingStrategy auxiliaryTypeNamingStrategy, List<TypeDescription> interfaceTypes, ElementMatcher<? super MethodDescription> ignoredMethods, BridgeMethodResolver.Factory bridgeMethodResolverFactory, ClassVisitorWrapper.Chain classVisitorWrapperChain, MethodRegistry methodRegistry, Definable<Integer> modifiers, TypeAttributeAppender typeAttributeAppender, MethodLookupEngine.Factory methodLookupEngineFactory, FieldAttributeAppender.Factory defaultFieldAttributeAppenderFactory, MethodAttributeAppender.Factory defaultMethodAttributeAppenderFactory, LatentMethodMatcher methodMatcher, MethodRegistry.Handler handler, MethodAttributeAppender.Factory attributeAppenderFactory) { super(classFileVersion, namingStrategy, auxiliaryTypeNamingStrategy, interfaceTypes, ignoredMethods, bridgeMethodResolverFactory, classVisitorWrapperChain, methodRegistry, modifiers, typeAttributeAppender, methodLookupEngineFactory, defaultFieldAttributeAppenderFactory, defaultMethodAttributeAppenderFactory); this.methodMatcher = methodMatcher; this.handler = handler; this.attributeAppenderFactory = attributeAppenderFactory; } /** * Defines a given attribute appender factory to be applied for the currently selected methods. * * @param attributeAppenderFactory The method attribute appender factory to apply to the currently * selected methods. * @return A method annotation target that represents the current configuration with the additional * attribute appender factory applied to the current method selection. */ public MethodAnnotationTarget attribute(MethodAttributeAppender.Factory attributeAppenderFactory) { return new MethodAnnotationTarget(classFileVersion, namingStrategy, auxiliaryTypeNamingStrategy, interfaceTypes, ignoredMethods, bridgeMethodResolverFactory, classVisitorWrapperChain, methodRegistry, modifiers, typeAttributeAppender, methodLookupEngineFactory, defaultFieldAttributeAppenderFactory, defaultMethodAttributeAppenderFactory, methodMatcher, handler, new MethodAttributeAppender.Factory.Compound(this.attributeAppenderFactory, nonNull(attributeAppenderFactory))); } /** * Defines an method annotation for the currently selected methods. * * @param annotation The annotations to defined for the currently selected methods. * @return A method annotation target that represents the current configuration with the additional * annotations added to the currently selected methods. */ public MethodAnnotationTarget annotateMethod(Annotation... annotation) { return annotateMethod(new AnnotationList.ForLoadedAnnotation(nonNull(annotation))); } /** * Defines an method annotation for the currently selected methods. * * @param annotation The annotations to defined for the currently selected methods. * @return A method annotation target that represents the current configuration with the additional * annotations added to the currently selected methods. */ public MethodAnnotationTarget annotateMethod(AnnotationDescription... annotation) { return annotateMethod(new AnnotationList.Explicit(Arrays.asList(nonNull(annotation)))); } /** * Defines an method annotation for the currently selected methods. * * @param annotations The annotations to defined for the currently selected methods. * @return A method annotation target that represents the current configuration with the additional * annotations added to the currently selected methods. */ public MethodAnnotationTarget annotateMethod(Collection<? extends AnnotationDescription> annotations) { return attribute(new MethodAttributeAppender.ForAnnotation(new ArrayList<AnnotationDescription>(nonNull(annotations)))); } /** * Defines an method annotation for a parameter of the currently selected methods. * * @param parameterIndex The index of the parameter for which the annotations should be applied * with the first parameter index by {@code 0}. * @param annotation The annotations to defined for the currently selected methods' parameters * ath the given index. * @return A method annotation target that represents the current configuration with the additional * annotations added to the currently selected methods' parameters at the given index. */ public MethodAnnotationTarget annotateParameter(int parameterIndex, Annotation... annotation) { return annotateParameter(parameterIndex, new AnnotationList.ForLoadedAnnotation(nonNull(annotation))); } /** * Defines an method annotation for a parameter of the currently selected methods. * * @param parameterIndex The index of the parameter for which the annotations should be applied * with the first parameter index by {@code 0}. * @param annotation The annotations to defined for the currently selected methods' parameters * ath the given index. * @return A method annotation target that represents the current configuration with the additional * annotations added to the currently selected methods' parameters at the given index. */ public MethodAnnotationTarget annotateParameter(int parameterIndex, AnnotationDescription... annotation) { return annotateParameter(parameterIndex, new AnnotationList.Explicit(Arrays.asList(nonNull(annotation)))); } /** * Defines an method annotation for a parameter of the currently selected methods. * * @param parameterIndex The index of the parameter for which the annotations should be applied * with the first parameter index by {@code 0}. * @param annotations The annotations to defined for the currently selected methods' parameters * ath the given index. * @return A method annotation target that represents the current configuration with the additional * annotations added to the currently selected methods' parameters at the given index. */ public MethodAnnotationTarget annotateParameter(int parameterIndex, Collection<? extends AnnotationDescription> annotations) { return attribute(new MethodAttributeAppender.ForAnnotation(parameterIndex, new ArrayList<AnnotationDescription>(nonNull(annotations)))); } @Override protected ByteBuddy materialize() { return new ByteBuddy(classFileVersion, namingStrategy, auxiliaryTypeNamingStrategy, interfaceTypes, ignoredMethods, bridgeMethodResolverFactory, classVisitorWrapperChain, methodRegistry.prepend(methodMatcher, handler, attributeAppenderFactory), modifiers, typeAttributeAppender, methodLookupEngineFactory, defaultFieldAttributeAppenderFactory, defaultMethodAttributeAppenderFactory ); } @Override public boolean equals(Object other) { if (this == other) return true; if (other == null || getClass() != other.getClass()) return false; if (!super.equals(other)) return false; MethodAnnotationTarget that = (MethodAnnotationTarget) other; return attributeAppenderFactory.equals(that.attributeAppenderFactory) && handler.equals(that.handler) && methodMatcher.equals(that.methodMatcher); } @Override public int hashCode() { int result = super.hashCode(); result = 31 * result + methodMatcher.hashCode(); result = 31 * result + handler.hashCode(); result = 31 * result + attributeAppenderFactory.hashCode(); return result; } @Override public String toString() { return "ByteBuddy.MethodAnnotationTarget{" + "classFileVersion=" + classFileVersion + ", namingStrategy=" + namingStrategy + ", auxiliaryTypeNamingStrategy=" + auxiliaryTypeNamingStrategy + ", interfaceTypes=" + interfaceTypes + ", ignoredMethods=" + ignoredMethods + ", bridgeMethodResolverFactory=" + bridgeMethodResolverFactory + ", classVisitorWrapperChain=" + classVisitorWrapperChain + ", methodRegistry=" + methodRegistry + ", modifiers=" + modifiers + ", methodLookupEngineFactory=" + methodLookupEngineFactory + ", typeAttributeAppender=" + typeAttributeAppender + ", defaultFieldAttributeAppenderFactory=" + defaultFieldAttributeAppenderFactory + ", defaultMethodAttributeAppenderFactory=" + defaultMethodAttributeAppenderFactory + ", methodMatcher=" + methodMatcher + ", handler=" + handler + ", attributeAppenderFactory=" + attributeAppenderFactory + '}'; } } /** * An optional method interception that allows to intercept a method selection only if this is needed. */ public static class OptionalMethodInterception extends ByteBuddy implements MethodInterceptable { /** * The method matcher that defines the selected that is represented by this instance. */ protected final LatentMethodMatcher methodMatcher; /** * Creates a new optional method interception. * * @param classFileVersion The currently defined class file version. * @param namingStrategy The currently defined naming strategy. * @param auxiliaryTypeNamingStrategy The currently defined naming strategy for auxiliary types. * @param interfaceTypes The currently defined collection of interfaces to be implemented * by any dynamically created type. * @param ignoredMethods The methods to always be ignored. * @param bridgeMethodResolverFactory The bridge method resolver factory to be applied to any implementation * process. * @param classVisitorWrapperChain The class visitor wrapper chain to be applied to any implementation * process. * @param methodRegistry The currently valid method registry. * @param modifiers The modifiers to define for any implementation process. * @param typeAttributeAppender The type attribute appender to apply to any implementation process. * @param methodLookupEngineFactory The method lookup engine factory to apply to this configuration. * @param defaultFieldAttributeAppenderFactory The field attribute appender to apply as a default for any field * definition. * @param defaultMethodAttributeAppenderFactory The method attribute appender to apply as a default for any * method definition or implementation. * @param methodMatcher The method matcher representing the current method selection. */ protected OptionalMethodInterception(ClassFileVersion classFileVersion, NamingStrategy.Unbound namingStrategy, AuxiliaryType.NamingStrategy auxiliaryTypeNamingStrategy, List<TypeDescription> interfaceTypes, ElementMatcher<? super MethodDescription> ignoredMethods, BridgeMethodResolver.Factory bridgeMethodResolverFactory, ClassVisitorWrapper.Chain classVisitorWrapperChain, MethodRegistry methodRegistry, Definable<Integer> modifiers, TypeAttributeAppender typeAttributeAppender, MethodLookupEngine.Factory methodLookupEngineFactory, FieldAttributeAppender.Factory defaultFieldAttributeAppenderFactory, MethodAttributeAppender.Factory defaultMethodAttributeAppenderFactory, LatentMethodMatcher methodMatcher) { super(classFileVersion, namingStrategy, auxiliaryTypeNamingStrategy, interfaceTypes, ignoredMethods, bridgeMethodResolverFactory, classVisitorWrapperChain, methodRegistry, modifiers, typeAttributeAppender, methodLookupEngineFactory, defaultFieldAttributeAppenderFactory, defaultMethodAttributeAppenderFactory); this.methodMatcher = methodMatcher; } @Override public MethodAnnotationTarget intercept(Implementation implementation) { return new MatchedMethodInterception(methodMatcher).intercept(implementation); } @Override public MethodAnnotationTarget withoutCode() { return new MatchedMethodInterception(methodMatcher).withoutCode(); } @Override public MethodAnnotationTarget withDefaultValue(Object value, Class<?> type) { return new MatchedMethodInterception(methodMatcher).withDefaultValue(value, type); } @Override public MethodAnnotationTarget withDefaultValue(Object value) { return new MatchedMethodInterception(methodMatcher).withDefaultValue(value); } @Override public boolean equals(Object other) { return this == other || !(other == null || getClass() != other.getClass()) && super.equals(other) && methodMatcher.equals(((OptionalMethodInterception) other).methodMatcher); } @Override public int hashCode() { return 31 * methodMatcher.hashCode() + super.hashCode(); } @Override public String toString() { return "ByteBuddy.OptionalMethodInterception{" + "classFileVersion=" + classFileVersion + ", namingStrategy=" + namingStrategy + ", auxiliaryTypeNamingStrategy=" + auxiliaryTypeNamingStrategy + ", interfaceTypes=" + interfaceTypes + ", ignoredMethods=" + ignoredMethods + ", bridgeMethodResolverFactory=" + bridgeMethodResolverFactory + ", classVisitorWrapperChain=" + classVisitorWrapperChain + ", methodRegistry=" + methodRegistry + ", modifiers=" + modifiers + ", methodLookupEngineFactory=" + methodLookupEngineFactory + ", typeAttributeAppender=" + typeAttributeAppender + ", defaultFieldAttributeAppenderFactory=" + defaultFieldAttributeAppenderFactory + ", defaultMethodAttributeAppenderFactory=" + defaultMethodAttributeAppenderFactory + ", methodMatcher=" + methodMatcher + '}'; } } /** * A proxy implementation for extending Byte Buddy while allowing for enhancing a {@link net.bytebuddy.ByteBuddy} * configuration. */ protected abstract static class Proxy extends ByteBuddy { /** * Defines a new proxy configuration for {@code ByteBuddy}. * * @param classFileVersion The currently defined class file version. * @param namingStrategy The currently defined naming strategy. * @param auxiliaryTypeNamingStrategy The currently defined naming strategy for auxiliary types. * @param interfaceTypes The currently defined collection of interfaces to be * implemented by any dynamically created type. * @param ignoredMethods The methods to always be ignored. * @param bridgeMethodResolverFactory The bridge method resolver factory to be applied to any * implementation process. * @param classVisitorWrapperChain The class visitor wrapper chain to be applied to any * implementation process. * @param methodRegistry The currently valid method registry. * @param modifiers The modifiers to define for any implementation process. * @param typeAttributeAppender The type attribute appender to apply to any implementation * process. * @param methodLookupEngineFactory The method lookup engine factory to apply to this configuration. * @param defaultFieldAttributeAppenderFactory The field attribute appender to apply as a default for any * field definition. * @param defaultMethodAttributeAppenderFactory The method attribute appender to apply as a default for any * method definition or implementation. */ protected Proxy(ClassFileVersion classFileVersion, NamingStrategy.Unbound namingStrategy, AuxiliaryType.NamingStrategy auxiliaryTypeNamingStrategy, List<TypeDescription> interfaceTypes, ElementMatcher<? super MethodDescription> ignoredMethods, BridgeMethodResolver.Factory bridgeMethodResolverFactory, ClassVisitorWrapper.Chain classVisitorWrapperChain, MethodRegistry methodRegistry, Definable<Integer> modifiers, TypeAttributeAppender typeAttributeAppender, MethodLookupEngine.Factory methodLookupEngineFactory, FieldAttributeAppender.Factory defaultFieldAttributeAppenderFactory, MethodAttributeAppender.Factory defaultMethodAttributeAppenderFactory) { super(classFileVersion, namingStrategy, auxiliaryTypeNamingStrategy, interfaceTypes, ignoredMethods, bridgeMethodResolverFactory, classVisitorWrapperChain, methodRegistry, modifiers, typeAttributeAppender, methodLookupEngineFactory, defaultFieldAttributeAppenderFactory, defaultMethodAttributeAppenderFactory); } @Override public ClassFileVersion getClassFileVersion() { return materialize().getClassFileVersion(); } @Override public NamingStrategy.Unbound getNamingStrategy() { return materialize().getNamingStrategy(); } @Override public List<TypeDescription> getInterfaceTypes() { return materialize().getInterfaceTypes(); } @Override public ElementMatcher<? super MethodDescription> getIgnoredMethods() { return materialize().getIgnoredMethods(); } @Override public BridgeMethodResolver.Factory getBridgeMethodResolverFactory() { return materialize().getBridgeMethodResolverFactory(); } @Override public ClassVisitorWrapper.Chain getClassVisitorWrapperChain() { return materialize().getClassVisitorWrapperChain(); } @Override public MethodRegistry getMethodRegistry() { return materialize().getMethodRegistry(); } @Override public Definable<Integer> getModifiers() { return materialize().getModifiers(); } @Override public MethodLookupEngine.Factory getMethodLookupEngineFactory() { return materialize().getMethodLookupEngineFactory(); } @Override public TypeAttributeAppender getTypeAttributeAppender() { return materialize().getTypeAttributeAppender(); } @Override public FieldAttributeAppender.Factory getDefaultFieldAttributeAppenderFactory() { return materialize().getDefaultFieldAttributeAppenderFactory(); } @Override public MethodAttributeAppender.Factory getDefaultMethodAttributeAppenderFactory() { return materialize().getDefaultMethodAttributeAppenderFactory(); } @Override public AuxiliaryType.NamingStrategy getAuxiliaryTypeNamingStrategy() { return materialize().getAuxiliaryTypeNamingStrategy(); } @Override public <T> DynamicType.Builder<T> subclass(Class<T> superType) { return materialize().subclass(superType); } @Override public <T> DynamicType.Builder<T> subclass(Class<T> superType, ConstructorStrategy constructorStrategy) { return materialize().subclass(superType, constructorStrategy); } @Override public <T> DynamicType.Builder<T> subclass(TypeDescription superType) { return materialize().subclass(superType); } @Override public <T> DynamicType.Builder<T> subclass(TypeDescription superType, ConstructorStrategy constructorStrategy) { return materialize().subclass(superType, constructorStrategy); } @Override public <T> DynamicType.Builder<T> redefine(Class<T> levelType) { return materialize().redefine(levelType); } @Override public <T> DynamicType.Builder<T> redefine(Class<T> levelType, ClassFileLocator classFileLocator) { return materialize().redefine(levelType, classFileLocator); } @Override public <T> DynamicType.Builder<T> redefine(TypeDescription levelType, ClassFileLocator classFileLocator) { return materialize().redefine(levelType, classFileLocator); } @Override public <T> DynamicType.Builder<T> rebase(Class<T> levelType) { return materialize().rebase(levelType); } @Override public <T> DynamicType.Builder<T> rebase(Class<T> levelType, ClassFileLocator classFileLocator) { return materialize().rebase(levelType, classFileLocator); } @Override public <T> DynamicType.Builder<T> rebase(Class<T> levelType, ClassFileLocator classFileLocator, MethodRebaseResolver.MethodNameTransformer methodNameTransformer) { return materialize().rebase(levelType, classFileLocator, methodNameTransformer); } @Override public <T> DynamicType.Builder<T> rebase(TypeDescription levelType, ClassFileLocator classFileLocator) { return materialize().rebase(levelType, classFileLocator); } @Override public <T> DynamicType.Builder<T> rebase(TypeDescription levelType, ClassFileLocator classFileLocator, MethodRebaseResolver.MethodNameTransformer methodNameTransformer) { return super.rebase(levelType, classFileLocator, methodNameTransformer); } @Override public ByteBuddy withClassFileVersion(ClassFileVersion classFileVersion) { return materialize().withClassFileVersion(classFileVersion); } @Override public ByteBuddy withNamingStrategy(NamingStrategy.Unbound namingStrategy) { return materialize().withNamingStrategy(namingStrategy); } @Override public ByteBuddy withNamingStrategy(NamingStrategy namingStrategy) { return materialize().withNamingStrategy(namingStrategy); } @Override public ByteBuddy withNamingStrategy(AuxiliaryType.NamingStrategy auxiliaryTypeNamingStrategy) { return materialize().withNamingStrategy(auxiliaryTypeNamingStrategy); } @Override public ByteBuddy withModifiers(ModifierContributor.ForType... modifierContributor) { return materialize().withModifiers(modifierContributor); } @Override public ByteBuddy withAttribute(TypeAttributeAppender typeAttributeAppender) { return materialize().withAttribute(typeAttributeAppender); } @Override public ByteBuddy withTypeAnnotation(Annotation... annotation) { return materialize().withTypeAnnotation(annotation); } @Override public ByteBuddy withTypeAnnotation(Iterable<? extends Annotation> annotations) { return materialize().withTypeAnnotation(annotations); } @Override public ByteBuddy withTypeAnnotation(Collection<? extends AnnotationDescription> annotations) { return materialize().withTypeAnnotation(annotations); } @Override public OptionalMethodInterception withImplementing(Class<?>... type) { return materialize().withImplementing(type); } @Override public OptionalMethodInterception withImplementing(Iterable<? extends Class<?>> types) { return materialize().withImplementing(types); } @Override public OptionalMethodInterception withImplementing(TypeDescription... type) { return materialize().withImplementing(type); } @Override public OptionalMethodInterception withImplementing(Collection<? extends TypeDescription> types) { return materialize().withImplementing(types); } @Override public ByteBuddy withIgnoredMethods(ElementMatcher<? super MethodDescription> ignoredMethods) { return materialize().withIgnoredMethods(ignoredMethods); } @Override public ByteBuddy withBridgeMethodResolver(BridgeMethodResolver.Factory bridgeMethodResolverFactory) { return materialize().withBridgeMethodResolver(bridgeMethodResolverFactory); } @Override public ByteBuddy withClassVisitor(ClassVisitorWrapper classVisitorWrapper) { return materialize().withClassVisitor(classVisitorWrapper); } @Override public ByteBuddy withMethodLookupEngine(MethodLookupEngine.Factory methodLookupEngineFactory) { return materialize().withMethodLookupEngine(methodLookupEngineFactory); } @Override public ByteBuddy withDefaultFieldAttributeAppender(FieldAttributeAppender.Factory attributeAppenderFactory) { return materialize().withDefaultFieldAttributeAppender(attributeAppenderFactory); } @Override public ByteBuddy withDefaultMethodAttributeAppender(MethodAttributeAppender.Factory attributeAppenderFactory) { return materialize().withDefaultMethodAttributeAppender(attributeAppenderFactory); } @Override public MatchedMethodInterception invokable(ElementMatcher<? super MethodDescription> methodMatcher) { return materialize().invokable(methodMatcher); } @Override public <T> DynamicType.Builder<T> makeInterface(Class<T> type) { return materialize().makeInterface(type); } @Override public DynamicType.Builder<?> makeInterface(Class<?>... type) { return materialize().makeInterface(type); } @Override public DynamicType.Builder<?> makeInterface(Iterable<? extends Class<?>> types) { return materialize().makeInterface(types); } @Override public DynamicType.Builder<?> makeInterface(Collection<? extends TypeDescription> typeDescriptions) { return materialize().makeInterface(typeDescriptions); } @Override public DynamicType.Builder<? extends Annotation> makeAnnotation() { return materialize().makeAnnotation(); } @Override public DynamicType.Builder<? extends Enum<?>> makeEnumeration(String... value) { return materialize().makeEnumeration(value); } @Override public DynamicType.Builder<? extends Enum<?>> makeEnumeration(Collection<String> values) { return materialize().makeEnumeration(values); } @Override public ByteBuddy withTypeAnnotation(AnnotationDescription... annotation) { return materialize().withTypeAnnotation(annotation); } @Override public MatchedMethodInterception invokeable(LatentMethodMatcher methodMatcher) { return materialize().invokeable(methodMatcher); } @Override public MatchedMethodInterception method(ElementMatcher<? super MethodDescription> methodMatcher) { return materialize().method(methodMatcher); } @Override public MatchedMethodInterception constructor(ElementMatcher<? super MethodDescription> methodMatcher) { return materialize().constructor(methodMatcher); } /** * Materializes the current extended configuration. * * @return The materialized Byte Buddy configuration. */ protected abstract ByteBuddy materialize(); } /** * A matched method interception for a non-optional method definition. */ public class MatchedMethodInterception implements MethodInterceptable { /** * A method matcher that represents the current method selection. */ protected final LatentMethodMatcher methodMatcher; /** * Creates a new matched method interception. * * @param methodMatcher The method matcher representing the current method selection. */ protected MatchedMethodInterception(LatentMethodMatcher methodMatcher) { this.methodMatcher = methodMatcher; } @Override public MethodAnnotationTarget intercept(Implementation implementation) { return new MethodAnnotationTarget(classFileVersion, namingStrategy, auxiliaryTypeNamingStrategy, interfaceTypes, ignoredMethods, bridgeMethodResolverFactory, classVisitorWrapperChain, methodRegistry, modifiers, typeAttributeAppender, methodLookupEngineFactory, defaultFieldAttributeAppenderFactory, defaultMethodAttributeAppenderFactory, methodMatcher, new MethodRegistry.Handler.ForImplementation(nonNull(implementation)), MethodAttributeAppender.NoOp.INSTANCE); } @Override public MethodAnnotationTarget withoutCode() { return new MethodAnnotationTarget(classFileVersion, namingStrategy, auxiliaryTypeNamingStrategy, interfaceTypes, ignoredMethods, bridgeMethodResolverFactory, classVisitorWrapperChain, methodRegistry, modifiers, typeAttributeAppender, methodLookupEngineFactory, defaultFieldAttributeAppenderFactory, defaultMethodAttributeAppenderFactory, methodMatcher, MethodRegistry.Handler.ForAbstractMethod.INSTANCE, MethodAttributeAppender.NoOp.INSTANCE); } @Override public MethodAnnotationTarget withDefaultValue(Object value, Class<?> type) { return withDefaultValue(AnnotationDescription.ForLoadedAnnotation.describe(nonNull(value), new TypeDescription.ForLoadedType(nonNull(type)))); } @Override public MethodAnnotationTarget withDefaultValue(Object value) { return new MethodAnnotationTarget(classFileVersion, namingStrategy, auxiliaryTypeNamingStrategy, interfaceTypes, ignoredMethods, bridgeMethodResolverFactory, classVisitorWrapperChain, methodRegistry, modifiers, typeAttributeAppender, methodLookupEngineFactory, defaultFieldAttributeAppenderFactory, defaultMethodAttributeAppenderFactory, methodMatcher, MethodRegistry.Handler.ForAnnotationValue.of(value), MethodAttributeAppender.NoOp.INSTANCE); } /** * Returns the outer class instance of this instance. * * @return The outer class instance. */ private ByteBuddy getByteBuddy() { return ByteBuddy.this; } @Override public boolean equals(Object other) { return this == other || !(other == null || getClass() != other.getClass()) && ByteBuddy.this.equals(((MatchedMethodInterception) other).getByteBuddy()) && methodMatcher.equals(((MatchedMethodInterception) other).methodMatcher); } @Override public int hashCode() { return 31 * methodMatcher.hashCode() + ByteBuddy.this.hashCode(); } @Override public String toString() { return "ByteBuddy.MatchedMethodInterception{" + "methodMatcher=" + methodMatcher + "byteBuddy=" + ByteBuddy.this.toString() + '}'; } } /** * An implementation fo the {@code values} method of an enumeration type. */ protected static class EnumerationImplementation implements Implementation { /** * The field modifiers to use for any field that is added to an enumeration. */ private static final int ENUM_FIELD_MODIFIERS = Opcodes.ACC_FINAL | Opcodes.ACC_STATIC | Opcodes.ACC_PUBLIC; /** * The name of the field containing an array of all enumeration values. */ private static final String ENUM_VALUES = "$VALUES"; /** * The name of the {@link java.lang.Object#clone()} method. */ protected static final String CLONE_METHOD_NAME = "clone"; /** * The name of the {@code valueOf} method that is defined for any enumeration. */ protected static final String ENUM_VALUE_OF_METHOD_NAME = "valueOf"; /** * The name of the {@code values} method that is defined for any enumeration. */ protected static final String ENUM_VALUES_METHOD_NAME = "values"; /** * The names of the enumerations to define for the enumeration. */ private final List<String> values; /** * Creates a new implementation of an enumeration type. * * @param values The values of the enumeration. */ protected EnumerationImplementation(List<String> values) { this.values = values; } @Override public InstrumentedType prepare(InstrumentedType instrumentedType) { for (String value : values) { instrumentedType = instrumentedType.withField(value, instrumentedType, ENUM_FIELD_MODIFIERS | Opcodes.ACC_ENUM); } return instrumentedType .withField(ENUM_VALUES, TypeDescription.ArrayProjection.of(instrumentedType, 1), ENUM_FIELD_MODIFIERS | Opcodes.ACC_SYNTHETIC) .withInitializer(new InitializationAppender(values)); } @Override public ByteCodeAppender appender(Target implementationTarget) { return new ValuesMethodAppender(implementationTarget.getTypeDescription()); } @Override public boolean equals(Object other) { return this == other || !(other == null || getClass() != other.getClass()) && values.equals(((EnumerationImplementation) other).values); } @Override public int hashCode() { return values.hashCode(); } @Override public String toString() { return "ByteBuddy.EnumerationImplementation{" + "values=" + values + '}'; } /** * A byte code appender for the {@code values} method of any enumeration type. */ protected static class ValuesMethodAppender implements ByteCodeAppender { /** * The instrumented enumeration type. */ private final TypeDescription instrumentedType; /** * Creates a new appender for the {@code values} method. * * @param instrumentedType The instrumented enumeration type. */ protected ValuesMethodAppender(TypeDescription instrumentedType) { this.instrumentedType = instrumentedType; } @Override public Size apply(MethodVisitor methodVisitor, Context implementationContext, MethodDescription instrumentedMethod) { FieldDescription valuesField = instrumentedType.getDeclaredFields().filter(named(ENUM_VALUES)).getOnly(); MethodDescription cloneArrayMethod = new MethodDescription.Latent(CLONE_METHOD_NAME, valuesField.getFieldType(), TypeDescription.OBJECT, Collections.<TypeDescription>emptyList(), Opcodes.ACC_PUBLIC, Collections.<TypeDescription>emptyList()); return new Size(new StackManipulation.Compound( FieldAccess.forField(valuesField).getter(), MethodInvocation.invoke(cloneArrayMethod), TypeCasting.to(valuesField.getFieldType()), MethodReturn.REFERENCE ).apply(methodVisitor, implementationContext).getMaximalSize(), instrumentedMethod.getStackSize()); } @Override public boolean equals(Object other) { return this == other || !(other == null || getClass() != other.getClass()) && instrumentedType.equals(((ValuesMethodAppender) other).instrumentedType); } @Override public int hashCode() { return instrumentedType.hashCode(); } @Override public String toString() { return "ByteBuddy.EnumerationImplementation.ValuesMethodAppender{" + "instrumentedType=" + instrumentedType + '}'; } } /** * A byte code appender for the type initializer of any enumeration type. */ protected static class InitializationAppender implements ByteCodeAppender { /** * The values of the enumeration that is being created. */ private final List<String> values; /** * Creates an appender for an enumerations type initializer. * * @param values The values of the enumeration that is being created. */ protected InitializationAppender(List<String> values) { this.values = values; } @Override public Size apply(MethodVisitor methodVisitor, Context implementationContext, MethodDescription instrumentedMethod) { TypeDescription instrumentedType = instrumentedMethod.getDeclaringType(); MethodDescription enumConstructor = instrumentedType.getDeclaredMethods() .filter(isConstructor().and(takesArguments(String.class, int.class))) .getOnly(); int ordinal = 0; StackManipulation stackManipulation = StackManipulation.LegalTrivial.INSTANCE; List<FieldDescription> enumerationFields = new ArrayList<FieldDescription>(values.size()); for (String value : values) { FieldDescription fieldDescription = instrumentedType.getDeclaredFields().filter(named(value)).getOnly(); stackManipulation = new StackManipulation.Compound(stackManipulation, TypeCreation.forType(instrumentedType), Duplication.SINGLE, new TextConstant(value), IntegerConstant.forValue(ordinal++), MethodInvocation.invoke(enumConstructor), FieldAccess.forField(fieldDescription).putter()); enumerationFields.add(fieldDescription); } List<StackManipulation> fieldGetters = new ArrayList<StackManipulation>(values.size()); for (FieldDescription fieldDescription : enumerationFields) { fieldGetters.add(FieldAccess.forField(fieldDescription).getter()); } stackManipulation = new StackManipulation.Compound( stackManipulation, ArrayFactory.forType(instrumentedType).withValues(fieldGetters), FieldAccess.forField(instrumentedType.getDeclaredFields().filter(named(ENUM_VALUES)).getOnly()).putter() ); return new Size(stackManipulation.apply(methodVisitor, implementationContext).getMaximalSize(), instrumentedMethod.getStackSize()); } @Override public boolean equals(Object other) { return this == other || !(other == null || getClass() != other.getClass()) && values.equals(((InitializationAppender) other).values); } @Override public int hashCode() { return values.hashCode(); } @Override public String toString() { return "ByteBuddy.EnumerationImplementation.InitializationAppender{" + "values=" + values + '}'; } } } }
package de.gw.auto.gui; import java.awt.ScrollPane; import java.lang.reflect.Field; import java.util.Vector; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; import de.gw.auto.domain.Auto; import de.gw.auto.domain.Settings; public class ShowAuto { private Settings setting; private String[] columns = { "Beschreibung", "Wert" }; private String[] dataBeschreibung = { "Kennzeichen", "Km Aktuell", "Km beim Kauf", "Datum Erstzulassung", "Kaufdatum", "Benzinarten" }; private Object[][] autoDetails = new Object[6][2]; private DefaultTableModel dtm = null; private JTable table = null; public ShowAuto(Settings setting) { super(); this.setting = setting; insertData(); dtm = new DefaultTableModel(autoDetails, columns); table = new JTable(dtm); } private void insertData() { Auto a = this.setting.getAktuellAuto(); int i = 0; int index = 0; for (String s : dataBeschreibung) { autoDetails[index][i] = s + ":"; index++; } i++; autoDetails[0][i] = a.getKfz(); autoDetails[1][i] = a.getKmAktuell(); autoDetails[2][i] = a.getKmKauf(); autoDetails[3][i] = a.getErstZulassung(); autoDetails[4][i] = a.getKauf(); autoDetails[5][i] = a.getBenzinartenString(); } public JScrollPane getTable() { return new JScrollPane(table); } }
package org.opendaylight.bgpcep.pcep.topology.provider; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.opendaylight.protocol.pcep.pcc.mock.spi.MsgBuilderUtil.createLspTlvs; import static org.opendaylight.protocol.util.CheckUtil.checkEquals; import static org.opendaylight.protocol.util.CheckUtil.checkNotPresentOperational; import static org.opendaylight.protocol.util.CheckUtil.readDataOperational; import com.google.common.base.Optional; import com.google.common.collect.Lists; import java.net.UnknownHostException; import java.util.Collections; import java.util.List; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import org.junit.Before; import org.junit.Test; import org.opendaylight.controller.config.yang.pcep.topology.provider.SessionState; import org.opendaylight.controller.md.sal.common.api.data.ReadFailedException; import org.opendaylight.controller.md.sal.common.api.data.TransactionCommitFailedException; import org.opendaylight.protocol.pcep.PCEPCloseTermination; import org.opendaylight.protocol.pcep.PCEPSession; import org.opendaylight.protocol.pcep.TerminationReason; import org.opendaylight.protocol.pcep.pcc.mock.spi.MsgBuilderUtil; import org.opendaylight.protocol.pcep.spi.AbstractMessageParser; import org.opendaylight.protocol.pcep.spi.PCEPErrors; import org.opendaylight.protocol.util.CheckUtil; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.network.topology.rev140113.NetworkTopologyRef; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.crabbe.initiated.rev131126.Pcinitiate; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.crabbe.initiated.rev131126.Stateful1; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.crabbe.initiated.rev131126.Stateful1Builder; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.crabbe.initiated.rev131126.pcinitiate.message.pcinitiate.message.Requests; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.Arguments1; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.Arguments1Builder; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.Arguments2; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.Arguments2Builder; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.Arguments3; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.Arguments3Builder; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.OperationalStatus; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.Pcrpt; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.PcrptBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.Pcupd; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.PlspId; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.SymbolicPathName; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.Tlvs1; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.Tlvs1Builder; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.lsp.identifiers.tlv.LspIdentifiersBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.lsp.object.LspBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.lsp.object.lsp.Tlvs; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.pcrpt.message.PcrptMessageBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.pcrpt.message.pcrpt.message.Reports; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.pcrpt.message.pcrpt.message.ReportsBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.pcrpt.message.pcrpt.message.reports.PathBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.pcupd.message.pcupd.message.Updates; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.stateful.capability.tlv.StatefulBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.ietf.stateful.rev131222.symbolic.path.name.tlv.SymbolicPathNameBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.Message; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.endpoints.address.family.Ipv4CaseBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.endpoints.address.family.ipv4._case.Ipv4Builder; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.endpoints.object.EndpointsObjBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.explicit.route.object.EroBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.open.object.Open; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.open.object.OpenBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.open.object.open.TlvsBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.pcep.error.object.ErrorObject; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.rsvp.rev150820.LspId; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.AddLspInput; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.AddLspInputBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.AddLspOutput; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.EnsureLspOperationalInput; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.EnsureLspOperationalInputBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.FailureType; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.OperationResult; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.RemoveLspInput; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.RemoveLspInputBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.UpdateLspInput; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.UpdateLspInputBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.UpdateLspOutput; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.add.lsp.args.ArgumentsBuilder; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.pcep.client.attributes.path.computation.client.ReportedLsp; import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.pcep.client.attributes.path.computation.client.reported.lsp.Path; import org.opendaylight.yangtools.yang.common.RpcResult; public class Stateful07TopologySessionListenerTest extends AbstractPCEPSessionTest<Stateful07TopologySessionListenerFactory> { private final String TUNNEL_NAME = "pcc_" + this.testAddress + "_tunnel_0"; private Stateful07TopologySessionListener listener; private PCEPSession session; @Override @Before public void setUp() throws Exception { super.setUp(); this.listener = (Stateful07TopologySessionListener) getSessionListener(); this.session = getPCEPSession(getLocalPref(), getRemotePref()); } @Test public void testStateful07TopologySessionListener() throws Exception { this.listener.onSessionUp(this.session); assertEquals(this.testAddress, this.listener.getPeerId()); final SessionState state = this.listener.getSessionState(); assertNotNull(state); assertEquals(DEAD_TIMER, state.getLocalPref().getDeadtimer().shortValue()); assertEquals(KEEP_ALIVE, state.getLocalPref().getKeepalive().shortValue()); assertEquals(0, state.getLocalPref().getSessionId().intValue()); assertEquals(this.testAddress, state.getLocalPref().getIpAddress()); assertEquals(DEAD_TIMER, state.getPeerPref().getDeadtimer().shortValue()); assertEquals(KEEP_ALIVE, state.getPeerPref().getKeepalive().shortValue()); assertEquals(0, state.getPeerPref().getSessionId().intValue()); assertEquals(this.testAddress, state.getPeerPref().getIpAddress()); // add-lsp this.topologyRpcs.addLsp(createAddLspInput()); assertEquals(1, this.receivedMsgs.size()); assertTrue(this.receivedMsgs.get(0) instanceof Pcinitiate); final Pcinitiate pcinitiate = (Pcinitiate) this.receivedMsgs.get(0); final Requests req = pcinitiate.getPcinitiateMessage().getRequests().get(0); final long srpId = req.getSrp().getOperationId().getValue(); final Tlvs tlvs = createLspTlvs(req.getLsp().getPlspId().getValue(), true, this.testAddress, this.testAddress, this.testAddress, Optional.absent()); final Pcrpt pcRpt = MsgBuilderUtil.createPcRtpMessage(new LspBuilder(req.getLsp()) .setTlvs(tlvs).setPlspId(new PlspId(1L)).setSync(false).setRemove(false) .setOperational(OperationalStatus.Active).build(), Optional.of(MsgBuilderUtil.createSrp(srpId)), MsgBuilderUtil.createPath(req.getEro().getSubobject())); final Pcrpt esm = MsgBuilderUtil.createPcRtpMessage(new LspBuilder().setSync(false).build(), Optional.of(MsgBuilderUtil.createSrp(0L)), null); this.listener.onMessage(this.session, esm); readDataOperational(getDataBroker(), this.pathComputationClientIId, pcc -> { assertEquals(this.testAddress, pcc.getIpAddress().getIpv4Address().getValue()); // reported lsp so far empty, has not received response (PcRpt) yet assertTrue(pcc.getReportedLsp().isEmpty()); return pcc; }); this.listener.onMessage(this.session, pcRpt); // check created lsp readDataOperational(getDataBroker(), this.pathComputationClientIId, pcc -> { assertEquals(1, pcc.getReportedLsp().size()); final ReportedLsp reportedLsp = pcc.getReportedLsp().get(0); assertEquals(this.TUNNEL_NAME, reportedLsp.getName()); assertEquals(1, reportedLsp.getPath().size()); final Path path = reportedLsp.getPath().get(0); assertEquals(1, path.getEro().getSubobject().size()); assertEquals(this.eroIpPrefix, getLastEroIpPrefix(path.getEro())); return pcc; }); // check stats checkEquals(()->assertEquals(1, this.listener.getDelegatedLspsCount().intValue())); checkEquals(()->assertTrue(this.listener.getSynchronized())); checkEquals(()->assertTrue(this.listener.getStatefulMessages().getLastReceivedRptMsgTimestamp() > 0)); checkEquals(()->assertEquals(2, this.listener.getStatefulMessages().getReceivedRptMsgCount().intValue())); checkEquals(()->assertEquals(1, this.listener.getStatefulMessages().getSentInitMsgCount().intValue())); checkEquals(()->assertEquals(0, this.listener.getStatefulMessages().getSentUpdMsgCount().intValue())); checkEquals(()->assertNotNull(this.listener.getSessionState())); // update-lsp final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.update.lsp.args .ArgumentsBuilder updArgsBuilder = new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang. topology.pcep.rev131024.update.lsp.args.ArgumentsBuilder(); updArgsBuilder.setEro(createEroWithIpPrefixes(Lists.newArrayList(this.eroIpPrefix, this.dstIpPrefix))); updArgsBuilder.addAugmentation(Arguments3.class, new Arguments3Builder().setLsp(new LspBuilder() .setDelegate(true).setAdministrative(true).build()).build()); final UpdateLspInput update = new UpdateLspInputBuilder().setArguments(updArgsBuilder.build()) .setName(this.TUNNEL_NAME).setNetworkTopologyRef(new NetworkTopologyRef(TOPO_IID)) .setNode(this.nodeId).build(); this.topologyRpcs.updateLsp(update); assertEquals(2, this.receivedMsgs.size()); assertTrue(this.receivedMsgs.get(1) instanceof Pcupd); final Pcupd updateMsg = (Pcupd) this.receivedMsgs.get(1); final Updates upd = updateMsg.getPcupdMessage().getUpdates().get(0); final long srpId2 = upd.getSrp().getOperationId().getValue(); final Tlvs tlvs2 = createLspTlvs(upd.getLsp().getPlspId().getValue(), false, this.newDestinationAddress, this.testAddress, this.testAddress, Optional.absent()); final Pcrpt pcRpt2 = MsgBuilderUtil.createPcRtpMessage(new LspBuilder(upd.getLsp()).setTlvs(tlvs2) .setSync(true).setRemove(false).setOperational(OperationalStatus.Active).build(), Optional.of(MsgBuilderUtil.createSrp(srpId2)), MsgBuilderUtil.createPath(upd.getPath() .getEro().getSubobject())); this.listener.onMessage(this.session, pcRpt2); //check updated lsp readDataOperational(getDataBroker(), this.pathComputationClientIId, pcc -> { assertEquals(1, pcc.getReportedLsp().size()); final ReportedLsp reportedLsp = pcc.getReportedLsp().get(0); assertEquals(this.TUNNEL_NAME, reportedLsp.getName()); assertEquals(1, reportedLsp.getPath().size()); final Path path = reportedLsp.getPath().get(0); assertEquals(2, path.getEro().getSubobject().size()); assertEquals(this.dstIpPrefix, getLastEroIpPrefix(path.getEro())); assertEquals(1, this.listener.getDelegatedLspsCount().intValue()); assertTrue(this.listener.getSynchronized()); assertTrue(this.listener.getStatefulMessages().getLastReceivedRptMsgTimestamp() > 0); assertEquals(3, this.listener.getStatefulMessages().getReceivedRptMsgCount().intValue()); assertEquals(1, this.listener.getStatefulMessages().getSentInitMsgCount().intValue()); assertEquals(1, this.listener.getStatefulMessages().getSentUpdMsgCount().intValue()); assertTrue(this.listener.getReplyTime().getAverageTime() > 0); assertTrue(this.listener.getReplyTime().getMaxTime() > 0); assertFalse(this.listener.getPeerCapabilities().getActive()); assertTrue(this.listener.getPeerCapabilities().getInstantiation()); assertTrue(this.listener.getPeerCapabilities().getStateful()); return pcc; }); // ensure-operational final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.ensure.lsp. operational.args.ArgumentsBuilder ensureArgs = new org.opendaylight.yang.gen.v1.urn.opendaylight.params. xml.ns.yang.topology.pcep.rev131024.ensure.lsp.operational.args.ArgumentsBuilder(); ensureArgs.addAugmentation(Arguments1.class, new Arguments1Builder().setOperational(OperationalStatus.Active) .build()); final EnsureLspOperationalInput ensure = new EnsureLspOperationalInputBuilder().setArguments(ensureArgs.build()) .setName(this.TUNNEL_NAME).setNetworkTopologyRef(new NetworkTopologyRef(TOPO_IID)) .setNode(this.nodeId).build(); final OperationResult result = this.topologyRpcs.ensureLspOperational(ensure).get().getResult(); //check result assertNull(result.getFailure()); // remove-lsp final RemoveLspInput remove = new RemoveLspInputBuilder().setName(this.TUNNEL_NAME) .setNetworkTopologyRef(new NetworkTopologyRef(TOPO_IID)).setNode(this.nodeId).build(); this.topologyRpcs.removeLsp(remove); assertEquals(3, this.receivedMsgs.size()); assertTrue(this.receivedMsgs.get(2) instanceof Pcinitiate); final Pcinitiate pcinitiate2 = (Pcinitiate) this.receivedMsgs.get(2); final Requests req2 = pcinitiate2.getPcinitiateMessage().getRequests().get(0); final long srpId3 = req2.getSrp().getOperationId().getValue(); final Tlvs tlvs3 = createLspTlvs(req2.getLsp().getPlspId().getValue(), false, this.testAddress, this.testAddress, this.testAddress, Optional.absent()); final Pcrpt pcRpt3 = MsgBuilderUtil.createPcRtpMessage(new LspBuilder(req2.getLsp()).setTlvs(tlvs3) .setRemove(true).setSync(true).setOperational(OperationalStatus.Down).build(), Optional.of(MsgBuilderUtil.createSrp(srpId3)), MsgBuilderUtil.createPath(Collections.emptyList())); this.listener.onMessage(this.session, pcRpt3); // check if lsp was removed readDataOperational(getDataBroker(), this.pathComputationClientIId, pcc -> { assertEquals(0, pcc.getReportedLsp().size()); return pcc; }); // check stats checkEquals(()->assertEquals(0, this.listener.getDelegatedLspsCount().intValue())); checkEquals(()->assertTrue(this.listener.getSynchronized())); checkEquals(()->assertTrue(this.listener.getStatefulMessages().getLastReceivedRptMsgTimestamp() > 0)); checkEquals(()->assertEquals(4, this.listener.getStatefulMessages().getReceivedRptMsgCount().intValue())); checkEquals(()->assertEquals(2, this.listener.getStatefulMessages().getSentInitMsgCount().intValue())); checkEquals(()->assertEquals(1, this.listener.getStatefulMessages().getSentUpdMsgCount().intValue())); checkEquals(()->this.listener.resetStats()); checkEquals(()->assertEquals(0, this.listener.getStatefulMessages().getLastReceivedRptMsgTimestamp().longValue())); checkEquals(()->assertEquals(0, this.listener.getStatefulMessages().getReceivedRptMsgCount().intValue())); checkEquals(()->assertEquals(0, this.listener.getStatefulMessages().getSentInitMsgCount().intValue())); checkEquals(()->assertEquals(0, this.listener.getStatefulMessages().getSentUpdMsgCount().intValue())); checkEquals(()->assertEquals(0, this.listener.getReplyTime().getAverageTime().longValue())); checkEquals(()->assertEquals(0, this.listener.getReplyTime().getMaxTime().longValue())); checkEquals(()->assertEquals(0, this.listener.getReplyTime().getMinTime().longValue())); } @Test public void testOnUnhandledErrorMessage() { final Message errorMsg = AbstractMessageParser.createErrorMsg(PCEPErrors.NON_ZERO_PLSPID, Optional.absent()); this.listener.onSessionUp(this.session); assertTrue(this.listener.onMessage(Optional.<AbstractTopologySessionListener.MessageContext>absent().orNull(), errorMsg)); } @Test public void testOnErrorMessage() throws InterruptedException, ExecutionException { final Message errorMsg = MsgBuilderUtil.createErrorMsg(PCEPErrors.NON_ZERO_PLSPID, 1L); this.listener.onSessionUp(this.session); final Future<RpcResult<AddLspOutput>> futureOutput = this.topologyRpcs.addLsp(createAddLspInput()); this.listener.onMessage(this.session, errorMsg); final AddLspOutput output = futureOutput.get().getResult(); assertEquals(FailureType.Failed ,output.getFailure()); assertEquals(1, output.getError().size()); final ErrorObject err = output.getError().get(0).getErrorObject(); assertEquals(PCEPErrors.NON_ZERO_PLSPID.getErrorType(), err.getType().shortValue()); assertEquals(PCEPErrors.NON_ZERO_PLSPID.getErrorValue(), err.getValue().shortValue()); } @Test public void testOnSessionDown() throws InterruptedException, ExecutionException { this.listener.onSessionUp(this.session); verify(this.listenerReg, times(0)).close(); // send request final Future<RpcResult<AddLspOutput>> futureOutput = this.topologyRpcs.addLsp(createAddLspInput()); this.listener.onSessionDown(this.session, new IllegalArgumentException()); verify(this.listenerReg, times(1)).close(); final AddLspOutput output = futureOutput.get().getResult(); // deal with unsent request after session down assertEquals(FailureType.Unsent, output.getFailure()); } /** * All the pcep session registration should be closed when the session manager is closed * @throws InterruptedException * @throws ExecutionException * @throws TransactionCommitFailedException */ @Test public void testOnServerSessionManagerDown() throws InterruptedException, ExecutionException, TransactionCommitFailedException { this.listener.onSessionUp(this.session); verify(this.listenerReg, times(0)).close(); // send request final Future<RpcResult<AddLspOutput>> futureOutput = this.topologyRpcs.addLsp(createAddLspInput()); this.manager.closeServiceInstance(); verify(this.listenerReg, times(1)).close(); final AddLspOutput output = futureOutput.get().getResult(); // deal with unsent request after session down assertEquals(FailureType.Unsent, output.getFailure()); } /** * Verify the PCEP session should not be up when server session manager is down, * otherwise it would be a problem when the session is up while it's not registered with session manager * @throws InterruptedException * @throws ExecutionException * @throws TransactionCommitFailedException */ @Test public void testOnServerSessionManagerUnstarted() throws InterruptedException, ExecutionException, TransactionCommitFailedException, ReadFailedException { this.manager.closeServiceInstance(); // the registration should not be closed since it's never initialized verify(this.listenerReg, times(0)).close(); this.listener.onSessionUp(this.session); // verify the session was NOT added to topology checkNotPresentOperational(getDataBroker(), TOPO_IID); // still, the session should not be registered and thus close() is never called verify(this.listenerReg, times(0)).close(); // send request final Future<RpcResult<AddLspOutput>> futureOutput = this.topologyRpcs.addLsp(createAddLspInput()); final AddLspOutput output = futureOutput.get().getResult(); // deal with unsent request after session down assertEquals(FailureType.Unsent, output.getFailure()); } @Test public void testOnSessionTermination() throws Exception { this.listener.onSessionUp(this.session); verify(this.listenerReg, times(0)).close(); // create node this.topologyRpcs.addLsp(createAddLspInput()); final Pcinitiate pcinitiate = (Pcinitiate) this.receivedMsgs.get(0); final Requests req = pcinitiate.getPcinitiateMessage().getRequests().get(0); final long srpId = req.getSrp().getOperationId().getValue(); final Tlvs tlvs = createLspTlvs(req.getLsp().getPlspId().getValue(), true, this.testAddress, this.testAddress, this.testAddress, Optional.absent()); final Pcrpt pcRpt = MsgBuilderUtil.createPcRtpMessage(new LspBuilder(req.getLsp()).setTlvs(tlvs).setSync(true) .setRemove(false).setOperational(OperationalStatus.Active).build(), Optional.of(MsgBuilderUtil.createSrp(srpId)), MsgBuilderUtil.createPath(req.getEro().getSubobject())); this.listener.onMessage(this.session, pcRpt); readDataOperational(getDataBroker(), TOPO_IID, topology -> { assertEquals(1, topology.getNode().size()); return topology; }); // node should be removed after termination this.listener.onSessionTerminated(this.session, new PCEPCloseTermination(TerminationReason.UNKNOWN)); verify(this.listenerReg, times(1)).close(); checkNotPresentOperational(getDataBroker(), this.pathComputationClientIId); } @Test public void testUnknownLsp() throws Exception { final List<Reports> reports = Lists.newArrayList(new ReportsBuilder().setPath(new PathBuilder() .setEro(new EroBuilder().build()).build()).setLsp(new LspBuilder().setPlspId(new PlspId(5L)) .setSync(false).setRemove(false).setTlvs(new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns. yang.pcep.ietf.stateful.rev131222.lsp.object.lsp.TlvsBuilder().setLspIdentifiers( new LspIdentifiersBuilder().setLspId(new LspId(1L)).build()).setSymbolicPathName( new SymbolicPathNameBuilder().setPathName(new SymbolicPathName(new byte[] { 22, 34 })) .build()).build()).build()).build()); final Pcrpt rptmsg = new PcrptBuilder().setPcrptMessage(new PcrptMessageBuilder().setReports(reports).build()) .build(); this.listener.onSessionUp(this.session); this.listener.onMessage(this.session, rptmsg); readDataOperational(getDataBroker(), TOPO_IID, node -> { assertFalse(node.getNode().isEmpty()); return node; }); } @Test public void testUpdateUnknownLsp() throws InterruptedException, ExecutionException { this.listener.onSessionUp(this.session); final org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.topology.pcep.rev131024.update.lsp.args .ArgumentsBuilder updArgsBuilder = new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang. topology.pcep.rev131024.update.lsp.args.ArgumentsBuilder(); updArgsBuilder.setEro(createEroWithIpPrefixes(Lists.newArrayList(this.eroIpPrefix, this.dstIpPrefix))); updArgsBuilder.addAugmentation(Arguments3.class, new Arguments3Builder().setLsp(new LspBuilder() .setDelegate(true).setAdministrative(true).build()).build()); final UpdateLspInput update = new UpdateLspInputBuilder().setArguments(updArgsBuilder.build()) .setName(this.TUNNEL_NAME).setNetworkTopologyRef(new NetworkTopologyRef(TOPO_IID)).setNode(this.nodeId) .build(); final UpdateLspOutput result = this.topologyRpcs.updateLsp(update).get().getResult(); assertEquals(FailureType.Unsent, result.getFailure()); assertEquals(1, result.getError().size()); final ErrorObject errorObject = result.getError().get(0).getErrorObject(); assertNotNull(errorObject); assertEquals(PCEPErrors.UNKNOWN_PLSP_ID, PCEPErrors.forValue(errorObject.getType(), errorObject.getValue())); } @Test public void testRemoveUnknownLsp() throws InterruptedException, ExecutionException { this.listener.onSessionUp(this.session); final RemoveLspInput remove = new RemoveLspInputBuilder().setName(this.TUNNEL_NAME).setNetworkTopologyRef( new NetworkTopologyRef(TOPO_IID)).setNode(this.nodeId).build(); final OperationResult result = this.topologyRpcs.removeLsp(remove).get().getResult(); assertEquals(FailureType.Unsent, result.getFailure()); assertEquals(1, result.getError().size()); final ErrorObject errorObject = result.getError().get(0).getErrorObject(); assertNotNull(errorObject); assertEquals(PCEPErrors.UNKNOWN_PLSP_ID, PCEPErrors.forValue(errorObject.getType(), errorObject.getValue())); } @Test public void testAddAlreadyExistingLsp() throws UnknownHostException, InterruptedException, ExecutionException { this.listener.onSessionUp(this.session); this.topologyRpcs.addLsp(createAddLspInput()); assertEquals(1, this.receivedMsgs.size()); assertTrue(this.receivedMsgs.get(0) instanceof Pcinitiate); final Pcinitiate pcinitiate = (Pcinitiate) this.receivedMsgs.get(0); final Requests req = pcinitiate.getPcinitiateMessage().getRequests().get(0); final long srpId = req.getSrp().getOperationId().getValue(); final Tlvs tlvs = createLspTlvs(req.getLsp().getPlspId().getValue(), true, this.testAddress, this.testAddress, this.testAddress, Optional.absent()); final Pcrpt pcRpt = MsgBuilderUtil.createPcRtpMessage(new LspBuilder(req.getLsp()).setTlvs(tlvs) .setPlspId(new PlspId(1L)).setSync(false).setRemove(false).setOperational(OperationalStatus.Active) .build(), Optional.of(MsgBuilderUtil.createSrp(srpId)), MsgBuilderUtil.createPath(req.getEro() .getSubobject())); this.listener.onMessage(this.session, pcRpt); //try to add already existing LSP final AddLspOutput result = this.topologyRpcs.addLsp(createAddLspInput()).get().getResult(); assertEquals(FailureType.Unsent, result.getFailure()); assertEquals(1, result.getError().size()); final ErrorObject errorObject = result.getError().get(0).getErrorObject(); assertNotNull(errorObject); assertEquals(PCEPErrors.USED_SYMBOLIC_PATH_NAME, PCEPErrors.forValue(errorObject.getType(), errorObject.getValue())); } @Test public void testPccResponseTimeout() throws Exception { this.listener.onSessionUp(this.session); final Future<RpcResult<AddLspOutput>> addLspResult = this.topologyRpcs.addLsp(createAddLspInput()); try { addLspResult.get(2, TimeUnit.SECONDS); fail(); } catch (final Exception e) { assertTrue(e instanceof TimeoutException); } Thread.sleep(AbstractPCEPSessionTest.RPC_TIMEOUT); CheckUtil.checkEquals(()-> { final RpcResult<AddLspOutput> rpcResult = addLspResult.get(); assertNotNull(rpcResult); assertEquals(rpcResult.getResult().getFailure(), FailureType.Unsent); }); } @Override protected Open getLocalPref() { return new OpenBuilder(super.getLocalPref()).setTlvs(new TlvsBuilder().addAugmentation(Tlvs1.class, new Tlvs1Builder().setStateful(new StatefulBuilder() .addAugmentation(Stateful1.class, new Stateful1Builder().setInitiation(Boolean.TRUE).build()) .addAugmentation(org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.controller.pcep.sync. optimizations.rev150714.Stateful1.class, new org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml. ns.yang.controller.pcep.sync.optimizations.rev150714.Stateful1Builder() .setTriggeredInitialSync(Boolean.TRUE).build()) .build()).build()).build()).build(); } @Override protected Open getRemotePref() { return getLocalPref(); } private AddLspInput createAddLspInput() { final ArgumentsBuilder argsBuilder = new ArgumentsBuilder(); final Ipv4CaseBuilder ipv4Builder = new Ipv4CaseBuilder(); ipv4Builder.setIpv4(new Ipv4Builder().setSourceIpv4Address(new Ipv4Address(this.testAddress)) .setDestinationIpv4Address(new Ipv4Address(this.testAddress)).build()); argsBuilder.setEndpointsObj(new EndpointsObjBuilder().setAddressFamily(ipv4Builder.build()).build()); argsBuilder.setEro(createEroWithIpPrefixes(Lists.newArrayList(this.eroIpPrefix))); argsBuilder.addAugmentation(Arguments2.class, new Arguments2Builder().setLsp(new LspBuilder() .setDelegate(true).setAdministrative(true).build()).build()); return new AddLspInputBuilder().setName(this.TUNNEL_NAME).setArguments(argsBuilder.build()) .setNetworkTopologyRef(new NetworkTopologyRef(TOPO_IID)).setNode(this.nodeId).build(); } }
package com.kb.mylibs.Tools; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; public class UtilPath { }
package com.viadeo.avrodiff; import java.io.File; import org.apache.avro.Schema; import org.apache.avro.file.DataFileReader; import org.apache.avro.file.DataFileWriter; import org.apache.avro.generic.GenericData.Record; import org.apache.avro.generic.GenericDatumReader; import org.apache.avro.generic.GenericDatumWriter; import org.apache.avro.generic.GenericRecord; import org.apache.avro.io.DatumReader; import org.apache.avro.io.DatumWriter; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import com.viadeo.avrodiff.GenerateSample.TestSchema; public class DiffTest { @Rule public TemporaryFolder tmpFolder = new TemporaryFolder(); public void create(String dirname, String filename, Record[] records) throws Exception { Schema schema = TestSchema.getSchema(); File dir = new File(tmpFolder.getRoot(), dirname); if(!dir.exists() ){ dir.mkdirs(); } File file = new File(dir,filename); DatumWriter<GenericRecord> datumWriter = new GenericDatumWriter<GenericRecord>(schema); DataFileWriter<GenericRecord> dataFileWriter = new DataFileWriter<GenericRecord>(datumWriter); dataFileWriter.create(schema, file); TestSchema.append(dataFileWriter,records); dataFileWriter.close(); } @Before public void setUp() throws Exception { Record[] records = {TestSchema.record("2", 2), TestSchema.record("3", 3)}; Record[] records2 = {TestSchema.record("4", 4), TestSchema.record("3", 3)}; create("a", "input.avro", records); create("b", "input.avro", records2); } public static void assertContainsOnly(String base, String dir, Record record) throws Exception { String path = base + dir + "/part-r-00000.avro"; DatumReader<GenericRecord> datumReader = new GenericDatumReader<GenericRecord>(); DataFileReader<GenericRecord> dataFileReader = new DataFileReader<GenericRecord>(new File(path), datumReader); //Read only one Record GenericRecord user = dataFileReader.next(); Assert.assertEquals("should only contains ", user, record); } @Test public void test42() throws Exception { String outStr = tmpFolder.getRoot().getPath() + "/out-generic2"; Path diffin = new Path( new File(tmpFolder.getRoot(), "a").toURI().toString()); Path diffout = new Path( new File(tmpFolder.getRoot(), "b").toURI().toString()); Path output = new Path(outStr); Configuration jobConf = new Configuration(); DiffJob job = new DiffJob(); Assert.assertTrue(job.internalRun(diffin, diffout, output, jobConf).waitForCompletion(true)); String base = outStr + "/"; assertContainsOnly(base, "type=kernel", TestSchema.record("3", 3)); assertContainsOnly(base, "type=add", TestSchema.record("4", 4)); assertContainsOnly(base, "type=del", TestSchema.record("2", 2)); } }
package com.facebook.react; import static com.facebook.react.uimanager.common.UIManagerType.DEFAULT; import static com.facebook.react.uimanager.common.UIManagerType.FABRIC; import static com.facebook.systrace.Systrace.TRACE_TAG_REACT_JAVA_BRIDGE; import android.content.Context; import android.graphics.Canvas; import android.graphics.Rect; import android.os.Build; import android.os.Bundle; import android.util.AttributeSet; import android.util.DisplayMetrics; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.Surface; import android.view.View; import android.view.ViewGroup; import android.view.ViewTreeObserver; import android.view.WindowManager; import android.widget.FrameLayout; import com.facebook.common.logging.FLog; import com.facebook.infer.annotation.Assertions; import com.facebook.react.bridge.Arguments; import com.facebook.react.bridge.CatalystInstance; import com.facebook.react.bridge.ReactContext; import com.facebook.react.bridge.ReactMarker; import com.facebook.react.bridge.ReactMarkerConstants; import com.facebook.react.bridge.UiThreadUtil; import com.facebook.react.bridge.WritableMap; import com.facebook.react.bridge.WritableNativeMap; import com.facebook.react.common.ReactConstants; import com.facebook.react.common.annotations.VisibleForTesting; import com.facebook.react.modules.appregistry.AppRegistry; import com.facebook.react.modules.core.DeviceEventManagerModule; import com.facebook.react.modules.deviceinfo.DeviceInfoModule; import com.facebook.react.surface.ReactStage; import com.facebook.react.uimanager.DisplayMetricsHolder; import com.facebook.react.uimanager.IllegalViewOperationException; import com.facebook.react.uimanager.JSTouchDispatcher; import com.facebook.react.uimanager.PixelUtil; import com.facebook.react.uimanager.RootView; import com.facebook.react.uimanager.ReactRoot; import com.facebook.react.uimanager.UIManagerHelper; import com.facebook.react.uimanager.UIManagerModule; import com.facebook.react.uimanager.common.UIManagerType; import com.facebook.react.uimanager.events.EventDispatcher; import com.facebook.systrace.Systrace; import javax.annotation.Nullable; /** * Default root view for catalyst apps. Provides the ability to listen for size changes so that a UI * manager can re-layout its elements. It delegates handling touch events for itself and child views * and sending those events to JS by using JSTouchDispatcher. This view is overriding {@link * ViewGroup#onInterceptTouchEvent} method in order to be notified about the events for all of its * children and it's also overriding {@link ViewGroup#requestDisallowInterceptTouchEvent} to make * sure that {@link ViewGroup#onInterceptTouchEvent} will get events even when some child view start * intercepting it. In case when no child view is interested in handling some particular touch event, * this view's {@link View#onTouchEvent} will still return true in order to be notified about all * subsequent touch events related to that gesture (in case when JS code wants to handle that * gesture). */ public class ReactRootView extends FrameLayout implements RootView, ReactRoot { /** * Listener interface for react root view events */ public interface ReactRootViewEventListener { /** * Called when the react context is attached to a ReactRootView. */ void onAttachedToReactInstance(ReactRootView rootView); } private @Nullable ReactInstanceManager mReactInstanceManager; private @Nullable String mJSModuleName; private @Nullable Bundle mAppProperties; private @Nullable String mInitialUITemplate; private @Nullable CustomGlobalLayoutListener mCustomGlobalLayoutListener; private @Nullable ReactRootViewEventListener mRootViewEventListener; private int mRootViewTag; private boolean mIsAttachedToInstance; private boolean mShouldLogContentAppeared; private @Nullable JSTouchDispatcher mJSTouchDispatcher; private final ReactAndroidHWInputDeviceHelper mAndroidHWInputDeviceHelper = new ReactAndroidHWInputDeviceHelper(this); private boolean mWasMeasured = false; private int mWidthMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); private int mHeightMeasureSpec = MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED); private int mLastWidth = 0; private int mLastHeight = 0; private @UIManagerType int mUIManagerType = DEFAULT; private final boolean mUseSurface; public ReactRootView(Context context) { super(context); mUseSurface = false; init(); } public ReactRootView(Context context, boolean useSurface) { super(context); mUseSurface = useSurface; init(); } public ReactRootView(Context context, AttributeSet attrs) { super(context, attrs); mUseSurface = false; init(); } public ReactRootView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); mUseSurface = false; init(); } private void init() { setClipChildren(false); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { if (mUseSurface) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); return; } Systrace.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "ReactRootView.onMeasure"); try { boolean measureSpecsUpdated = widthMeasureSpec != mWidthMeasureSpec || heightMeasureSpec != mHeightMeasureSpec; mWidthMeasureSpec = widthMeasureSpec; mHeightMeasureSpec = heightMeasureSpec; int width = 0; int height = 0; int widthMode = MeasureSpec.getMode(widthMeasureSpec); if (widthMode == MeasureSpec.AT_MOST || widthMode == MeasureSpec.UNSPECIFIED) { for (int i = 0; i < getChildCount(); i++) { View child = getChildAt(i); int childSize = child.getLeft() + child.getMeasuredWidth() + child.getPaddingLeft() + child.getPaddingRight(); width = Math.max(width, childSize); } } else { width = MeasureSpec.getSize(widthMeasureSpec); } int heightMode = MeasureSpec.getMode(heightMeasureSpec); if (heightMode == MeasureSpec.AT_MOST || heightMode == MeasureSpec.UNSPECIFIED) { for (int i = 0; i < getChildCount(); i++) { View child = getChildAt(i); int childSize = child.getTop() + child.getMeasuredHeight() + child.getPaddingTop() + child.getPaddingBottom(); height = Math.max(height, childSize); } } else { height = MeasureSpec.getSize(heightMeasureSpec); } setMeasuredDimension(width, height); mWasMeasured = true; // Check if we were waiting for onMeasure to attach the root view. if (mReactInstanceManager != null && !mIsAttachedToInstance) { attachToReactInstanceManager(); } else if (measureSpecsUpdated || mLastWidth != width || mLastHeight != height) { updateRootLayoutSpecs(mWidthMeasureSpec, mHeightMeasureSpec); } mLastWidth = width; mLastHeight = height; } finally { Systrace.endSection(TRACE_TAG_REACT_JAVA_BRIDGE); } } @Override public void onChildStartedNativeGesture(MotionEvent androidEvent) { if (mReactInstanceManager == null || !mIsAttachedToInstance || mReactInstanceManager.getCurrentReactContext() == null) { FLog.w( ReactConstants.TAG, "Unable to dispatch touch to JS as the catalyst instance has not been attached"); return; } if (mJSTouchDispatcher == null) { FLog.w( ReactConstants.TAG, "Unable to dispatch touch to JS before the dispatcher is available"); return; } ReactContext reactContext = mReactInstanceManager.getCurrentReactContext(); EventDispatcher eventDispatcher = reactContext.getNativeModule(UIManagerModule.class).getEventDispatcher(); mJSTouchDispatcher.onChildStartedNativeGesture(androidEvent, eventDispatcher); } @Override public boolean onInterceptTouchEvent(MotionEvent ev) { dispatchJSTouchEvent(ev); return super.onInterceptTouchEvent(ev); } @Override public boolean onTouchEvent(MotionEvent ev) { dispatchJSTouchEvent(ev); super.onTouchEvent(ev); // In case when there is no children interested in handling touch event, we return true from // the root view in order to receive subsequent events related to that gesture return true; } @Override protected void dispatchDraw(Canvas canvas) { try { super.dispatchDraw(canvas); } catch (StackOverflowError e) { // Adding special exception management for StackOverflowError for logging purposes. // This will be removed in the future. handleException(e); } } @Override public boolean dispatchKeyEvent(KeyEvent ev) { if (mReactInstanceManager == null || !mIsAttachedToInstance || mReactInstanceManager.getCurrentReactContext() == null) { FLog.w( ReactConstants.TAG, "Unable to handle key event as the catalyst instance has not been attached"); return super.dispatchKeyEvent(ev); } mAndroidHWInputDeviceHelper.handleKeyEvent(ev); return super.dispatchKeyEvent(ev); } @Override protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) { if (mReactInstanceManager == null || !mIsAttachedToInstance || mReactInstanceManager.getCurrentReactContext() == null) { FLog.w( ReactConstants.TAG, "Unable to handle focus changed event as the catalyst instance has not been attached"); super.onFocusChanged(gainFocus, direction, previouslyFocusedRect); return; } mAndroidHWInputDeviceHelper.clearFocus(); super.onFocusChanged(gainFocus, direction, previouslyFocusedRect); } @Override public void requestChildFocus(View child, View focused) { if (mReactInstanceManager == null || !mIsAttachedToInstance || mReactInstanceManager.getCurrentReactContext() == null) { FLog.w( ReactConstants.TAG, "Unable to handle child focus changed event as the catalyst instance has not been attached"); super.requestChildFocus(child, focused); return; } mAndroidHWInputDeviceHelper.onFocusChanged(focused); super.requestChildFocus(child, focused); } private void dispatchJSTouchEvent(MotionEvent event) { if (mReactInstanceManager == null || !mIsAttachedToInstance || mReactInstanceManager.getCurrentReactContext() == null) { FLog.w( ReactConstants.TAG, "Unable to dispatch touch to JS as the catalyst instance has not been attached"); return; } if (mJSTouchDispatcher == null) { FLog.w( ReactConstants.TAG, "Unable to dispatch touch to JS before the dispatcher is available"); return; } ReactContext reactContext = mReactInstanceManager.getCurrentReactContext(); EventDispatcher eventDispatcher = reactContext.getNativeModule(UIManagerModule.class).getEventDispatcher(); mJSTouchDispatcher.handleTouchEvent(event, eventDispatcher); } @Override public void requestDisallowInterceptTouchEvent(boolean disallowIntercept) { // Override in order to still receive events to onInterceptTouchEvent even when some other // views disallow that, but propagate it up the tree if possible. if (getParent() != null) { getParent().requestDisallowInterceptTouchEvent(disallowIntercept); } } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { if (mUseSurface) { super.onLayout(changed, left, top, right, bottom); } // No-op since UIManagerModule handles actually laying out children. } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); if (mIsAttachedToInstance) { removeOnGlobalLayoutListener(); getViewTreeObserver().addOnGlobalLayoutListener(getCustomGlobalLayoutListener()); } } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); if (mIsAttachedToInstance) { removeOnGlobalLayoutListener(); } } private void removeOnGlobalLayoutListener() { getViewTreeObserver().removeOnGlobalLayoutListener(getCustomGlobalLayoutListener()); } @Override public void onViewAdded(View child) { super.onViewAdded(child); if (mShouldLogContentAppeared) { mShouldLogContentAppeared = false; if (mJSModuleName != null) { ReactMarker.logMarker(ReactMarkerConstants.CONTENT_APPEARED, mJSModuleName, mRootViewTag); } } } @Override public ViewGroup getRootViewGroup() { return this; } /** * {@see #startReactApplication(ReactInstanceManager, String, android.os.Bundle)} */ public void startReactApplication(ReactInstanceManager reactInstanceManager, String moduleName) { startReactApplication(reactInstanceManager, moduleName, null); } /** * {@see #startReactApplication(ReactInstanceManager, String, android.os.Bundle, String)} */ public void startReactApplication(ReactInstanceManager reactInstanceManager, String moduleName, @Nullable Bundle initialProperties) { startReactApplication(reactInstanceManager, moduleName, initialProperties, null); } /** * Schedule rendering of the react component rendered by the JS application from the given JS * module (@{param moduleName}) using provided {@param reactInstanceManager} to attach to the * JS context of that manager. Extra parameter {@param launchOptions} can be used to pass initial * properties for the react component. */ public void startReactApplication( ReactInstanceManager reactInstanceManager, String moduleName, @Nullable Bundle initialProperties, @Nullable String initialUITemplate) { Systrace.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "startReactApplication"); try { UiThreadUtil.assertOnUiThread(); // TODO(6788889): Use POJO instead of bundle here, apparently we can't just use WritableMap // here as it may be deallocated in native after passing via JNI bridge, but we want to reuse // it in the case of re-creating the catalyst instance Assertions.assertCondition( mReactInstanceManager == null, "This root view has already been attached to a catalyst instance manager"); mReactInstanceManager = reactInstanceManager; mJSModuleName = moduleName; mAppProperties = initialProperties; mInitialUITemplate = initialUITemplate; if (mUseSurface) { // TODO initialize surface here } if (!mReactInstanceManager.hasStartedCreatingInitialContext()) { mReactInstanceManager.createReactContextInBackground(); } attachToReactInstanceManager(); } finally { Systrace.endSection(TRACE_TAG_REACT_JAVA_BRIDGE); } } private void updateRootLayoutSpecs(final int widthMeasureSpec, final int heightMeasureSpec) { if (mReactInstanceManager == null) { FLog.w( ReactConstants.TAG, "Unable to update root layout specs for uninitialized ReactInstanceManager"); return; } final ReactContext reactApplicationContext = mReactInstanceManager.getCurrentReactContext(); if (reactApplicationContext != null) { UIManagerHelper.getUIManager(reactApplicationContext, getUIManagerType()) .updateRootLayoutSpecs(getRootViewTag(), widthMeasureSpec, heightMeasureSpec); } } /** * Unmount the react application at this root view, reclaiming any JS memory associated with that * application. If {@link #startReactApplication} is called, this method must be called before the * ReactRootView is garbage collected (typically in your Activity's onDestroy, or in your * Fragment's onDestroyView). */ public void unmountReactApplication() { if (mReactInstanceManager != null && mIsAttachedToInstance) { mReactInstanceManager.detachRootView(this); mReactInstanceManager = null; mIsAttachedToInstance = false; } mShouldLogContentAppeared = false; } @Override public void onStage(int stage) { switch(stage) { case ReactStage.ON_ATTACH_TO_INSTANCE: onAttachedToReactInstance(); break; default: break; } } public void onAttachedToReactInstance() { // Create the touch dispatcher here instead of having it always available, to make sure // that all touch events are only passed to JS after React/JS side is ready to consume // them. Otherwise, these events might break the states expected by JS. // Note that this callback was invoked from within the UI thread. mJSTouchDispatcher = new JSTouchDispatcher(this); if (mRootViewEventListener != null) { mRootViewEventListener.onAttachedToReactInstance(this); } } public void setEventListener(ReactRootViewEventListener eventListener) { mRootViewEventListener = eventListener; } /* package */ String getJSModuleName() { return Assertions.assertNotNull(mJSModuleName); } @Override public @Nullable Bundle getAppProperties() { return mAppProperties; } @Override public @Nullable String getInitialUITemplate() { return mInitialUITemplate; } public void setAppProperties(@Nullable Bundle appProperties) { UiThreadUtil.assertOnUiThread(); mAppProperties = appProperties; if (getRootViewTag() != 0) { runApplication(); } } /** * Calls into JS to start the React application. Can be called multiple times with the * same rootTag, which will re-render the application from the root. */ @Override public void runApplication() { Systrace.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "ReactRootView.runApplication"); try { if (mReactInstanceManager == null || !mIsAttachedToInstance) { return; } ReactContext reactContext = mReactInstanceManager.getCurrentReactContext(); if (reactContext == null) { return; } CatalystInstance catalystInstance = reactContext.getCatalystInstance(); String jsAppModuleName = getJSModuleName(); if (mUseSurface) { // TODO call surface's runApplication } else { boolean isFabric = getUIManagerType() == FABRIC; // Fabric requires to call updateRootLayoutSpecs before starting JS Application, // this ensures the root will hace the correct pointScaleFactor. if (mWasMeasured || isFabric) { updateRootLayoutSpecs(mWidthMeasureSpec, mHeightMeasureSpec); } WritableNativeMap appParams = new WritableNativeMap(); appParams.putDouble("rootTag", getRootViewTag()); @Nullable Bundle appProperties = getAppProperties(); if (appProperties != null) { appParams.putMap("initialProps", Arguments.fromBundle(appProperties)); } if (isFabric) { appParams.putBoolean("fabric", true); } mShouldLogContentAppeared = true; catalystInstance.getJSModule(AppRegistry.class).runApplication(jsAppModuleName, appParams); } } finally { Systrace.endSection(TRACE_TAG_REACT_JAVA_BRIDGE); } } /** * Is used by unit test to setup mIsAttachedToWindow flags, that will let this * view to be properly attached to catalyst instance by startReactApplication call */ @VisibleForTesting /* package */ void simulateAttachForTesting() { mIsAttachedToInstance = true; mJSTouchDispatcher = new JSTouchDispatcher(this); } private CustomGlobalLayoutListener getCustomGlobalLayoutListener() { if (mCustomGlobalLayoutListener == null) { mCustomGlobalLayoutListener = new CustomGlobalLayoutListener(); } return mCustomGlobalLayoutListener; } private void attachToReactInstanceManager() { Systrace.beginSection(TRACE_TAG_REACT_JAVA_BRIDGE, "attachToReactInstanceManager"); try { if (mIsAttachedToInstance) { return; } mIsAttachedToInstance = true; Assertions.assertNotNull(mReactInstanceManager).attachRootView(this); getViewTreeObserver().addOnGlobalLayoutListener(getCustomGlobalLayoutListener()); } finally { Systrace.endSection(TRACE_TAG_REACT_JAVA_BRIDGE); } } @Override protected void finalize() throws Throwable { super.finalize(); Assertions.assertCondition( !mIsAttachedToInstance, "The application this ReactRootView was rendering was not unmounted before the " + "ReactRootView was garbage collected. This usually means that your application is " + "leaking large amounts of memory. To solve this, make sure to call " + "ReactRootView#unmountReactApplication in the onDestroy() of your hosting Activity or in " + "the onDestroyView() of your hosting Fragment."); } public int getRootViewTag() { return mRootViewTag; } public void setRootViewTag(int rootViewTag) { mRootViewTag = rootViewTag; } @Override public void handleException(final Throwable t) { if (mReactInstanceManager == null || mReactInstanceManager.getCurrentReactContext() == null) { throw new RuntimeException(t); } Exception e = new IllegalViewOperationException(t.getMessage(), this, t); mReactInstanceManager.getCurrentReactContext().handleException(e); } public void setIsFabric(boolean isFabric) { mUIManagerType = isFabric ? FABRIC : DEFAULT; } @Override public @UIManagerType int getUIManagerType() { return mUIManagerType; } @Nullable public ReactInstanceManager getReactInstanceManager() { return mReactInstanceManager; } /* package */ void sendEvent(String eventName, @Nullable WritableMap params) { if (mReactInstanceManager != null) { mReactInstanceManager.getCurrentReactContext() .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class) .emit(eventName, params); } } private class CustomGlobalLayoutListener implements ViewTreeObserver.OnGlobalLayoutListener { private final Rect mVisibleViewArea; private final int mMinKeyboardHeightDetected; private int mKeyboardHeight = 0; private int mDeviceRotation = 0; private DisplayMetrics mWindowMetrics = new DisplayMetrics(); private DisplayMetrics mScreenMetrics = new DisplayMetrics(); /* package */ CustomGlobalLayoutListener() { DisplayMetricsHolder.initDisplayMetricsIfNotInitialized(getContext().getApplicationContext()); mVisibleViewArea = new Rect(); mMinKeyboardHeightDetected = (int) PixelUtil.toPixelFromDIP(60); } @Override public void onGlobalLayout() { if (mReactInstanceManager == null || !mIsAttachedToInstance || mReactInstanceManager.getCurrentReactContext() == null) { return; } checkForKeyboardEvents(); checkForDeviceOrientationChanges(); checkForDeviceDimensionsChanges(); } private void checkForKeyboardEvents() { getRootView().getWindowVisibleDisplayFrame(mVisibleViewArea); final int heightDiff = DisplayMetricsHolder.getWindowDisplayMetrics().heightPixels - mVisibleViewArea.bottom; if (mKeyboardHeight != heightDiff && heightDiff > mMinKeyboardHeightDetected) { // keyboard is now showing, or the keyboard height has changed mKeyboardHeight = heightDiff; WritableMap params = Arguments.createMap(); WritableMap coordinates = Arguments.createMap(); coordinates.putDouble("screenY", PixelUtil.toDIPFromPixel(mVisibleViewArea.bottom)); coordinates.putDouble("screenX", PixelUtil.toDIPFromPixel(mVisibleViewArea.left)); coordinates.putDouble("width", PixelUtil.toDIPFromPixel(mVisibleViewArea.width())); coordinates.putDouble("height", PixelUtil.toDIPFromPixel(mKeyboardHeight)); params.putMap("endCoordinates", coordinates); sendEvent("keyboardDidShow", params); } else if (mKeyboardHeight != 0 && heightDiff <= mMinKeyboardHeightDetected) { // keyboard is now hidden mKeyboardHeight = 0; sendEvent("keyboardDidHide", null); } } private void checkForDeviceOrientationChanges() { final int rotation = ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE)) .getDefaultDisplay().getRotation(); if (mDeviceRotation == rotation) { return; } mDeviceRotation = rotation; emitOrientationChanged(rotation); } private void checkForDeviceDimensionsChanges() { // Get current display metrics. DisplayMetricsHolder.initDisplayMetrics(getContext()); // Check changes to both window and screen display metrics since they may not update at the same time. if (!areMetricsEqual(mWindowMetrics, DisplayMetricsHolder.getWindowDisplayMetrics()) || !areMetricsEqual(mScreenMetrics, DisplayMetricsHolder.getScreenDisplayMetrics())) { mWindowMetrics.setTo(DisplayMetricsHolder.getWindowDisplayMetrics()); mScreenMetrics.setTo(DisplayMetricsHolder.getScreenDisplayMetrics()); emitUpdateDimensionsEvent(); } } private boolean areMetricsEqual(DisplayMetrics displayMetrics, DisplayMetrics otherMetrics) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) { return displayMetrics.equals(otherMetrics); } else { // DisplayMetrics didn't have an equals method before API 17. // Check all public fields manually. return displayMetrics.widthPixels == otherMetrics.widthPixels && displayMetrics.heightPixels == otherMetrics.heightPixels && displayMetrics.density == otherMetrics.density && displayMetrics.densityDpi == otherMetrics.densityDpi && displayMetrics.scaledDensity == otherMetrics.scaledDensity && displayMetrics.xdpi == otherMetrics.xdpi && displayMetrics.ydpi == otherMetrics.ydpi; } } private void emitOrientationChanged(final int newRotation) { String name; double rotationDegrees; boolean isLandscape = false; switch (newRotation) { case Surface.ROTATION_0: name = "portrait-primary"; rotationDegrees = 0.0; break; case Surface.ROTATION_90: name = "landscape-primary"; rotationDegrees = -90.0; isLandscape = true; break; case Surface.ROTATION_180: name = "portrait-secondary"; rotationDegrees = 180.0; break; case Surface.ROTATION_270: name = "landscape-secondary"; rotationDegrees = 90.0; isLandscape = true; break; default: return; } WritableMap map = Arguments.createMap(); map.putString("name", name); map.putDouble("rotationDegrees", rotationDegrees); map.putBoolean("isLandscape", isLandscape); sendEvent("namedOrientationDidChange", map); } private void emitUpdateDimensionsEvent() { mReactInstanceManager .getCurrentReactContext() .getNativeModule(DeviceInfoModule.class) .emitUpdateDimensionsEvent(); } } }
package org.animotron.bridge; import junit.framework.Assert; import org.animotron.ATest; import org.junit.Ignore; import org.junit.Test; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; /** * @author <a href="mailto:shabanovd@gmail.com">Dmitriy Shabanov</a> * @author <a href="mailto:gazdovsky@gmail.com">Evgeny Gazdovsky</a> * */ public class ServletTest extends ATest { @Test @Ignore //problem that db is static field public void test() throws Exception { FSBridge.load("src/test/animo/"); AnimoServlet servlet = new AnimoServlet(); HttpRequest request = new HttpRequest("/","localhost"); HttpResponse response = new HttpResponse(false); servlet.doGet(request, response); Assert.assertEquals( "<?xml version='1.0' encoding='UTF-8'?>" + "<html>" + "<head>" + "<title>Welcome to Animo</title>" + "<meta name=\"keywords\" content=\"\"/>" + "<meta name=\"description\" content=\"\"/>" + "</head>" + "<body>" + "<h1>Welcome to Animo</h1>" + "<p>It is working!</p>" + "<ul>" + "<li>Host: <strong>localhost</strong></li>" + "<li>URI: <strong>/</strong></li>" + "</ul>" + "</body>" + "</html>", response.getResponseString() ); } @Test @Ignore //problem that db is static field public void testBinay() throws Exception { FSBridge.load("src/test/animo/"); AnimoServlet servlet = new AnimoServlet(); HttpRequest request = new HttpRequest("/favicon.ico","localhost"); HttpResponse response = new HttpResponse(false); servlet.doGet(request, response); org.junit.Assert.assertArrayEquals(getBytesFromFile(new File("src/test/animo/localhost/favicon.ico")),response.getResponse()); } private byte[] getBytesFromFile(File file) throws IOException { InputStream is = new FileInputStream(file); long length = file.length(); if (length > Integer.MAX_VALUE) { throw new RuntimeException("File too big ["+file.getPath()+"]"); } byte[] bytes = new byte[(int)length]; int offset = 0; int numRead = 0; while (offset < bytes.length && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) { offset += numRead; } if (offset < bytes.length) { throw new IOException("Could not completely read file "+file.getName()); } is.close(); return bytes; } }
package org.basex.http.rest; import static org.basex.http.rest.RESTText.*; import java.io.*; import java.util.*; import javax.xml.parsers.*; import javax.xml.transform.dom.*; import org.basex.core.*; import org.basex.http.*; import org.basex.io.*; import org.basex.io.in.*; import org.basex.io.serial.*; import org.basex.query.*; import org.basex.query.util.*; import org.basex.query.value.item.*; import org.basex.query.value.node.*; import org.basex.util.*; public final class RESTPost { /** Private constructor. */ private RESTPost() { } /** * Creates REST code. * @param rs REST session * @return code * @throws IOException I/O exception */ public static RESTCmd get(final RESTSession rs) throws IOException { final HTTPContext http = rs.http; String enc = http.req.getCharacterEncoding(); if(enc == null) enc = Token.UTF8; // perform queries final byte[] input = new NewlineInput(http.req.getInputStream()).encoding(enc).content(); validate(input); final Context ctx = rs.context; DBNode doc; try { doc = new DBNode(new IOContent(input), ctx.options); } catch(final IOException ex) { throw HTTPCode.BAD_REQUEST_X.thrw(ex); } try { // handle serialization parameters final SerializerOptions sopts = http.serialization; QueryProcessor qp = new QueryProcessor("*/*:parameter", ctx).context(doc); for(final Item param : qp.value()) { final String name = value("@name", param, ctx); final String value = value("@value", param, ctx); if(sopts.option(name) != null) { sopts.assign(name, value); } else if(name.equals(WRAP)) { http.wrapping = Util.yes(value); } else { HTTPCode.UNKNOWN_PARAM_X.thrw(name); } } // handle database options qp = new QueryProcessor("*/*:option", ctx).context(doc); for(final Item it : qp.value()) { final String name = value("@name", it, ctx).toUpperCase(Locale.ENGLISH); final String value = value("@value", it, ctx); ctx.options.assign(name, value); } // handle variables final Map<String, String[]> vars = new HashMap<String, String[]>(); qp = new QueryProcessor("*/*:variable", ctx).context(doc); for(final Item it : qp.value()) { final String name = value("@name", it, ctx); final String value = value("@value", it, ctx); final String type = value("@type", it, ctx); vars.put(name, new String[] { value, type }); } // handle input String value = null; qp = new QueryProcessor("*/*:context/node()", ctx).context(doc); for(final Item it : qp.value()) { if(value != null) HTTPCode.MULTIPLE_CONTEXT_X.thrw(); // create main memory instance of the specified node value = DataBuilder.stripNS((ANode) it, Token.token(RESTURI), ctx).serialize().toString(); } // handle request final String request = value("local-name(*)", doc, ctx); final String text = value("*/*:text/text()", doc, ctx); if(request.equals(COMMAND)) return RESTCommand.get(rs, text); if(request.equals(RUN)) return RESTRun.get(rs, text, vars, value); return RESTQuery.get(rs, text, vars, value); } catch(final QueryException ex) { throw HTTPCode.BAD_REQUEST_X.thrw(ex); } } /** * Returns the atomized item for the specified query. * @param query query * @param item context item * @param ctx database context * @return atomized item * @throws QueryException query exception */ private static String value(final String query, final Item item, final Context ctx) throws QueryException { final QueryProcessor qp = new QueryProcessor(query, ctx).context(item); final Item it = qp.iter().next(); return it == null ? null : Token.string(it.string(null)); } /** * Validates the specified XML input against the POST schema. * @param input input document * @throws HTTPException exception */ private static void validate(final byte[] input) throws HTTPException { try { final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); dbf.setNamespaceAware(true); final DocumentBuilder db = dbf.newDocumentBuilder(); RESTSchema.newValidator().validate(new DOMSource(db.parse(new ArrayInput(input)))); } catch(final Exception ex) { Util.debug("Error while validating \"" + Token.string(input) + '"'); // validation fails HTTPCode.BAD_REQUEST_X.thrw(ex); } } }
package org.gertje.abacus; import org.gertje.abacus.exception.CompilerException; import org.gertje.abacus.functions.RandFunction; import org.gertje.abacus.lexer.AbacusLexer; import org.gertje.abacus.lexer.Lexer; import org.gertje.abacus.nodes.AbacusNodeFactory; import org.gertje.abacus.nodes.AbstractNode; import org.gertje.abacus.nodes.NodeFactory; import org.gertje.abacus.nodevisitors.Evaluator; import org.gertje.abacus.parser.Parser; import org.gertje.abacus.nodevisitors.SemanticsChecker; import org.gertje.abacus.nodevisitors.Simplifier; import org.gertje.abacus.nodevisitors.VisitingException; import org.gertje.abacus.symboltable.NoSuchVariableException; import org.gertje.abacus.symboltable.SimpleSymbolTable; import org.gertje.abacus.symboltable.SymbolTable; import java.util.Map; public class AbacusTestCase { private String expression; private Object expectedValue; private boolean expectException; private Map<String, Object> symbolsBefore; private Map<String, Object> symbolsAfter; private String exception; private boolean result; public AbacusTestCase(String expression, Object expectedValue, boolean expectException, Map<String, Object> symbolsBefore, Map<String, Object> symbolsAfter) { this.expression = expression; this.expectedValue = expectedValue; this.expectException = expectException; this.symbolsBefore = symbolsBefore; this.symbolsAfter = symbolsAfter; } public boolean run() { result = runTest(); return result; } private boolean runTest() { // Maak een nieuwe symboltable en vul deze met wat waarden. SymbolTable sym = createSymbolTable(); NodeFactory nodeFactory = new AbacusNodeFactory(); Lexer lexer = new AbacusLexer(expression); Parser parser = new Parser(lexer, nodeFactory); AbstractNode tree; try { tree = parser.parse(); } catch (CompilerException e) { exception = e.getMessage(); return expectException; } SemanticsChecker semanticsChecker = new SemanticsChecker(sym); Simplifier simplifier = new Simplifier(sym, nodeFactory); Evaluator evaluator = new Evaluator(sym); Object value; try { semanticsChecker.check(tree); tree = simplifier.simplify(tree); value = evaluator.evaluate(tree); } catch (VisitingException e) { exception = e.getMessage(); return expectException; } if (expectException) { return false; } // Wanneer het resultaat null is en we hadden dit ook verwacht geven we true terug. if (value == null && expectedValue == null) { return true; } // Wanneer het resultaat of de verwachting null is geven we false terug, dit kan omdat als ze allebei null // hadden moeten zijn hadden we al true terug gegeven bij vorige vergelijking. if (value == null || expectedValue == null) { return false; } if (!expectedValue.getClass().equals(value.getClass())) { return false; } if (((Comparable) value).compareTo(expectedValue) != 0) { return false; } if (!checkSymbolTable(sym)) { return false; } return true; } private boolean checkSymbolTable(SymbolTable sym) { try { for (Map.Entry<String, Object> entry : symbolsAfter.entrySet()) { if (((Comparable) entry.getValue()).compareTo(sym.getVariableValue(entry.getKey())) != 0) { return false; } } } catch (NoSuchVariableException e) { return false; } return true; } private SymbolTable createSymbolTable() { SimpleSymbolTable sym = new SimpleSymbolTable(); sym.setVariables(symbolsBefore); sym.registerFunction(new RandFunction()); return sym; } public boolean printResult() { if (result) { System.out.println("OK: " + expression + " " + (exception != null ? exception : "")); } else { System.out.println("Error: " + expression + " " + (exception != null ? exception : "")); } return result; } public String getException() { return exception; } public String getExpression() { return expression; } public void setExpression(String expression) { this.expression = expression; } }
package net.hyperic.sigar.test; import net.hyperic.sigar.Sigar; import net.hyperic.sigar.SigarException; import net.hyperic.sigar.SigarNotImplementedException; import net.hyperic.sigar.SigarProxy; import net.hyperic.sigar.SigarProxyCache; import net.hyperic.sigar.jmx.SigarInvokerJMX; public class TestInvoker extends SigarTestCase { private static final String[][] OK_QUERIES = { { "sigar:Type=Mem", "Free" }, { "sigar:Type=Mem", "Total" }, { "sigar:Type=Cpu", "User" }, { "sigar:Type=Cpu", "Sys" }, { "sigar:Type=CpuPerc", "User" }, { "sigar:Type=CpuPerc", "Sys" }, { "sigar:Type=Swap", "Free" }, { "sigar:Type=Swap", "Used" }, { "sigar:Type=Uptime", "Uptime" }, { "sigar:Type=LoadAverage", "0" }, { "sigar:Type=LoadAverage", "1" }, { "sigar:Type=LoadAverage", "2" }, { "sigar:Type=ProcMem,Arg=$$", "Size" }, { "sigar:Type=ProcMem,Arg=$$", "Vsize" }, { "sigar:Type=ProcTime,Arg=$$", "Sys" }, { "sigar:Type=ProcTime,Arg=$$", "User" }, { "sigar:Type=ProcTime,Arg=$$", "Total" }, { "sigar:Type=MultiProcCpu,Arg=CredName.User.eq%3Ddougm", "Sys" }, { "sigar:Type=MultiProcMem,Arg=CredName.User.eq%3Ddougm", "Size" }, //test Utime/Stime backcompat. { "sigar:Type=ProcTime,Arg=$$", "Stime" }, { "sigar:Type=ProcTime,Arg=$$", "Utime" }, { "sigar:Type=CpuPercList,Arg=0", "Idle" }, { "sigar:Type=NetStat", "TcpOutboundTotal" }, { "sigar:Type=NetStat", "TcpListen" }, }; private static final String[][] BROKEN_QUERIES = { { "sigar:Type=BREAK", "Free" }, { "sigar:Type=Mem", "BREAK" }, { "sigar:Type=ProcTime,Arg=BREAK", "Sys" }, { "sigar:Type=CpuPercList,Arg=1000", "Idle" }, { "sigar:Type=CpuPercList,Arg=BREAK", "Idle" }, }; public TestInvoker(String name) { super(name); } public void testCreate() throws Exception { Sigar sigar = new Sigar(); SigarProxy proxy = SigarProxyCache.newInstance(sigar); testOK(proxy); } private void testOK(SigarProxy proxy) throws Exception { for (int i=0; i<OK_QUERIES.length; i++) { String[] query = OK_QUERIES[i]; SigarInvokerJMX invoker = SigarInvokerJMX.getInstance(proxy, query[0]); try { Object o = invoker.invoke(query[1]); traceln(query[0] + ":" + query[1] + "=" + o); assertTrue(true); } catch (SigarNotImplementedException e) { traceln(query[0] + " NotImplemented"); } catch (SigarException e) { assertTrue(false); } } for (int i=0; i<BROKEN_QUERIES.length; i++) { String[] query = BROKEN_QUERIES[i]; SigarInvokerJMX invoker = SigarInvokerJMX.getInstance(proxy, query[0]); try { Object o = invoker.invoke(query[1]); assertTrue(false); } catch (SigarException e) { traceln(query[0] + ":" + query[1] + "=" + e.getMessage()); assertTrue(true); } } } }
package org.jbake.app; import static org.assertj.core.api.Assertions.assertThat; import com.orientechnologies.orient.core.db.document.ODatabaseDocumentTx; import org.apache.commons.configuration.CompositeConfiguration; import org.apache.commons.io.FileUtils; import org.jbake.model.DocumentTypes; import org.junit.After; import org.junit.Assert; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import java.io.File; import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; import java.util.Iterator; import java.util.Map; import java.util.Scanner; public class GroovyRendererTest { @Rule public TemporaryFolder folder = new TemporaryFolder(); private File sourceFolder; private File destinationFolder; private File templateFolder; private CompositeConfiguration config; private ODatabaseDocumentTx db; @Before public void setup() throws Exception, IOException, URISyntaxException { URL sourceUrl = this.getClass().getResource("/"); sourceFolder = new File(sourceUrl.getFile()); if (!sourceFolder.exists()) { throw new Exception("Cannot find sample data structure!"); } destinationFolder = folder.getRoot(); templateFolder = new File(sourceFolder, "groovyTemplates"); if (!templateFolder.exists()) { throw new Exception("Cannot find template folder!"); } config = ConfigUtil.load(new File(this.getClass().getResource("/").getFile())); Iterator<String> keys = config.getKeys(); while (keys.hasNext()) { String key = keys.next(); if (key.startsWith("template") && key.endsWith(".file")) { String old = (String)config.getProperty(key); config.setProperty(key, old.substring(0, old.length()-4)+".gsp"); } } Assert.assertEquals(".html", config.getString("output.extension")); db = DBUtil.createDB("memory", "documents"+System.currentTimeMillis()); } @After public void cleanup() throws InterruptedException { db.drop(); db.close(); } @Test public void render() throws Exception { Parser parser = new Parser(config, sourceFolder.getPath()); Renderer renderer = new Renderer(db, destinationFolder, templateFolder, config); File sampleFile = new File(sourceFolder.getPath() + File.separator + "content" + File.separator + "blog" + File.separator + "2013" + File.separator + "second-post.html"); Map<String, Object> content = parser.processFile(sampleFile); content.put("uri", "/second-post.html"); renderer.render(content); File outputFile = new File(destinationFolder, "second-post.html"); Assert.assertTrue(outputFile.exists()); Scanner scanner = new Scanner(outputFile); boolean foundTitle = false; boolean foundDate = false; boolean foundBody = false; while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (line.contains("<h2>Second Post</h2>")) { foundTitle = true; } if (line.trim().startsWith("<p class=\"post-date\">28") && line.endsWith("2013</p>")) { foundDate = true; } if (line.contains("Lorem ipsum dolor sit amet")) { foundBody = true; } if (foundTitle && foundDate && foundBody) { break; } } Assert.assertTrue(foundTitle); Assert.assertTrue(foundDate); Assert.assertTrue(foundBody); } @Test public void renderIndex() throws Exception { //setup Crawler crawler = new Crawler(db, sourceFolder, config); crawler.crawl(new File(sourceFolder.getPath() + File.separator + "content")); Renderer renderer = new Renderer(db, destinationFolder, templateFolder, config); //exec renderer.renderIndex("index.html"); //validate File outputFile = new File(destinationFolder, "index.html"); Assert.assertTrue(outputFile.exists()); Scanner scanner = new Scanner(outputFile); boolean foundFirstTitle = false; boolean foundSecondTitle = false; while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (line.contains("<h4><a href=\"/blog/2012/first-post.html\">First Post</a></h4>")) { foundFirstTitle = true; } if (line.contains("<h4><a href=\"/blog/2013/second-post.html\">Second Post</a></h4>")) { foundSecondTitle = true; } if (foundFirstTitle && foundSecondTitle) { break; } } Assert.assertTrue(foundFirstTitle); Assert.assertTrue(foundSecondTitle); } @Test public void renderFeed() throws Exception { Crawler crawler = new Crawler(db, sourceFolder, config); crawler.crawl(new File(sourceFolder.getPath() + File.separator + "content")); Renderer renderer = new Renderer(db, destinationFolder, templateFolder, config); renderer.renderFeed("feed.xml"); File outputFile = new File(destinationFolder, "feed.xml"); Assert.assertTrue(outputFile.exists()); Scanner scanner = new Scanner(outputFile); boolean foundDescription = false; boolean foundFirstTitle = false; boolean foundSecondTitle = false; while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (line.contains("<description>My corner of the Internet</description>")) { foundDescription = true; } if (line.contains("<title>Second Post</title>")) { foundFirstTitle = true; } if (line.contains("<title>First Post</title>")) { foundSecondTitle = true; } if (foundDescription && foundFirstTitle && foundSecondTitle) { break; } } Assert.assertTrue(foundDescription); Assert.assertTrue(foundFirstTitle); Assert.assertTrue(foundSecondTitle); } @Test public void renderArchive() throws Exception { Crawler crawler = new Crawler(db, sourceFolder, config); crawler.crawl(new File(sourceFolder.getPath() + File.separator + "content")); Renderer renderer = new Renderer(db, destinationFolder, templateFolder, config); renderer.renderArchive("archive.html"); File outputFile = new File(destinationFolder, "archive.html"); Assert.assertTrue(outputFile.exists()); Scanner scanner = new Scanner(outputFile); boolean foundFirstPost = false; boolean foundSecondPost = false; while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (line.contains("<a href=\"/blog/2013/second-post.html\">Second Post</a></h4>")) { foundFirstPost = true; } if (line.contains("<a href=\"/blog/2012/first-post.html\">First Post</a></h4>")) { foundSecondPost = true; } if (foundFirstPost && foundSecondPost) { break; } } Assert.assertTrue(foundFirstPost); Assert.assertTrue(foundSecondPost); } @Test public void renderTags() throws Exception { Crawler crawler = new Crawler(db, sourceFolder, config); crawler.crawl(new File(sourceFolder.getPath() + File.separator + "content")); Renderer renderer = new Renderer(db, destinationFolder, templateFolder, config); renderer.renderTags(crawler.getTags(), "tags"); File outputFile = new File(destinationFolder + File.separator + "tags" + File.separator + "blog.html"); Assert.assertTrue(outputFile.exists()); Scanner scanner = new Scanner(outputFile); boolean foundFirstPost = false; boolean foundSecondPost = false; while (scanner.hasNextLine()) { String line = scanner.nextLine(); if (line.contains("<a href=\"/blog/2013/second-post.html\">Second Post</a></h4>")) { foundFirstPost = true; } if (line.contains("<a href=\"/blog/2012/first-post.html\">First Post</a></h4>")) { foundSecondPost = true; } if (foundFirstPost && foundSecondPost) { break; } } Assert.assertTrue(foundFirstPost); Assert.assertTrue(foundSecondPost); } @Test public void renderSitemap() throws Exception { DocumentTypes.addDocumentType("paper"); DBUtil.updateSchema(db); Crawler crawler = new Crawler(db, sourceFolder, config); crawler.crawl(new File(sourceFolder.getPath() + File.separator + "content")); Renderer renderer = new Renderer(db, destinationFolder, templateFolder, config); renderer.renderSitemap("sitemap.xml"); File outputFile = new File(destinationFolder, "sitemap.xml"); Assert.assertTrue(outputFile.exists()); // verify String output = FileUtils.readFileToString(outputFile); assertThat(output) .contains("/blog/2013/second-post.html") .contains("/blog/2012/first-post.html") .contains("/papers/published-paper.html") .doesNotContain("draft-paper.html"); } }
package org.mvel.tests.main; import junit.framework.TestCase; import org.mvel.ExpressionCompiler; import org.mvel.MVEL; import org.mvel.ParserContext; import org.mvel.debug.DebugTools; import org.mvel.optimizers.OptimizerFactory; import org.mvel.tests.main.res.*; import org.mvel.util.StringAppender; import java.io.CharArrayWriter; import java.io.PrintWriter; import java.io.Serializable; import java.math.BigDecimal; import java.math.BigInteger; import java.text.SimpleDateFormat; import java.util.*; public abstract class AbstractTest extends TestCase { protected Foo foo = new Foo(); protected Map<String, Object> map = new HashMap<String, Object>(); protected Base base = new Base(); protected DerivedClass derived = new DerivedClass(); public void testNothing() { // to satify Eclipse and Surefire. } public AbstractTest() { foo.setBar(new Bar()); map.put("foo", foo); map.put("a", null); map.put("b", null); map.put("c", "cat"); map.put("BWAH", ""); map.put("misc", new MiscTestClass()); map.put("pi", "3.14"); map.put("hour", "60"); map.put("zero", 0); map.put("order", new Order()); map.put("$id", 20); map.put("testImpl", new TestInterface() { public String getName() { return "FOOBAR!"; } public boolean isFoo() { return true; } }); map.put("derived", derived); } protected Object test(String ex) { return test(ex, this.base, this.map); } protected Object test(String ex, Object base, Map map) { ExpressionCompiler compiler = new ExpressionCompiler(ex); StringAppender failErrors = null; Serializable compiled = compiler.compile(); Object first = null, second = null, third = null, fourth = null, fifth = null, sixth = null, seventh = null; if (!Boolean.getBoolean("mvel.disable.jit")) { OptimizerFactory.setDefaultOptimizer("ASM"); try { first = MVEL.executeExpression(compiled, base, map); } catch (Exception e) { failErrors = new StringAppender(); failErrors.append("\nFIRST TEST: { " + ex + " }: EXCEPTION REPORT: \n\n"); CharArrayWriter writer = new CharArrayWriter(); e.printStackTrace(new PrintWriter(writer)); failErrors.append(writer.toCharArray()); } try { second = MVEL.executeExpression(compiled, base, map); } catch (Exception e) { if (failErrors == null) failErrors = new StringAppender(); failErrors.append("\nSECOND TEST: { " + ex + " }: EXCEPTION REPORT: \n\n"); CharArrayWriter writer = new CharArrayWriter(); e.printStackTrace(new PrintWriter(writer)); failErrors.append(writer.toCharArray()); } } try { third = MVEL.eval(ex, base, map); } catch (Exception e) { if (failErrors == null) failErrors = new StringAppender(); failErrors.append("\nTHIRD TEST: { " + ex + " }: EXCEPTION REPORT: \n\n"); CharArrayWriter writer = new CharArrayWriter(); e.printStackTrace(new PrintWriter(writer)); failErrors.append(writer.toCharArray()); } if (first != null && !first.getClass().isArray()) { if (!first.equals(second)) { throw new AssertionError("Different result from test 1 and 2 (Compiled Re-Run / JIT) [first: " + String.valueOf(first) + "; second: " + String.valueOf(second) + "]"); } if (!first.equals(third)) { throw new AssertionError("Different result from test 1 and 3 (Compiled to Interpreted) [first: " + String.valueOf(first) + " (" + first.getClass().getName() + "); third: " + String.valueOf(third) + " (" + (second != null ? first.getClass().getName() : "null") + ")]"); } } OptimizerFactory.setDefaultOptimizer("reflective"); compiled = MVEL.compileExpression(ex); try { fourth = MVEL.executeExpression(compiled, base, map); } catch (Exception e) { if (failErrors == null) failErrors = new StringAppender(); failErrors.append("\nFOURTH TEST: { " + ex + " }: EXCEPTION REPORT: \n\n"); CharArrayWriter writer = new CharArrayWriter(); e.printStackTrace(new PrintWriter(writer)); failErrors.append(writer.toCharArray()); } try { fifth = MVEL.executeExpression(compiled, base, map); } catch (Exception e) { if (failErrors == null) failErrors = new StringAppender(); failErrors.append("\nFIFTH TEST: { " + ex + " }: EXCEPTION REPORT: \n\n"); CharArrayWriter writer = new CharArrayWriter(); e.printStackTrace(new PrintWriter(writer)); failErrors.append(writer.toCharArray()); } if (fourth != null && !fourth.getClass().isArray()) { if (!fourth.equals(fifth)) { throw new AssertionError("Different result from test 4 and 5 (Compiled Re-Run / Reflective) [first: " + String.valueOf(first) + "; second: " + String.valueOf(second) + "]"); } } ParserContext ctx = new ParserContext(); ctx.setSourceFile("unittest"); ExpressionCompiler debuggingCompiler = new ExpressionCompiler(ex); debuggingCompiler.setDebugSymbols(true); Serializable compiledD = debuggingCompiler.compile(ctx); try { sixth = MVEL.executeExpression(compiledD, base, map); } catch (Exception e) { if (failErrors == null) failErrors = new StringAppender(); failErrors.append("\nSIXTH TEST: { " + ex + " }: EXCEPTION REPORT: \n\n"); CharArrayWriter writer = new CharArrayWriter(); e.printStackTrace(new PrintWriter(writer)); failErrors.append(writer.toCharArray()); } if (sixth != null && !sixth.getClass().isArray()) { if (!fifth.equals(sixth)) { System.out.println("Payload 1 -- No Symbols: "); System.out.println(DebugTools.decompile(compiled)); System.out.println(); System.out.println("Payload 2 -- With Symbols: "); System.out.println(DebugTools.decompile(compiledD)); System.out.println(); throw new AssertionError("Different result from test 5 and 6 (Compiled to Compiled+DebuggingSymbols) [first: " + String.valueOf(fifth) + "; second: " + String.valueOf(sixth) + "]"); } } try { seventh = MVEL.executeExpression(compiledD, base, map); } catch (Exception e) { if (failErrors == null) failErrors = new StringAppender(); failErrors.append("\nSEVENTH TEST: { " + ex + " }: EXCEPTION REPORT: \n\n"); CharArrayWriter writer = new CharArrayWriter(); e.printStackTrace(new PrintWriter(writer)); failErrors.append(writer.toCharArray()); } if (seventh != null && !seventh.getClass().isArray()) { if (!seventh.equals(sixth)) { throw new AssertionError("Different result from test 4 and 5 (Compiled Re-Run / Reflective) [first: " + String.valueOf(first) + "; second: " + String.valueOf(second) + "]"); } } if (failErrors != null) { throw new AssertionError("Detailed Failure Report:\n" + failErrors.toString()); } return fourth; } public static class MiscTestClass { int exec = 0; @SuppressWarnings({"unchecked", "UnnecessaryBoxing"}) public List toList(Object object1, String string, int integer, Map map, List list) { exec++; List l = new ArrayList(); l.add(object1); l.add(string); l.add(new Integer(integer)); l.add(map); l.add(list); return l; } public int getExec() { return exec; } } public static class Bean { private Date myDate = new Date(); public Date getToday() { return new Date(); } public Date getNullDate() { return null; } public String getNullString() { return null; } public Date getMyDate() { return myDate; } public void setMyDate(Date myDate) { this.myDate = myDate; } } public static class Context { private final SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yy"); private Bean bean; public Bean getBean() { return bean; } public void setBean(Bean bean) { this.bean = bean; } public String formatDate(Date date) { return date == null ? null : dateFormat.format(date); } public String formatString(String str) { return str == null ? "<NULL>" : str; } } public static class Person { private String name; private int age; public Person() { } public Person(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } public static class Address { private String street; public Address(String street) { super(); this.street = street; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } } public static class Drools { public void insert(Object obj) { } } public static class Model { private List latestHeadlines; public List getLatestHeadlines() { return latestHeadlines; } public void setLatestHeadlines(List latestHeadlines) { this.latestHeadlines = latestHeadlines; } } public static class Message { public static final int HELLO = 0; public static final int GOODBYE = 1; private String message; private int status; public String getMessage() { return this.message; } public void setMessage(String message) { this.message = message; } public int getStatus() { return this.status; } public void setStatus(int status) { this.status = status; } } public class ClassA { private Integer i; private double d; private String s; public Date date; private BigDecimal bigdec; private BigInteger bigint; public Integer getI() { return i; } public void setI(Integer i) { this.i = i; } public double getD() { return d; } public void setD(double d) { this.d = d; } public String getS() { return s; } public void setS(String s) { this.s = s; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public BigDecimal getBigdec() { return bigdec; } public void setBigdec(BigDecimal bigdec) { this.bigdec = bigdec; } public BigInteger getBigint() { return bigint; } public void setBigint(BigInteger bigint) { this.bigint = bigint; } } public class ClassB { private Integer i; private double d; private String s; public String date; private BigDecimal bigdec; private BigInteger bigint; public Integer getI() { return i; } public void setI(Integer i) { this.i = i; } public double getD() { return d; } public void setD(double d) { this.d = d; } public String getS() { return s; } public void setS(String s) { this.s = s; } public String getDate() { return date; } public void setDate(String date) { this.date = date; } public BigDecimal getBigdec() { return bigdec; } public void setBigdec(BigDecimal bigdec) { this.bigdec = bigdec; } public BigInteger getBigint() { return bigint; } public void setBigint(BigInteger bigint) { this.bigint = bigint; } } public static class Order { private int number = 20; public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } } }
package net.dump247.docker; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonToken; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientHandlerException; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.UniformInterfaceException; import com.sun.jersey.api.client.WebResource; import com.sun.jersey.api.client.filter.HTTPBasicAuthFilter; import com.sun.jersey.client.urlconnection.HTTPSProperties; import com.sun.jersey.core.util.MultivaluedMapImpl; import javax.net.ssl.HostnameVerifier; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSession; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.UriBuilder; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.MalformedURLException; import java.net.Socket; import java.net.URI; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Collections; import java.util.List; import static java.lang.String.format; /** * Client for interacting with docker. * <p/> * Only supports the docker API via TCP. You must bind docker to a TCP * port. For example: docker -H 127.0.0.1:4243 */ public class DockerClient { /** * Version of the docker API this client uses ({@value}). */ public static final String API_VERSION = "v1.8"; public static final URI DEFAULT_LOCAL_URI = URI.create("http://localhost:4243"); public static final String APPLICATION_DOCKER_RAW_STREAM = "application/vnd.docker.raw-stream"; public static final MediaType APPLICATION_DOCKER_RAW_STREAM_TYPE = MediaType.valueOf(APPLICATION_DOCKER_RAW_STREAM); private static final int STDOUT_STREAM = 1; private static final int STDERR_STREAM = 2; private final URI _apiEndpoint; private final Client _httpClient; private final SSLContext _sslContext; public DockerClient(URI dockerEndpoint) { this(dockerEndpoint, null, null, null, null); } public DockerClient(URI dockerEndpoint, SSLContext sslContext, HostnameVerifier hostnameVerifier, String username, String password) { _apiEndpoint = UriBuilder.fromUri(dockerEndpoint).path(API_VERSION).build(); _httpClient = Client.create(); _sslContext = sslContext; if (!"http".equals(dockerEndpoint.getScheme()) && !"https".equals(dockerEndpoint.getScheme())) { throw new IllegalArgumentException(format("Unsupported endpoint scheme. Only http and https are supported: [dockerEndpoint=%s]", dockerEndpoint)); } if (sslContext == null && !"http".equals(dockerEndpoint.getScheme())) { // Attach currently directly uses sockets, so we need to ensure the jersey client and // the raw sockets implementation uses the same settings. This check may be overly // conservative and unnecessary. throw new IllegalArgumentException(format("SSL context is required for HTTPS connections: [dockerEndpoint=%s]", dockerEndpoint)); } else if (sslContext != null) { _httpClient.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties(hostnameVerifier, sslContext)); } username = username == null ? "" : username; password = password == null ? "" : password; if (username.length() > 0 || password.length() > 0) { _httpClient.addFilter(new HTTPBasicAuthFilter(username, password)); } } public URI getEndpoint() { return _apiEndpoint; } /** * Get docker version information. * * @return version info * @throws DockerException if the server reports an error * @throws ClientHandlerException if an error occurs sending the request or receiving the response * (i.e. server is not listing on specified port, etc) */ public DockerVersionResponse version() throws DockerException { try { return api("version").get(DockerVersionResponse.class); } catch (UniformInterfaceException ex) { throw new DockerException("Failed to get docker version information: [uri=" + uri("version") + "]", ex); } } /** * Create a new client that communicates with the local docker service. * * @return local docker client * @see #DEFAULT_LOCAL_URI */ public static DockerClient localClient() { return new DockerClient(DEFAULT_LOCAL_URI, null, null, null, null); } /** * Pull an image from the registry so it is available locally. * <p/> * This method blocks until the image is downloaded. As such, it may take a long time to * complete. * * @param request image pull options * @throws DockerException if the server reports an error * @throws ImageNotFoundException if the requested image does not exist in the registry * @throws ClientHandlerException if an error occurs sending the request or receiving the response * (i.e. server is not listing on specified port, etc) */ public void pullImage(PullImageRequest request) throws DockerException { pullImage(request, ProgressListener.NULL); } /** * Pull an image from the registry so it is available locally. * <p/> * This method blocks until the image is downloaded. As such, it may take a long time to * complete. * * @param request image pull options * @param progress receive progress messages * @throws DockerException if the server reports an error * @throws ImageNotFoundException if the requested image does not exist in the registry * @throws ClientHandlerException if an error occurs sending the request or receiving the response * (i.e. server is not listing on specified port, etc) */ public void pullImage(PullImageRequest request, ProgressListener progress) throws DockerException { if (request == null) { throw new NullPointerException("request"); } if (request.getImage() == null) { throw new IllegalArgumentException("request.image is required"); } if (progress == null) { throw new NullPointerException("progress"); } ProgressEvent response; try { WebResource resource = resource("images/create"); MultivaluedMap<String, String> params = new MultivaluedMapImpl(); params.add("fromImage", request.getImage()); if (request.getTag().length() > 0) { params.add("tag", request.getTag()); } response = readLastResponse(json(resource.queryParams(params)).post(ClientResponse.class), progress); } catch (IOException ex) { throw new DockerException("Error handling request: [uri=" + uri("images/create") + "]", ex); } catch (UniformInterfaceException ex) { switch (ex.getResponse().getStatus()) { case 500: throw new DockerException("Server error", ex); default: throw new DockerException("Unexpected response from server: [code=" + ex.getResponse().getStatus() + "]", ex); } } // Check if the response contains an error message switch (response.getCode()) { case Ok: // Operation was successful break; case NotFound: throw new ImageNotFoundException(format("Image %s does not exist.", request.getImage())); default: throw new DockerException(response.getStatusMessage()); } } /** * Pull an image from the registry so it is available locally. * <p/> * This method blocks until the image is downloaded. As such, it may take a long time to * complete. * * @param image name of the image to pull * @throws DockerException if the server reports an error * @throws ImageNotFoundException if the requested image does not exist in the registry * @throws ClientHandlerException if an error occurs sending the request or receiving the response * (i.e. server is not listing on specified port, etc) */ public void pullImage(String image) throws DockerException { if (image == null) { throw new NullPointerException("image"); } pullImage(new PullImageRequest().withImage(image), ProgressListener.NULL); } /** * Pull an image from the registry so it is available locally. * <p/> * This method blocks until the image is downloaded. As such, it may take a long time to * complete. * * @param image name of the image to pull * @param progress receive progress messages * @throws DockerException if the server reports an error * @throws ImageNotFoundException if the requested image does not exist in the registry * @throws ClientHandlerException if an error occurs sending the request or receiving the response * (i.e. server is not listing on specified port, etc) */ public void pullImage(String image, ProgressListener progress) throws DockerException { if (image == null) { throw new NullPointerException("image"); } pullImage(new PullImageRequest().withImage(image), progress); } /** * Remove an image from the filesystem. * <p/> * Returns successfully if the image does not exist. * * @param request remove options * @throws DockerException if the server reports an error * @throws ClientHandlerException if an error occurs sending the request or receiving the response * (i.e. server is not listing on specified port, etc) */ public void removeImage(RemoveImageRequest request) throws DockerException { if (request == null) { throw new NullPointerException("request"); } if (request.getImage() == null) { throw new IllegalArgumentException("request.image is required"); } try { api("images/%s", request.getImage()).delete(); } catch (UniformInterfaceException ex) { switch (ex.getResponse().getStatus()) { case 404: // Image does not exist. break; case 500: throw new DockerException("Server error", ex); default: throw new DockerException("Unexpected response from server: [code=" + ex.getResponse().getStatus() + "]", ex); } } } /** * Remove an image from the filesystem. * <p/> * Returns successfully if the image does not exist. * * @param image Name of the image to remove * @throws DockerException if the server reports an error * @throws ClientHandlerException if an error occurs sending the request or receiving the response * (i.e. server is not listing on specified port, etc) */ public void removeImage(String image) throws DockerException { if (image == null) { throw new NullPointerException("image"); } removeImage(new RemoveImageRequest().withImage(image)); } /** * Create a new container. * <p/> * The source image for the container must exist locally. If it does * not exist locally, the image must be pulled from the registry * with {@link #pullImage(PullImageRequest)}. * * @param request container configuration * @return response from the server * @throws DockerException if the server reports an error * @throws ImageNotFoundException if the requested image does not exist locally and must be pulled * @throws ClientHandlerException if an error occurs sending the request or receiving the response * (i.e. server is not listing on specified port, etc) */ public CreateContainerResponse createContainer(CreateContainerRequest request) throws DockerException { if (request == null) { throw new NullPointerException("request"); } if (request.getImage() == null) { throw new IllegalArgumentException("request.image is required"); } if (request.getCommand().size() == 0) { throw new IllegalArgumentException("request.command is required"); } try { return api("containers/create").post(CreateContainerResponse.class, request); } catch (UniformInterfaceException ex) { switch (ex.getResponse().getStatus()) { case 404: throw new ImageNotFoundException(format("Image %s does not exist. Be sure to pull the image before creating a container.", request.getImage()), ex); case 406: // TODO What does this error really mean? throw new DockerException("Impossible to attach (container not running).", ex); case 500: throw new DockerException("Server error", ex); default: throw new DockerException("Unexpected response from server: [code=" + ex.getResponse().getStatus() + "]", ex); } } } /** * Start an existing container. * * @param request container options * @throws DockerException if the server reports an error * @throws ContainerNotFoundException if the container does not exist * @throws ClientHandlerException if an error occurs sending the request or receiving the response * (i.e. server is not listing on specified port, etc) */ public void startContainer(StartContainerRequest request) throws DockerException { if (request == null) { throw new NullPointerException("request"); } if (request.getContainerId() == null) { throw new IllegalArgumentException("request.containerId is required"); } try { api("containers/%s/start", request.getContainerId()).post(request); } catch (UniformInterfaceException ex) { switch (ex.getResponse().getStatus()) { case 404: throw new ContainerNotFoundException(format("Container %s does not exist.", request.getContainerId()), ex); case 500: throw new DockerException("Server error", ex); default: throw new DockerException("Unexpected response from server: [code=" + ex.getResponse().getStatus() + "]", ex); } } } /** * Start an existing container. * * @param containerId ID of the container to start * @throws DockerException if the server reports an error * @throws ContainerNotFoundException if the container does not exist * @throws ClientHandlerException if an error occurs sending the request or receiving the response * (i.e. server is not listing on specified port, etc) */ public void startContainer(String containerId) throws DockerException { if (containerId == null) { throw new NullPointerException("containerId"); } startContainer(new StartContainerRequest().withContainerId(containerId)); } /** * Create a new image from a container's changes. * * @param request commit options * @throws DockerException if the server reports an error * @throws ContainerNotFoundException if the container does not exist * @throws ClientHandlerException if an error occurs sending the request or receiving the response * (i.e. server is not listing on specified port, etc) */ public CommitContainerResponse commitContainer(CommitContainerRequest request) throws DockerException { if (request == null) { throw new NullPointerException("request"); } if (request.getContainerId() == null) { throw new IllegalArgumentException("request.containerId is required"); } try { WebResource resource = resource("commit"); MultivaluedMap<String, String> params = new MultivaluedMapImpl(); params.add("container", request.getContainerId()); if (request.getRepository().length() > 0) { params.add("repo", request.getRepository()); } if (request.getTag().length() > 0) { params.add("tag", request.getTag()); } if (request.getMessage().length() > 0) { params.add("m", request.getMessage()); } if (request.getAuthor().length() > 0) { params.add("author", request.getAuthor()); } return json(resource.queryParams(params)).post(CommitContainerResponse.class); } catch (UniformInterfaceException ex) { switch (ex.getResponse().getStatus()) { case 404: throw new ContainerNotFoundException(format("Container %s does not exist.", request.getContainerId()), ex); case 500: throw new DockerException("Server error", ex); default: throw new DockerException("Unexpected response from server: [code=" + ex.getResponse().getStatus() + "]", ex); } } } /** * Block until the specified container stops. * * @param request wait options * @throws DockerException if the server reports an error * @throws ContainerNotFoundException if the container does not exist * @throws ClientHandlerException if an error occurs sending the request or receiving the response * (i.e. server is not listing on specified port, etc) */ public WaitContainerResponse waitContainer(WaitContainerRequest request) throws DockerException { if (request == null) { throw new NullPointerException("request"); } if (request.getContainerId() == null) { throw new IllegalArgumentException("request.containerId is required"); } try { return api("containers/%s/wait", request.getContainerId()).post(WaitContainerResponse.class); } catch (UniformInterfaceException ex) { switch (ex.getResponse().getStatus()) { case 404: throw new ContainerNotFoundException(format("Container %s does not exist.", request.getContainerId()), ex); case 500: throw new DockerException("Server error", ex); default: throw new DockerException("Unexpected response from server: [code=" + ex.getResponse().getStatus() + "]", ex); } } } /** * Block until the specified container stops. * <p/> * Returns successfully if the container has already stopped. * * @param containerId ID of the container to wait for * @throws DockerException if the server reports an error * @throws ContainerNotFoundException if the container does not exist * @throws ClientHandlerException if an error occurs sending the request or receiving the response * (i.e. server is not listing on specified port, etc) */ public WaitContainerResponse waitContainer(String containerId) throws DockerException { if (containerId == null) { throw new NullPointerException("containerId"); } return waitContainer(new WaitContainerRequest().withContainerId(containerId)); } /** * Remove a container from the filesystem. * <p/> * Returns successfully if the container does not exist. * * @param request remove options * @throws DockerException if the server reports an error * @throws ClientHandlerException if an error occurs sending the request or receiving the response * (i.e. server is not listing on specified port, etc) */ public void removeContainer(RemoveContainerRequest request) throws DockerException { if (request == null) { throw new NullPointerException("request"); } if (request.getContainerId() == null) { throw new IllegalArgumentException("request.containerId is required"); } try { api("containers/%s", request.getContainerId()).delete(); } catch (UniformInterfaceException ex) { switch (ex.getResponse().getStatus()) { case 404: // Container does not exist already. break; case 500: throw new DockerException("Server error", ex); default: throw new DockerException("Unexpected response from server: [code=" + ex.getResponse().getStatus() + "]", ex); } } } /** * Remove a container from the filesystem. * <p/> * Returns successfully if the container does not exist. * * @param containerId ID of the container to remove * @throws DockerException if the server reports an error * @throws ClientHandlerException if an error occurs sending the request or receiving the response * (i.e. server is not listing on specified port, etc) */ public void removeContainer(String containerId) throws DockerException { if (containerId == null) { throw new NullPointerException("containerId"); } removeContainer(new RemoveContainerRequest().withContainerId(containerId)); } /** * Kill a container. * * @param request kill options * @throws DockerException if the server reports an error * @throws ContainerNotFoundException if the container does not exist * @throws ClientHandlerException if an error occurs sending the request or receiving the response * (i.e. server is not listing on specified port, etc) */ public void killContainer(KillContainerRequest request) throws DockerException { if (request == null) { throw new NullPointerException("request"); } if (request.getContainerId() == null) { throw new IllegalArgumentException("request.containerId is required"); } try { api("containers/%s/kill", request.getContainerId()).post(); } catch (UniformInterfaceException ex) { switch (ex.getResponse().getStatus()) { case 404: throw new ContainerNotFoundException(format("Container %s does not exist.", request.getContainerId()), ex); case 500: throw new DockerException("Server error", ex); default: throw new DockerException("Unexpected response from server: [code=" + ex.getResponse().getStatus() + "]", ex); } } } public static class ContainerStreams { public final InputStream stdout; public final InputStream stderr; public final OutputStream stdin; public ContainerStreams(InputStream stdout, InputStream stderr, OutputStream stdin) { this.stdout = stdout; this.stderr = stderr; this.stdin = stdin; } } private static String path(URI uri) { String path = uri.getRawPath(); String query = uri.getRawQuery(); return query == null ? path : path + "?" + query; } /** * Attach to the input and output streams of a container. * * @param containerId id of the container to attach to * @return container stdin and stdout/stderr * @throws DockerException if the server reports an error * @throws ContainerNotFoundException if the container does not exist * @throws ClientHandlerException if an error occurs sending the request or receiving the response * (i.e. server is not listing on specified port, etc) */ public ContainerStreams attachContainerStreams(String containerId) throws DockerException { if (containerId == null) { throw new NullPointerException("containerId"); } try { URI uri = UriBuilder.fromUri(_apiEndpoint).path(format("containers/%s/attach", containerId)) .queryParam("stream", "1") .queryParam("logs", "1") .queryParam("stdin", "1") .queryParam("stdout", "1") .queryParam("stderr", "1") .build(); Socket socket = "https".equals(_apiEndpoint.getScheme()) ? _sslContext.getSocketFactory().createSocket(_apiEndpoint.getHost(), _apiEndpoint.getPort()) : new Socket(_apiEndpoint.getHost(), _apiEndpoint.getPort()); OutputStream socketOut = socket.getOutputStream(); socketOut.write(("" + format("POST %s HTTP/1.0\r\n", path(uri)) + format("Accept: %s\r\n", APPLICATION_DOCKER_RAW_STREAM) + format("Content-Type: %s\r\n", APPLICATION_DOCKER_RAW_STREAM) + format("User-Agent: DockerClient\r\n") + "\r\n" ).getBytes()); InputStream socketIn = socket.getInputStream(); // TODO better response processing int ch; int prevChar = 0; while ((ch = socketIn.read()) >= 0) { if (ch == '\r') { continue; } if (ch == '\n' && prevChar == ch) { break; } prevChar = ch; } MultiplexedStream multiplexedStream = new MultiplexedStream(socketIn); return new ContainerStreams( new AttachedStream(STDOUT_STREAM, multiplexedStream), new AttachedStream(STDERR_STREAM, multiplexedStream), socketOut ); } catch (MalformedURLException ex) { throw new RuntimeException("Unexpected error", ex); } catch (IOException ex) { throw new DockerException("Error attaching to container: [containerId=" + containerId + "]", ex); } } /** * Attach to the container to receive stdout and stderr. * * @param request options for receiving container output * @return response content * @throws DockerException if the server reports an error * @throws ContainerNotFoundException if the container does not exist * @throws ClientHandlerException if an error occurs sending the request or receiving the response * (i.e. server is not listing on specified port, etc) */ public AttachResponse attachContainer(AttachRequest request) throws DockerException { if (request == null) { throw new NullPointerException("request"); } if (request.getContainerId() == null) { throw new IllegalArgumentException("request.containerId is required"); } if ((!request.isStderrIncluded() && !request.isStdoutIncluded()) || (!request.isLogs() && !request.isStream())) { return new AttachResponse(); } MultivaluedMap<String, String> params = new MultivaluedMapImpl(); AttachResponse response = new AttachResponse(); if (request.isLogs()) { params.add("logs", "true"); } if (request.isStream()) { params.add("stream", "true"); } // TODO demultiplex both stdout and stderr over single connection if (request.isStderrIncluded()) { response.setStderr(attachStream(request.getContainerId(), params, STDERR_STREAM, "stderr")); } if (request.isStdoutIncluded()) { response.setStdout(attachStream(request.getContainerId(), params, STDOUT_STREAM, "stdout")); } return response; } private InputStream attachStream(String containerId, MultivaluedMap<String, String> params, int streamNum, String streamName) throws DockerException { ClientResponse response = resource("containers/%s/attach", containerId) .queryParams(params) .queryParam(streamName, "true") .accept(APPLICATION_DOCKER_RAW_STREAM_TYPE) .type(MediaType.APPLICATION_JSON_TYPE) .post(ClientResponse.class); switch (response.getStatus()) { case 200: return new AttachStream(streamNum, response.getEntityInputStream()); case 404: throw new ContainerNotFoundException(format("Container %s does not exist.", containerId)); case 500: throw new DockerException("Server error"); default: throw new DockerException("Unexpected response from server: [code=" + response.getStatus() + "]"); } } /** * Attach to a container to receive stdout and stderr. * * @param containerId ID of the container to attach to * @return response content * @throws DockerException if the server reports an error * @throws ContainerNotFoundException if the container does not exist * @throws ClientHandlerException if an error occurs sending the request or receiving the response * (i.e. server is not listing on specified port, etc) */ public AttachResponse attachContainer(String containerId) throws DockerException { if (containerId == null) { throw new NullPointerException("containerId"); } // TODO validate containerId return attachContainer(new AttachRequest().withContainerId(containerId)); } /** * Kill a container. * <p/> * Sends SIGKILL. * * @param containerId ID of the container to kill * @throws DockerException if the server reports an error * @throws ContainerNotFoundException if the container does not exist * @throws ClientHandlerException if an error occurs sending the request or receiving the response * (i.e. server is not listing on specified port, etc) */ public void killContainer(String containerId) throws DockerException { if (containerId == null) { throw new NullPointerException("containerId"); } killContainer(new KillContainerRequest().withContainerId(containerId)); } /** * Remove a container from the filesystem. * <p/> * This method blocks until the container stops. * <p/> * Send SIGTERM, and then SIGKILL after timeout. If the timeout is 0, * SIGTERM is sent and this method blocks until the container stops * (SIGKILL is not sent). * * @param request remove options * @throws DockerException if the server reports an error * @throws ContainerNotFoundException if the container does not exist * @throws ClientHandlerException if an error occurs sending the request or receiving the response * (i.e. server is not listing on specified port, etc) */ public void stopContainer(StopContainerRequest request) throws DockerException { if (request == null) { throw new NullPointerException("request"); } if (request.getContainerId() == null) { throw new IllegalArgumentException("request.containerId is required"); } try { WebResource resource = resource("containers/%s/stop", request.getContainerId()); if (request.getTimeoutSeconds() != 0) { resource.queryParam("t", Integer.toString(request.getTimeoutSeconds())); } json(resource).post(); } catch (UniformInterfaceException ex) { switch (ex.getResponse().getStatus()) { case 404: throw new ContainerNotFoundException(format("Container %s does not exist.", request.getContainerId()), ex); case 304: // The container's status has not changed. The container must already have been stopped. return; case 500: throw new DockerException("Server error", ex); default: throw new DockerException("Unexpected response from server: [code=" + ex.getResponse().getStatus() + "]", ex); } } } public void stopContainer(String containerId) throws DockerException { if (containerId == null) { throw new NullPointerException("containerId"); } stopContainer(new StopContainerRequest().withContainerId(containerId)); } public ListContainersResponse listContainers() throws DockerException { return listContainers(new ListContainersRequest()); } public ListContainersResponse listContainers(ListContainersRequest request) throws DockerException { if (request == null) { throw new NullPointerException("request"); } try { WebResource resource = resource("/containers/json"); if (request.getLimit() > 0) { resource.queryParam("limit", Integer.toString(request.getLimit())); } // Docker v0.8.0 returns Content-Type = text/plain // Jersey expected Content-Type = application/json and raises an exception ClientResponse response = json(resource).get(ClientResponse.class); if (response.getClientResponseStatus() != ClientResponse.Status.OK) { throw new UniformInterfaceException(response); } List<ContainerInfo> containers = new ObjectMapper().readValue(response.getEntityInputStream(), new TypeReference<List<ContainerInfo>>() { }); return new ListContainersResponse(containers == null ? Collections.<ContainerInfo>emptyList() : containers); } catch (IOException ex) { throw new DockerException("Server error", ex); } catch (UniformInterfaceException ex) { throw new DockerException("Server error", ex); } } /** * Get system-wide information. * * @return system info * @throws DockerException if the server reports an error * @throws ClientHandlerException if an error occurs sending the request or receiving the response * (i.e. server is not listing on specified port, etc) */ public SystemInfoResponse info() throws DockerException { try { return api("info").get(SystemInfoResponse.class); } catch (UniformInterfaceException ex) { throw new DockerException("Failed to get docker system information: [uri=" + uri("info") + "]", ex); } } private ProgressEvent readLastResponse(ClientResponse clientResponse, ProgressListener progress) throws IOException { JsonParser jsonParser = new ObjectMapper().getFactory().createParser(clientResponse.getEntityInputStream()); JsonToken jsonToken; ProgressEvent responseObject = null; while ((jsonToken = jsonParser.nextToken()) != null) { switch (jsonToken) { case START_OBJECT: responseObject = jsonParser.readValueAs(ProgressEvent.class); progress.progress(responseObject); break; default: // Ignore all other token types break; } } return responseObject; } private URI uri(String path) { return UriBuilder.fromUri(_apiEndpoint).path(path).build(); } private WebResource resource(String path, Object... args) { return _httpClient.resource(UriBuilder.fromUri(_apiEndpoint).path(format(path, args)).build()); } private WebResource.Builder json(WebResource resource) { return resource .accept(MediaType.APPLICATION_JSON_TYPE) .type(MediaType.APPLICATION_JSON_TYPE); } private WebResource.Builder api(String path, Object... args) { return json(resource(path, args)); } private static class MultiplexedStream { private final InputStream _dataStream; private final byte[] _headerBuf = new byte[8]; private boolean _endOfStream; private int _streamClosed; private int _streamNum; private long _messageLen; public MultiplexedStream(InputStream dataStream) { _dataStream = dataStream; } public synchronized int read(final int streamNum, final byte[] bytes, final int off, final int len) throws IOException { readHeader(streamNum); if (_endOfStream) { return -1; } int readLen = (int) Math.min(_messageLen, len); int readCount = _dataStream.read(bytes, off, readLen); if (readCount < 0) { this.endOfStream(); return -1; } _messageLen -= readCount; return readCount; } public synchronized int read(final int streamNum) throws IOException { readHeader(streamNum); if (_endOfStream) { return -1; } int value = _dataStream.read(); if (value < 0) { this.endOfStream(); return -1; } _messageLen -= 1; return value; } public synchronized void close(final int streamNum) throws IOException { _streamClosed |= streamNum; if (_streamClosed == (STDERR_STREAM | STDOUT_STREAM)) { _dataStream.close(); } } private void endOfStream() { _endOfStream = true; this.notify(); } private void readHeader(int streamNum) throws IOException { if ((_streamClosed & streamNum) != 0) { throw new IOException("Stream closed"); } while (!_endOfStream && _messageLen == 0) { // read 8 bytes header // header is [TYPE, 0, 0, 0, SIZE, SIZE, SIZE, SIZE] // TYPE is 1:stdout, 2:stderr // SIZE is 4-byte, unsigned, big endian length of message payload int count = 0; while (count < 8) { int result = _dataStream.read(_headerBuf, count, 8 - count); if (result < 0) { this.endOfStream(); return; } count += result; } if (_headerBuf[1] != 0 || _headerBuf[2] != 0 || _headerBuf[3] != 0) { throw new IOException("Unexpected stream header content."); } _streamNum = _headerBuf[0]; // Clear the type because ByteBuffer needs 8 bytes to read the long _headerBuf[0] = 0; ByteBuffer buffer = ByteBuffer.wrap(_headerBuf); buffer.order(ByteOrder.BIG_ENDIAN); _messageLen = buffer.getLong(); } while (!_endOfStream && _streamNum != streamNum) { this.notify(); try { this.wait(); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } } } private static class AttachedStream extends InputStream { private final int _streamNum; private final MultiplexedStream _dataStream; public AttachedStream(final int streamNum, final MultiplexedStream dataStream) { _streamNum = streamNum; _dataStream = dataStream; } @Override public int read(final byte[] bytes, final int off, final int len) throws IOException { return _dataStream.read(_streamNum, bytes, off, len); } @Override public int read() throws IOException { return _dataStream.read(_streamNum); } @Override public void close() throws IOException { _dataStream.close(_streamNum); } } private static class AttachStream extends InputStream { private final int _streamNum; private final InputStream _dataStream; private final byte[] _headerBuf = new byte[8]; private boolean _streamClosed; private boolean _endOfStream; private long _messageLen; public AttachStream(int streamNum, InputStream dataStream) { _streamNum = streamNum; _dataStream = dataStream; } @Override public int read() throws IOException { ensureBuf(); if (_endOfStream) { return -1; } int value = _dataStream.read(); if (value < 0) { _endOfStream = true; return -1; } _messageLen -= 1; return value; } @Override public int read(final byte[] b, final int off, final int len) throws IOException { ensureBuf(); if (_endOfStream) { return -1; } int readLen = (int) Math.min(_messageLen, len); int readCount = _dataStream.read(b, off, readLen); if (readCount < 0) { _endOfStream = true; return -1; } _messageLen -= readCount; return readCount; } @Override public void close() throws IOException { _streamClosed = true; _dataStream.close(); } private void ensureBuf() throws IOException { if (_streamClosed) { throw new IOException("Stream closed"); } while (!_endOfStream && _messageLen == 0) { // read 8 bytes header // header is [TYPE, 0, 0, 0, SIZE, SIZE, SIZE, SIZE] // TYPE is 1:stdout, 2:stderr // SIZE is 4-byte, unsigned, big endian length of message payload int count = 0; while (count < 8) { int result = _dataStream.read(_headerBuf, count, 8 - count); if (result < 0) { _endOfStream = true; return; } count += result; } if ((_headerBuf[0] & _streamNum) == 0 || _headerBuf[1] != 0 || _headerBuf[2] != 0 || _headerBuf[3] != 0) { throw new IOException("Unexpected stream header content."); } // Clear the type because ByteBuffer needs 8 bytes to read the long _headerBuf[0] = 0; ByteBuffer buffer = ByteBuffer.wrap(_headerBuf); buffer.order(ByteOrder.BIG_ENDIAN); _messageLen = buffer.getLong(); } } } private static final HostnameVerifier ALLOW_ALL_HOSTNAMES = new HostnameVerifier() { @Override public boolean verify(String s, SSLSession sslSession) { return true; } }; }
package org.turner.oath.totp; import java.math.BigInteger; import java.security.NoSuchAlgorithmException; import java.util.Arrays; import java.util.Collection; import javax.crypto.Mac; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import org.junit.runners.Parameterized.Parameters; import org.turner.oath.OATHGenerator; import org.turner.oath.OATHSecretState; /** * * @author turner */ @RunWith(Parameterized.class) public class TOTPRFCTest { private static final byte[] SECRET = hexStr2Bytes("12345678901234567890"); private static final long TIME_STEP = 30; private static final long INITIAL_UNIX_TIME = 0; @Parameters public static Collection<Object[]> rfcTestVectors() { return Arrays.asList(new Object[][] { {"HmacSHA1", 59L, "94287082" }, {"HmacSHA256", 59L, "46119246"}, {"HmacSHA512", 59L, "90693936"}, {"HmacSHA1", 1111111109L, "07081804"}, {"HmacSHA256", 1111111109L, "68084774"}, {"HmacSHA512", 1111111109L, "25091201"}, {"HmacSHA1", 1111111111L, "14050471"}, {"HmacSHA256", 1111111111L, "67062674"}, {"HmacSHA512", 1111111111L, "99943326"}, {"HmacSHA1", 1234567890L, "89005924"}, {"HmacSHA256", 1234567890L, "91819424"}, {"HmacSHA512", 1234567890L, "93441116"}, {"HmacSHA1", 2000000000L, "69279037"}, {"HmacSHA256", 2000000000L, "90698825"}, {"HmacSHA512", 2000000000L, "38618901"}, {"HmacSHA1", 20000000000L, "65353130"}, {"HmacSHA256", 20000000000L, "77737706"}, {"HmacSHA512", 20000000000L, "47863826"} }); } private String algorithmName; private long currentUnixTime; private String expectedOtp; public TOTPRFCTest(String algorithmName, long currentUnixTime, String expectedOtp) { this.algorithmName = algorithmName; this.currentUnixTime = currentUnixTime; this.expectedOtp = expectedOtp; } @Test public void rfcVector() throws NoSuchAlgorithmException { OATHGenerator totpGenerator = getTOTPGenerator(algorithmName); String generateOtp = totpGenerator.generateOtp(getOATHSecretState(currentUnixTime)); Assert.assertEquals(expectedOtp, generateOtp); } private static OATHGenerator getTOTPGenerator(String algorithmName) throws NoSuchAlgorithmException { Mac sha1Mac = Mac.getInstance(algorithmName); return new TOTPGenerator(sha1Mac); } private static OATHSecretState getOATHSecretState(long currentTime) { return new TOTPSecretState(SECRET, 8, TIME_STEP, INITIAL_UNIX_TIME, currentTime); } private static byte[] hexStr2Bytes(String hex) { // Adding one byte to get the right conversion // Values starting with "0" can be converted byte[] bArray = new BigInteger("10" + hex, 16).toByteArray(); // Copy all the REAL bytes, not the "first" byte[] ret = new byte[bArray.length - 1]; for (int i = 0; i < ret.length; i++) { ret[i] = bArray[i + 1]; } return ret; } }
package org.jdesktop.swingx; import java.awt.GraphicsEnvironment; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.SortedSet; import java.util.TimeZone; import java.util.logging.Logger; import javax.swing.Action; import javax.swing.Box; import javax.swing.JComboBox; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.ListSelectionModel; import javax.swing.SwingUtilities; import javax.swing.table.DefaultTableModel; import javax.swing.tree.DefaultMutableTreeNode; import org.jdesktop.swingx.JXMonthView.SelectionMode; import org.jdesktop.swingx.action.AbstractActionExt; import org.jdesktop.swingx.calendar.CalendarUtils; import org.jdesktop.swingx.combobox.ListComboBoxModel; import org.jdesktop.swingx.event.DateSelectionEvent.EventType; import org.jdesktop.swingx.test.DateSelectionReport; import org.jdesktop.swingx.test.XTestUtils; /** * Test to expose known issues with JXMonthView. * * @author Jeanette Winzenburg */ public class JXMonthViewIssues extends InteractiveTestCase { @SuppressWarnings("all") private static final Logger LOG = Logger.getLogger(JXMonthViewIssues.class .getName()); // Constants used internally; unit is milliseconds @SuppressWarnings("unused") private static final int ONE_MINUTE = 60*1000; @SuppressWarnings("unused") private static final int ONE_HOUR = 60*ONE_MINUTE; @SuppressWarnings("unused") private static final int THREE_HOURS = 3 * ONE_HOUR; @SuppressWarnings("unused") private static final int ONE_DAY = 24*ONE_HOUR; public static void main(String[] args) { // setSystemLF(true); JXMonthViewIssues test = new JXMonthViewIssues(); try { // test.runInteractiveTests(); // test.runInteractiveTests("interactive.*Locale.*"); test.runInteractiveTests("interactive.*AutoScroll.*"); // test.runInteractiveTests("interactive.*Blank.*"); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } @SuppressWarnings("unused") private Calendar calendar; /** * #702-swingx: no days shown? * * Not reproducible. */ public void interactiveBlankMonthViewOnAdd() { final JComponent comp = Box.createHorizontalBox(); comp.add(new JXMonthView()); final JXFrame frame = wrapInFrame(comp, "blank view on add"); Action next = new AbstractActionExt("new monthView") { public void actionPerformed(ActionEvent e) { comp.add(new JXMonthView()); frame.pack(); } }; addAction(frame, next); frame.pack(); frame.setVisible(true); }; /** * #703-swingx: set date to first of next doesn't update the view. * * Behaviour is consistent with core components. Except that it is doing * too much: revalidate most probably shouldn't change the scrolling state? * */ public void interactiveAutoScrollOnSelectionMonthView() { final JXMonthView us = new JXMonthView(); us.setSelectionMode(JXMonthView.SelectionMode.SINGLE_INTERVAL_SELECTION); final Calendar today = Calendar.getInstance(); CalendarUtils.endOfMonth(today); us.setSelectedDate(today.getTime()); JXFrame frame = wrapInFrame(us, "first day of next month"); Action nextMonthInterval = new AbstractActionExt("next month interval") { public void actionPerformed(ActionEvent e) { if (us.isSelectionEmpty()) return; today.setTime(us.getSelectedDate()); today.add(Calendar.DAY_OF_MONTH, -20); Date start = today.getTime(); today.add(Calendar.DAY_OF_MONTH, +40); us.setSelectionInterval(start, today.getTime()); // shouldn't effect scrolling state us.revalidate(); // client code must trigger // us.ensureDateVisible(start.getTime()); } }; addAction(frame, nextMonthInterval); Action next = new AbstractActionExt("next month") { public void actionPerformed(ActionEvent e) { if (us.isSelectionEmpty()) return; if (!CalendarUtils.isEndOfMonth(today)) { CalendarUtils.endOfMonth(today); } today.add(Calendar.DAY_OF_MONTH, 1); us.setSelectedDate(today.getTime()); LOG.info("firstDisplayed before: " + new Date(us.getFirstDisplayedDate())); // shouldn't effect scrolling state us.revalidate(); LOG.info("firstDisplayed: " + new Date(us.getFirstDisplayedDate())); // client code must trigger // us.ensureDateVisible(today.getTimeInMillis()); } }; addAction(frame, next); frame.pack(); frame.setVisible(true); } /** * #703-swingx: select date doesn't ensure visibility of selected. * * compare with core list: doesn't scroll as well. * */ public void interactiveAutoScrollOnSelectionList() { // add hoc model SortedSet<Date> dates = getDates(); final JXList us = new JXList(new ListComboBoxModel<Date>(new ArrayList<Date>(dates))); us.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION); JXFrame frame = wrapWithScrollingInFrame(us, "list - autoscroll on selection"); Action next = new AbstractActionExt("select last + 1") { public void actionPerformed(ActionEvent e) { int last = us.getLastVisibleIndex(); us.setSelectedIndex(last + 1); // shouldn't effect scrolling state us.revalidate(); // client code must trigger // us.ensureIndexIsVisible(last+1); } }; addAction(frame, next); frame.pack(); frame.setVisible(true); } /** * #703-swingx: set date to first of next doesn't "scroll". * * compare with core tree: doesn't scroll as well. * */ public void interactiveAutoScrollOnSelectionTree() { // add hoc model SortedSet<Date> dates = getDates(); DefaultMutableTreeNode root = new DefaultMutableTreeNode("dates"); for (Date date : dates) { root.add(new DefaultMutableTreeNode(date)); } final JXTree us = new JXTree(root); JXFrame frame = wrapWithScrollingInFrame(us, "tree - autoscroll on selection"); Action next = new AbstractActionExt("select last + 1") { public void actionPerformed(ActionEvent e) { int last = us.getLeadSelectionRow(); us.setSelectionRow(last + 1); // shouldn't effect scrolling state us.revalidate(); // client code must trigger // us.scrollRowToVisible(last + 1); } }; addAction(frame, next); frame.pack(); frame.setVisible(true); } /** * #703-swingx: set date to first of next doesn't "scroll". * * compare with core tree: doesn't scroll as well. * */ public void interactiveAutoScrollOnSelectionTable() { // add hoc model SortedSet<Date> dates = getDates(); DefaultTableModel model = new DefaultTableModel(0, 1); for (Date date : dates) { model.addRow(new Object[] {date}); } final JXTable us = new JXTable(model); JXFrame frame = wrapWithScrollingInFrame(us, "table - autoscroll on selection"); Action next = new AbstractActionExt("select last + 1") { public void actionPerformed(ActionEvent e) { int last = us.getSelectedRow(); us.setRowSelectionInterval(last + 1, last + 1); // shouldn't effect scrolling state us.revalidate(); // client code must trigger // us.scrollRowToVisible(last + 1); } }; addAction(frame, next); frame.pack(); frame.setVisible(true); } /** * Convenience to get a bunch of dates. * * @return */ private SortedSet<Date> getDates() { JXMonthView source = new JXMonthView(); source.setSelectionMode(JXMonthView.SelectionMode.SINGLE_INTERVAL_SELECTION); final Calendar today = Calendar.getInstance(); Date start = today.getTime(); today.add(Calendar.DAY_OF_MONTH, +40); source.setSelectionInterval(start, today.getTime()); SortedSet<Date> dates = source.getSelection(); return dates; } /** * #681-swingx: first row overlaps days. * * Looks like a problem with the constructor taking a locale? * Default is okay (even if German), US is okay, explicit german is wrong. */ public void interactiveFirstRowOfMonthSetLocale() { JPanel p = new JPanel(); // default constructor p.add(new JXMonthView()); // explicit us locale JXMonthView us = new JXMonthView(); us.setLocale(Locale.US); p.add(us); // explicit german locale JXMonthView german = new JXMonthView(); german.setLocale(Locale.GERMAN); p.add(german); showInFrame(p, "first row overlapping - setLocale"); } /** * #681-swingx: first row overlaps days. * * Looks like a problem with the constructor taking a locale? * Default is okay (even if German), US is okay, explicit german is wrong. */ public void interactiveFirstRowOfMonthLocaleConstructor() { JPanel p = new JPanel(); // default constructor p.add(new JXMonthView()); // explicit us locale p.add(new JXMonthView(Locale.US)); // explicit german locale p.add(new JXMonthView(Locale.GERMAN)); showInFrame(p, "first row overlapping - constructor"); } /** * #681-swingx: first row overlaps days. * Here everything looks okay. * * @see #interactiveFirstRowOfMonthLocaleDependent() */ public void interactiveFirstRowOfMonth() { JXMonthView monthView = new JXMonthView(); calendar.set(2008, 1, 1); monthView.setSelectedDate(calendar.getTime()); showInFrame(monthView, "first row"); } /** * Issue #618-swingx: JXMonthView displays problems with non-default * timezones. * */ public void interactiveUpdateOnTimeZone() { JPanel panel = new JPanel(); final JComboBox zoneSelector = new JComboBox(TimeZone.getAvailableIDs()); final JXDatePicker picker = new JXDatePicker(); final JXMonthView monthView = new JXMonthView(); monthView.setSelectedDate(picker.getDate()); monthView.setTraversable(true); // Synchronize the picker and selector's zones. zoneSelector.setSelectedItem(picker.getTimeZone().getID()); // Set the picker's time zone based on the selected time zone. zoneSelector.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { String zone = (String) zoneSelector.getSelectedItem(); TimeZone tz = TimeZone.getTimeZone(zone); picker.setTimeZone(tz); monthView.setTimeZone(tz); assertEquals(tz, monthView.getCalendar().getTimeZone()); } }); panel.add(zoneSelector); panel.add(picker); panel.add(monthView); JXFrame frame = showInFrame(panel, "display problems with non-default timezones"); Action assertAction = new AbstractActionExt("assert dates") { public void actionPerformed(ActionEvent e) { Calendar cal = monthView.getCalendar(); LOG.info("cal/firstDisplayed" + cal.getTime() +"/" + new Date(monthView.getFirstDisplayedDate())); } }; addAction(frame, assertAction); frame.pack(); } /** * Issue #618-swingx: JXMonthView displays problems with non-default * timezones. * */ public void interactiveUpdateOnTimeZoneJP() { JComponent panel = Box.createVerticalBox(); final JComboBox zoneSelector = new JComboBox(TimeZone.getAvailableIDs()); final JXMonthView monthView = new JXMonthView(); monthView.setTraversable(true); // Synchronize the picker and selector's zones. zoneSelector.setSelectedItem(monthView.getTimeZone().getID()); // Set the picker's time zone based on the selected time zone. zoneSelector.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { String zone = (String) zoneSelector.getSelectedItem(); TimeZone tz = TimeZone.getTimeZone(zone); monthView.setTimeZone(tz); assertEquals(tz, monthView.getCalendar().getTimeZone()); } }); panel.add(monthView); // JPanel bar = new JPanel(); JLabel label = new JLabel("Select TimeZone:"); label.setHorizontalAlignment(JLabel.CENTER); // panel.add(label); panel.add(zoneSelector); JXFrame frame = wrapInFrame(panel, "TimeZone"); frame.pack(); frame.setVisible(true); } /** * Issue #618-swingx: JXMonthView displays problems with non-default * timezones. * */ public void interactiveTimeZoneClearDateState() { JPanel panel = new JPanel(); final JComboBox zoneSelector = new JComboBox(TimeZone.getAvailableIDs()); final JXDatePicker picker = new JXDatePicker(); final JXMonthView monthView = new JXMonthView(); monthView.setSelectedDate(picker.getDate()); monthView.setLowerBound(XTestUtils.getStartOfToday(-10)); monthView.setUpperBound(XTestUtils.getStartOfToday(10)); monthView.setUnselectableDates(XTestUtils.getStartOfToday(2)); monthView.setFlaggedDates(new long[] {XTestUtils.getStartOfToday(4).getTime()}); monthView.setTraversable(true); // Synchronize the picker and selector's zones. zoneSelector.setSelectedItem(picker.getTimeZone().getID()); // Set the picker's time zone based on the selected time zone. zoneSelector.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent event) { String zone = (String) zoneSelector.getSelectedItem(); TimeZone tz = TimeZone.getTimeZone(zone); picker.setTimeZone(tz); monthView.setTimeZone(tz); assertEquals(tz, monthView.getCalendar().getTimeZone()); } }); panel.add(zoneSelector); panel.add(picker); panel.add(monthView); JXFrame frame = showInFrame(panel, "clear internal date-related state"); Action assertAction = new AbstractActionExt("assert dates") { public void actionPerformed(ActionEvent e) { Calendar cal = monthView.getCalendar(); LOG.info("cal/firstDisplayed" + cal.getTime() +"/" + new Date(monthView.getFirstDisplayedDate())); } }; addAction(frame, assertAction); frame.pack(); } /** * Issue #659-swingx: lastDisplayedDate must be synched. * */ public void interactiveLastDisplayed() { final JXMonthView month = new JXMonthView(); month.setSelectionMode(SelectionMode.SINGLE_INTERVAL_SELECTION); month.setTraversable(true); Action action = new AbstractActionExt("check lastDisplayed") { public void actionPerformed(ActionEvent e) { Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(month.getLastDisplayedDate()); Date viewLast = cal.getTime(); cal.setTimeInMillis(month.getUI().getLastDisplayedDate()); Date uiLast = cal.getTime(); LOG.info("last(view/ui): " + viewLast + "/" + uiLast); } }; JXFrame frame = wrapInFrame(month, "default - for debugging only"); addAction(frame, action); frame.setVisible(true); } /** * #703-swingx: set date to first of next doesn't update the view. * * Behaviour is consistent with core components. Except that it is doing * too much: revalidate most probably shouldn't change the scrolling state? * */ public void testAutoScrollOnSelection() { JXMonthView us = new JXMonthView(); final Calendar today = Calendar.getInstance(); CalendarUtils.endOfMonth(today); us.setSelectedDate(today.getTime()); long first = us.getFirstDisplayedDate(); today.add(Calendar.DAY_OF_MONTH, 1); us.setSelectedDate(today.getTime()); assertEquals(first, us.getFirstDisplayedDate()); fail("expected behaviour but test is unsafe as long as the revalidate doesn't fail"); } /** * #703-swingx: set date to first of next doesn't update the view. * * Behaviour is consistent with core components. Except that it is doing * too much: revalidate most probably shouldn't change the scrolling state? * * Note: this test is inconclusive - expected to fail because the Handler.layoutContainer * actually triggers a ensureVisible (which it shouldn't) which changes the * firstDisplayedDate, but the change has not yet happened in the invoke. Can be seen * while debugging, though. * * * @throws InvocationTargetException * @throws InterruptedException * */ public void testAutoScrollOnSelectionRevalidate() throws InterruptedException, InvocationTargetException { // This test will not work in a headless configuration. if (GraphicsEnvironment.isHeadless()) { LOG.info("cannot run test - headless environment"); return; } final JXMonthView us = new JXMonthView(); final Calendar today = Calendar.getInstance(); CalendarUtils.endOfMonth(today); us.setSelectedDate(today.getTime()); final long first = us.getFirstDisplayedDate(); JXFrame frame = showInFrame(us, ""); today.add(Calendar.DAY_OF_MONTH, 1); us.setSelectedDate(today.getTime()); us.revalidate(); LOG.info("firstdisplayed: " + new Date(us.getFirstDisplayedDate())); SwingUtilities.invokeAndWait(new Runnable() { public void run() { LOG.info("firstdisplayed: " + new Date(us.getFirstDisplayedDate())); assertEquals(first, us.getFirstDisplayedDate()); fail("weird (threading issue?): the firstDisplayed is changed in layoutContainer - not testable here"); } }); } /** * characterize calendar: minimal days in first week * Different for US (1) and Europe (4) */ public void testCalendarMinimalDaysInFirstWeek() { Calendar us = Calendar.getInstance(Locale.US); assertEquals(1, us.getMinimalDaysInFirstWeek()); Calendar french = Calendar.getInstance(Locale.FRENCH); assertEquals("french/european calendar", 4, french.getMinimalDaysInFirstWeek()); fail("Revisit: monthView should respect locale setting? (need to test)"); } /** * characterize calendar: first day of week * Can be set arbitrarily. Hmmm ... when is that useful? */ public void testCalendarFirstDayOfWeek() { Calendar french = Calendar.getInstance(Locale.FRENCH); assertEquals(Calendar.MONDAY, french.getFirstDayOfWeek()); Calendar us = Calendar.getInstance(Locale.US); assertEquals(Calendar.SUNDAY, us.getFirstDayOfWeek()); // JW: when would we want that? us.setFirstDayOfWeek(Calendar.FRIDAY); assertEquals(Calendar.FRIDAY, us.getFirstDayOfWeek()); fail("Revisit: why expose setting of firstDayOfWeek? Auto-set with locale"); } /** * BasicMonthViewUI: use adjusting api in keyboard actions. * Here: test add selection action. * * TODO: this fails (unrelated to the adjusting) because the * the selectionn changing event type is DATES_SET instead of * the expected DATES_ADDED. What's wrong - expectation or type? */ public void testAdjustingSetOnAdd() { JXMonthView view = new JXMonthView(); // otherwise the add action isn't called view.setSelectionMode(SelectionMode.SINGLE_INTERVAL_SELECTION); DateSelectionReport report = new DateSelectionReport(); view.getSelectionModel().addDateSelectionListener(report); Action select = view.getActionMap().get("adjustSelectionNextDay"); select.actionPerformed(null); assertTrue("ui keyboard action must have started model adjusting", view.getSelectionModel().isAdjusting()); assertEquals(2, report.getEventCount()); // assert that the adjusting is fired before the add // only: the ui fires a set instead - bug or feature? assertEquals(EventType.DATES_ADDED, report.getLastEvent().getEventType()); } /** * Returns a timezone with a rawoffset with a different offset. * * * PENDING: this is acutally for european time, not really thought of * negative/rolling +/- problem? * * @param timeZone the timezone to start with * @param diffRawOffset the raw offset difference. * @return */ @SuppressWarnings("unused") private TimeZone getTimeZone(TimeZone timeZone, int diffRawOffset) { int offset = timeZone.getRawOffset(); int newOffset = offset < 0 ? offset + diffRawOffset : offset - diffRawOffset; String[] availableIDs = TimeZone.getAvailableIDs(newOffset); TimeZone newTimeZone = TimeZone.getTimeZone(availableIDs[0]); return newTimeZone; } @SuppressWarnings("unused") private String[] getTimeZoneIDs() { List<String> zoneIds = new ArrayList<String>(); for (int i = -12; i <= 12; i++) { String sign = i < 0 ? "-" : "+"; zoneIds.add("GMT" + sign + i); } return zoneIds.toArray(new String[zoneIds.size()]); } @Override protected void setUp() throws Exception { calendar = Calendar.getInstance(); } }
package org.jdesktop.swingx; import java.awt.Color; import java.awt.Component; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.lang.reflect.InvocationTargetException; import java.util.Vector; import java.util.logging.Logger; import javax.swing.AbstractAction; import javax.swing.Action; import javax.swing.BorderFactory; import javax.swing.DefaultCellEditor; import javax.swing.JComboBox; import javax.swing.JFrame; import javax.swing.JTree; import javax.swing.SwingUtilities; import javax.swing.Timer; import javax.swing.UIManager; import javax.swing.border.Border; import javax.swing.event.TableModelEvent; import javax.swing.tree.DefaultMutableTreeNode; import javax.swing.tree.DefaultTreeCellRenderer; import javax.swing.tree.DefaultTreeModel; import javax.swing.tree.TreeCellRenderer; import javax.swing.tree.TreePath; import org.jdesktop.swingx.action.AbstractActionExt; import org.jdesktop.swingx.decorator.Highlighter; import org.jdesktop.swingx.decorator.HighlighterFactory; import org.jdesktop.swingx.hyperlink.AbstractHyperlinkAction; import org.jdesktop.swingx.renderer.CellContext; import org.jdesktop.swingx.renderer.CheckBoxProvider; import org.jdesktop.swingx.renderer.ComponentProvider; import org.jdesktop.swingx.renderer.DefaultTableRenderer; import org.jdesktop.swingx.renderer.DefaultTreeRenderer; import org.jdesktop.swingx.renderer.HyperlinkProvider; import org.jdesktop.swingx.renderer.LabelProvider; import org.jdesktop.swingx.renderer.StringValue; import org.jdesktop.swingx.renderer.StringValues; import org.jdesktop.swingx.renderer.WrappingIconPanel; import org.jdesktop.swingx.renderer.WrappingProvider; import org.jdesktop.swingx.renderer.RendererVisualCheck.TextAreaProvider; import org.jdesktop.swingx.test.ActionMapTreeTableModel; import org.jdesktop.swingx.test.ComponentTreeTableModel; import org.jdesktop.swingx.test.TreeTableUtils; import org.jdesktop.swingx.treetable.AbstractMutableTreeTableNode; import org.jdesktop.swingx.treetable.DefaultMutableTreeTableNode; import org.jdesktop.swingx.treetable.DefaultTreeTableModel; import org.jdesktop.swingx.treetable.FileSystemModel; import org.jdesktop.swingx.treetable.MutableTreeTableNode; import org.jdesktop.swingx.treetable.TreeTableModel; import org.jdesktop.swingx.treetable.TreeTableNode; import org.jdesktop.test.TableModelReport; /** * Test to exposed known issues of <code>JXTreeTable</code>. <p> * * Ideally, there would be at least one failing test method per open * issue in the issue tracker. Plus additional failing test methods for * not fully specified or not yet decided upon features/behaviour.<p> * * Once the issues are fixed and the corresponding methods are passing, they * should be moved over to the XXTest. * * @author Jeanette Winzenburg */ public class JXTreeTableIssues extends InteractiveTestCase { private static final Logger LOG = Logger.getLogger(JXTreeTableIssues.class .getName()); public static void main(String[] args) { setSystemLF(true); JXTreeTableIssues test = new JXTreeTableIssues(); try { // test.runInteractiveTests(); // test.runInteractiveTests(".*Combo.*"); // test.runInteractiveTests(".*Text.*"); // test.runInteractiveTests(".*TreeExpand.*"); test.runInteractiveTests("interactive.*EditWith.*"); // test.runInteractiveTests("interactive.*CustomColor.*"); } catch (Exception e) { System.err.println("exception when executing interactive tests:"); e.printStackTrace(); } } /** * Issue #1126: combo editor is closed immediately after starting * * Happens if row is not selected at the moment of starting, okay if selected. * Inserts on pressed, removes on released. Same for 1.5 and 1.6 */ public void interactiveEditWithComboBox() { // quick for having an editable treeTableModel (non hierarchical column) TreeTableModel model = new ComponentTreeTableModel(new JXFrame()); JXTreeTable treeTable = new JXTreeTable(model); treeTable.expandAll(); JComboBox box = new JComboBox(new Object[] {200, 300, 400}); box.setEditable(true); treeTable.getColumn(3).setCellEditor(new DefaultCellEditor(box)); JXTable table = new JXTable(treeTable.getModel()); JComboBox box2 = new JComboBox(new Object[] {200, 300, 400}); box2.setEditable(true); table.getColumn(3).setCellEditor(new DefaultCellEditor(box2)); showWithScrollingInFrame(treeTable, table, "combo editor in column 3"); } /** * Custom renderer colors of Swingx DefaultTreeRenderer not respected. * (same in J/X/Tree). * * A bit surprising - probably due to the half-hearted support (backward * compatibility) of per-provider colors: they are set by the glueing * renderer to the provider's default visuals. Which is useless if the * provider is a wrapping provider - the wrappee's default visuals are unchanged. * * PENDING JW: think about complete removal. Client code should move over * completely to highlighter/renderer separation anyway. * * */ public void interactiveXRendererCustomColor() { JXTreeTable treeTable = new JXTreeTable(new FileSystemModel()); treeTable.addHighlighter(HighlighterFactory.createSimpleStriping()); DefaultTreeRenderer swingx = new DefaultTreeRenderer(); // in a treetable this has no effect: treetable.applyRenderer // internally resets them to the same colors as tree itself // (configured by the table's highlighters swingx.setBackground(Color.YELLOW); treeTable.setTreeCellRenderer(swingx); JTree tree = new JXTree(treeTable.getTreeTableModel()); DefaultTreeRenderer other = new DefaultTreeRenderer(); other.setBackground(Color.YELLOW); // other.setBackgroundSelectionColor(Color.RED); tree.setCellRenderer(other); JXFrame frame = wrapWithScrollingInFrame(treeTable, tree, "swingx renderers - highlight complete cell"); frame.setVisible(true); } /** * Custom renderer colors of core DefaultTreeCellRenderer not respected. * This is intentional: treeTable's highlighters must rule, so the * renderer colors are used to force the treecellrenderer to use the * correct values. */ public void interactiveCoreRendererCustomColor() { JXTreeTable treeTable = new JXTreeTable(new FileSystemModel()); treeTable.addHighlighter(HighlighterFactory.createSimpleStriping()); DefaultTreeCellRenderer legacy = createBackgroundTreeRenderer(); // in a treetable this has no effect: treetable.applyRenderer // internally resets them to the same colors as tree itself // (configured by the table's highlighters legacy.setBackgroundNonSelectionColor(Color.YELLOW); legacy.setBackgroundSelectionColor(Color.RED); treeTable.setTreeCellRenderer(legacy); JTree tree = new JXTree(treeTable.getTreeTableModel()); DefaultTreeCellRenderer other = createBackgroundTreeRenderer(); other.setBackgroundNonSelectionColor(Color.YELLOW); other.setBackgroundSelectionColor(Color.RED); tree.setCellRenderer(other); JXFrame frame = wrapWithScrollingInFrame(treeTable, tree, "legacy renderers - highlight complete cell"); frame.setVisible(true); } private DefaultTreeCellRenderer createBackgroundTreeRenderer() { DefaultTreeCellRenderer legacy = new DefaultTreeCellRenderer() { @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { Component comp = super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus); if (sel) { comp.setBackground(getBackgroundSelectionColor()); } else { comp.setBackground(getBackgroundNonSelectionColor()); } return comp; } }; return legacy; } /** * Issue #493-swingx: incorrect table events fired. * Issue #592-swingx: (no structureChanged table events) is a special * case of the former. * * Here: add support to prevent a structureChanged even when setting * the root. May be required if the columns are stable and the * model lazily loaded. Quick hack would be to add a clientProperty? * * @throws InvocationTargetException * @throws InterruptedException */ public void testTableEventOnSetRootNoStructureChange() throws InterruptedException, InvocationTargetException { TreeTableModel model = createCustomTreeTableModelFromDefault(); final JXTreeTable table = new JXTreeTable(model); table.setRootVisible(true); table.expandAll(); final TableModelReport report = new TableModelReport(); table.getModel().addTableModelListener(report); ((DefaultTreeTableModel) model).setRoot(new DefaultMutableTreeTableNode("other")); SwingUtilities.invokeAndWait(new Runnable() { public void run() { assertEquals("tableModel must have fired", 1, report.getEventCount()); assertTrue("event type must be dataChanged " + TableModelReport.printEvent(report.getLastEvent()), report.isDataChanged(report.getLastEvent())); } }); } /** * Issue #576-swingx: sluggish scrolling (?). * Here - use default model */ public void interactiveScrollAlternateHighlightDefaultModel() { final JXTable table = new JXTable(0, 6); DefaultMutableTreeTableNode root = new DefaultMutableTreeTableNode("root"); for (int i = 0; i < 5000; i++) { root.insert(new DefaultMutableTreeTableNode(i), i); } final JXTreeTable treeTable = new JXTreeTable(new DefaultTreeTableModel(root)); treeTable.expandAll(); table.setModel(treeTable.getModel()); final Highlighter hl = HighlighterFactory.createAlternateStriping(UIManager.getColor("Panel.background"), Color.WHITE); treeTable.setHighlighters(hl); table.setHighlighters(hl); final JXFrame frame = wrapWithScrollingInFrame(treeTable, table, "sluggish scrolling"); Action toggleHighlighter = new AbstractActionExt("toggle highlighter") { public void actionPerformed(ActionEvent e) { if (treeTable.getHighlighters().length == 0) { treeTable.addHighlighter(hl); table.addHighlighter(hl); } else { treeTable.removeHighlighter(hl); table.removeHighlighter(hl); } } }; Action scroll = new AbstractActionExt("start scroll") { public void actionPerformed(ActionEvent e) { for (int i = 0; i < table.getRowCount(); i++) { table.scrollRowToVisible(i); treeTable.scrollRowToVisible(i); } } }; addAction(frame, toggleHighlighter); addAction(frame, scroll); frame.setVisible(true); } /** * Issue #576-swingx: sluggish scrolling (?) * * Here: use FileSystemModel */ public void interactiveScrollAlternateHighlight() { final JXTable table = new JXTable(0, 6); final JXTreeTable treeTable = new JXTreeTable(new FileSystemModel()); final Highlighter hl = HighlighterFactory.createAlternateStriping(UIManager.getColor("Panel.background"), Color.WHITE); treeTable.setHighlighters(hl); table.setHighlighters(hl); final JXFrame frame = wrapWithScrollingInFrame(treeTable, table, "sluggish scrolling"); Action expand = new AbstractActionExt("start expand") { public void actionPerformed(ActionEvent e) { for (int i = 0; i < 5000; i++) { treeTable.expandRow(i); } table.setModel(treeTable.getModel()); } }; Action toggleHighlighter = new AbstractActionExt("toggle highlighter") { public void actionPerformed(ActionEvent e) { if (treeTable.getHighlighters().length == 0) { treeTable.addHighlighter(hl); table.addHighlighter(hl); } else { treeTable.removeHighlighter(hl); table.removeHighlighter(hl); } } }; Action scroll = new AbstractActionExt("start scroll") { public void actionPerformed(ActionEvent e) { for (int i = 0; i < table.getRowCount(); i++) { table.scrollRowToVisible(i); treeTable.scrollRowToVisible(i); } } }; addAction(frame, expand); addAction(frame, toggleHighlighter); addAction(frame, scroll); frame.setVisible(true); } /** * Issue #493-swingx: JXTreeTable.TreeTableModelAdapter: Inconsistency * firing update. * * Test update events after updating table. * * from tiberiu@dev.java.net * * @throws InvocationTargetException * @throws InterruptedException */ public void testTableEventUpdateOnTreeTableSetValueForRoot() throws InterruptedException, InvocationTargetException { TreeTableModel model = createCustomTreeTableModelFromDefault(); final JXTreeTable table = new JXTreeTable(model); table.setRootVisible(true); table.expandAll(); final int row = 0; // sanity assertEquals("JTree", table.getValueAt(row, 0).toString()); assertTrue("root must be editable", table.getModel().isCellEditable(0, 0)); final TableModelReport report = new TableModelReport(); table.getModel().addTableModelListener(report); // doesn't fire or isn't detectable? // Problem was: model was not-editable. table.setValueAt("games", row, 0); SwingUtilities.invokeAndWait(new Runnable() { public void run() { assertEquals("tableModel must have fired", 1, report.getEventCount()); assertEquals("the event type must be update " + TableModelReport.printEvent(report.getLastEvent()) , 1, report.getUpdateEventCount()); TableModelEvent event = report.getLastUpdateEvent(); assertEquals("the updated row ", row, event.getFirstRow()); } }); } /** * Issue #493-swingx: JXTreeTable.TreeTableModelAdapter: Inconsistency * firing update on a recursive delete on a parent node. * * By recursive delete on a parent node it is understood that first we * remove its children and then the parent node. After each child removed * we are making an update over the parent. During this update the problem * occurs: the index row for the parent is -1 and hence it is made an update * over the row -1 (the header) and as it can be seen the preffered widths * of column header are not respected anymore and are restored to the default * preferences (all equal). * * from tiberiu@dev.java.net */ public void interactiveTreeTableModelAdapterDeleteUpdate() { final DefaultTreeTableModel customTreeTableModel = (DefaultTreeTableModel) createCustomTreeTableModelFromDefault(); final JXTreeTable table = new JXTreeTable(customTreeTableModel); table.setRootVisible(true); table.expandAll(); table.getColumn("A").setPreferredWidth(100); table.getColumn("A").setMinWidth(100); table.getColumn("A").setMaxWidth(100); JXTree xtree = new JXTree(customTreeTableModel); xtree.setRootVisible(true); xtree.expandAll(); final JXFrame frame = wrapWithScrollingInFrame(table, xtree, "JXTreeTable.TreeTableModelAdapter: Inconsistency firing update on recursive delete"); final MutableTreeTableNode deletedNode = (MutableTreeTableNode) table.getPathForRow(6).getLastPathComponent(); MutableTreeTableNode child1 = (MutableTreeTableNode) table.getPathForRow(6+1).getLastPathComponent(); MutableTreeTableNode child2 = (MutableTreeTableNode) table.getPathForRow(6+2).getLastPathComponent(); MutableTreeTableNode child3 = (MutableTreeTableNode) table.getPathForRow(6+3).getLastPathComponent(); MutableTreeTableNode child4 = (MutableTreeTableNode) table.getPathForRow(6+4).getLastPathComponent(); final MutableTreeTableNode[] children = {child1, child2, child3, child4 }; final String[] values = {"v1", "v2", "v3", "v4"}; final ActionListener l = new ActionListener() { int count = 0; public void actionPerformed(ActionEvent e) { if (count > values.length) return; if (count == values.length) { customTreeTableModel.removeNodeFromParent(deletedNode); count++; } else { // one in each run removeChild(customTreeTableModel, deletedNode, children, values); count++; // all in one // for (int i = 0; i < values.length; i++) { // removeChild(customTreeTableModel, deletedNode, children, values); // count++; } } /** * @param customTreeTableModel * @param deletedNode * @param children * @param values */ private void removeChild(final DefaultTreeTableModel customTreeTableModel, final MutableTreeTableNode deletedNode, final MutableTreeTableNode[] children, final String[] values) { customTreeTableModel.removeNodeFromParent(children[count]); customTreeTableModel.setValueAt(values[count], deletedNode, 0); } }; Action changeValue = new AbstractAction("delete node sports recursively") { Timer timer; public void actionPerformed(ActionEvent e) { if (timer == null) { timer = new Timer(10, l); timer.start(); } else { timer.stop(); setEnabled(false); } } }; addAction(frame, changeValue); frame.setVisible(true); } /** * Issue #493-swingx: JXTreeTable.TreeTableModelAdapter: Inconsistency * firing update. Use the second child of root - first is accidentally okay. * * from tiberiu@dev.java.net * * TODO DefaultMutableTreeTableNodes do not allow value changes, so this * test will never work */ public void interactiveTreeTableModelAdapterUpdate() { TreeTableModel customTreeTableModel = createCustomTreeTableModelFromDefault(); final JXTreeTable table = new JXTreeTable(customTreeTableModel); table.setRootVisible(true); table.expandAll(); table.setLargeModel(true); JXTree xtree = new JXTree(customTreeTableModel); xtree.setRootVisible(true); xtree.expandAll(); final JXFrame frame = wrapWithScrollingInFrame(table, xtree, "JXTreeTable.TreeTableModelAdapter: Inconsistency firing update"); Action changeValue = new AbstractAction("change sports to games") { public void actionPerformed(ActionEvent e) { String newValue = "games"; table.getTreeTableModel().setValueAt(newValue, table.getPathForRow(6).getLastPathComponent(), 0); } }; addAction(frame, changeValue); Action changeRoot = new AbstractAction("change root") { public void actionPerformed(ActionEvent e) { DefaultMutableTreeTableNode newRoot = new DefaultMutableTreeTableNode("new Root"); ((DefaultTreeTableModel) table.getTreeTableModel()).setRoot(newRoot); } }; addAction(frame, changeRoot); frame.pack(); frame.setVisible(true); } /** * Issue #493-swingx: JXTreeTable.TreeTableModelAdapter: Inconsistency * firing delete. * * from tiberiu@dev.java.net */ public void interactiveTreeTableModelAdapterDelete() { final TreeTableModel customTreeTableModel = createCustomTreeTableModelFromDefault(); final JXTreeTable table = new JXTreeTable(customTreeTableModel); table.setRootVisible(true); table.expandAll(); JXTree xtree = new JXTree(customTreeTableModel); xtree.setRootVisible(true); xtree.expandAll(); final JXFrame frame = wrapWithScrollingInFrame(table, xtree, "JXTreeTable.TreeTableModelAdapter: Inconsistency firing update"); Action changeValue = new AbstractAction("delete first child of sports") { public void actionPerformed(ActionEvent e) { MutableTreeTableNode firstChild = (MutableTreeTableNode) table.getPathForRow(6 +1).getLastPathComponent(); ((DefaultTreeTableModel) customTreeTableModel).removeNodeFromParent(firstChild); } }; addAction(frame, changeValue); frame.setVisible(true); } /** * Issue #493-swingx: JXTreeTable.TreeTableModelAdapter: Inconsistency * firing delete. * * from tiberiu@dev.java.net */ public void interactiveTreeTableModelAdapterMutateSelected() { final TreeTableModel customTreeTableModel = createCustomTreeTableModelFromDefault(); final JXTreeTable table = new JXTreeTable(customTreeTableModel); table.setRootVisible(true); table.expandAll(); JXTree xtree = new JXTree(customTreeTableModel); xtree.setRootVisible(true); xtree.expandAll(); final JXFrame frame = wrapWithScrollingInFrame(table, xtree, "JXTreeTable.TreeTableModelAdapter: Inconsistency firing delete expanded folder"); Action changeValue = new AbstractAction("delete selected node") { public void actionPerformed(ActionEvent e) { int row = table.getSelectedRow(); if (row < 0) return; MutableTreeTableNode firstChild = (MutableTreeTableNode) table.getPathForRow(row).getLastPathComponent(); ((DefaultTreeTableModel) customTreeTableModel).removeNodeFromParent(firstChild); } }; addAction(frame, changeValue); Action changeValue1 = new AbstractAction("insert as first child of selected node") { public void actionPerformed(ActionEvent e) { int row = table.getSelectedRow(); if (row < 0) return; MutableTreeTableNode firstChild = (MutableTreeTableNode) table.getPathForRow(row).getLastPathComponent(); MutableTreeTableNode newChild = new DefaultMutableTreeTableNode("inserted"); ((DefaultTreeTableModel) customTreeTableModel) .insertNodeInto(newChild, firstChild, 0); } }; addAction(frame, changeValue1); frame.pack(); frame.setVisible(true); } /** * Issue #493-swingx: JXTreeTable.TreeTableModelAdapter: Inconsistency * firing delete. * * from tiberiu@dev.java.net */ public void interactiveTreeTableModelAdapterMutateSelectedDiscontinous() { final TreeTableModel customTreeTableModel = createCustomTreeTableModelFromDefault(); final JXTreeTable table = new JXTreeTable(customTreeTableModel); table.setRootVisible(true); table.expandAll(); JXTree xtree = new JXTree(customTreeTableModel); xtree.setRootVisible(true); xtree.expandAll(); final JXFrame frame = wrapWithScrollingInFrame(table, xtree, "JXTreeTable.TreeTableModelAdapter: Inconsistency firing delete expanded folder"); Action changeValue = new AbstractAction("delete selected node + sibling") { public void actionPerformed(ActionEvent e) { int row = table.getSelectedRow(); if (row < 0) return; MutableTreeTableNode firstChild = (MutableTreeTableNode) table.getPathForRow(row).getLastPathComponent(); MutableTreeTableNode parent = (MutableTreeTableNode) firstChild.getParent(); MutableTreeTableNode secondNextSibling = null; int firstIndex = parent.getIndex(firstChild); if (firstIndex + 2 < parent.getChildCount()) { secondNextSibling = (MutableTreeTableNode) parent.getChildAt(firstIndex + 2); } if (secondNextSibling != null) { ((DefaultTreeTableModel) customTreeTableModel).removeNodeFromParent(secondNextSibling); } ((DefaultTreeTableModel) customTreeTableModel).removeNodeFromParent(firstChild); } }; addAction(frame, changeValue); Action changeValue1 = new AbstractAction("insert as first child of selected node") { public void actionPerformed(ActionEvent e) { int row = table.getSelectedRow(); if (row < 0) return; MutableTreeTableNode firstChild = (MutableTreeTableNode) table.getPathForRow(row).getLastPathComponent(); MutableTreeTableNode newChild = new DefaultMutableTreeTableNode("inserted"); ((DefaultTreeTableModel) customTreeTableModel) .insertNodeInto(newChild, firstChild, 0); } }; addAction(frame, changeValue1); frame.pack(); frame.setVisible(true); } /** * Creates and returns a custom model from JXTree default model. The model * is of type DefaultTreeModel, allowing for easy insert/remove. * * @return */ private TreeTableModel createCustomTreeTableModelFromDefault() { JXTree tree = new JXTree(); DefaultTreeModel treeModel = (DefaultTreeModel) tree.getModel(); TreeTableModel customTreeTableModel = TreeTableUtils .convertDefaultTreeModel(treeModel); return customTreeTableModel; } /** * A TreeTableModel inheriting from DefaultTreeModel (to ease * insert/delete). */ public static class CustomTreeTableModel extends DefaultTreeTableModel { /** * @param root */ public CustomTreeTableModel(TreeTableNode root) { super(root); } @Override public int getColumnCount() { return 1; } @Override public String getColumnName(int column) { return "User Object"; } @Override public Object getValueAt(Object node, int column) { return ((DefaultMutableTreeNode) node).getUserObject(); } @Override public boolean isCellEditable(Object node, int column) { return true; } @Override public void setValueAt(Object value, Object node, int column) { ((MutableTreeTableNode) node).setUserObject(value); modelSupport.firePathChanged(new TreePath(getPathToRoot((TreeTableNode) node))); } } /** * Issue #??-swingx: hyperlink in JXTreeTable hierarchical column not * active. * */ public void interactiveTreeTableLinkRendererSimpleText() { AbstractHyperlinkAction<Object> simpleAction = new AbstractHyperlinkAction<Object>(null) { public void actionPerformed(ActionEvent e) { LOG.info("hit: " + getTarget()); } }; JXTreeTable tree = new JXTreeTable(new FileSystemModel()); HyperlinkProvider provider = new HyperlinkProvider(simpleAction); tree.getColumn(2).setCellRenderer(new DefaultTableRenderer(provider)); tree.setTreeCellRenderer(new DefaultTreeRenderer( //provider)); new WrappingProvider(provider))); // tree.setCellRenderer(new LinkRenderer(simpleAction)); tree.setHighlighters(HighlighterFactory.createSimpleStriping()); JFrame frame = wrapWithScrollingInFrame(tree, "table and simple links"); frame.setVisible(true); } /** * Issue ??-swingx: hyperlink/rollover in hierarchical column. * */ public void testTreeRendererInitialRollover() { JXTreeTable tree = new JXTreeTable(new FileSystemModel()); assertEquals(tree.isRolloverEnabled(), ((JXTree) tree.getCellRenderer(0, 0)).isRolloverEnabled()); } /** * Issue ??-swingx: hyperlink/rollover in hierarchical column. * */ public void testTreeRendererModifiedRollover() { JXTreeTable tree = new JXTreeTable(new FileSystemModel()); tree.setRolloverEnabled(!tree.isRolloverEnabled()); assertEquals(tree.isRolloverEnabled(), ((JXTree) tree.getCellRenderer(0, 0)).isRolloverEnabled()); } /** * example how to use a custom component as * renderer in tree column of TreeTable. * */ public void interactiveTreeTableCustomRenderer() { JXTreeTable tree = new JXTreeTable(new FileSystemModel()); StringValue sv = new StringValue( ){ public String getString(Object value) { return "..." + StringValues.TO_STRING.getString(value); } }; ComponentProvider<?> provider = new CheckBoxProvider(sv); // /** // * custom tooltip: show row. Note: the context is that // * of the rendering tree. No way to get at table state? // */ // @Override // protected void configureState(CellContext context) { // super.configureState(context); // rendererComponent.setToolTipText("Row: " + context.getRow()); tree.setTreeCellRenderer(new DefaultTreeRenderer(provider)); tree.setHighlighters(HighlighterFactory.createSimpleStriping()); JFrame frame = wrapWithScrollingInFrame(tree, "treetable and custom renderer"); frame.setVisible(true); } /** * Quick example to use a TextArea in the hierarchical column * of a treeTable. Not really working .. the wrap is not reliable?. * */ public void interactiveTextAreaTreeTable() { TreeTableModel model = createTreeTableModelWithLongNode(); JXTreeTable treeTable = new JXTreeTable(model); treeTable.setVisibleRowCount(5); treeTable.setRowHeight(50); treeTable.getColumnExt(0).setPreferredWidth(200); TreeCellRenderer renderer = new DefaultTreeRenderer( new WrappingProvider(new TextAreaProvider())); treeTable.setTreeCellRenderer(renderer); showWithScrollingInFrame(treeTable, "TreeTable with text wrapping"); } /** * @return */ private TreeTableModel createTreeTableModelWithLongNode() { MutableTreeTableNode root = createLongNode("some really, maybe really really long text - " + "wrappit .... where needed "); root.insert(createLongNode("another really, maybe really really long text - " + "with nothing but junk. wrappit .... where needed"), 0); root.insert(createLongNode("another really, maybe really really long text - " + "with nothing but junk. wrappit .... where needed"), 0); MutableTreeTableNode node = createLongNode("some really, maybe really really long text - " + "wrappit .... where needed "); node.insert(createLongNode("another really, maybe really really long text - " + "with nothing but junk. wrappit .... where needed"), 0); root.insert(node, 0); root.insert(createLongNode("another really, maybe really really long text - " + "with nothing but junk. wrappit .... where needed"), 0); Vector<String> ids = new Vector<String>(); ids.add("long text"); ids.add("dummy"); return new DefaultTreeTableModel(root, ids); } /** * @param string * @return */ private MutableTreeTableNode createLongNode(final String string) { AbstractMutableTreeTableNode node = new AbstractMutableTreeTableNode() { Object rnd = Math.random(); public int getColumnCount() { return 2; } public Object getValueAt(int column) { if (column == 0) { return string; } return rnd; } }; node.setUserObject(string); return node; } /** * Experiments to try and understand clipping issues: occasionally, the text * in the tree column is clipped even if there is enough space available. * * To visualize the rendering component's size we use a WrappingIconProvider * which sets a red border. * * Calling packxx might pose a problem: for non-large models the node size * is cached. In this case, packing before replacing the renderer will lead * to incorrect sizes which are hard to invalidate (no way except faking a * structural tree event? temporaryly set large model and back, plus repaint * works). * */ public void interactiveTreeTableClipIssueWrappingProvider() { final JXTreeTable treeTable = new JXTreeTable(createActionTreeModel()); treeTable.setHorizontalScrollEnabled(true); treeTable.setColumnControlVisible(true); // BEWARE: do not pack before setting the renderer treeTable.packColumn(0, -1); StringValue format = new StringValue() { public String getString(Object value) { if (value instanceof Action) { return ((Action) value).getValue(Action.NAME) + "xx"; } return StringValues.TO_STRING.getString(value); } }; ComponentProvider<?> tableProvider = new LabelProvider(format); WrappingProvider wrappingProvider = new WrappingProvider(tableProvider) { Border redBorder = BorderFactory.createLineBorder(Color.RED); @Override public WrappingIconPanel getRendererComponent(CellContext context) { super.getRendererComponent(context); rendererComponent.setBorder(redBorder); return rendererComponent; } }; DefaultTreeRenderer treeCellRenderer = new DefaultTreeRenderer( wrappingProvider); treeTable.setTreeCellRenderer(treeCellRenderer); treeTable.setHighlighters(HighlighterFactory.createSimpleStriping()); // at this point a pack is okay, caching will get the correct values // treeTable.packColumn(0, -1); final JXTree tree = new JXTree(treeTable.getTreeTableModel()); tree.setCellRenderer(treeCellRenderer); tree.setScrollsOnExpand(false); JXFrame frame = wrapWithScrollingInFrame(treeTable, tree, "treetable and tree with wrapping provider"); // revalidate doesn't help Action revalidate = new AbstractActionExt("revalidate") { public void actionPerformed(ActionEvent e) { treeTable.revalidate(); tree.revalidate(); treeTable.repaint(); } }; // hack around incorrect cached node sizes Action large = new AbstractActionExt("large-circle") { public void actionPerformed(ActionEvent e) { treeTable.setLargeModel(true); treeTable.setLargeModel(false); treeTable.repaint(); } }; addAction(frame, revalidate); addAction(frame, large); show(frame); } /** * Experiments to try and understand clipping issues: occasionally, the text * in the tree column is clipped even if there is enough space available. * * Here we don't change any renderers. */ public void interactiveTreeTableClipIssueDefaultRenderer() { final JXTreeTable treeTable = new JXTreeTable(createActionTreeModel()); treeTable.setHorizontalScrollEnabled(true); treeTable.setRootVisible(true); treeTable.collapseAll(); treeTable.packColumn(0, -1); final JTree tree = new JTree(treeTable.getTreeTableModel()); tree.collapseRow(0); JXFrame frame = wrapWithScrollingInFrame(treeTable, tree, "JXTreeTable vs. JTree: default renderer"); Action revalidate = new AbstractActionExt("revalidate") { public void actionPerformed(ActionEvent e) { treeTable.revalidate(); tree.revalidate(); } }; addAction(frame, revalidate); frame.setVisible(true); } /** * Experiments to try and understand clipping issues: occasionally, the text * in the tree column is clipped even if there is enough space available. * Here we set a custom (unchanged default) treeCellRenderer which * removes ellipses altogether. * */ public void interactiveTreeTableClipIssueCustomDefaultRenderer() { TreeCellRenderer renderer = new DefaultTreeCellRenderer() { @Override public Component getTreeCellRendererComponent(JTree tree, Object value, boolean sel, boolean expanded, boolean leaf, int row, boolean hasFocus) { return super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus); } }; final JXTreeTable treeTable = new JXTreeTable(createActionTreeModel()); treeTable.setTreeCellRenderer(renderer); treeTable.setHorizontalScrollEnabled(true); treeTable.setRootVisible(true); treeTable.collapseAll(); treeTable.packColumn(0, -1); final JTree tree = new JTree(treeTable.getTreeTableModel()); tree.setCellRenderer(renderer); tree.collapseRow(0); JXFrame frame = wrapWithScrollingInFrame(treeTable, tree, "JXTreeTable vs. JTree: custom default renderer"); Action revalidate = new AbstractActionExt("revalidate") { public void actionPerformed(ActionEvent e) { treeTable.revalidate(); tree.revalidate(); } }; addAction(frame, revalidate); frame.setVisible(true); } /** * Dirty example how to configure a custom renderer to use * treeTableModel.getValueAt(...) for showing. * */ public void interactiveTreeTableGetValueRenderer() { JXTreeTable tree = new JXTreeTable(new ComponentTreeTableModel(new JXFrame())); ComponentProvider<?> provider = new CheckBoxProvider(StringValues.TO_STRING) { @Override protected String getValueAsString(CellContext context) { // this is dirty because the design idea was to keep the renderer // unaware of the context type TreeTableModel model = (TreeTableModel) ((JXTree) context.getComponent()).getModel(); // beware: currently works only if the node is not a DefaultMutableTreeNode // otherwise the WrappingProvider tries to be smart and replaces the node // by the userObject before passing on to the wrappee! Object nodeValue = model.getValueAt(context.getValue(), 0); return formatter.getString(nodeValue); } }; tree.setTreeCellRenderer(new DefaultTreeRenderer(provider)); tree.expandAll(); tree.setHighlighters(HighlighterFactory.createSimpleStriping()); JFrame frame = wrapWithScrollingInFrame(tree, "treeTable and getValueAt renderer"); frame.setVisible(true); } /** * Issue #399-swingx: editing terminated by selecting editing row. * */ public void testSelectionKeepsEditingWithExpandsTrue() { JXTreeTable treeTable = new JXTreeTable(new FileSystemModel()) { @Override public boolean isCellEditable(int row, int column) { return true; } }; // sanity: default value of expandsSelectedPath assertTrue(treeTable.getExpandsSelectedPaths()); boolean canEdit = treeTable.editCellAt(1, 2); // sanity: editing started assertTrue(canEdit); // sanity: nothing selected assertTrue(treeTable.getSelectionModel().isSelectionEmpty()); int editingRow = treeTable.getEditingRow(); treeTable.setRowSelectionInterval(editingRow, editingRow); assertEquals("after selection treeTable editing state must be unchanged", canEdit, treeTable.isEditing()); } /** * Issue #212-jdnc: reuse editor, install only once. * */ public void testReuseEditor() { //TODO rework this test, since we no longer use TreeTableModel.class // JXTreeTable treeTable = new JXTreeTable(treeTableModel); // CellEditor editor = treeTable.getDefaultEditor(TreeTableModel.class); // assertTrue(editor instanceof TreeTableCellEditor); // treeTable.setTreeTableModel(simpleTreeTableModel); // assertSame("hierarchical editor must be unchanged", editor, // treeTable.getDefaultEditor(TreeTableModel.class)); fail("#212-jdnc - must be revisited after treeTableModel overhaul"); } /** * sanity: toggling select/unselect via mouse the lead is * always painted, doing unselect via model (clear/remove path) * seems to clear the lead? * */ public void testBasicTreeLeadSelection() { JXTree tree = new JXTree(); TreePath path = tree.getPathForRow(0); tree.setSelectionPath(path); assertEquals(0, tree.getSelectionModel().getLeadSelectionRow()); assertEquals(path, tree.getLeadSelectionPath()); tree.removeSelectionPath(path); assertNotNull(tree.getLeadSelectionPath()); assertEquals(0, tree.getSelectionModel().getLeadSelectionRow()); } /** * Issue #341-swingx: missing synch of lead. * test lead after setting selection via table. * * PENDING: this passes locally, fails on server */ public void testLeadSelectionFromTable() { JXTreeTable treeTable = prepareTreeTable(false); assertEquals(-1, treeTable.getSelectionModel().getLeadSelectionIndex()); assertEquals(-1, treeTable.getTreeSelectionModel().getLeadSelectionRow()); treeTable.setRowSelectionInterval(0, 0); assertEquals(treeTable.getSelectionModel().getLeadSelectionIndex(), treeTable.getTreeSelectionModel().getLeadSelectionRow()); fail("lead selection synch passes locally, fails on server"); } /** * Issue #341-swingx: missing synch of lead. * test lead after setting selection via treeSelection. * PENDING: this passes locally, fails on server * */ public void testLeadSelectionFromTree() { JXTreeTable treeTable = prepareTreeTable(false); assertEquals(-1, treeTable.getSelectionModel().getLeadSelectionIndex()); assertEquals(-1, treeTable.getTreeSelectionModel().getLeadSelectionRow()); treeTable.getTreeSelectionModel().setSelectionPath(treeTable.getPathForRow(0)); assertEquals(treeTable.getSelectionModel().getLeadSelectionIndex(), treeTable.getTreeSelectionModel().getLeadSelectionRow()); assertEquals(0, treeTable.getTreeSelectionModel().getLeadSelectionRow()); fail("lead selection synch passes locally, fails on server"); } /** * Issue #341-swingx: missing synch of lead. * test lead after remove selection via tree. * */ public void testLeadAfterRemoveSelectionFromTree() { JXTreeTable treeTable = prepareTreeTable(true); treeTable.getTreeSelectionModel().removeSelectionPath( treeTable.getTreeSelectionModel().getLeadSelectionPath()); assertEquals(treeTable.getSelectionModel().getLeadSelectionIndex(), treeTable.getTreeSelectionModel().getLeadSelectionRow()); } /** * Issue #341-swingx: missing synch of lead. * test lead after clear selection via table. * */ public void testLeadAfterClearSelectionFromTable() { JXTreeTable treeTable = prepareTreeTable(true); treeTable.clearSelection(); assertEquals(treeTable.getSelectionModel().getLeadSelectionIndex(), treeTable.getTreeSelectionModel().getLeadSelectionRow()); } /** * Issue #341-swingx: missing synch of lead. * test lead after clear selection via table. * */ public void testLeadAfterClearSelectionFromTree() { JXTreeTable treeTable = prepareTreeTable(true); treeTable.getTreeSelectionModel().clearSelection(); assertEquals(treeTable.getSelectionModel().getLeadSelectionIndex(), treeTable.getTreeSelectionModel().getLeadSelectionRow()); } /** * creates and configures a treetable for usage in selection tests. * * @param selectFirstRow boolean to indicate if the first row should * be selected. * @return */ protected JXTreeTable prepareTreeTable(boolean selectFirstRow) { JXTreeTable treeTable = new JXTreeTable(new ComponentTreeTableModel(new JXFrame())); treeTable.setRootVisible(true); // sanity: assert that we have at least two rows to change selection assertTrue(treeTable.getRowCount() > 1); if (selectFirstRow) { treeTable.setRowSelectionInterval(0, 0); } return treeTable; } public void testDummy() { } /** * @return */ private TreeTableModel createActionTreeModel() { JXTable table = new JXTable(10, 10); table.setHorizontalScrollEnabled(true); return new ActionMapTreeTableModel(table); } }
package org.kevoree.modeling.addons.template; import org.junit.Test; import org.kevoree.modeling.KActionType; import org.kevoree.modeling.KCallback; import org.kevoree.modeling.KModel; import org.kevoree.modeling.KObject; import org.kevoree.modeling.drivers.websocket.WebSocketGateway; import org.kevoree.modeling.meta.*; import org.kevoree.modeling.meta.impl.MetaModel; public class TemplateTest { //@Test public static void main(String[] args) { KMetaModel metaModel = new MetaModel("IoTModel"); KMetaClass sensorClass = metaModel.addMetaClass("Sensor"); KMetaAttribute sensorValueAtt = sensorClass.addAttribute("value", KPrimitiveTypes.LONG); KMetaReference sensorsRef = sensorClass.addReference("sensors", sensorClass, null, true); KModel model = metaModel.model(); model.connect(new KCallback() { @Override public void on(Object o) { KObject sensor = model.create(sensorClass, 0, 0); sensor.set(sensorValueAtt, "42"); KObject sensor2 = model.create(sensorClass, 0, 0); sensor2.set(sensorValueAtt, "42_2"); KObject sensor3 = model.create(sensorClass, 0, 0); sensor3.set(sensorValueAtt, "42_3"); sensor.mutate(KActionType.ADD, sensorsRef, sensor2); sensor.mutate(KActionType.ADD, sensorsRef, sensor3); model.save(new KCallback() { @Override public void on(Object o) { } }); } }); WebSocketGateway gateway = WebSocketGateway.exposeModelAndResources(model, 8080, TemplateTest.class.getClassLoader()); gateway.start(); try { Thread.sleep(100000); } catch (InterruptedException e) { e.printStackTrace(); } } }
package edu.northwestern.bioinformatics.studycalendar.security.plugin; import edu.northwestern.bioinformatics.studycalendar.StudyCalendarValidationException; import gov.nih.nci.cabig.ctms.tools.configuration.Configuration; import gov.nih.nci.cabig.ctms.tools.configuration.ConfigurationProperties; import org.acegisecurity.Authentication; import org.acegisecurity.AuthenticationManager; import org.acegisecurity.ui.AuthenticationEntryPoint; import javax.servlet.Filter; /** * This interface defines a facade for pluggable authentication modules. * It is expected that most implementations will delegate to a library * implementation (e.g., one of the many included in Acegi Security). * <p> * Implementors must have a public default constructor. * Most initialization should happen in the {@link #initialize} method. * </p> * * @author Rhett Sutphin */ public interface AuthenticationSystem { String DEFAULT_TARGET_PATH = "/"; String PSC_URL_CONFIGURATION_PROPERTY_NAME = "psc.url"; /** * List the configuration properties this plugin would like to read. * These properties will probably be statically defined in implementing * classes. * * @see gov.nih.nci.cabig.ctms.tools.configuration.Configuration * @see gov.nih.nci.cabig.ctms.tools.configuration.DefaultConfigurationProperties * @see gov.nih.nci.cabig.ctms.tools.configuration.DefaultConfigurationProperties#empty */ ConfigurationProperties configurationProperties(); /** * The short name for this authentication scheme. */ String name(); /** * A phrase describing the behavior of this scheme. * E.g., "delegates authentication decisions to an enterprise-wide CAS server". */ String behaviorDescription(); /** * Validate that the provided configuration is sufficent to initialize this system. Should * not have any side effects. * @throws StudyCalendarValidationException if any of the configuration properties * have invalid values */ void validate(Configuration configuration) throws StudyCalendarValidationException; /** * Initialize any internal objects needed to perform authentication. * This method will be called before this object is used for any other purpose, except for * {@link #configurationProperties}, {@link #name}, and {@link #behaviorDescription}. * <p> * A simple authenticator might directly create any required objects in this method; * a more complex one might prefer to load an * {@link org.springframework.context.ApplicationContext} from the classpath. * <p> * It is guaranteed that this method will only be called once per instance. * * @param configuration the object from which the configuration properties * specified with {@link #configurationProperties()} may be read * @throws AuthenticationSystemInitializationFailure if initialization cannot complete for * an unexpected reason * @see org.springframework.context.support.ClassPathXmlApplicationContext */ void initialize(Configuration configuration) throws AuthenticationSystemInitializationFailure; /** * Acegi {@link AuthenticationManager} for this system. * <p> * This method may not return <code>null</code> after {@link #initialize} has been called. * <p> * On successful authentication, the {@link org.acegisecurity.Authentication#getPrincipal() principal} * in the {@link Authentication} token returned by this authentication manager must be a value * returned by the {@link org.acegisecurity.userdetails.UserDetailsService} available as * an OSGi service in the execution environment. In general that means you need to use * that service instance in your Acegi configuration whereever <tt>UserDetailsService</tt> * is called for. * * @see AuthenticationSystemTools#createProviderManager * @see edu.northwestern.bioinformatics.studycalendar.security.plugin.AbstractAuthenticationSystem#getUserDetailsService() */ AuthenticationManager authenticationManager(); * that matches <code>/auth/*</code>. Its {@link Filter#init} method will * not be called. * <p> * If you need more than one filter, consider {@link edu.northwestern.bioinformatics.studycalendar.tools.MultipleFilterFilter} or Acegi's * {@link org.acegisecurity.util.FilterChainProxy}. * <p> * If you don't need a filter, return <code>null</code>. * <p> * Note that this filter need not implement the entire authentication process * from top to bottom -- just the parts that are particular to this system. */ Filter filter(); /** * Acegi entry point for this system. * <p> * This method may not return <code>null</code> after {@link #initialize} has been called. */ AuthenticationEntryPoint entryPoint(); /** * Returns a filter which handles <code>/auth/logout</code> and performs whatever * actions are required to log out in this system. At a minimum, this will include * the behavior implemented in {@link org.acegisecurity.ui.logout.SecurityContextLogoutHandler}. * <p> * If this method returns null, PSC will use a sensible default. */ Filter logoutFilter(); /** * Create an unauthenticated Acegi {@link Authentication} token for the given username * and password. This token should be authenticable by the {@link AuthenticationManager} * returned by {@link #authenticationManager}. * <p> * If this implementation doesn't support username and password authentication, this method * should return null. * * @see org.acegisecurity.providers.UsernamePasswordAuthenticationToken */ Authentication createUsernamePasswordAuthenticationRequest(String username, String password); /** * Create an unauthenticated Acegi {@link Authentication} from the given token which can be * serviced by the configured {@link AuthenticationManager}. * This {@link Authentication} will be used to verify tokens passed to the RESTful API * using the <code>psc_token</code> authentication scheme. * <p> * If this authentication system does not support token-based authentication, this method * should return null. */ Authentication createTokenAuthenticationRequest(String token); /** * Does this authentication system use the passwords that are stored in PSC? If not, * the system administrators will not be prompted to set them. */ boolean usesLocalPasswords(); /** * Does this authentication system use PSC's internal login screen? If not, attempts to * access it will redirect to the root to allow the auth system's filters to process them. * @see UsernameAndPasswordAuthenticationSystem */ boolean usesLocalLoginScreen(); interface ServiceKeys { String NAME = "name"; String BEHAVIOR_DESCRIPTION = "behaviorDescription"; String CONFIGURATION_PROPERTIES = "configurationProperties"; } }
package gov.nih.nci.cagrid.introduce.codegen.serializers; import gov.nih.nci.cagrid.common.Utils; import gov.nih.nci.cagrid.introduce.beans.namespace.NamespaceType; import gov.nih.nci.cagrid.introduce.beans.namespace.SchemaElementType; import gov.nih.nci.cagrid.introduce.beans.service.ServiceType; import gov.nih.nci.cagrid.introduce.codegen.common.SyncTool; import gov.nih.nci.cagrid.introduce.codegen.common.SynchronizationException; import gov.nih.nci.cagrid.introduce.common.CommonTools; import gov.nih.nci.cagrid.introduce.info.ServiceInformation; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.io.StringWriter; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import javax.xml.namespace.QName; import org.apache.axis.deployment.wsdd.WSDDTypeMapping; import org.apache.axis.encoding.SerializationContext; import org.projectmobius.common.MobiusException; import org.projectmobius.common.XMLUtilities; /** * Reads client-config.wsdd and server-config.wsdd, and adds any typemappings * that are required. * * &lt;typeMapping qname=&quot;(from Namespace namespace, and SchemaElement * type)&quot; languageSpecificType=&quot;java:(from Namespace * packageName+.+SchemaElement className)&quot; serializer=&quot;(from * SchemaElement serializer)&quot; deserializer=&quot;(from SchemaElement * deserializer)&quot; encodingStyle=&quot;&quot;/&gt; * * editors will look for: &lt;!-- START INTRODUCE TYPEMAPPINGS --&gt; * * if it exists, it dump the type mappings from its start, replacing evertying * in the file until finding: &lt;!-- END INTRODUCE TYPEMAPPINGS --&gt; * * if the tag isn't found, the tags (and type mappings) will be added to the end * of the file (in appropriate location for server and client) * * * @author oster */ public class SyncSerialization extends SyncTool { public static final String WSDD_END_TAG = "</deployment>"; public static final String MAPPING_HEADER = "<!-- START INTRODUCE TYPEMAPPINGS -->"; public static final String MAPPING_FOOTER = "<!-- END INTRODUCE TYPEMAPPINGS -->"; public SyncSerialization(File baseDirectory, ServiceInformation info) { super(baseDirectory, info); } /** * @throws SynchronizationException * if unable to locate and write to client-config.wsdd and * server-config.wsdd */ public void sync() throws SynchronizationException { File clientWSDD; File serverWSDD; List mappingList = buildTypeMappings(getServiceInformation().getNamespaces().getNamespace()); String replacement = ""; if (mappingList.size() > 0) { StringBuffer mappingReplacement = new StringBuffer(); Iterator iter = mappingList.iterator(); while (iter.hasNext()) { WSDDTypeMapping mapping = (WSDDTypeMapping) iter.next(); mappingReplacement.append(mappingToString(mapping) + "\n"); } replacement = mappingReplacement.toString(); } serverWSDD = new File(getBaseDirectory() + File.separator + "server-config.wsdd"); if (!(serverWSDD.exists() && serverWSDD.canRead() && serverWSDD.canWrite())) { throw new SynchronizationException("Unable to locate or write to service wsdd files: " + serverWSDD); } editFile(serverWSDD, replacement); if (getServiceInformation().getServices() != null && getServiceInformation().getServices().getService() != null) { for (int i = 0; i < getServiceInformation().getServices().getService().length; i++) { ServiceType service = getServiceInformation().getServices().getService(i); clientWSDD = new File(getBaseDirectory().getAbsolutePath() + File.separator + "src" + File.separator + CommonTools.getPackageDir(service) + File.separator + "client" + File.separator + "client-config.wsdd"); if (!(clientWSDD.exists() && clientWSDD.canRead() && clientWSDD.canWrite())) { throw new SynchronizationException("Unable to locate or write to client wsdd files: " + clientWSDD); } editFile(clientWSDD, replacement); } } } public static void editFile(File wsddFile, String replacement) throws SynchronizationException { String contents = null; try { contents = XMLUtilities.fileToString(wsddFile); } catch (MobiusException e) { throw new SynchronizationException("Unable to load file [" + wsddFile + "] contents:" + e.getMessage(), e); } // find where to replace, by looking for header int startInd = contents.indexOf(MAPPING_HEADER); int endInd = -1; if (startInd < 0) { // header isnt found, so write at end of file (don't even look for // footer) startInd = contents.indexOf(WSDD_END_TAG); endInd = startInd; } else { endInd = contents.indexOf(MAPPING_FOOTER); if (endInd < startInd && endInd > 0) { throw new SynchronizationException("Malformed wsdd file:" + wsddFile); } else if (endInd < 0) { // footer wasnt found, so write directly after end of start endInd = startInd + MAPPING_HEADER.length(); } else { endInd += MAPPING_FOOTER.length(); } } if (startInd < 0 || endInd < 0) { throw new SynchronizationException("Unable to parse file:" + wsddFile); } String newConents = ""; if (Utils.clean(replacement) == null) { // clear out anything that was there newConents = contents.substring(0, startInd) + contents.substring(endInd); } else { // replace what was there with the new replacement newConents = contents.substring(0, startInd) + MAPPING_HEADER + "\n" + replacement + "\n" + MAPPING_FOOTER + contents.substring(endInd); } FileWriter fw; try { fw = new FileWriter(wsddFile); fw.write(newConents); fw.close(); } catch (IOException e) { throw new SynchronizationException("Problem rewriting file:" + e.getMessage(), e); } } public static List buildTypeMappings(NamespaceType[] namespaces) throws SynchronizationException { List mappings = new ArrayList(); if (namespaces != null) { for (int i = 0; i < namespaces.length; i++) { NamespaceType ns = namespaces[i]; SchemaElementType[] schemaElements = ns.getSchemaElement(); if (schemaElements == null) { continue; } for (int j = 0; j < schemaElements.length; j++) { SchemaElementType typeDesc = schemaElements[j]; if (typeContainsAllAttributes(typeDesc)) { WSDDTypeMapping mapping = new WSDDTypeMapping(); mapping.setDeserializer(typeDesc.getDeserializer()); mapping.setSerializer(typeDesc.getSerializer()); mapping.setEncodingStyle(""); mapping.setLanguageSpecificType(ns.getPackageName() + "." + typeDesc.getClassName()); mapping.setQName(new QName(ns.getNamespace(), typeDesc.getType())); mappings.add(mapping); } } } } return mappings; } public static String mappingToString(WSDDTypeMapping mapping) throws SynchronizationException { StringWriter writer = new StringWriter(); SerializationContext context = new SerializationContext(writer, null); context.setPretty(true); context.setSendDecl(false); try { mapping.writeToContext(context); writer.close(); } catch (Exception e) { throw new SynchronizationException("Error writting type mappings out:" + e.getMessage(), e); } return writer.getBuffer().toString(); } public static boolean typeContainsAllAttributes(SchemaElementType type) throws SynchronizationException { String ser = Utils.clean(type.getSerializer()); String deser = Utils.clean(type.getDeserializer()); if (ser != null && deser != null) { return true; } else if (ser != null || deser != null) { throw new SynchronizationException("Invalid SchemaElement[" + type.getType() + "]! Must specify either ALL of serializer[" + ser + "], deserializer[" + deser + "], or NONE of them."); } return false; } }
package org.hisp.dhis.analytics.security; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hisp.dhis.analytics.AnalyticsSecurityManager; import org.hisp.dhis.analytics.DataQueryParams; import org.hisp.dhis.analytics.event.EventQueryParams; import org.hisp.dhis.common.*; import org.hisp.dhis.dataapproval.DataApproval; import org.hisp.dhis.dataapproval.DataApprovalLevel; import org.hisp.dhis.dataapproval.DataApprovalLevelService; import org.hisp.dhis.organisationunit.OrganisationUnit; import org.hisp.dhis.program.Program; import org.hisp.dhis.security.acl.AclService; import org.hisp.dhis.setting.SystemSettingManager; import org.hisp.dhis.user.CurrentUserService; import org.hisp.dhis.user.User; import org.springframework.beans.factory.annotation.Autowired; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; /** * @author Lars Helge Overland */ public class DefaultAnalyticsSecurityManager implements AnalyticsSecurityManager { private static final Log log = LogFactory.getLog( DefaultAnalyticsSecurityManager.class ); private static final String AUTH_VIEW_EVENT_ANALYTICS = "F_VIEW_EVENT_ANALYTICS"; @Autowired private DataApprovalLevelService approvalLevelService; @Autowired private SystemSettingManager systemSettingManager; @Autowired private DimensionService dimensionService; @Autowired private AclService aclService; @Autowired private CurrentUserService currentUserService; // AnalyticsSecurityManager implementation @Override public void decideAccess( DataQueryParams params ) { User user = currentUserService.getCurrentUser(); decideAccessDataViewOrgUnits( params, user ); decideAccessPrograms( params, user ); } private void decideAccessDataViewOrgUnits( DataQueryParams params, User user ) throws IllegalQueryException { List<DimensionalItemObject> queryOrgUnits = params.getDimensionOrFilterItems( DimensionalObject.ORGUNIT_DIM_ID ); if ( queryOrgUnits.isEmpty() || user == null || !user.hasDataViewOrganisationUnit() ) { return; // Allow if no } Set<OrganisationUnit> viewOrgUnits = user.getDataViewOrganisationUnits(); for ( DimensionalItemObject object : queryOrgUnits ) { OrganisationUnit queryOrgUnit = (OrganisationUnit) object; boolean notDescendant = !queryOrgUnit.isDescendant( viewOrgUnits ); throwExWhenTrue( notDescendant, String.format( "User: %s is not allowed to view org unit: %s", user.getUsername(), queryOrgUnit.getUid() ) ); } } private void decideAccessPrograms( DataQueryParams params, User user ) throws IllegalQueryException { Set<Program> programs = params.getAllProgramsInAttributesAndDataElements(); if ( params.hasProgram() ) { programs.add( params.getProgram() ); } for ( Program program : programs ) { boolean canNotRead = !aclService.canDataRead( user, program ); throwExWhenTrue( canNotRead, String.format( "User: %s is not allowed to read program: %s", user.getUsername(), program.getUid() ) ); } } @Override public void decideAccessEventQuery( EventQueryParams params ) { User user = currentUserService.getCurrentUser(); decideAccess( params ); boolean notAuthorized = user != null && !user.isAuthorized( AUTH_VIEW_EVENT_ANALYTICS ); throwExWhenTrue( notAuthorized, String.format( "User: %s is not allowed to view event analytics", user.getUsername() ) ); } @Override public User getCurrentUser( DataQueryParams params ) { return params != null && params.hasCurrentUser() ? params.getCurrentUser() : currentUserService.getCurrentUser(); } @Override public DataQueryParams withDataApprovalConstraints( DataQueryParams params ) { DataQueryParams.Builder paramsBuilder = DataQueryParams.newBuilder( params ); User user = currentUserService.getCurrentUser(); boolean hideUnapprovedData = systemSettingManager.hideUnapprovedDataInAnalytics(); boolean canViewUnapprovedData = user != null ? user.getUserCredentials().isAuthorized( DataApproval.AUTH_VIEW_UNAPPROVED_DATA ) : true; if ( hideUnapprovedData && user != null ) { Map<OrganisationUnit, Integer> approvalLevels = null; if ( params.hasApprovalLevel() ) { // Set approval level from query DataApprovalLevel approvalLevel = approvalLevelService.getDataApprovalLevel( params.getApprovalLevel() ); throwExWhenTrue( approvalLevel == null, String.format( "Approval level does not exist: %s", params.getApprovalLevel() ) ); approvalLevels = approvalLevelService.getUserReadApprovalLevels( approvalLevel ); } else if ( !canViewUnapprovedData ) { // Set approval level from user level approvalLevels = approvalLevelService.getUserReadApprovalLevels(); } if ( approvalLevels != null && !approvalLevels.isEmpty() ) { paramsBuilder.withDataApprovalLevels( approvalLevels ); log.debug( String.format( "User: %s constrained by data approval levels: %s", user.getUsername(), approvalLevels.values() ) ); } } return paramsBuilder.build(); } @Override public DataQueryParams withDimensionConstraints( DataQueryParams params ) { DataQueryParams.Builder builder = DataQueryParams.newBuilder( params ); applyOrganisationUnitConstraint( builder, params ); applyUserConstraints( builder, params ); return builder.build(); } /** * Applies organisation unit security constraint. * * @param builder the data query parameters builder. * @param params the data query parameters. */ private void applyOrganisationUnitConstraint( DataQueryParams.Builder builder, DataQueryParams params ) { User user = currentUserService.getCurrentUser(); // Check if current user has data view organisation units if ( params == null || user == null || !user.hasDataViewOrganisationUnit() ) { return; } // Check if request already has organisation units specified if ( params.hasDimensionOrFilterWithItems( DimensionalObject.ORGUNIT_DIM_ID ) ) { return; } // Apply constraint as filter, and remove potential all-dimension builder.removeDimensionOrFilter( DimensionalObject.ORGUNIT_DIM_ID ); List<OrganisationUnit> orgUnits = new ArrayList<>( user.getDataViewOrganisationUnits() ); DimensionalObject constraint = new BaseDimensionalObject( DimensionalObject.ORGUNIT_DIM_ID, DimensionType.ORGANISATION_UNIT, orgUnits ); builder.addFilter( constraint ); log.debug( String.format( "User: %s constrained by data view organisation units", user.getUsername() ) ); } /** * Applies user security constraint. * * @param builder the data query parameters builder. * @param params the data query parameters. */ private void applyUserConstraints( DataQueryParams.Builder builder, DataQueryParams params ) { User user = currentUserService.getCurrentUser(); // Check if current user has dimension constraints if ( params == null || user == null || user.getUserCredentials() == null || !user.getUserCredentials().hasDimensionConstraints() ) { return; } Set<DimensionalObject> dimensionConstraints = user.getUserCredentials().getDimensionConstraints(); for ( DimensionalObject dimension : dimensionConstraints ) { // Check if constraint already is specified with items if ( params.hasDimensionOrFilterWithItems( dimension.getUid() ) ) { continue; } List<DimensionalItemObject> canReadItems = dimensionService.getCanReadDimensionItems( dimension.getDimension() ); // Check if current user has access to any items from constraint boolean hasNoReadItems = canReadItems == null || canReadItems.isEmpty(); throwExWhenTrue( hasNoReadItems, String.format( "Current user is constrained by a dimension but has access to no associated dimension items: %s", dimension.getDimension() ) ); // Apply constraint as filter, and remove potential all-dimension builder.removeDimensionOrFilter( dimension.getDimension() ); DimensionalObject constraint = new BaseDimensionalObject( dimension.getDimension(), dimension.getDimensionType(), null, dimension.getDisplayName(), canReadItems ); builder.addFilter( constraint ); log.debug( String.format( "User: %s constrained by dimension: %s", user.getUsername(), constraint.getDimension() ) ); } } private void throwExWhenTrue( boolean condition, String message ) { if ( condition ) { throw new IllegalQueryException( message ); } } }
package org.eclipse.birt.report.engine.emitter.excel; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.OutputStream; import java.io.PrintWriter; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.logging.Level; import java.util.logging.Logger; import org.eclipse.birt.report.engine.content.IHyperlinkAction; import org.eclipse.birt.report.engine.css.engine.value.css.CSSConstants; import org.eclipse.birt.report.engine.emitter.XMLWriter; public class ExcelWriter { private XMLWriterXLS writer = new XMLWriterXLS( ); private static HashSet splitChar = new HashSet( ); static { splitChar.add( new Character( ' ' ) ); splitChar.add( new Character( '\r' ) ); splitChar.add( new Character( '\n' ) ); }; private class XMLWriterXLS extends XMLWriter { public PrintWriter getPrint( ) { return printWriter; } protected String getEscapedStr( String s, boolean whitespace ) { s = super.getEscapedStr( s, whitespace ); StringBuffer result = null; char[] s2char = s.toCharArray( ); for ( int i = 0, max = s2char.length, delta = 0; i < max; i++ ) { char c = s2char[i]; String replacement = null; if ( c == '\n' ) { replacement = "&#10;"; //$NON-NLS-1$ } if ( replacement != null ) { if ( result == null ) { result = new StringBuffer( s ); } result.replace( i + delta, i + delta + 1, replacement ); delta += ( replacement.length( ) - 1 ); } } if ( result == null ) { return s; } return result.toString( ); } } protected static Logger logger = Logger.getLogger( ExcelWriter.class .getName( ) ); public ExcelWriter( OutputStream out ) { this( out, "UTF-8" ); } public ExcelWriter( OutputStream out, String encoding ) { writer.open( out, encoding ); } // If possible, we can pass a format according the data type public void writeText( Data d ) { writer.openTag( "Data" ); if ( d.getDatatype( ).equals( Data.NUMBER ) && ExcelUtil.isNumber( d.getText( ) ) ) { writer.attribute( "ss:Type", "Number" ); } else if ( d.getDatatype( ).equals( Data.DATE ) ) { writer.attribute( "ss:Type", "DateTime" ); } else { writer.attribute( "ss:Type", "String" ); } String txt = d.getText( ); if ( CSSConstants.CSS_CAPITALIZE_VALUE.equalsIgnoreCase( d .getStyleEntry( ).getProperty( StyleConstant.TEXT_TRANSFORM ) ) ) { txt = capitalize( txt ); } else if ( CSSConstants.CSS_UPPERCASE_VALUE.equalsIgnoreCase( d .getStyleEntry( ).getProperty( StyleConstant.TEXT_TRANSFORM ) ) ) { txt = txt.toUpperCase( ); } else if ( CSSConstants.CSS_LOWERCASE_VALUE.equalsIgnoreCase( d .getStyleEntry( ).getProperty( StyleConstant.TEXT_TRANSFORM ) ) ) { txt = txt.toLowerCase( ); } writer.text( txt ); writer.closeTag( "Data" ); } private String capitalize( String text ) { boolean capitalizeNextChar = true; char[] array = text.toCharArray( ); for ( int i = 0; i < array.length; i++ ) { Character c = new Character( text.charAt( i ) ); if ( splitChar.contains( c ) ) capitalizeNextChar = true; else if ( capitalizeNextChar ) { array[i] = Character.toUpperCase( array[i] ); capitalizeNextChar = false; } } return new String( array ); } public void startRow( ) { writer.openTag( "Row" ); } public void endRow( ) { writer.closeTag( "Row" ); } public void startCell( int cellindex, int colspan, int rowspan, int styleid, HyperlinkDef hyperLink ) { writer.openTag( "Cell" ); writer.attribute( "ss:Index", cellindex ); writer.attribute( "ss:StyleID", styleid ); if ( hyperLink != null ) { String urlAddress = hyperLink.getUrl( ); if ( hyperLink.getType( ) == IHyperlinkAction.ACTION_BOOKMARK ) { urlAddress = "#Sheet1!" + urlAddress; } if ( urlAddress.length( ) >= 255 ) { urlAddress = urlAddress.substring( 0, 254 ); } writer.attribute( "ss:HRef", urlAddress ); } writer.attribute( "ss:MergeAcross", colspan ); writer.attribute( "ss:MergeDown", rowspan ); } public void writeDefaultCell( Data d ) { writer.openTag( "Cell" ); if ( d.getStyleId( ) != 0 ) { writer.attribute( "ss:StyleID", d.getStyleId( ) ); } writeText( d ); writer.closeTag( "Cell" ); } protected void writeTxtData( Data d ) { startCell( d.span.getCol( ), d.span.getColSpan( ), d.getRowSpan( ), d.styleId, d.url ); writeText( d ); endCell( ); } protected void writeFormulaData( Data d ) { writer.openTag( "Cell" ); writer.attribute( "ss:Index", d.span.getCol( ) ); writer.attribute( "ss:Formula", d.txt.toString( ) ); writer.attribute( "ss:MergeAcross", d.span.getColSpan( ) ); writer.attribute( "ss:StyleID", d.styleId ); writer.closeTag( "Cell" ); } public void endCell( ) { writer.closeTag( "Cell" ); } public void writeAlignment( String horizontal, String vertical ) { writer.openTag( "Alignment" ); if ( isValid( horizontal ) ) { writer.attribute( "ss:Horizontal", horizontal ); } if ( isValid( vertical ) ) { writer.attribute( "ss:Vertical", vertical ); } writer.attribute( "ss:WrapText", "1" ); writer.closeTag( "Alignment" ); } public void writeBorder( String position, String lineStyle, String weight, String color ) { writer.openTag( "Border" ); writer.attribute( "ss:Position", position ); if ( isValid( lineStyle ) ) { writer.attribute( "ss:LineStyle", lineStyle ); } if ( isValid( weight ) ) { writer.attribute( "ss:Weight", weight ); } if ( isValid( color ) ) { writer.attribute( "ss:Color", color ); } writer.closeTag( "Border" ); } public void writeFont( String fontName, String size, String bold, String italic, String strikeThrough, String underline, String color ) { writer.openTag( "Font" ); if ( isValid( fontName ) ) { writer.attribute( "ss:FontName", fontName ); } if ( isValid( size ) ) { writer.attribute( "ss:Size", size ); } if ( isValid( bold ) ) { writer.attribute( "ss:Bold", bold ); } if ( isValid( italic ) ) { writer.attribute( "ss:Italic", italic ); } if ( isValid( strikeThrough ) ) { writer.attribute( "ss:StrikeThrough", strikeThrough ); } if ( isValid( underline ) && !"0".equalsIgnoreCase( underline ) ) { writer.attribute( "ss:Underline", "Single" ); } if ( isValid( color ) ) { writer.attribute( "ss:Color", color ); } writer.closeTag( "Font" ); } public void writeBackGroudColor( String bgColor ) { if ( isValid( bgColor ) ) { writer.openTag( "Interior" ); writer.attribute( "ss:Color", bgColor ); writer.attribute( "ss:Pattern", "Solid" ); writer.closeTag( "Interior" ); } } private boolean isValid( String value ) { return !StyleEntry.isNull( value ); } private void declareStyle( StyleEntry style, int id ) { writer.openTag( "Style" ); writer.attribute( "ss:ID", id ); if ( id >= StyleEngine.RESERVE_STYLE_ID ) { String horizontalAlign = style .getProperty( StyleConstant.H_ALIGN_PROP ); String verticalAlign = style .getProperty( StyleConstant.V_ALIGN_PROP ); writeAlignment( horizontalAlign, verticalAlign ); writer.openTag( "Borders" ); String bottomColor = style .getProperty( StyleConstant.BORDER_BOTTOM_COLOR_PROP ); String bottomLineStyle = style .getProperty( StyleConstant.BORDER_BOTTOM_STYLE_PROP ); String bottomWeight = style .getProperty( StyleConstant.BORDER_BOTTOM_WIDTH_PROP ); writeBorder( "Bottom", bottomLineStyle, bottomWeight, bottomColor ); String topColor = style .getProperty( StyleConstant.BORDER_TOP_COLOR_PROP ); String topLineStyle = style .getProperty( StyleConstant.BORDER_TOP_STYLE_PROP ); String topWeight = style .getProperty( StyleConstant.BORDER_TOP_WIDTH_PROP ); writeBorder( "Top", topLineStyle, topWeight, topColor ); String leftColor = style .getProperty( StyleConstant.BORDER_LEFT_COLOR_PROP ); String leftLineStyle = style .getProperty( StyleConstant.BORDER_LEFT_STYLE_PROP ); String leftWeight = style .getProperty( StyleConstant.BORDER_LEFT_WIDTH_PROP ); writeBorder( "Left", leftLineStyle, leftWeight, leftColor ); String rightColor = style .getProperty( StyleConstant.BORDER_RIGHT_COLOR_PROP ); String rightLineStyle = style .getProperty( StyleConstant.BORDER_RIGHT_STYLE_PROP ); String rightWeight = style .getProperty( StyleConstant.BORDER_RIGHT_WIDTH_PROP ); writeBorder( "Right", rightLineStyle, rightWeight, rightColor ); writer.closeTag( "Borders" ); String fontName = style .getProperty( StyleConstant.FONT_FAMILY_PROP ); String size = style.getProperty( StyleConstant.FONT_SIZE_PROP ); String fontStyle = style .getProperty( StyleConstant.FONT_STYLE_PROP ); String fontWeight = style .getProperty( StyleConstant.FONT_WEIGHT_PROP ); String strikeThrough = style .getProperty( StyleConstant.TEXT_LINE_THROUGH_PROP ); String underline = style .getProperty( StyleConstant.TEXT_UNDERLINE_PROP ); String color = style.getProperty( StyleConstant.COLOR_PROP ); writeFont( fontName, size, fontWeight, fontStyle, strikeThrough, underline, color ); String bgColor = style .getProperty( StyleConstant.BACKGROUND_COLOR_PROP ); writeBackGroudColor( bgColor ); } writeDataFormat( style ); writer.closeTag( "Style" ); } public void writeDataFormat( StyleEntry style ) { if ( style.getProperty( StyleConstant.DATA_TYPE_PROP ) == Data.DATE && style.getProperty( StyleConstant.DATE_FORMAT_PROP ) != null ) { writer.openTag( "NumberFormat" ); writer.attribute( "ss:Format", style .getProperty( StyleConstant.DATE_FORMAT_PROP ) ); writer.closeTag( "NumberFormat" ); } if ( style.getProperty( StyleConstant.DATA_TYPE_PROP ) == Data.NUMBER && style.getProperty( StyleConstant.NUMBER_FORMAT_PROP ) != null ) { writer.openTag( "NumberFormat" ); String numberStyle = style .getProperty( StyleConstant.NUMBER_FORMAT_PROP ); numberStyle = format( numberStyle ); writer.attribute( "ss:Format", numberStyle ); writer.closeTag( "NumberFormat" ); } } // here the user input can be divided into two cases : // the case in the birt input like G and the Currency // the case in excel format : like 0.00E00 private String format( String givenValue ) { String returnStr = "\\"; if ( givenValue.length( ) == 1 ) { char ch = givenValue.charAt( 0 ); if ( ch == 'G' || ch == 'g' || ch == 'd' || ch == 'D' ) { returnStr = givenValue + " } if ( ch == 'C' || ch == 'c' ) { return "###,##0.00"; } if ( ch == 'f' || ch == 'F' ) { return "#0.00"; } if ( ch == 'N' || ch == 'n' ) { return "###,##0.00"; } if ( ch == 'p' || ch == 'P' ) { return "###,##0.00 %"; } if ( ch == 'e' || ch == 'E' ) { return "0.000000E00"; } if ( ch == 'x' || ch == 'X' ) { returnStr = " } returnStr = returnStr + givenValue + " } else { if ( givenValue.equals( "Fixed" ) || givenValue.equals( "#0.00" ) ) return "#0.00"; if ( givenValue.equals( "Percent" ) || givenValue.equals( "0.00%" ) ) return "0.00%"; if ( givenValue.equals( "Scientific" ) || givenValue.equals( "0.00E00" ) ) return "0.00E00"; if ( givenValue.equals( "Standard" ) || givenValue.equals( "###,##0.00" ) ) return "###,##0.00"; if(givenValue.equals( "General Number" )){ return "General"; } if(validType(givenValue)){ return givenValue + " } int count = givenValue.length( ); for ( int num = 0; num < count - 1; num++ ) { returnStr = returnStr + givenValue.charAt( num ) + "\\"; } returnStr = returnStr + givenValue.charAt( count - 1 ) + " } return returnStr; } private boolean validType(String str){ for(int count = 0 ; count < str.length( ) ; count ++){ char ch = str.charAt( count ); if(ch != '$' && ch != '0' && ch != '#' && ch != '?' && ch != '@' && ch != '%' && ch != '.' && ch != ';' && ch != ' '){ return false; } } return true; } public void writeDeclarations( ) { writer.startWriter( ); writer.getPrint( ).println( ); writer.getPrint( ).println( "<?mso-application progid=\"Excel.Sheet\"?>" ); writer.openTag( "Workbook" ); writer.attribute( "xmlns", "urn:schemas-microsoft-com:office:spreadsheet" ); writer.attribute( "xmlns:o", "urn:schemas-microsoft-com:office:office" ); writer.attribute( "xmlns:x", "urn:schemas-microsoft-com:office:excel" ); writer.attribute( "xmlns:ss", "urn:schemas-microsoft-com:office:spreadsheet" ); writer.attribute( "xmlns:html", "http: } public void declareStyles( Map style2id ) { writer.openTag( "Styles" ); for ( Iterator it = style2id.entrySet( ).iterator( ); it.hasNext( ); ) { Map.Entry entry = (Map.Entry) it.next( ); Object style = entry.getKey( ); int id = ( (Integer) entry.getValue( ) ).intValue( ); declareStyle( (StyleEntry) style, id ); } writer.closeTag( "Styles" ); } public void defineNames( List namesRefer ) { writer.openTag( "Names" ); for ( Iterator it = namesRefer.iterator( ); it.hasNext( ); ) { BookmarkDef bookmark = (BookmarkDef) it.next( ); String name = bookmark.getName( ); String refer = bookmark.getRefer( ); defineName( name, refer ); } writer.closeTag( "Names" ); } private void defineName( String name, String refer ) { writer.openTag( "NamedRange" ); writer.attribute( "ss:Name", name ); writer.attribute( "ss:RefersTo", refer ); writer.closeTag( "NamedRange" ); } public void close( boolean complete ) { if ( complete ) { writer.closeTag( "Workbook" ); } writer.close( ); } public void startSheet( String name ) { writer.openTag( "Worksheet" ); writer.attribute( "ss:Name", name ); } public void startSheet( ) { startSheet( "Sheet1" ); } public void closeSheet( ) { writer.closeTag( "Worksheet" ); } public void startTable( int[] width ) { writer.openTag( "ss:Table" ); if ( width == null ) { logger.log( Level.SEVERE, "Invalid columns width" ); return; } for ( int i = 0; i < width.length; i++ ) { writer.openTag( "ss:Column" ); writer.attribute( "ss:Width", width[i] ); writer.closeTag( "ss:Column" ); } } public void endTable( ) { writer.closeTag( "ss:Table" ); } public void insertHorizontalMargin( int height, int span ) { writer.openTag( "Row" ); writer.attribute( "ss:AutoFitHeight", 0 ); writer.attribute( "ss:Height", height ); writer.openTag( "Cell" ); writer.attribute( " ss:MergeAcross", span ); writer.closeTag( "Cell" ); writer.closeTag( "Row" ); } public void insertVerticalMargin( int start, int end, int length ) { writer.openTag( "Row" ); writer.attribute( "ss:AutoFitHeight", 0 ); writer.attribute( "ss:Height", 1 ); writer.openTag( "Cell" ); writer.attribute( "ss:Index", start ); writer.attribute( " ss:MergeDown", length ); writer.closeTag( "Cell" ); writer.openTag( "Cell" ); writer.attribute( "ss:Index", end ); writer.attribute( " ss:MergeDown", length ); writer.closeTag( "Cell" ); writer.closeTag( "Row" ); } public void insertSheet( File file ) { try { BufferedReader reader = new BufferedReader( new FileReader( file ) ); String line = reader.readLine( ); while ( line != null ) { writer.literal( line ); line = reader.readLine( ); } reader.close( ); } catch ( IOException e ) { logger.log( Level.WARNING, e.getMessage( ), e ); } } }
package org.modeshape.connector.filesystem; import static org.hamcrest.core.Is.is; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import org.junit.Test; import org.modeshape.common.FixFor; import org.modeshape.common.util.FileUtil; import org.modeshape.common.util.StringUtil; import org.modeshape.graph.Graph; import org.modeshape.graph.JcrLexicon; import org.modeshape.graph.JcrNtLexicon; import org.modeshape.graph.Graph.Batch; import org.modeshape.graph.connector.RepositorySource; import org.modeshape.graph.connector.RepositorySourceException; import org.modeshape.graph.connector.test.AbstractConnectorTest; import org.modeshape.graph.property.InvalidPathException; import org.modeshape.graph.request.InvalidRequestException; public class FileSystemConnectorWritableTest extends AbstractConnectorTest { public static final String ARBITRARY_PROPERTIES_NOT_SUPPORTED = "This connector does not support setting arbitrary properties"; private static final String REPO_PATH = "./target/repositories/"; private static final String REPO_SOURCE_PATH = "./src/test/resources/repositories/"; private final String TEST_CONTENT = "Test content"; protected File testWorkspaceRoot; protected File otherWorkspaceRoot; protected File newWorkspaceRoot; protected File scratchDirectory; private FileSystemSource source; @Override protected RepositorySource setUpSource() throws Exception { // Copy the directories into the target ... File sourceRepo = new File(REPO_SOURCE_PATH); scratchDirectory = new File(REPO_PATH); scratchDirectory.mkdirs(); FileUtil.delete(scratchDirectory); FileUtil.copy(sourceRepo, scratchDirectory); // Set the connection properties to be use the content of "./src/test/resources/repositories" as a repository ... String[] predefinedWorkspaceNames = new String[] {"test", "otherWorkspace", "airplanes", "cars"}; source = new FileSystemSource(); source.setName("Test Repository"); source.setWorkspaceRootPath(REPO_PATH); source.setPredefinedWorkspaceNames(predefinedWorkspaceNames); source.setDefaultWorkspaceName(predefinedWorkspaceNames[0]); source.setCreatingWorkspacesAllowed(true); source.setUpdatesAllowed(true); source.setExclusionPattern("\\.svn"); testWorkspaceRoot = new File(REPO_PATH, "test"); testWorkspaceRoot.mkdir(); otherWorkspaceRoot = new File(REPO_PATH, "otherWorkspace"); otherWorkspaceRoot.mkdir(); newWorkspaceRoot = new File(REPO_PATH, "newWorkspace"); newWorkspaceRoot.mkdir(); return source; } @Override protected void initializeContent( Graph graph ) { // No setup required } @Override public void afterEach() throws Exception { FileUtil.delete(scratchDirectory); super.afterEach(); } @Test public void shouldBeAbleToCreateFileWithContentAndNotRequiringOrReplace() { graph.create("/testFile").with(JcrLexicon.PRIMARY_TYPE, JcrNtLexicon.FILE).and(); graph.create("/testFile/jcr:content") .with(JcrLexicon.PRIMARY_TYPE, JcrNtLexicon.RESOURCE) .and(JcrLexicon.DATA, TEST_CONTENT.getBytes()) .and(); File newFile = new File(testWorkspaceRoot, "testFile"); assertContents(newFile, TEST_CONTENT); } @Test public void shouldBeAbleToCreateFileWithContent() { graph.create("/testFile").with(JcrLexicon.PRIMARY_TYPE, JcrNtLexicon.FILE).orReplace().and(); graph.create("/testFile/jcr:content") .with(JcrLexicon.PRIMARY_TYPE, JcrNtLexicon.RESOURCE) .and(JcrLexicon.DATA, TEST_CONTENT.getBytes()) .orReplace() .and(); File newFile = new File(testWorkspaceRoot, "testFile"); assertContents(newFile, TEST_CONTENT); } @Test public void shouldRespectConflictBehaviorOnCreate() { graph.create("/testFile").with(JcrLexicon.PRIMARY_TYPE, JcrNtLexicon.FILE).orReplace().and(); graph.create("/testFile/jcr:content") .with(JcrLexicon.PRIMARY_TYPE, JcrNtLexicon.RESOURCE) .and(JcrLexicon.DATA, TEST_CONTENT.getBytes()) .orReplace() .and(); graph.create("/testFile/jcr:content") .with(JcrLexicon.PRIMARY_TYPE, JcrNtLexicon.RESOURCE) .and(JcrLexicon.DATA, "Should not overwrite".getBytes()) .ifAbsent() .and(); File newFile = new File(testWorkspaceRoot, "testFile"); assertContents(newFile, TEST_CONTENT); } @Test public void shouldBeAbleToCreateFileWithNoContent() { graph.create("/testEmptyFile").with(JcrLexicon.PRIMARY_TYPE, JcrNtLexicon.FILE).orReplace().and(); File newFile = new File(testWorkspaceRoot, "testEmptyFile"); assertThat(newFile.exists(), is(true)); assertThat(newFile.isFile(), is(true)); } @Test public void shouldBeAbleToCreateFolder() { graph.create("/testFolder").orReplace().and(); File newFile = new File(testWorkspaceRoot, "testFolder"); assertThat(newFile.exists(), is(true)); assertThat(newFile.isDirectory(), is(true)); } @Test public void shouldBeAbleToAddChildrenToFolder() throws Exception { graph.create("/testFolder").orReplace().and(); File newFolder = new File(testWorkspaceRoot, "testFolder"); assertThat(newFolder.exists(), is(true)); assertThat(newFolder.isDirectory(), is(true)); graph.create("/testFolder/testFile").with(JcrLexicon.PRIMARY_TYPE, JcrNtLexicon.FILE).orReplace().and(); graph.create("/testFolder/testFile/jcr:content") .with(JcrLexicon.PRIMARY_TYPE, JcrNtLexicon.RESOURCE) .and(JcrLexicon.DATA, TEST_CONTENT.getBytes()) .orReplace() .and(); File newFile = new File(testWorkspaceRoot, "testFolder/testFile"); assertContents(newFile, TEST_CONTENT); } @Test( expected = RepositorySourceException.class ) public void shouldNotBeAbleToCreateInvalidTypeForRepository() { graph.create("/testFile").with(JcrLexicon.PRIMARY_TYPE, JcrNtLexicon.UNSTRUCTURED).orReplace().and(); } @Test public void shouldBeAbleToCopyFile() { graph.create("/testFile").with(JcrLexicon.PRIMARY_TYPE, JcrNtLexicon.FILE).orReplace().and(); graph.create("/testFile/jcr:content") .with(JcrLexicon.PRIMARY_TYPE, JcrNtLexicon.RESOURCE) .and(JcrLexicon.DATA, TEST_CONTENT.getBytes()) .orReplace() .and(); File newFile = new File(testWorkspaceRoot, "testFile"); assertContents(newFile, TEST_CONTENT); graph.copy("/testFile").to("/copiedFile"); File copiedFile = new File(testWorkspaceRoot, "copiedFile"); assertContents(copiedFile, TEST_CONTENT); } @Test public void shouldBeAbleToCopyFolder() { graph.create("/testFolder").orReplace().and(); graph.create("/testFolder/testFile").with(JcrLexicon.PRIMARY_TYPE, JcrNtLexicon.FILE).orReplace().and(); graph.create("/testFolder/testFile/jcr:content") .with(JcrLexicon.PRIMARY_TYPE, JcrNtLexicon.RESOURCE) .and(JcrLexicon.DATA, TEST_CONTENT.getBytes()) .orReplace() .and(); File newFile = new File(testWorkspaceRoot, "testFolder/testFile"); assertContents(newFile, TEST_CONTENT); graph.copy("/testFolder").to("/copiedFolder"); File copiedFolder = new File(testWorkspaceRoot, "copiedFolder"); assertTrue(copiedFolder.exists()); assertTrue(copiedFolder.isDirectory()); File copiedFile = new File(testWorkspaceRoot, "copiedFolder/testFile"); assertContents(copiedFile, TEST_CONTENT); } @Test public void shouldBeAbleToMoveFile() { graph.create("/testFile").with(JcrLexicon.PRIMARY_TYPE, JcrNtLexicon.FILE).orReplace().and(); graph.create("/testFile/jcr:content") .with(JcrLexicon.PRIMARY_TYPE, JcrNtLexicon.RESOURCE) .and(JcrLexicon.DATA, TEST_CONTENT.getBytes()) .orReplace() .and(); File newFile = new File(testWorkspaceRoot, "testFile"); assertContents(newFile, TEST_CONTENT); graph.create("/newFolder").orReplace().and(); graph.move("/testFile").into("/newFolder"); assertThat(newFile.exists(), is(false)); File copiedFile = new File(testWorkspaceRoot, "newFolder/testFile"); assertContents(copiedFile, TEST_CONTENT); } @Test public void shouldBeAbleToMoveFolder() { graph.create("/testFolder").orReplace().and(); graph.create("/testFolder/testFile").with(JcrLexicon.PRIMARY_TYPE, JcrNtLexicon.FILE).orReplace().and(); graph.create("/testFolder/testFile/jcr:content") .with(JcrLexicon.PRIMARY_TYPE, JcrNtLexicon.RESOURCE) .and(JcrLexicon.DATA, TEST_CONTENT.getBytes()) .orReplace() .and(); File newFile = new File(testWorkspaceRoot, "testFolder/testFile"); assertContents(newFile, TEST_CONTENT); graph.create("/newFolder").orReplace().and(); graph.move("/testFolder").into("/newFolder"); assertThat(newFile.exists(), is(false)); File copiedFolder = new File(testWorkspaceRoot, "newFolder/testFolder"); assertTrue(copiedFolder.exists()); assertTrue(copiedFolder.isDirectory()); File copiedFile = new File(testWorkspaceRoot, "newFolder/testFolder/testFile"); assertContents(copiedFile, TEST_CONTENT); } @Test public void shouldBeAbleToDeleteFolderWithContents() { graph.create("/testFolder").orReplace().and(); graph.create("/testFolder/testFile").with(JcrLexicon.PRIMARY_TYPE, JcrNtLexicon.FILE).orReplace().and(); graph.create("/testFolder/testFile/jcr:content") .with(JcrLexicon.PRIMARY_TYPE, JcrNtLexicon.RESOURCE) .and(JcrLexicon.DATA, TEST_CONTENT.getBytes()) .orReplace() .and(); File newFolder = new File(testWorkspaceRoot, "testFolder"); assertTrue(newFolder.exists()); assertTrue(newFolder.isDirectory()); File newFile = new File(testWorkspaceRoot, "testFolder/testFile"); assertContents(newFile, TEST_CONTENT); graph.delete("/testFolder"); assertThat(newFolder.exists(), is(false)); } @Test public void shouldBeAbleToDeleteFile() { graph.create("/testFolder").orReplace().and(); graph.create("/testFolder/testFile").with(JcrLexicon.PRIMARY_TYPE, JcrNtLexicon.FILE).orReplace().and(); graph.create("/testFolder/testFile/jcr:content") .with(JcrLexicon.PRIMARY_TYPE, JcrNtLexicon.RESOURCE) .and(JcrLexicon.DATA, TEST_CONTENT.getBytes()) .orReplace() .and(); File newFolder = new File(testWorkspaceRoot, "testFolder"); assertTrue(newFolder.exists()); assertTrue(newFolder.isDirectory()); File newFile = new File(testWorkspaceRoot, "testFolder/testFile"); assertContents(newFile, TEST_CONTENT); graph.delete("/testFolder/testFile"); assertTrue(newFolder.exists()); assertThat(newFile.exists(), is(false)); } /** * Since the FS connector does not support UUIDs (under the root node), all clones are just copies (clone for * non-referenceable nodes is a copy to the corresponding path). */ @Test public void shouldBeAbleToCloneFolder() { graph.useWorkspace("otherWorkspace"); graph.create("/testFolder").orReplace().and(); graph.create("/testFolder/testFile").with(JcrLexicon.PRIMARY_TYPE, JcrNtLexicon.FILE).orReplace().and(); graph.create("/testFolder/testFile/jcr:content") .with(JcrLexicon.PRIMARY_TYPE, JcrNtLexicon.RESOURCE) .and(JcrLexicon.DATA, TEST_CONTENT.getBytes()) .orReplace() .and(); File newFile = new File(otherWorkspaceRoot, "testFolder/testFile"); assertContents(newFile, TEST_CONTENT); graph.useWorkspace("test"); graph.clone("/testFolder").fromWorkspace("otherWorkspace").as("clonedFolder").into("/").failingIfAnyUuidsMatch(); File copiedFolder = new File(testWorkspaceRoot, "clonedFolder"); assertTrue(copiedFolder.exists()); assertTrue(copiedFolder.isDirectory()); File copiedFile = new File(testWorkspaceRoot, "clonedFolder/testFile"); assertContents(copiedFile, TEST_CONTENT); } /** * Since the FS connector does not support UUIDs (under the root node), all clones are just copies (clone for * non-referenceable nodes is a copy to the corresponding path). */ @Test public void shouldBeAbleToCloneFile() { graph.useWorkspace("otherWorkspace"); graph.create("/testFile").with(JcrLexicon.PRIMARY_TYPE, JcrNtLexicon.FILE).orReplace().and(); graph.create("/testFile/jcr:content") .with(JcrLexicon.PRIMARY_TYPE, JcrNtLexicon.RESOURCE) .and(JcrLexicon.DATA, TEST_CONTENT.getBytes()) .orReplace() .and(); File newFile = new File(otherWorkspaceRoot, "testFile"); assertContents(newFile, TEST_CONTENT); graph.useWorkspace("test"); graph.clone("/testFile").fromWorkspace("otherWorkspace").as("clonedFile").into("/").failingIfAnyUuidsMatch(); File copiedFile = new File(testWorkspaceRoot, "clonedFile"); assertContents(copiedFile, TEST_CONTENT); } @Test( expected = InvalidRequestException.class ) public void shouldNotBeAbleToReorderFolder() { graph.create("/testFolder").orReplace().and(); graph.create("/testFolder2").orReplace().and(); File newFolder = new File(testWorkspaceRoot, "testFolder"); assertTrue(newFolder.exists()); assertTrue(newFolder.isDirectory()); File newFolder2 = new File(testWorkspaceRoot, "testFolder2"); assertTrue(newFolder2.exists()); assertTrue(newFolder2.isDirectory()); graph.move("/testFolder2").before("/testFolder"); } @Test( expected = InvalidRequestException.class ) public void shouldNotBeAbleToReorderFile() { graph.create("/testFolder").orReplace().and(); graph.create("/testFolder/testFile").with(JcrLexicon.PRIMARY_TYPE, JcrNtLexicon.FILE).orReplace().and(); graph.create("/testFolder/testFile/jcr:content") .with(JcrLexicon.PRIMARY_TYPE, JcrNtLexicon.RESOURCE) .and(JcrLexicon.DATA, TEST_CONTENT.getBytes()) .orReplace() .and(); graph.create("/testFolder/testFile2").with(JcrLexicon.PRIMARY_TYPE, JcrNtLexicon.FILE).orReplace().and(); graph.create("/testFolder/testFile2/jcr:content") .with(JcrLexicon.PRIMARY_TYPE, JcrNtLexicon.RESOURCE) .and(JcrLexicon.DATA, TEST_CONTENT.getBytes()) .orReplace() .and(); File newFolder = new File(testWorkspaceRoot, "testFolder"); assertTrue(newFolder.exists()); assertTrue(newFolder.isDirectory()); File newFile = new File(testWorkspaceRoot, "testFolder/testFile"); assertContents(newFile, TEST_CONTENT); File newFile2 = new File(testWorkspaceRoot, "testFolder/testFile2"); assertContents(newFile2, TEST_CONTENT); graph.move("/testFolder/testFile2").before("/testFolder/testFile"); } @Test public void shouldBeAbleToRenameFolder() { graph.create("/testFolder").orReplace().and(); graph.create("/testFolder/testFile").with(JcrLexicon.PRIMARY_TYPE, JcrNtLexicon.FILE).orReplace().and(); graph.create("/testFolder/testFile/jcr:content") .with(JcrLexicon.PRIMARY_TYPE, JcrNtLexicon.RESOURCE) .and(JcrLexicon.DATA, TEST_CONTENT.getBytes()) .orReplace() .and(); File newFile = new File(testWorkspaceRoot, "testFolder/testFile"); assertContents(newFile, TEST_CONTENT); graph.move("/testFolder").as("newFolder").into("/"); assertThat(newFile.exists(), is(false)); File copiedFolder = new File(testWorkspaceRoot, "newFolder"); assertTrue(copiedFolder.exists()); assertTrue(copiedFolder.isDirectory()); File copiedFile = new File(testWorkspaceRoot, "newFolder/testFile"); assertContents(copiedFile, TEST_CONTENT); } @Test public void shouldBeAbleToRenameFile() { graph.create("/testFile").with(JcrLexicon.PRIMARY_TYPE, JcrNtLexicon.FILE).orReplace().and(); graph.create("/testFile/jcr:content") .with(JcrLexicon.PRIMARY_TYPE, JcrNtLexicon.RESOURCE) .and(JcrLexicon.DATA, TEST_CONTENT.getBytes()) .orReplace() .and(); File newFile = new File(testWorkspaceRoot, "testFile"); assertContents(newFile, TEST_CONTENT); graph.move("/testFile").as("copiedFile").into("/"); assertThat(newFile.exists(), is(false)); File copiedFile = new File(testWorkspaceRoot, "copiedFile"); assertContents(copiedFile, TEST_CONTENT); } @FixFor( "MODE-944" ) @Test public void shouldBeAbleToRenameFileInBatch() { Batch batch = graph.batch(); batch.create("/testFile").with(JcrLexicon.PRIMARY_TYPE, JcrNtLexicon.FILE).orReplace().and(); batch.create("/testFile/jcr:content") .with(JcrLexicon.PRIMARY_TYPE, JcrNtLexicon.RESOURCE) .and(JcrLexicon.DATA, TEST_CONTENT.getBytes()) .orReplace() .and(); batch.move("/testFile").as("copiedFile").into("/"); batch.execute(); File newFile = new File(testWorkspaceRoot, "testFile"); assertThat(newFile.exists(), is(false)); File copiedFile = new File(testWorkspaceRoot, "copiedFile"); assertContents(copiedFile, TEST_CONTENT); } @Test public void shouldBeAbleToCreateWorkspace() { graph.createWorkspace().named("newWorkspace"); graph.useWorkspace("newWorkspace"); graph.create("/testFile").with(JcrLexicon.PRIMARY_TYPE, JcrNtLexicon.FILE).orReplace().and(); graph.create("/testFile/jcr:content") .with(JcrLexicon.PRIMARY_TYPE, JcrNtLexicon.RESOURCE) .and(JcrLexicon.DATA, TEST_CONTENT.getBytes()) .orReplace() .and(); File newFile = new File(newWorkspaceRoot, "testFile"); assertContents(newFile, TEST_CONTENT); } @Test public void shouldBeAbleToCloneWorkspace() { graph.create("/testFile").with(JcrLexicon.PRIMARY_TYPE, JcrNtLexicon.FILE).orReplace().and(); graph.create("/testFile/jcr:content") .with(JcrLexicon.PRIMARY_TYPE, JcrNtLexicon.RESOURCE) .and(JcrLexicon.DATA, TEST_CONTENT.getBytes()) .orReplace() .and(); File newFile = new File(testWorkspaceRoot, "testFile"); assertContents(newFile, TEST_CONTENT); graph.createWorkspace().clonedFrom("test").named("newWorkspace"); newFile = new File(newWorkspaceRoot, "testFile"); assertContents(newFile, TEST_CONTENT); } @Test public void shouldBeAbleToCreateDeepPath() { String pathName = ""; for (int i = 0; i < 20; i++) { pathName += "/test"; // Check whether the java.io.File length would be too long // (if so, then we'd get a RepositorySourceException here) ... if (pathLengthExceedsOSLimits(pathName)) break; graph.create(pathName).orReplace().and(); } } protected boolean pathLengthExceedsOSLimits( String path ) { return (scratchDirectory.getAbsolutePath() + path).length() > source.getMaxPathLength(); } @Test( expected = RepositorySourceException.class ) public void shouldNotBeAbleToCreateTooDeepPath() { String pathName = ""; for (int i = 0; i < 100; i++) { pathName += "/testFolder"; graph.create(pathName).orReplace().and(); } } @Test public void shouldBeAllOrNothing() { String longTestFileName = "/testFileWithTooLongName" + StringUtil.createString('x', 300); Batch batch = graph.batch(); batch.create("/testFile").with(JcrLexicon.PRIMARY_TYPE, JcrNtLexicon.FILE).orReplace().and(); batch.create("/testFile/jcr:content") .with(JcrLexicon.PRIMARY_TYPE, JcrNtLexicon.RESOURCE) .and(JcrLexicon.DATA, TEST_CONTENT.getBytes()) .orReplace() .and(); batch.create(longTestFileName).and(); try { batch.execute(); fail("The overly long test file name (" + longTestFileName + ") did not fail"); } catch (RepositorySourceException rse) { // Expected } File newFile = new File(testWorkspaceRoot, "testFile"); assertFalse(newFile.exists()); } /** * This method attempts to create a small subgraph and then delete some of the nodes in that subgraph, all within the same * batch operation. */ @FixFor( "MODE-788" ) @Test public void shouldCreateSubgraphAndDeletePartOfThatSubgraphInSameOperation() { graph.batch() .create("/a") .with(JcrLexicon.PRIMARY_TYPE, JcrNtLexicon.FOLDER) .orReplace() .and() .create("/a/b") .with(JcrLexicon.PRIMARY_TYPE, JcrNtLexicon.FOLDER) .orReplace() .and() .create("/a/b/c") .with(JcrLexicon.PRIMARY_TYPE, JcrNtLexicon.FOLDER) .orReplace() .and() .delete("/a/b") .and() .execute(); // Now look up node A ... File newFile = new File(testWorkspaceRoot, "a"); assertTrue(newFile.exists()); assertTrue(newFile.isDirectory()); assertTrue(newFile.list().length == 0); assertFalse(new File(newFile, "b").exists()); } /** * This method attempts to create a small subgraph and then delete some of the nodes in that subgraph, all within the same * batch operation. */ @FixFor( "MODE-788" ) @Test public void shouldCreateSubgraphAndDeleteSubgraphInSameOperation() { graph.batch() .create("/a") .with(JcrLexicon.PRIMARY_TYPE, JcrNtLexicon.FOLDER) .orReplace() .and() .create("/a/b") .with(JcrLexicon.PRIMARY_TYPE, JcrNtLexicon.FOLDER) .orReplace() .and() .create("/a/b/c") .with(JcrLexicon.PRIMARY_TYPE, JcrNtLexicon.FOLDER) .orReplace() .and() .delete("/a") .and() .execute(); // Now look up node A ... assertTrue(testWorkspaceRoot.list().length == 0); assertFalse(new File(testWorkspaceRoot, "a").exists()); } @Test( expected = InvalidPathException.class ) public void shouldNotAllowWriteToExcludedFilename() { graph.create("/.svn").and(); } @Test( expected = InvalidPathException.class ) public void shouldNotAllowMoveToExcludedFilename() { graph.create("/test").and(); graph.move("/test").as(".svn").into("/"); } @Test( expected = InvalidPathException.class ) public void shouldNotAllowCopyToExcludedFilename() { graph.create("/test").and(); graph.copy("/test").to("/.svn"); } protected void assertContents( File file, String contents ) { assertTrue(file.exists()); assertTrue(file.isFile()); StringBuilder buff = new StringBuilder(); final int BUFF_SIZE = 8192; byte[] bytes = new byte[BUFF_SIZE]; int len; FileInputStream fis = null; try { fis = new FileInputStream(file); while (-1 != (len = fis.read(bytes, 0, BUFF_SIZE))) { buff.append(new String(bytes, 0, len)); } assertThat(buff.toString(), is(contents)); } catch (IOException ioe) { ioe.printStackTrace(); fail(ioe.getMessage()); return; } finally { if (fis != null) { try { fis.close(); } catch (Exception ignore) { } finally { fis = null; } } } } }
package com.dominikschreiber.underscore; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; public class _Test { private List<Integer> range(int from, int to) { List<Integer> result = new ArrayList<Integer>(to - from + 1); for (int i = from; i < to; i++) { result.add(i); } return result; } private List<Integer> range(int to) { return range(1, to); } @Test public void staticEachWithStringBuilder() { final StringBuilder result = new StringBuilder(); _.each(range(6), new Fn<Integer, Void>() { @Override public Void apply(Integer input) { result.append(Integer.toString(input, 10)); return null; } }); assertEquals("12345", result.toString()); } @Test public void chainedEachWithStringBuilder() { final StringBuilder result = new StringBuilder(); new _<Integer>(range(6)) .each(new Fn<Integer, Void>() { public Void apply(Integer input) { result.append(Integer.toString(input, 10)); return null; } }); assertEquals("12345", result.toString()); } @Test public void staticMapWithSquare() { List<Integer> result = _.map(range(6), new Fn<Integer, Integer>() { @Override public Integer apply(Integer input) { return input * input; } }); assertEquals(Arrays.asList(new Integer[] {1, 4, 9, 16, 25}), result); } @Test public void chainedMapWithSquare() { Iterable<Integer> result = new _<Integer>(range(6)) .map(new Fn<Integer, Integer>() { @Override public Integer apply(Integer input) { return input * input; } }) .value(); assertEquals(Arrays.asList(new Integer[] {1, 4, 9, 16, 25}), result); } @Test public void staticFilterWithIsEven() { List<Integer> result = _.filter(range(6), new Fn<Integer, Boolean>() { public Boolean apply(Integer input) { return input % 2 == 0; } }); assertEquals(Arrays.asList(new Integer[] {2, 4}), result); } @Test public void chainedFilterWithIsEven() { Iterable<Integer> result = new _<Integer>(range(6)) .filter(new Fn<Integer, Boolean>() { public Boolean apply(Integer input) { return input % 2 == 0; } }) .value(); assertEquals(Arrays.asList(new Integer[] {2, 4}), result); } @Test public void staticReduceWithSum() { Integer result = _.reduce(range(6), new BinaryFn<Integer, Integer, Integer>() { @Override public Integer apply(Integer current, Integer sum) { return current + sum; } }, 0); assertTrue(1 + 2 + 3 + 4 + 5 == result); } @Test public void chainedReduceWithSum() { Integer result = new _<Integer>(range(6)) .reduce(new BinaryFn<Integer, Integer, Integer>() { @Override public Integer apply(Integer current, Integer sum) { return current + sum; } }, 0); assertTrue(1 + 2 + 3 + 4 + 5 == result); } @Test public void chainedComplexWithSumOfEvenSquares() { Integer sumOfEvenSquares = new _<Integer>(range(11)) .map(new Fn<Integer, Integer>() { @Override public Integer apply(Integer input) { return input * input; } }) .filter(new Fn<Integer, Boolean>() { @Override public Boolean apply(Integer input) { return input % 2 == 0; } }) .reduce(new BinaryFn<Integer, Integer, Integer>() { @Override public Integer apply(Integer current, Integer sum) { return current + sum; } }, 0); assertTrue(4 + 16 + 36 + 64 + 100 == sumOfEvenSquares); } }
package com.dominikschreiber.underscore; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; public class _Test { private Function<Integer, Integer> square = new Function<Integer, Integer>() { @Override public Integer apply(Integer input) { return input * input; } }; private Predicate<Integer> isEven = new Predicate<Integer>() { @Override public boolean test(Integer input) { return input % 2 == 0; } }; private BiFunction<Integer, Integer, Integer> sum = new BiFunction<Integer, Integer, Integer>() { @Override public Integer apply(Integer current, Integer sum) { return current + sum; } }; private BiFunction<String, String, Boolean> stringEquals = new BiFunction<String, String, Boolean>() { @Override public Boolean apply(String a, String b) { return a.equals(b); } }; private List<Integer> range(int from, int to) { List<Integer> result = new ArrayList<Integer>(to - from + 1); for (int i = from; i < to; i++) { result.add(i); } return result; } private List<Integer> range(int to) { return range(1, to); } @Test public void staticEachWithStringBuilder() { final StringBuilder result = new StringBuilder(); _.each(range(6), new Consumer<Integer>() { @Override public void accept(Integer input) { result.append(Integer.toString(input, 10)); } }); assertEquals("12345", result.toString()); } @Test public void staticEachNullInput() { _.each(null, new Consumer<Object>() { @Override public void accept(Object input) { } }); // tests pass if no exception is thrown -- no need to Assert.pass() } @Test public void chainedEachWithStringBuilder() { final StringBuilder result = new StringBuilder(); new _<>(range(6)) .each(new Consumer<Integer>() { @Override public void accept(Integer input) { result.append(Integer.toString(input, 10)); } }); assertEquals("12345", result.toString()); } @Test public void staticMapWithSquare() { List<Integer> result = _.map(range(6), square); assertEquals(_.list(1, 4, 9, 16, 25), result); } @Test public void staticMapWithNullInput() { assertEquals(Collections.emptyList(), _.map(null, square)); } @Test public void chainedMapWithSquare() { Iterable<Integer> result = new _<>(range(6)) .map(square) .value(); assertEquals(Arrays.asList(new Integer[] {1, 4, 9, 16, 25}), result); } @Test public void staticFilterWithIsEven() { List<Integer> result = _.filter(range(6), isEven); assertEquals(Arrays.asList(new Integer[] {2, 4}), result); } @Test public void staticFilterWithNullInput() { assertEquals(Collections.emptyList(), _.filter(null, isEven)); } @Test public void chainedFilterWithIsEven() { Iterable<Integer> result = new _<>(range(6)) .filter(isEven) .value(); assertEquals(_.list(2, 4), result); } @Test public void staticFindWithIsEven() { assertEquals( 2, (int) _.find(range(6), isEven) ); } @Test public void staticFindWithNullInput() { assertEquals(null, _.find(null, isEven)); } @Test public void chainedFindWithIsEven() { assertEquals( 2, (int) new _<>(range(6)).find(isEven) ); } @Test public void staticReduceWithSum() { Integer result = _.reduce(range(6), sum, 0); assertTrue(1 + 2 + 3 + 4 + 5 == result); } @Test public void staticReduceWithNullInput() { assertEquals( 5, (int) _.reduce(null, sum, 5) ); } @Test public void chainedReduceWithSum() { Integer result = new _<>(range(6)) .reduce(sum, 0); assertTrue(1 + 2 + 3 + 4 + 5 == result); } @Test public void chainedComplexWithSumOfEvenSquares() { Integer sumOfEvenSquares = new _<>(range(11)) .map(square) .filter(isEven) .reduce(sum, 0); assertTrue(4 + 16 + 36 + 64 + 100 == sumOfEvenSquares); } @Test public void staticContainsWithIntegers() { assertTrue(_.contains(range(6), 4)); assertFalse(_.contains(range(4), 6)); } @Test public void staticContainsWithNullInput() { assertFalse(_.contains(null, "foo")); } @Test public void chainedContainsWithIntegers() { assertTrue(new _<>(range(6)).contains(4)); assertFalse(new _<>(range(4)).contains(6)); } @Test public void staticContainsWithStringEquals() { assertTrue(_.contains(_.list("foo", "bar", "baz"), "foo", stringEquals)); assertFalse(_.contains(_.list("foo", "bar"), "baz", stringEquals)); } @Test public void chainedContainsWithStringEquals() { assertTrue(new _<>(_.list("foo", "bar", "baz")).contains("foo", stringEquals)); assertFalse(new _<>(_.list("foo", "bar")).contains("baz", stringEquals)); } @Test public void staticRejectWithIsEven() { assertEquals(_.list(1,3,5), _.reject(range(6), isEven)); } @Test public void staticRejectWithIsEvenWithNullInput() { assertEquals(Collections.emptyList(), _.reject(null, isEven)); } @Test public void chainedRejectWithIsEven() { assertEquals(_.list(1,3,5), new _<>(range(6)).reject(isEven).value()); } @Test public void chainedRejectWithIsEvenWithNullInput() { assertEquals(Collections.emptyList(), new _<Integer>(null).reject(isEven).value()); } @Test public void staticSize() { assertEquals(3, _.size(range(4))); } @Test public void staticSizeWithNullInput() { assertEquals(0, _.size(null)); } @Test public void chainedSize() { assertEquals(3, new _<>(range(4)).size()); } @Test public void staticFirst() { assertEquals(range(4), _.first(range(5), 3)); } @Test public void staticFirstWithNullInput() { assertEquals(Collections.emptyList(), _.first(null, 3)); } @Test public void staticFirstDefaultN() { assertEquals(range(2), _.first(range(5))); } @Test public void chainedFirst() { assertEquals(range(4),new _<>(range(5)).first(3).value()); } @Test public void chainedFirstDefaultN() { assertEquals( range(2), new _<>(range(5)).first().value() ); } @Test public void staticInitial() { assertEquals(_.list("foo"), _.initial(_.list("foo", "bar", "baz"), 2)); } @Test public void staticInitialWithNullInput() { assertEquals(Collections.emptyList(), _.initial(null, 2)); } @Test public void staticInitialDefaultN() { assertEquals(_.list("foo", "bar"), _.initial(_.list("foo", "bar", "baz"))); } @Test public void chainedInitial() { assertEquals(_.list("foo"), new _<>(_.list("foo", "bar", "baz")).initial(2).value()); } @Test public void chainedInitialDefaultN() { assertEquals(_.list("foo", "bar"), new _<>(_.list("foo", "bar", "baz")).initial().value()); } @Test public void staticLast() { assertEquals(range(4, 6), _.last(range(6), 2)); } @Test public void staticLastDefaultN() { assertEquals(range(4, 5), _.last(range(5))); } @Test public void chainedLast() { assertEquals(range(4, 6), new _<>(range(6)).last(2).value()); } @Test public void chainedLastDefaultN() { assertEquals(range(4, 5), new _<>(range(5)).last().value()); } @Test public void staticRest() { assertEquals(range(3, 5), _.rest(range(5), 2)); } @Test public void staticRestWithNullInput() { assertEquals(Collections.emptyList(), _.rest(null, 2)); } @Test public void staticRestDefaultN() { assertEquals(range(2, 5), _.rest(range(5))); } @Test public void chainedRest() { assertEquals(range(3, 5), new _<>(range(5)).rest(2).value()); } @Test public void chainedRestDefaultN() { assertEquals(range(2, 5), new _<>(range(5)).rest().value()); } @Test public void extendWithNothing() { Datastore defaults = datastore(0, 1); Datastore options = datastore(null, null); Datastore expected = datastore(defaults.a, defaults.b); try { Datastore result = _.extend(defaults, options); assertEquals(expected.a, result.a); assertEquals(expected.b, result.b); } catch (Exception e) { fail(e.getMessage()); } } @Test public void extendWithOverrides() { Datastore defaults = datastore(0, 1); Datastore options = datastore(2, 3); Datastore expected = datastore(options.a, options.b); try { Datastore result = _.extend(defaults, options); assertEquals(expected.a, result.a); assertEquals(expected.b, result.b); } catch (Exception e) { fail(e.getMessage()); } } @Test public void extendWithPartialOverrides() { Datastore defaults = datastore(0, 1); Datastore options = datastore(null, 3); Datastore expected = datastore(defaults.a, options.b); try { Datastore result = _.extend(defaults, options); assertEquals(expected.a, result.a); assertEquals(expected.b, result.b); } catch (Exception e) { fail(e.getMessage()); } } private Datastore datastore(Integer a, Integer b) { Datastore result = new Datastore(); result.a = a; result.b = b; return result; } private static class Datastore { public Integer a; public Integer b; } @Test public void extendWithPartialOverridesAndMethodsInDatastore() { MethodDatastore defaults = methodDatastore(0, 1); MethodDatastore options = methodDatastore(null, 3); MethodDatastore expected = methodDatastore(defaults.a, options.b); try { MethodDatastore result = _.extend(defaults, options); assertEquals(expected.a, result.a); assertEquals(expected.b, result.b); } catch (Exception e) { fail(e.getMessage()); } } private MethodDatastore methodDatastore(Integer a, Integer b) { MethodDatastore result = new MethodDatastore(); result.a = a; result.b = b; return result; } private static class MethodDatastore extends Datastore { public void foo() {} } @Test public void extendWithPartialOverridesAndBuilderInDatastore() { BuilderDatastore defaults = new BuilderDatastore.Builder() .setA(0) .setB(1) .build(); BuilderDatastore options = new BuilderDatastore.Builder() .setA(null) .setB(2) .build(); BuilderDatastore expected = new BuilderDatastore.Builder() .setA(defaults.a) .setB(options.b) .build(); try { BuilderDatastore result = _.extend(defaults, options); assertEquals(expected.a, result.a); assertEquals(expected.b, result.b); } catch (Exception e) { fail(e.getMessage()); } } private static class BuilderDatastore extends Datastore { public static class Builder { private BuilderDatastore store = new BuilderDatastore(); public Builder setA(Integer a) { store.a = a; return this; } public Builder setB(Integer b) { store.b = b; return this; } public BuilderDatastore build() { return store; } } } @Test public void list() { assertTrue(_.list("foo", "bar", "baz") instanceof List); assertEquals(Arrays.asList(new String[] {"foo", "bar"}), _.list(new String[] {"foo", "bar"})); } @Test public void listWithNullInput() { assertEquals(Collections.emptyList(), _.list()); } @Test public void staticJoin() { assertEquals("foo::bar", _.join(_.list("foo", "bar"), "::")); } @Test public void staticJoinDefaultSeparator() { assertEquals("foo,bar", _.join(_.list("foo", "bar"))); } @Test public void staticJoinWithNullInput() { assertEquals("", _.join(null, ",")); } @Test public void staticJoinDefaultSeparatorWithNullInput() { // need to cast -- otherwise multiple methods match _.join(null) assertEquals("", _.join((Iterable<String>) null)); } @Test public void chainedJoin() { assertEquals("foo::bar", new _<>(_.list("foo", "bar")).join("::")); } @Test public void chainedJoinDefaultSeparator() { assertEquals("foo,bar", new _<>(_.list("foo", "bar")).join()); } @Test public void chainedJoinWithNullInput() { assertEquals("", new _<>(null).join("::")); } @Test public void chainedJoinDefaultSeparatorWithNullInput() { assertEquals("", new _<>(null).join()); } }
package com.github.kratorius.jefs; import org.junit.Test; import java.util.ArrayList; import java.util.NoSuchElementException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; public class LFStackTest { class FixedValuePusherThread<E> implements Runnable { final int max; final LFStack<E> stack; final E value; public FixedValuePusherThread(LFStack<E> stack, int max, E value) { this.max = max; this.stack = stack; this.value = value; } @Override public void run() { for (int i = 0; i < max; i++) { stack.push(value); } } } class PopperThread<E> implements Runnable { final int max; final LFStack<E> stack; volatile Exception exception = null; public PopperThread(LFStack<E> stack, int max) { this.stack = stack; this.max = max; } @Override public void run() { for (int i = 0; i < max; i++) { try { stack.pop(); } catch (Exception e) { exception = e; return; } } } } @Test public void testSingleThread() { LFStack<Integer> stack = new LFStack<>(); stack.push(1); stack.push(2); stack.push(3); stack.push(4); assertFalse(stack.empty()); assertEquals(4, (int) stack.peek()); assertEquals(4, (int) stack.pop()); assertEquals(3, (int) stack.peek()); assertEquals(3, (int) stack.pop()); assertEquals(2, (int) stack.peek()); assertEquals(2, (int) stack.pop()); assertEquals(1, (int) stack.peek()); assertEquals(1, (int) stack.pop()); assertTrue(stack.empty()); } @Test(expected = NoSuchElementException.class) public void testEmptyStack_peek() { LFStack<Integer> stack = new LFStack<>(); stack.peek(); } @Test(expected = NoSuchElementException.class) public void testEmptyStack_pop() { LFStack<Integer> stack = new LFStack<>(); stack.pop(); } @Test public void testAddAndRemove() { LFStack<String> stack = new LFStack<>(); assertTrue(stack.add("test1")); assertTrue(stack.add("test2")); assertEquals("test2", stack.remove()); assertEquals("test1", stack.remove()); assertNull(stack.remove()); } @Test public void testPush_asManyThreadsAsCores() throws InterruptedException { int logicalCores = Runtime.getRuntime().availableProcessors(); ArrayList<Thread> threads = new ArrayList<>(logicalCores); LFStack<Integer> stack = new LFStack<>(); for (int i = 0; i < logicalCores; i++) { threads.add(new Thread(new FixedValuePusherThread<>(stack, 1000000, 42))); } for (Thread t : threads) { t.start(); } for (Thread t : threads) { t.join(); } assertFalse(stack.empty()); assertEquals(logicalCores * 1000000, stack.size()); for (int i = 0; i < logicalCores * 1000000; i++) { stack.pop(); } assertTrue(stack.empty()); } @Test public void testPop_asManyThreadsAsCores() throws Exception { int logicalCores = Runtime.getRuntime().availableProcessors(); ArrayList<PopperThread<Integer>> poppers = new ArrayList<>(logicalCores); ArrayList<Thread> threads = new ArrayList<>(logicalCores); LFStack<Integer> stack = new LFStack<>(); for (int i = 0; i < logicalCores * 1000000; i++) { stack.push(i); } for (int i = 0; i < logicalCores; i++) { PopperThread<Integer> popper = new PopperThread<>(stack, 1000000); poppers.add(popper); threads.add(new Thread(popper)); } for (Thread t : threads) { t.start(); } for (Thread t : threads) { t.join(); } for (PopperThread p : poppers) { if (p.exception != null) { throw p.exception; } } assertTrue(stack.empty()); } }
package com.hearthsim.test; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import org.junit.Before; import org.junit.Test; import com.hearthsim.card.Card; import com.hearthsim.card.minion.Minion; import com.hearthsim.card.minion.concrete.KoboldGeomancer; import com.hearthsim.card.spellcard.concrete.ArcaneExplosion; import com.hearthsim.card.spellcard.concrete.Consecration; import com.hearthsim.card.spellcard.concrete.Hellfire; import com.hearthsim.exception.HSException; import com.hearthsim.model.BoardModel; import com.hearthsim.model.PlayerSide; import com.hearthsim.util.tree.HearthTreeNode; public class TestSpellDamageAoe { private HearthTreeNode board; private static final byte mana = 2; private static final byte attack0 = 2; private static final byte health0 = 5; private static final byte health1 = 1; @Before public void setup() throws HSException { board = new HearthTreeNode(new BoardModel()); Minion minion0 = new Minion("" + 0, mana, attack0, health0, attack0, health0, health0); Minion minion1 = new Minion("" + 0, mana, attack0, health0, attack0, health0, health0); Minion minion2 = new Minion("" + 0, mana, attack0, health1, attack0, health1, health1); Minion minion3 = new Minion("" + 0, mana, attack0, health0, attack0, health0, health0); ArcaneExplosion fb = new ArcaneExplosion(); board.data_.placeCardHandCurrentPlayer(fb); board.data_.placeMinion(PlayerSide.CURRENT_PLAYER, minion0); board.data_.placeMinion(PlayerSide.WAITING_PLAYER, minion1); board.data_.placeMinion(PlayerSide.WAITING_PLAYER, minion2); board.data_.placeMinion(PlayerSide.WAITING_PLAYER, minion3); board.data_.getCurrentPlayer().setMana(3); } @Test public void testHitsEnemyMinions() throws HSException { Minion target = board.data_.getCharacter(PlayerSide.WAITING_PLAYER, 0); // Opponent hero Card theCard = board.data_.getCurrentPlayerCardHand(0); HearthTreeNode ret = theCard.useOn(PlayerSide.WAITING_PLAYER, target, board, null, null); assertEquals(board, ret); assertEquals(board.data_.getCurrentPlayer().getMana(), 1); assertEquals(board.data_.getNumCards_hand(), 0); assertEquals(board.data_.getCurrentPlayerHero().getHealth(), 30); assertEquals(board.data_.getWaitingPlayerHero().getHealth(), 30); assertEquals(board.data_.getCurrentPlayer().getNumMinions(), 1); assertEquals(board.data_.getWaitingPlayer().getNumMinions(), 2); assertEquals(board.data_.getCurrentPlayer().getMinions().get(0).getHealth(), health0); assertEquals(board.data_.getCurrentPlayer().getMinions().get(0).getTotalAttack(), attack0); assertEquals(board.data_.getWaitingPlayer().getMinions().get(0).getHealth(), health0 - 1); assertEquals(board.data_.getWaitingPlayer().getMinions().get(0).getTotalAttack(), attack0); assertEquals(board.data_.getWaitingPlayer().getMinions().get(1).getHealth(), health0 - 1); assertEquals(board.data_.getWaitingPlayer().getMinions().get(1).getTotalAttack(), attack0); } @Test public void testHitsEnemyCharacters() throws HSException { Consecration consecration = new Consecration(); board.data_.placeCardHandCurrentPlayer(consecration); board.data_.getCurrentPlayer().setMana(5); Minion target = board.data_.getCharacter(PlayerSide.WAITING_PLAYER, 0); // Opponent hero Card theCard = board.data_.getCurrentPlayerCardHand(1); HearthTreeNode ret = theCard.useOn(PlayerSide.WAITING_PLAYER, target, board, null, null); assertEquals(board, ret); assertEquals(board.data_.getCurrentPlayer().getMana(), 1); assertEquals(board.data_.getNumCards_hand(), 1); assertEquals(board.data_.getCurrentPlayerHero().getHealth(), 30); assertEquals(board.data_.getWaitingPlayerHero().getHealth(), 28); assertEquals(board.data_.getCurrentPlayer().getNumMinions(), 1); assertEquals(board.data_.getWaitingPlayer().getNumMinions(), 2); assertEquals(board.data_.getCurrentPlayer().getMinions().get(0).getHealth(), health0); assertEquals(board.data_.getCurrentPlayer().getMinions().get(0).getTotalAttack(), attack0); assertEquals(board.data_.getWaitingPlayer().getMinions().get(0).getHealth(), health0 - 2); assertEquals(board.data_.getWaitingPlayer().getMinions().get(0).getTotalAttack(), attack0); assertEquals(board.data_.getWaitingPlayer().getMinions().get(1).getHealth(), health0 - 2); assertEquals(board.data_.getWaitingPlayer().getMinions().get(1).getTotalAttack(), attack0); } @Test public void testHitsAllCharacters() throws HSException { Hellfire hellfire = new Hellfire(); board.data_.placeCardHandCurrentPlayer(hellfire); board.data_.getCurrentPlayer().setMana(5); Minion target = board.data_.getCharacter(PlayerSide.WAITING_PLAYER, 0); // Opponent hero Card theCard = board.data_.getCurrentPlayerCardHand(1); HearthTreeNode ret = theCard.useOn(PlayerSide.WAITING_PLAYER, target, board, null, null); assertEquals(board, ret); assertEquals(board.data_.getCurrentPlayer().getMana(), 1); assertEquals(board.data_.getNumCards_hand(), 1); assertEquals(board.data_.getCurrentPlayerHero().getHealth(), 27); assertEquals(board.data_.getWaitingPlayerHero().getHealth(), 27); assertEquals(board.data_.getCurrentPlayer().getNumMinions(), 1); assertEquals(board.data_.getWaitingPlayer().getNumMinions(), 2); assertEquals(board.data_.getCurrentPlayer().getMinions().get(0).getHealth(), health0 - 3); assertEquals(board.data_.getCurrentPlayer().getMinions().get(0).getTotalAttack(), attack0); assertEquals(board.data_.getWaitingPlayer().getMinions().get(0).getHealth(), health0 - 3); assertEquals(board.data_.getWaitingPlayer().getMinions().get(0).getTotalAttack(), attack0); assertEquals(board.data_.getWaitingPlayer().getMinions().get(1).getHealth(), health0 - 3); assertEquals(board.data_.getWaitingPlayer().getMinions().get(1).getTotalAttack(), attack0); } @Test public void testSpellpower() throws HSException { Minion kobold = new KoboldGeomancer(); board.data_.placeMinion(PlayerSide.CURRENT_PLAYER, kobold); Minion target = board.data_.getCharacter(PlayerSide.WAITING_PLAYER, 0); // Opponent hero Card theCard = board.data_.getCurrentPlayerCardHand(0); HearthTreeNode ret = theCard.useOn(PlayerSide.WAITING_PLAYER, target, board, null, null); assertEquals(board, ret); assertEquals(board.data_.getCurrentPlayer().getMana(), 1); assertEquals(board.data_.getNumCards_hand(), 0); assertEquals(board.data_.getCurrentPlayerHero().getHealth(), 30); assertEquals(board.data_.getWaitingPlayerHero().getHealth(), 30); assertEquals(board.data_.getCurrentPlayer().getNumMinions(), 2); assertEquals(board.data_.getWaitingPlayer().getNumMinions(), 2); assertEquals(board.data_.getCurrentPlayer().getMinions().get(0).getHealth(), health0); assertEquals(board.data_.getCurrentPlayer().getMinions().get(0).getTotalAttack(), attack0); assertEquals(board.data_.getWaitingPlayer().getMinions().get(0).getHealth(), health0 - 2); assertEquals(board.data_.getWaitingPlayer().getMinions().get(0).getTotalAttack(), attack0); assertEquals(board.data_.getWaitingPlayer().getMinions().get(1).getHealth(), health0 - 2); assertEquals(board.data_.getWaitingPlayer().getMinions().get(1).getTotalAttack(), attack0); } @Test public void testCannotTargetOpponentMinion() throws HSException { Minion target = board.data_.getCharacter(PlayerSide.WAITING_PLAYER, 1); Card theCard = board.data_.getCurrentPlayerCardHand(0); HearthTreeNode ret = theCard.useOn(PlayerSide.WAITING_PLAYER, target, board, null, null); assertNull(ret); assertEquals(board.data_.getNumCards_hand(), 1); assertEquals(board.data_.getCurrentPlayer().getMana(), 3); assertEquals(board.data_.getCurrentPlayer().getNumMinions(), 1); assertEquals(board.data_.getWaitingPlayer().getNumMinions(), 3); assertEquals(board.data_.getCurrentPlayer().getMinions().get(0).getHealth(), health0); assertEquals(board.data_.getCurrentPlayer().getMinions().get(0).getTotalAttack(), attack0); assertEquals(board.data_.getWaitingPlayer().getMinions().get(0).getHealth(), health0); assertEquals(board.data_.getWaitingPlayer().getMinions().get(0).getTotalAttack(), attack0); assertEquals(board.data_.getWaitingPlayer().getMinions().get(1).getHealth(), health1); assertEquals(board.data_.getWaitingPlayer().getMinions().get(1).getTotalAttack(), attack0); assertEquals(board.data_.getWaitingPlayer().getMinions().get(2).getHealth(), health0); assertEquals(board.data_.getWaitingPlayer().getMinions().get(2).getTotalAttack(), attack0); } @Test public void testCannotTargetSelf() throws HSException { Minion target = board.data_.getCharacter(PlayerSide.CURRENT_PLAYER, 0); // Self Card theCard = board.data_.getCurrentPlayerCardHand(0); HearthTreeNode ret = theCard.useOn(PlayerSide.CURRENT_PLAYER, target, board, null, null); assertNull(ret); assertEquals(board.data_.getNumCards_hand(), 1); assertEquals(board.data_.getCurrentPlayer().getMana(), 3); assertEquals(board.data_.getCurrentPlayer().getNumMinions(), 1); assertEquals(board.data_.getWaitingPlayer().getNumMinions(), 3); assertEquals(board.data_.getCurrentPlayer().getMinions().get(0).getHealth(), health0); assertEquals(board.data_.getCurrentPlayer().getMinions().get(0).getTotalAttack(), attack0); assertEquals(board.data_.getWaitingPlayer().getMinions().get(0).getHealth(), health0); assertEquals(board.data_.getWaitingPlayer().getMinions().get(0).getTotalAttack(), attack0); assertEquals(board.data_.getWaitingPlayer().getMinions().get(1).getHealth(), health1); assertEquals(board.data_.getWaitingPlayer().getMinions().get(1).getTotalAttack(), attack0); assertEquals(board.data_.getWaitingPlayer().getMinions().get(2).getHealth(), health0); assertEquals(board.data_.getWaitingPlayer().getMinions().get(2).getTotalAttack(), attack0); } @Test public void testCannotTargetMinion() throws HSException { Minion target = board.data_.getCharacter(PlayerSide.CURRENT_PLAYER, 1); Card theCard = board.data_.getCurrentPlayerCardHand(0); HearthTreeNode ret = theCard.useOn(PlayerSide.CURRENT_PLAYER, target, board, null, null); assertNull(ret); assertEquals(board.data_.getNumCards_hand(), 1); assertEquals(board.data_.getCurrentPlayer().getMana(), 3); assertEquals(board.data_.getCurrentPlayer().getNumMinions(), 1); assertEquals(board.data_.getWaitingPlayer().getNumMinions(), 3); assertEquals(board.data_.getCurrentPlayer().getMinions().get(0).getHealth(), health0); assertEquals(board.data_.getCurrentPlayer().getMinions().get(0).getTotalAttack(), attack0); assertEquals(board.data_.getWaitingPlayer().getMinions().get(0).getHealth(), health0); assertEquals(board.data_.getWaitingPlayer().getMinions().get(0).getTotalAttack(), attack0); assertEquals(board.data_.getWaitingPlayer().getMinions().get(1).getHealth(), health1); assertEquals(board.data_.getWaitingPlayer().getMinions().get(1).getTotalAttack(), attack0); assertEquals(board.data_.getWaitingPlayer().getMinions().get(2).getHealth(), health0); assertEquals(board.data_.getWaitingPlayer().getMinions().get(2).getTotalAttack(), attack0); } @Test public void testCannotReuse() throws HSException { Minion target = board.data_.getCharacter(PlayerSide.CURRENT_PLAYER, 1); Card theCard = board.data_.getCurrentPlayerCardHand(0); theCard.hasBeenUsed(true); HearthTreeNode ret = theCard.useOn(PlayerSide.CURRENT_PLAYER, target, board, null, null); assertNull(ret); assertEquals(board.data_.getNumCards_hand(), 1); assertEquals(board.data_.getCurrentPlayer().getMana(), 3); } }
package com.thankjava.wqq.test.qq; import com.thankjava.toolkit3d.fastjson.FastJson; import com.thankjava.wqq.SmartQQClient; import com.thankjava.wqq.SmartQQClientBuilder; import com.thankjava.wqq.entity.enums.LoginResultStatus; import com.thankjava.wqq.entity.sys.LoginResult; import com.thankjava.wqq.extend.ActionListener; import com.thankjava.wqq.extend.CallBackListener; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; /** * SmartQQClient version >= 1.1.x * * @author acexy */ public class TestSmartQQ { private static final Logger logger = LoggerFactory.getLogger(TestSmartQQ.class); public static void main(String[] args) { /** * step 1 > SmartQQClientBuilderSmartQQClient */ SmartQQClientBuilder builder = SmartQQClientBuilder.custom( // SmartQQClient new MessageListener() ); /** * step 2 > (set) */ builder .setAutoGetInfoAfterLogin() .setExceptionRetryMaxTimes(3) .setAutoRefreshQrcode() // .setOffLineListener(new CallBackListener() { // // @Override // public void onListener(ActionListener actionListener) { // logger.info("QQ()"); ; /** * step 3 > create SmartQQClient */ // A: byte CallBackListener getQrListener = new CallBackListener() { // login CallBackListener // byte[] ListenerAction.data @Override public void onListener(ActionListener actionListener) { try { // byte[]iopng // log/qrcode.png ImageIO.write((BufferedImage) actionListener.getData(), "png", new File("./log/qrcode.png")); logger.debug(",QQ ./log/qrcode.png "); } catch (Exception e) { logger.error("byte[]", e); } } }; CallBackListener loginListener = new CallBackListener() { // ListenerAction.data com.thankjava.wqq.entity.sys.LoginResult @Override public void onListener(ActionListener actionListener) { LoginResult loginResult = (LoginResult) actionListener.getData(); logger.info(": " + loginResult.getLoginStatus()); if (loginResult.getLoginStatus() == LoginResultStatus.success) { SmartQQClient smartQQClient = loginResult.getClient(); // TODO: smartQQClientAPI logger.info(": " + FastJson.toJSONString(smartQQClient.getFriendsList(true))); // TODO: } } }; builder.createAndLogin(getQrListener, loginListener); } }
package lombok.website; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.URL; import java.util.regex.Matcher; import java.util.regex.Pattern; public class FetchCurrentVersion { private FetchCurrentVersion() {} private static final Pattern VERSION_PATTERN = Pattern.compile("^.*<\\s*span\\s+id\\s*=\\s*[\"'](currentVersion|currentVersionFull)[\"'](?:\\s+style\\s*=\\s*[\"']display\\s*:\\s*none;?[\"'])?\\s*>\\s*([^\t<]+)\\s*<\\s*/\\s*span\\s*>.*$"); public static void main(String[] args) throws IOException { System.out.print(fetchVersionFromSite(args.length == 0 || args[0].equals("full"))); } public static String fetchVersionFromSite(boolean fetchFull) throws IOException { InputStream in = new URL("https://projectlombok.org/download").openStream(); try { BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8")); for (String line = br.readLine(); line != null; line = br.readLine()) { Matcher m = VERSION_PATTERN.matcher(line); if (m.matches() && m.group(1).equals("currentVersionFull") == fetchFull) return m.group(2).replace("&quot;", "\""); } throw new IOException("Expected a span with id 'currentVersion'"); } finally { in.close(); } } }
package info.javaspec.runner; import de.bechte.junit.runners.context.HierarchicalContextRunner; import info.javaspecproto.ContextClasses; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.junit.runner.Description; import org.junit.runner.RunWith; import org.junit.runner.notification.RunNotifier; import org.mockito.Mockito; import static com.google.common.collect.Lists.newArrayList; import static com.google.common.collect.Sets.newHashSet; import static info.javaspec.runner.Descriptions.isSuiteDescription; import static info.javaspec.runner.Descriptions.isTestDescription; import static org.hamcrest.Matchers.contains; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.not; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.mock; @RunWith(HierarchicalContextRunner.class) public class ClassContextTest { private ClassContext subject; public class getDescription { private Description returned; public class givenNoSpecsOrSubContexts { @Test public void hasNoChildren() throws Exception { subject = AClassContext.of(ContextClasses.Empty.class); returned = subject.getDescription(); assertThat(returned.getChildren(), equalTo(newArrayList())); } } public class givenAContextClassWithSpecsOrSubContexts { @Before public void setup() throws Exception { subject = AClassContext.of(ContextClasses.OneIt.class); returned = subject.getDescription(); } @Test public void returnsASuiteDescription() throws Exception { assertThat(returned, isSuiteDescription()); } @Test public void namesTheRootDescriptionWithTheSimpleNameOfTheRootContextClass() throws Exception { assertThat(returned.getDisplayName(), equalTo("OneIt")); } } public class givenAContextClassWithSpecs { @Test public void hasTestDescriptionsForEachSpecInTheContext() throws Exception { subject = AClassContext.of(ContextClasses.TwoIts.class); returned = subject.getDescription(); assertThat(Descriptions.childMethodNames(returned), equalTo(newHashSet("one", "two"))); assertThat(returned.getChildren(), contains(isTestDescription(), isTestDescription())); } @Test public void setsTheDescriptionClassNameToThatOfTheParentContext() throws Exception { subject = AClassContext.of(ContextClasses.UnderscoreSubContext.class); returned = subject.getDescription(); assertThat(Descriptions.onlyTest(returned).getClassName(), equalTo("read me")); } @Test public void setsTheDescriptionMethodNameToTheHumanizedFieldName() throws Exception { subject = AClassContext.of(ContextClasses.UnderscoreIt.class); returned = subject.getDescription(); assertThat(Descriptions.childMethodNames(returned), equalTo(newHashSet("read me"))); } //Two specs can have the same field name, if they are declared in different parts of the hierarchy. //This is a problem for test Descriptions if the identically-named fields are also in identically-named classes. @Test public void identifiesTestDescriptionsByTheFullyQualifiedFieldName() throws Exception { subject = AClassContext.of(ContextClasses.DuplicateSpecNames.class); returned = subject.getDescription(); Description leftLeaf = Descriptions.onlyTest(returned.getChildren().get(0)); Description rightLeaf = Descriptions.onlyTest(returned.getChildren().get(1)); assertThat(leftLeaf, not(equalTo(rightLeaf))); } } public class givenAContextClassWithSubContextClasses { @Test public void hasSuiteDescriptionsForEachSubContextClass() throws Exception { subject = AClassContext.of(ContextClasses.TwoContexts.class); returned = subject.getDescription(); assertThat(Descriptions.childClassNames(returned), equalTo(newHashSet("subcontext1", "subcontext2"))); assertThat(returned.getChildren(), contains(isSuiteDescription(), isSuiteDescription())); } @Test public void humanizesSubContextClassNamesIntoHumanReadableClassNames_replacingUnderscoreWithSpace() throws Exception { subject = AClassContext.of(ContextClasses.UnderscoreSubContext.class); returned = subject.getDescription(); assertThat(Descriptions.childClassNames(returned), equalTo(newHashSet("read me"))); } //Two context classes in different parts of the hierarchy can have the same simple name. //Make sure something unique is used for each Suite Description fUniqueId. @Test public void identifiesSuiteDescriptionsWithTheFullyQualifiedClassName() throws Exception { subject = AClassContext.of(ContextClasses.DuplicateContextNames.class); returned = subject.getDescription(); Description leftLeaf = Descriptions.onlyChild(returned.getChildren().get(0)); Description rightLeaf = Descriptions.onlyChild(returned.getChildren().get(1)); assertThat(leftLeaf, not(equalTo(rightLeaf))); } } } public class hasSpecs { @Test public void givenAClassWithoutAnySpecs_returns_false() throws Exception { subject = AClassContext.of(ContextClasses.Empty.class); assertThat(subject.hasSpecs(), equalTo(false)); } @Test public void givenAClassWithSpecs_returns_true() throws Exception { subject = AClassContext.of(ContextClasses.OneIt.class); assertThat(subject.hasSpecs(), equalTo(true)); } @Test public void givenAClassWhereASubContextHasSpecs_returns_true() throws Exception { subject = AClassContext.of(ContextClasses.NestedIt.class); assertThat(subject.hasSpecs(), equalTo(true)); } } public class numSpecs { @Test public void givenNoSpecsOrChildContexts_returns_0() throws Exception { subject = AClassContext.of(ContextClasses.Empty.class); assertThat(subject.numSpecs(), equalTo(0L)); } @Test public void givenAClassWith1OrMoreSpecs_countsThoseSpecs() throws Exception { subject = AClassContext.of(ContextClasses.TwoIt.class); assertThat(subject.numSpecs(), equalTo(2L)); } @Test public void givenAClassWithSubContexts_sumsSpecsInThoseClasses() throws Exception { subject = AClassContext.of(ContextClasses.NestedContexts.class); assertThat(subject.numSpecs(), equalTo(2L)); } } public class run { private final RunNotifier notifier = mock(RunNotifier.class); @Test @Ignore public void createsSpecsWithContextFields() throws Exception {} public class given1OrMoreSpecs { @Test public void runsEachSpec() throws Exception { Spec firstChild = MockSpec.anyValid(); Spec secondChild = MockSpec.anyValid(); subject = AClassContext.withSpecs(firstChild, secondChild); subject.run(notifier); Mockito.verify(firstChild).run(); Mockito.verify(secondChild).run(); } } public class given1OrMoreSubContexts { @Test public void runsEachSubContext() throws Exception { Context firstChild = info.javaspec.runner.MockContext.anyValid(); Context secondChild = info.javaspec.runner.MockContext.anyValid(); subject = AClassContext.withSubContexts(firstChild, secondChild); subject.run(notifier); Mockito.verify(firstChild).run(notifier); Mockito.verify(secondChild).run(notifier); } } public class givenAContextWithAnEstablishField { @Test public void createsSpecsWithThatAsABeforeEachFixtureLambda() throws Exception { assertThat("pending", equalTo("passing")); } } public class givenAContextWithABecauseField { @Test @Ignore public void createsSpecsWithThatAsABeforeEachFixtureLambda() throws Exception {} } public class givenAContextWithACleanupField { @Test @Ignore public void createsSpecsWithThatAsAnAfterEachFixtureLambda() throws Exception {} } public class whenASpecPasses { @Test @Ignore public void notifiesTestSuccess() throws Exception {} } public class whenASpecThrowsAnything { @Test @Ignore public void runsRemainingSpecs() throws Exception {} } public class whenASpecThrowsTestSetupFailed { @Test @Ignore public void notifiesTestError() throws Exception {} } public class whenASpecThrowsAnythingElse { @Test @Ignore public void notifiesTestFailure() throws Exception {} } } @Test public void aSpecIs_anNonStaticItField() throws Exception { subject = AClassContext.of(ContextClasses.StaticIt.class); assertThat(subject.numSpecs(), equalTo(0L)); } @Test public void aSubContextIs_aNonStaticInnerClass() throws Exception { subject = AClassContext.of(ContextClasses.NestedStaticClassIt.class); assertThat(subject.numSpecs(), equalTo(0L)); } private static final class AClassContext { public static ClassContext of(Class<?> source) { return ClassContext.createRootContext(source); } public static ClassContext withSpecs(Spec... specs) { return new ClassContext("withSpecs", "withSpecs", newArrayList(specs), newArrayList()); } public static ClassContext withSubContexts(Context... subContexts) { return new ClassContext("withSubContexts", "withSubContexts", newArrayList(), newArrayList(subContexts)); } } }
package net.imagej.ops.math; import net.imagej.ops.AbstractNamespaceTest; import net.imagej.ops.MathOps.Abs; import net.imagej.ops.MathOps.Add; import net.imagej.ops.MathOps.AddNoise; import net.imagej.ops.MathOps.And; import net.imagej.ops.MathOps.Arccos; import net.imagej.ops.MathOps.Arccosh; import net.imagej.ops.MathOps.Arccot; import net.imagej.ops.MathOps.Arccoth; import net.imagej.ops.MathOps.Arccsc; import net.imagej.ops.MathOps.Arccsch; import net.imagej.ops.MathOps.Arcsec; import net.imagej.ops.MathOps.Arcsech; import net.imagej.ops.MathOps.Arcsin; import net.imagej.ops.MathOps.Arcsinh; import net.imagej.ops.MathOps.Arctan; import net.imagej.ops.MathOps.Arctanh; import net.imagej.ops.MathOps.Ceil; import net.imagej.ops.MathOps.Complement; import net.imagej.ops.MathOps.Copy; import net.imagej.ops.MathOps.Cos; import net.imagej.ops.MathOps.Cosh; import net.imagej.ops.MathOps.Cot; import net.imagej.ops.MathOps.Coth; import net.imagej.ops.MathOps.Csc; import net.imagej.ops.MathOps.Csch; import net.imagej.ops.MathOps.CubeRoot; import net.imagej.ops.MathOps.Divide; import net.imagej.ops.MathOps.Exp; import net.imagej.ops.MathOps.ExpMinusOne; import net.imagej.ops.MathOps.Floor; import net.imagej.ops.MathOps.Gamma; import net.imagej.ops.MathOps.GaussianRandom; import net.imagej.ops.MathOps.Invert; import net.imagej.ops.MathOps.LeftShift; import net.imagej.ops.MathOps.Log; import net.imagej.ops.MathOps.Log10; import net.imagej.ops.MathOps.Log2; import net.imagej.ops.MathOps.LogOnePlusX; import net.imagej.ops.MathOps.Max; import net.imagej.ops.MathOps.Min; import net.imagej.ops.MathOps.Multiply; import net.imagej.ops.MathOps.NearestInt; import net.imagej.ops.MathOps.Negate; import net.imagej.ops.MathOps.Or; import net.imagej.ops.MathOps.Power; import net.imagej.ops.MathOps.Reciprocal; import net.imagej.ops.MathOps.Remainder; import net.imagej.ops.MathOps.RightShift; import net.imagej.ops.MathOps.Round; import net.imagej.ops.MathOps.Sec; import net.imagej.ops.MathOps.Sech; import net.imagej.ops.MathOps.Signum; import net.imagej.ops.MathOps.Sin; import net.imagej.ops.MathOps.Sinc; import net.imagej.ops.MathOps.SincPi; import net.imagej.ops.MathOps.Sinh; import net.imagej.ops.MathOps.Sqr; import net.imagej.ops.MathOps.Sqrt; import net.imagej.ops.MathOps.Step; import net.imagej.ops.MathOps.Subtract; import net.imagej.ops.MathOps.Tan; import net.imagej.ops.MathOps.Tanh; import org.junit.Test; /** * Tests that the ops of the math namespace have corresponding type-safe Java * method signatures declared in the {@link MathNamespace} class. * * @author Curtis Rueden */ public class MathNamespaceTest extends AbstractNamespaceTest { /** Tests for {@link Abs} method convergence. */ @Test public void testAbs() { assertComplete("math", MathNamespace.class, Abs.NAME); } /** Tests for {@link Add} method convergence. */ @Test public void testAdd() { assertComplete("math", MathNamespace.class, Add.NAME); } /** Tests for {@link AddNoise} method convergence. */ @Test public void testAddNoise() { assertComplete("math", MathNamespace.class, AddNoise.NAME); } /** Tests for {@link And} method convergence. */ @Test public void testAnd() { assertComplete("math", MathNamespace.class, And.NAME); } /** Tests for {@link Arccos} method convergence. */ @Test public void testArccos() { assertComplete("math", MathNamespace.class, Arccos.NAME); } /** Tests for {@link Arccosh} method convergence. */ @Test public void testArccosh() { assertComplete("math", MathNamespace.class, Arccosh.NAME); } /** Tests for {@link Arccot} method convergence. */ @Test public void testArccot() { assertComplete("math", MathNamespace.class, Arccot.NAME); } /** Tests for {@link Arccoth} method convergence. */ @Test public void testArccoth() { assertComplete("math", MathNamespace.class, Arccoth.NAME); } /** Tests for {@link Arccsc} method convergence. */ @Test public void testArccsc() { assertComplete("math", MathNamespace.class, Arccsc.NAME); } /** Tests for {@link Arccsch} method convergence. */ @Test public void testArccsch() { assertComplete("math", MathNamespace.class, Arccsch.NAME); } /** Tests for {@link Arcsec} method convergence. */ @Test public void testArcsec() { assertComplete("math", MathNamespace.class, Arcsec.NAME); } /** Tests for {@link Arcsech} method convergence. */ @Test public void testArcsech() { assertComplete("math", MathNamespace.class, Arcsech.NAME); } /** Tests for {@link Arcsin} method convergence. */ @Test public void testArcsin() { assertComplete("math", MathNamespace.class, Arcsin.NAME); } /** Tests for {@link Arcsinh} method convergence. */ @Test public void testArcsinh() { assertComplete("math", MathNamespace.class, Arcsinh.NAME); } /** Tests for {@link Arctan} method convergence. */ @Test public void testArctan() { assertComplete("math", MathNamespace.class, Arctan.NAME); } /** Tests for {@link Arctanh} method convergence. */ @Test public void testArctanh() { assertComplete("math", MathNamespace.class, Arctanh.NAME); } /** Tests for {@link Ceil} method convergence. */ @Test public void testCeil() { assertComplete("math", MathNamespace.class, Ceil.NAME); } /** Tests for {@link Complement} method convergence. */ @Test public void testComplement() { assertComplete("math", MathNamespace.class, Complement.NAME); } /** Tests for {@link Copy} method convergence. */ @Test public void testCopy() { assertComplete("math", MathNamespace.class, Copy.NAME); } /** Tests for {@link Cos} method convergence. */ @Test public void testCos() { assertComplete("math", MathNamespace.class, Cos.NAME); } /** Tests for {@link Cosh} method convergence. */ @Test public void testCosh() { assertComplete("math", MathNamespace.class, Cosh.NAME); } /** Tests for {@link Cot} method convergence. */ @Test public void testCot() { assertComplete("math", MathNamespace.class, Cot.NAME); } /** Tests for {@link Coth} method convergence. */ @Test public void testCoth() { assertComplete("math", MathNamespace.class, Coth.NAME); } /** Tests for {@link Csc} method convergence. */ @Test public void testCsc() { assertComplete("math", MathNamespace.class, Csc.NAME); } /** Tests for {@link Csch} method convergence. */ @Test public void testCsch() { assertComplete("math", MathNamespace.class, Csch.NAME); } /** Tests for {@link CubeRoot} method convergence. */ @Test public void testCubeRoot() { assertComplete("math", MathNamespace.class, CubeRoot.NAME); } /** Tests for {@link Divide} method convergence. */ @Test public void testDivide() { assertComplete("math", MathNamespace.class, Divide.NAME); } /** Tests for {@link Exp} method convergence. */ @Test public void testExp() { assertComplete("math", MathNamespace.class, Exp.NAME); } /** Tests for {@link ExpMinusOne} method convergence. */ @Test public void testExpMinusOne() { assertComplete("math", MathNamespace.class, ExpMinusOne.NAME); } /** Tests for {@link Floor} method convergence. */ @Test public void testFloor() { assertComplete("math", MathNamespace.class, Floor.NAME); } /** Tests for {@link Gamma} method convergence. */ @Test public void testGamma() { assertComplete("math", MathNamespace.class, Gamma.NAME); } /** Tests for {@link GaussianRandom} method convergence. */ @Test public void testGaussianRandom() { assertComplete("math", MathNamespace.class, GaussianRandom.NAME); } /** Tests for {@link Invert} method convergence. */ @Test public void testInvert() { assertComplete("math", MathNamespace.class, Invert.NAME); } /** Tests for {@link LeftShift} method convergence. */ @Test public void testLeftShift() { assertComplete("math", MathNamespace.class, LeftShift.NAME); } /** Tests for {@link Log} method convergence. */ @Test public void testLog() { assertComplete("math", MathNamespace.class, Log.NAME); } /** Tests for {@link Log2} method convergence. */ @Test public void testLog2() { assertComplete("math", MathNamespace.class, Log2.NAME); } /** Tests for {@link Log10} method convergence. */ @Test public void testLog10() { assertComplete("math", MathNamespace.class, Log10.NAME); } /** Tests for {@link LogOnePlusX} method convergence. */ @Test public void testLogOnePlusX() { assertComplete("math", MathNamespace.class, LogOnePlusX.NAME); } /** Tests for {@link Max} method convergence. */ @Test public void testMax() { assertComplete("math", MathNamespace.class, Max.NAME); } /** Tests for {@link Min} method convergence. */ @Test public void testMin() { assertComplete("math", MathNamespace.class, Min.NAME); } /** Tests for {@link Multiply} method convergence. */ @Test public void testMultiply() { assertComplete("math", MathNamespace.class, Multiply.NAME); } /** Tests for {@link NearestInt} method convergence. */ @Test public void testNearestInt() { assertComplete("math", MathNamespace.class, NearestInt.NAME); } /** Tests for {@link Negate} method convergence. */ @Test public void testNegate() { assertComplete("math", MathNamespace.class, Negate.NAME); } /** Tests for {@link Or} method convergence. */ @Test public void testOr() { assertComplete("math", MathNamespace.class, Or.NAME); } /** Tests for {@link Power} method convergence. */ @Test public void testPower() { assertComplete("math", MathNamespace.class, Power.NAME); } /** Tests for {@link Reciprocal} method convergence. */ @Test public void testReciprocal() { assertComplete("math", MathNamespace.class, Reciprocal.NAME); } /** Tests for {@link Remainder} method convergence. */ @Test public void testRemainder() { assertComplete("math", MathNamespace.class, Remainder.NAME); } /** Tests for {@link RightShift} method convergence. */ @Test public void testRightShift() { assertComplete("math", MathNamespace.class, RightShift.NAME); } /** Tests for {@link Round} method convergence. */ @Test public void testRound() { assertComplete("math", MathNamespace.class, Round.NAME); } /** Tests for {@link Sec} method convergence. */ @Test public void testSec() { assertComplete("math", MathNamespace.class, Sec.NAME); } /** Tests for {@link Sech} method convergence. */ @Test public void testSech() { assertComplete("math", MathNamespace.class, Sech.NAME); } /** Tests for {@link Signum} method convergence. */ @Test public void testSignum() { assertComplete("math", MathNamespace.class, Signum.NAME); } /** Tests for {@link Sin} method convergence. */ @Test public void testSin() { assertComplete("math", MathNamespace.class, Sin.NAME); } /** Tests for {@link Sinc} method convergence. */ @Test public void testSinc() { assertComplete("math", MathNamespace.class, Sinc.NAME); } /** Tests for {@link SincPi} method convergence. */ @Test public void testSincPi() { assertComplete("math", MathNamespace.class, SincPi.NAME); } /** Tests for {@link Sinh} method convergence. */ @Test public void testSinh() { assertComplete("math", MathNamespace.class, Sinh.NAME); } /** Tests for {@link Sqr} method convergence. */ @Test public void testSqr() { assertComplete("math", MathNamespace.class, Sqr.NAME); } /** Tests for {@link Sqrt} method convergence. */ @Test public void testSqrt() { assertComplete("math", MathNamespace.class, Sqrt.NAME); } /** Tests for {@link Step} method convergence. */ @Test public void testStep() { assertComplete("math", MathNamespace.class, Step.NAME); } /** Tests for {@link Subtract} method convergence. */ @Test public void testSubtract() { assertComplete("math", MathNamespace.class, Subtract.NAME); } /** Tests for {@link Tan} method convergence. */ @Test public void testTan() { assertComplete("math", MathNamespace.class, Tan.NAME); } /** Tests for {@link Tanh} method convergence. */ @Test public void testTanh() { assertComplete("math", MathNamespace.class, Tanh.NAME); } }
package org.lightmare.bean; import javax.ejb.Stateless; import javax.ejb.TransactionAttribute; import javax.ejb.TransactionAttributeType; @Stateless @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED) public class LightMareFalseBean implements LightMareFalseBeanRemote { @Override public boolean isFalse() { return true; } }
package org.purl.wf4ever.robundle; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; import static org.junit.Assert.assertTrue; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.nio.charset.Charset; import java.nio.file.DirectoryStream; import java.nio.file.FileSystem; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.Test; public class TestBundles { protected void checkSignature(Path zip) throws IOException { String MEDIATYPE = "application/vnd.wf4ever.robundle+zip"; // Check position 30++ according to RO Bundle specification // http://purl.org/wf4ever/ro-bundle#ucf byte[] expected = ("mimetype" + MEDIATYPE + "PK").getBytes("ASCII"); try (InputStream in = Files.newInputStream(zip)) { byte[] signature = new byte[expected.length]; int MIME_OFFSET = 30; assertEquals(MIME_OFFSET, in.skip(MIME_OFFSET)); assertEquals(expected.length, in.read(signature)); assertArrayEquals(expected, signature); } } @Test public void close() throws Exception { Bundle bundle = Bundles.createBundle(); assertTrue(Files.exists(bundle.getSource())); assertTrue(bundle.getRoot().getFileSystem().isOpen()); bundle.close(); assertFalse(Files.exists(bundle.getSource())); assertFalse(bundle.getRoot().getFileSystem().isOpen()); } @Test public void closeAndOpenBundle() throws Exception { Bundle bundle = Bundles.createBundle(); Path zip = Bundles.closeBundle(bundle); Bundles.openBundle(zip); } @Test public void closeAndOpenBundleWithPortValue() throws Exception { Bundle bundle = Bundles.createBundle(); Path hello = bundle.getRoot().resolve("hello.txt"); Bundles.setStringValue(hello, "Hello"); Path zip = Bundles.closeBundle(bundle); Bundle newBundle = Bundles.openBundle(zip); Path newHello = newBundle.getRoot().resolve("hello.txt"); assertEquals("Hello", Bundles.getStringValue(newHello)); } @Test public void closeAndSaveBundle() throws Exception { Bundle bundle = Bundles.createBundle(); Path destination = Files.createTempFile("test", ".zip"); Files.delete(destination); assertFalse(Files.exists(destination)); Bundles.closeAndSaveBundle(bundle, destination); assertTrue(Files.exists(destination)); } @Test public void closeBundle() throws Exception { Bundle bundle = Bundles.createBundle(); Path zip = Bundles.closeBundle(bundle); assertTrue(Files.isReadable(zip)); assertEquals(zip, bundle.getSource()); checkSignature(zip); } @Test public void createBundle() throws Exception { Bundle bundle = Bundles.createBundle(); assertTrue(Files.isDirectory(bundle.getRoot())); // TODO: Should this instead return a FileSystem so we can close() it? } @Test public void getReference() throws Exception { Bundle bundle = Bundles.createBundle(); Path hello = bundle.getRoot().resolve("hello"); Bundles.setReference(hello, URI.create("http://example.org/test")); URI uri = Bundles.getReference(hello); assertEquals("http://example.org/test", uri.toASCIIString()); } @Test public void getReferenceFromWin8() throws Exception { Bundle bundle = Bundles.createBundle(); Path win8 = bundle.getRoot().resolve("win8"); Path win8Url = bundle.getRoot().resolve("win8.url"); Files.copy(getClass().getResourceAsStream("/win8.url"), win8Url); URI uri = Bundles.getReference(win8); assertEquals("http://example.com/made-in-windows-8", uri.toASCIIString()); } @Test public void getStringValue() throws Exception { Bundle bundle = Bundles.createBundle(); Path hello = bundle.getRoot().resolve("hello"); String string = "A string"; Bundles.setStringValue(hello, string); assertEquals(string, Bundles.getStringValue(hello)); assertEquals(null, Bundles.getStringValue(null)); } protected boolean isEmpty(Path path) throws IOException { try (DirectoryStream<Path> ds = Files.newDirectoryStream(path)) { return !ds.iterator().hasNext(); } } @Test public void isMissing() throws Exception { Bundle bundle = Bundles.createBundle(); Path missing = bundle.getRoot().resolve("missing"); assertFalse(Bundles.isValue(missing)); assertTrue(Bundles.isMissing(missing)); assertFalse(Bundles.isReference(missing)); } @Test public void isReference() throws Exception { Bundle bundle = Bundles.createBundle(); Path ref = bundle.getRoot().resolve("ref"); Bundles.setReference(ref, URI.create("http://example.org/test")); assertTrue(Bundles.isReference(ref)); assertFalse(Bundles.isMissing(ref)); assertFalse(Bundles.isValue(ref)); } @Test public void isValue() throws Exception { Bundle bundle = Bundles.createBundle(); Path hello = bundle.getRoot().resolve("hello"); Bundles.setStringValue(hello, "Hello"); assertTrue(Bundles.isValue(hello)); assertFalse(Bundles.isReference(hello)); } protected List<String> ls(Path path) throws IOException { List<String> paths = new ArrayList<>(); try (DirectoryStream<Path> ds = Files.newDirectoryStream(path)) { for (Path p : ds) { paths.add(p.getFileName() + ""); } } Collections.sort(paths); return paths; } @Test public void safeMove() throws Exception { Path tmp = Files.createTempDirectory("test"); Path f1 = tmp.resolve("f1"); Files.createFile(f1); assertFalse(isEmpty(tmp)); Bundle db = Bundles.createBundle(); Path f2 = db.getRoot().resolve("f2"); Bundles.safeMove(f1, f2); assertTrue(isEmpty(tmp)); assertEquals(Arrays.asList("f2", "mimetype"), ls(db.getRoot())); } @Test(expected = IOException.class) public void safeMoveFails() throws Exception { Path tmp = Files.createTempDirectory("test"); Path f1 = tmp.resolve("f1"); Path d1 = tmp.resolve("d1"); Files.createFile(f1); Files.createDirectory(d1); try { Bundles.safeMove(f1, d1); } finally { assertTrue(Files.exists(f1)); assertEquals(Arrays.asList("d1", "f1"), ls(tmp)); } } @Test public void setReference() throws Exception { Bundle bundle = Bundles.createBundle(); Path ref = bundle.getRoot().resolve("ref"); Bundles.setReference(ref, URI.create("http://example.org/test")); URI uri = URI.create("http://example.org/test"); Path f = Bundles.setReference(ref, uri); assertEquals("ref.url", f.getFileName().toString()); assertEquals(bundle.getRoot(), f.getParent()); assertFalse(Files.exists(ref)); List<String> uriLines = Files.readAllLines(f, Charset.forName("ASCII")); assertEquals(3, uriLines.size()); assertEquals("[InternetShortcut]", uriLines.get(0)); assertEquals("URL=http://example.org/test", uriLines.get(1)); assertEquals("", uriLines.get(2)); } @Test public void setReferenceIri() throws Exception { Bundle bundle = Bundles.createBundle(); Path ref = bundle.getRoot().resolve("ref"); URI uri = new URI("http", "xn--bcher-kva.example.com", "/s\u00F8iland/\u2603snowman", "\u2605star"); Path f = Bundles.setReference(ref, uri); List<String> uriLines = Files.readAllLines(f, Charset.forName("ASCII")); // TODO: Double-check that this is actually correct escaping :) assertEquals("URL=http://xn--bcher-kva.example.com/s%C3%B8iland/%E2%98%83snowman#%E2%98%85star", uriLines.get(1)); } @Test public void setStringValue() throws Exception { Bundle bundle = Bundles.createBundle(); Path ref = bundle.getRoot().resolve("ref"); String string = "A string"; Bundles.setStringValue(ref, string); assertEquals(string, Files.readAllLines(ref, Charset.forName("UTF-8")).get(0)); } @Test public void withExtension() throws Exception { Path testDir = Files.createTempDirectory("test"); Path fileTxt = testDir.resolve("file.txt"); assertEquals("file.txt", fileTxt.getFileName().toString()); // better be! Path fileHtml = Bundles.withExtension(fileTxt, ".html"); assertEquals(fileTxt.getParent(), fileHtml.getParent()); assertEquals("file.html", fileHtml.getFileName().toString()); Path fileDot = Bundles.withExtension(fileTxt, "."); assertEquals("file.", fileDot.getFileName().toString()); Path fileEmpty = Bundles.withExtension(fileTxt, ""); assertEquals("file", fileEmpty.getFileName().toString()); Path fileDoc = Bundles.withExtension(fileEmpty, ".doc"); assertEquals("file.doc", fileDoc.getFileName().toString()); Path fileManyPdf = Bundles.withExtension(fileTxt, ".test.many.pdf"); assertEquals("file.test.many.pdf", fileManyPdf.getFileName().toString()); Path fileManyTxt = Bundles.withExtension(fileManyPdf, ".txt"); assertEquals("file.test.many.txt", fileManyTxt.getFileName().toString()); } }
package org.purl.wf4ever.robundle; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URI; import java.nio.charset.Charset; import java.nio.file.DirectoryNotEmptyException; import java.nio.file.DirectoryStream; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.apache.commons.io.IOUtils; import org.junit.Test; import org.purl.wf4ever.robundle.fs.BundleFileSystem; import org.purl.wf4ever.robundle.fs.BundleFileSystemProvider; import org.purl.wf4ever.robundle.utils.TemporaryFiles; public class TestBundles { private static final int MIME_OFFSET = 30; protected void checkSignature(Path zip) throws IOException { String MEDIATYPE = "application/vnd.wf4ever.robundle+zip"; // Check position 30++ according to RO Bundle specification // http://purl.org/wf4ever/ro-bundle#ucf byte[] expected = ("mimetype" + MEDIATYPE + "PK").getBytes("ASCII"); try (InputStream in = Files.newInputStream(zip)) { byte[] signature = new byte[expected.length]; int MIME_OFFSET = 30; assertEquals(MIME_OFFSET, in.skip(MIME_OFFSET)); assertEquals(expected.length, in.read(signature)); assertArrayEquals(expected, signature); } } @Test public void closeDeleteTemp() throws Exception { Bundle bundle = Bundles.createBundle(); assertTrue(Files.exists(bundle.getSource())); assertTrue(bundle.getFileSystem().isOpen()); assertTrue(bundle.isDeleteOnClose()); bundle.close(); assertFalse(Files.exists(bundle.getSource())); assertFalse(bundle.getFileSystem().isOpen()); } @Test public void closeNotDelete() throws Exception { Path path = Files.createTempFile("bundle", ".zip"); Bundle bundle = Bundles.createBundle(path); assertFalse(bundle.isDeleteOnClose()); assertTrue(Files.exists(bundle.getSource())); assertTrue(bundle.getFileSystem().isOpen()); bundle.close(); assertTrue(Files.exists(bundle.getSource())); assertFalse(bundle.getFileSystem().isOpen()); } @Test public void closeAndOpenBundle() throws Exception { Bundle bundle = Bundles.createBundle(); Path zip = Bundles.closeBundle(bundle); Bundles.openBundle(zip).close(); } @Test public void closeAndOpenBundleWithStringValue() throws Exception { Bundle bundle = Bundles.createBundle(); Path hello = bundle.getRoot().resolve("hello.txt"); Bundles.setStringValue(hello, "Hello"); Path zip = Bundles.closeBundle(bundle); try (Bundle newBundle = Bundles.openBundle(zip)) { Path newHello = newBundle.getRoot().resolve("hello.txt"); assertEquals("Hello", Bundles.getStringValue(newHello)); } } @Test public void closeAndSaveBundleDelete() throws Exception { Bundle bundle = Bundles.createBundle(); Path destination = Files.createTempFile("test", ".zip"); destination.toFile().deleteOnExit(); Files.delete(destination); assertFalse(Files.exists(destination)); Bundles.closeAndSaveBundle(bundle, destination); assertTrue(Files.exists(destination)); assertFalse(Files.exists(bundle.getSource())); } @Test public void closeAndSaveBundleNotDelete() throws Exception { Path path = Files.createTempFile("bundle", ".zip"); Bundle bundle = Bundles.createBundle(path); Path destination = Files.createTempFile("test", ".zip"); destination.toFile().deleteOnExit(); Files.delete(destination); assertFalse(Files.exists(destination)); Bundles.closeAndSaveBundle(bundle, destination); assertTrue(Files.exists(destination)); assertTrue(Files.exists(bundle.getSource())); } @Test public void closeBundle() throws Exception { Bundle bundle = Bundles.createBundle(); Path zip = Bundles.closeBundle(bundle); assertTrue(Files.isReadable(zip)); assertEquals(zip, bundle.getSource()); checkSignature(zip); } @Test public void mimeTypePosition() throws Exception { Bundle bundle = Bundles.createBundle(); String mimetype = "application/x-test"; Bundles.setMimeType(bundle, mimetype); assertEquals(mimetype, Bundles.getMimeType(bundle)); Path zip = Bundles.closeBundle(bundle); assertTrue(Files.exists(zip)); ZipFile zipFile = new ZipFile(zip.toFile()); // Must be first entry ZipEntry mimeEntry = zipFile.entries().nextElement(); assertEquals("First zip entry is not 'mimetype'", "mimetype", mimeEntry.getName()); assertEquals( "mimetype should be uncompressed, but compressed size mismatch", mimeEntry.getCompressedSize(), mimeEntry.getSize()); assertEquals("mimetype should have STORED method", ZipEntry.STORED, mimeEntry.getMethod()); assertEquals("Wrong mimetype", mimetype, IOUtils.toString(zipFile.getInputStream(mimeEntry), "ASCII")); // Check position 30++ according to // http://livedocs.adobe.com/navigator/9/Navigator_SDK9_HTMLHelp/wwhelp/wwhimpl/common/html/wwhelp.htm?context=Navigator_SDK9_HTMLHelp&file=Appx_Packaging.6.1.html#1522568 byte[] expected = ("mimetype" + mimetype + "PK") .getBytes("ASCII"); FileInputStream in = new FileInputStream(zip.toFile()); byte[] actual = new byte[expected.length]; try { assertEquals(MIME_OFFSET, in.skip(MIME_OFFSET)); assertEquals(expected.length, in.read(actual)); } finally { in.close(); } assertArrayEquals(expected, actual); } @Test public void createBundle() throws Exception { Path source = null; try (Bundle bundle = Bundles.createBundle()) { assertTrue(Files.isDirectory(bundle.getRoot())); source = bundle.getSource(); assertTrue(Files.exists(source)); } // As it was temporary file it should be deleted on close assertFalse(Files.exists(source)); } @Test public void createBundlePath() throws Exception { Path source = Files.createTempFile("test", ".zip"); source.toFile().deleteOnExit(); Files.delete(source); try (Bundle bundle = Bundles.createBundle(source)) { assertTrue(Files.isDirectory(bundle.getRoot())); assertEquals(source, bundle.getSource()); assertTrue(Files.exists(source)); } // As it was a specific path, it should NOT be deleted on close assertTrue(Files.exists(source)); } @Test public void createBundlePathExists() throws Exception { Path source = Files.createTempFile("test", ".zip"); source.toFile().deleteOnExit(); assertTrue(Files.exists(source)); // will be overwritten try (Bundle bundle = Bundles.createBundle(source)) { } // As it was a specific path, it should NOT be deleted on close assertTrue(Files.exists(source)); } @Test(expected=IOException.class) public void createBundleExistsAsDirFails() throws Exception { Path source = Files.createTempDirectory("test"); source.toFile().deleteOnExit(); try (Bundle bundle = Bundles.createBundle(source)) { } } @Test public void getMimeType() throws Exception { Path bundlePath = TemporaryFiles.temporaryBundle(); try (BundleFileSystem bundleFs = BundleFileSystemProvider.newFileSystemFromNew(bundlePath, "application/x-test")) { Bundle bundle = new Bundle(bundleFs.getPath("/"), false); assertEquals("application/x-test", Bundles.getMimeType(bundle)); } } @Test public void setMimeType() throws Exception { try (Bundle bundle = Bundles.createBundle()) { Path mimetypePath = bundle.getRoot().resolve("mimetype"); assertEquals("application/vnd.wf4ever.robundle+zip", Bundles.getStringValue(mimetypePath)); Bundles.setMimeType(bundle, "application/x-test"); assertEquals("application/x-test", Bundles.getStringValue(mimetypePath)); } } @Test(expected=IllegalArgumentException.class) public void setMimeTypeNoNewlines() throws Exception { try (Bundle bundle = Bundles.createBundle()) { Bundles.setMimeType(bundle, "application/x-test\nNo newlines allowed"); } } @Test(expected=IllegalArgumentException.class) public void setMimeTypeNoSlash() throws Exception { try (Bundle bundle = Bundles.createBundle()) { Bundles.setMimeType(bundle, "test"); } } @Test(expected=IllegalArgumentException.class) public void setMimeTypeEmpty() throws Exception { try (Bundle bundle = Bundles.createBundle()) { Bundles.setMimeType(bundle, ""); } } @Test(expected=IllegalArgumentException.class) public void setMimeTypeNonAscii() throws Exception { try (Bundle bundle = Bundles.createBundle()) { Bundles.setMimeType(bundle, "application/x-test-\u00E9"); // Include the e accent from latin1 } } @Test public void getMimeTypeMissing() throws Exception { try (Bundle bundle = Bundles.createBundle()) { Path mimetypePath = bundle.getRoot().resolve("mimetype"); Files.delete(mimetypePath); // Fall back according to our spec assertEquals("application/vnd.wf4ever.robundle+zip", Bundles.getMimeType(bundle)); } } @Test(expected=IOException.class) public void setMimeTypeMissing() throws Exception { try (Bundle bundle = Bundles.createBundle()) { Path mimetypePath = bundle.getRoot().resolve("mimetype"); Files.delete(mimetypePath); // sadly now we can't set it (the mimetype file must be uncompressed and at beginning of file, // which we don't have the possibility to do now that file system is open) Bundles.setMimeType(bundle, "application/x-test"); } } @Test public void getReference() throws Exception { try (Bundle bundle = Bundles.createBundle()) { Path hello = bundle.getRoot().resolve("hello"); Bundles.setReference(hello, URI.create("http://example.org/test")); URI uri = Bundles.getReference(hello); assertEquals("http://example.org/test", uri.toASCIIString()); } } @Test public void getReferenceFromWin8() throws Exception { try (Bundle bundle = Bundles.createBundle()) { Path win8 = bundle.getRoot().resolve("win8"); Path win8Url = bundle.getRoot().resolve("win8.url"); Files.copy(getClass().getResourceAsStream("/win8.url"), win8Url); URI uri = Bundles.getReference(win8); assertEquals("http://example.com/made-in-windows-8", uri.toASCIIString()); } } @Test public void getStringValue() throws Exception { try (Bundle bundle = Bundles.createBundle()) { Path hello = bundle.getRoot().resolve("hello"); String string = "A string"; Bundles.setStringValue(hello, string); assertEquals(string, Bundles.getStringValue(hello)); assertEquals(null, Bundles.getStringValue(null)); } } protected boolean isEmpty(Path path) throws IOException { try (DirectoryStream<Path> ds = Files.newDirectoryStream(path)) { return !ds.iterator().hasNext(); } } @Test public void isMissing() throws Exception { try (Bundle bundle = Bundles.createBundle()) { Path missing = bundle.getRoot().resolve("missing"); assertFalse(Bundles.isValue(missing)); assertTrue(Bundles.isMissing(missing)); assertFalse(Bundles.isReference(missing)); } } @Test public void isReference() throws Exception { try (Bundle bundle = Bundles.createBundle()) { Path ref = bundle.getRoot().resolve("ref"); Bundles.setReference(ref, URI.create("http://example.org/test")); assertTrue(Bundles.isReference(ref)); assertFalse(Bundles.isMissing(ref)); assertFalse(Bundles.isValue(ref)); } } @Test public void isValue() throws Exception { try (Bundle bundle = Bundles.createBundle()) { Path hello = bundle.getRoot().resolve("hello"); Bundles.setStringValue(hello, "Hello"); assertTrue(Bundles.isValue(hello)); assertFalse(Bundles.isReference(hello)); } } protected List<String> ls(Path path) throws IOException { List<String> paths = new ArrayList<>(); try (DirectoryStream<Path> ds = Files.newDirectoryStream(path)) { for (Path p : ds) { paths.add(p.getFileName() + ""); } } Collections.sort(paths); return paths; } @Test public void safeMove() throws Exception { Path tmp = Files.createTempDirectory("test"); tmp.toFile().deleteOnExit(); Path f1 = tmp.resolve("f1"); f1.toFile().deleteOnExit(); Files.createFile(f1); assertFalse(isEmpty(tmp)); try (Bundle db = Bundles.createBundle()) { Path f2 = db.getRoot().resolve("f2"); Bundles.safeMove(f1, f2); assertFalse(Files.exists(f1)); assertTrue(isEmpty(tmp)); assertEquals(Arrays.asList("f2", "mimetype"), ls(db.getRoot())); } } @Test public void openBundleReadOnly() throws Exception { Path untouched = Files.createTempFile("test-openBundleReadOnly", ".zip"); try (Bundle bundle = Bundles.createBundle(untouched)) { Bundles.setStringValue(bundle.getRoot().resolve("file.txt"), "Untouched"); } try (Bundle readOnly = Bundles.openBundleReadOnly(untouched)) { Path file = readOnly.getRoot().resolve("file.txt"); // You can change the open file system Bundles.setStringValue(file, "Modified"); assertEquals("Modified", Bundles.getStringValue(file)); // and even make new resources Path newFile = readOnly.getRoot().resolve("newfile.txt"); Files.createFile(newFile); assertTrue(Files.exists(newFile)); } try (Bundle readOnly = Bundles.openBundleReadOnly(untouched)) { // But that is not persisted in the zip Path file = readOnly.getRoot().resolve("file.txt"); assertEquals("Untouched", Bundles.getStringValue(file)); Path newfile = readOnly.getRoot().resolve("newfile.txt"); assertFalse(Files.exists(newfile)); } } @Test public void safeCopy() throws Exception { Path tmp = Files.createTempDirectory("test"); tmp.toFile().deleteOnExit(); Path f1 = tmp.resolve("f1"); f1.toFile().deleteOnExit(); Files.createFile(f1); assertFalse(isEmpty(tmp)); try (Bundle db = Bundles.createBundle()) { Path f2 = db.getRoot().resolve("f2"); Bundles.safeCopy(f1, f2); assertTrue(Files.exists(f1)); assertTrue(Files.exists(f2)); assertEquals(Arrays.asList("f2", "mimetype"), ls(db.getRoot())); } } @Test(expected = DirectoryNotEmptyException.class) public void safeCopyFails() throws Exception { Path tmp = Files.createTempDirectory("test"); tmp.toFile().deleteOnExit(); Path f1 = tmp.resolve("f1"); f1.toFile().deleteOnExit(); Path d1 = tmp.resolve("d1"); d1.toFile().deleteOnExit(); Files.createFile(f1); // Make d1 difficult to overwrite Files.createDirectory(d1); Files.createFile(d1.resolve("child")); try { // Files.copy(f1, d1, StandardCopyOption.REPLACE_EXISTING); Bundles.safeCopy(f1, d1); } finally { assertEquals(Arrays.asList("d1", "f1"), ls(tmp)); assertTrue(Files.exists(f1)); assertTrue(Files.isDirectory(d1)); } } @Test(expected = IOException.class) public void safeMoveFails() throws Exception { Path tmp = Files.createTempDirectory("test"); tmp.toFile().deleteOnExit(); Path f1 = tmp.resolve("f1"); f1.toFile().deleteOnExit(); Path d1 = tmp.resolve("d1"); d1.toFile().deleteOnExit(); Files.createFile(f1); // Make d1 difficult to overwrite Files.createDirectory(d1); Files.createFile(d1.resolve("child")); try { Bundles.safeMove(f1, d1); } finally { assertTrue(Files.exists(f1)); assertEquals(Arrays.asList("d1", "f1"), ls(tmp)); } } @Test public void setReference() throws Exception { try (Bundle bundle = Bundles.createBundle()) { Path ref = bundle.getRoot().resolve("ref"); Bundles.setReference(ref, URI.create("http://example.org/test")); URI uri = URI.create("http://example.org/test"); Path f = Bundles.setReference(ref, uri); assertEquals("ref.url", f.getFileName().toString()); assertEquals(bundle.getRoot(), f.getParent()); assertFalse(Files.exists(ref)); List<String> uriLines = Files.readAllLines(f, Charset.forName("ASCII")); assertEquals(3, uriLines.size()); assertEquals("[InternetShortcut]", uriLines.get(0)); assertEquals("URL=http://example.org/test", uriLines.get(1)); assertEquals("", uriLines.get(2)); } } @Test public void setReferenceIri() throws Exception { try (Bundle bundle = Bundles.createBundle()) { Path ref = bundle.getRoot().resolve("ref"); URI uri = new URI("http", "xn--bcher-kva.example.com", "/s\u00F8iland/\u2603snowman", "\u2605star"); Path f = Bundles.setReference(ref, uri); List<String> uriLines = Files.readAllLines(f, Charset.forName("ASCII")); // TODO: Double-check that this is actually correct escaping :) assertEquals("URL=http://xn--bcher-kva.example.com/s%C3%B8iland/%E2%98%83snowman#%E2%98%85star", uriLines.get(1)); } } @Test public void setStringValue() throws Exception { try (Bundle bundle = Bundles.createBundle()) { Path file = bundle.getRoot().resolve("file"); String string = "A string"; Bundles.setStringValue(file, string); assertEquals(string, Files.readAllLines(file, Charset.forName("UTF-8")).get(0)); } } @Test public void withExtension() throws Exception { Path testDir = Files.createTempDirectory("test"); testDir.toFile().deleteOnExit(); Path fileTxt = testDir.resolve("file.txt"); fileTxt.toFile().deleteOnExit(); assertEquals("file.txt", fileTxt.getFileName().toString()); // better be! Path fileHtml = Bundles.withExtension(fileTxt, ".html"); assertEquals(fileTxt.getParent(), fileHtml.getParent()); assertEquals("file.html", fileHtml.getFileName().toString()); Path fileDot = Bundles.withExtension(fileTxt, "."); assertEquals("file.", fileDot.getFileName().toString()); Path fileEmpty = Bundles.withExtension(fileTxt, ""); assertEquals("file", fileEmpty.getFileName().toString()); Path fileDoc = Bundles.withExtension(fileEmpty, ".doc"); assertEquals("file.doc", fileDoc.getFileName().toString()); Path fileManyPdf = Bundles.withExtension(fileTxt, ".test.many.pdf"); assertEquals("file.test.many.pdf", fileManyPdf.getFileName().toString()); Path fileManyTxt = Bundles.withExtension(fileManyPdf, ".txt"); assertEquals("file.test.many.txt", fileManyTxt.getFileName().toString()); } }
package seedu.taskboss.logic; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import static seedu.taskboss.commons.core.Messages.MESSAGE_INVALID_COMMAND_FORMAT; import static seedu.taskboss.commons.core.Messages.MESSAGE_INVALID_TASK_DISPLAYED_INDEX; import static seedu.taskboss.commons.core.Messages.MESSAGE_UNKNOWN_COMMAND; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TemporaryFolder; import com.google.common.eventbus.Subscribe; import seedu.taskboss.commons.core.EventsCenter; import seedu.taskboss.commons.events.model.TaskBossChangedEvent; import seedu.taskboss.commons.events.ui.JumpToListRequestEvent; import seedu.taskboss.commons.events.ui.ShowHelpRequestEvent; import seedu.taskboss.commons.exceptions.IllegalValueException; import seedu.taskboss.logic.commands.AddCommand; import seedu.taskboss.logic.commands.ClearCommand; import seedu.taskboss.logic.commands.Command; import seedu.taskboss.logic.commands.CommandResult; import seedu.taskboss.logic.commands.DeleteCommand; import seedu.taskboss.logic.commands.ExitCommand; import seedu.taskboss.logic.commands.FindCommand; import seedu.taskboss.logic.commands.HelpCommand; import seedu.taskboss.logic.commands.ListCommand; import seedu.taskboss.logic.commands.SelectCommand; import seedu.taskboss.logic.commands.exceptions.CommandException; import seedu.taskboss.logic.parser.DateParser; import seedu.taskboss.logic.parser.ParserUtil; import seedu.taskboss.model.Model; import seedu.taskboss.model.ModelManager; import seedu.taskboss.model.ReadOnlyTaskBoss; import seedu.taskboss.model.TaskBoss; import seedu.taskboss.model.category.Category; import seedu.taskboss.model.category.UniqueCategoryList; import seedu.taskboss.model.task.DateTime; import seedu.taskboss.model.task.Information; import seedu.taskboss.model.task.Name; import seedu.taskboss.model.task.PriorityLevel; import seedu.taskboss.model.task.ReadOnlyTask; import seedu.taskboss.model.task.Task; import seedu.taskboss.storage.StorageManager; public class LogicManagerTest { @Rule public TemporaryFolder saveFolder = new TemporaryFolder(); private Model model; private Logic logic; // These are for checking the correctness of the events raised private ReadOnlyTaskBoss latestSavedTaskBoss; private boolean helpShown; private int targetedJumpIndex; @Subscribe private void handleLocalModelChangedEvent(TaskBossChangedEvent abce) { latestSavedTaskBoss = new TaskBoss(abce.data); } @Subscribe private void handleShowHelpRequestEvent(ShowHelpRequestEvent she) { helpShown = true; } @Subscribe private void handleJumpToListRequestEvent(JumpToListRequestEvent je) { targetedJumpIndex = je.targetIndex; } @Before public void setUp() { model = new ModelManager(); String tempTaskBossFile = saveFolder.getRoot().getPath() + "TempTaskBoss.xml"; String tempPreferencesFile = saveFolder.getRoot().getPath() + "TempPreferences.json"; logic = new LogicManager(model, new StorageManager(tempTaskBossFile, tempPreferencesFile)); EventsCenter.getInstance().registerHandler(this); latestSavedTaskBoss = new TaskBoss(model.getTaskBoss()); // last saved // assumed // to be up // to date helpShown = false; targetedJumpIndex = -1; // non yet } @After public void tearDown() { EventsCenter.clearSubscribers(); } @Test public void execute_invalid() { String invalidCommand = " "; assertCommandFailure(invalidCommand, String.format(MESSAGE_INVALID_COMMAND_FORMAT, HelpCommand.MESSAGE_USAGE)); } /** * Executes the command, confirms that a CommandException is not thrown and * that the result message is correct. Also confirms that both the * 'taskboss' and the 'last shown list' are as specified. * * @see #assertCommandBehavior(boolean, String, String, ReadOnlyTaskBoss, * List) */ private void assertCommandSuccess(String inputCommand, String expectedMessage, ReadOnlyTaskBoss expectedTaskBoss, List<? extends ReadOnlyTask> expectedShownList) { assertCommandBehavior(false, inputCommand, expectedMessage, expectedTaskBoss, expectedShownList); } /** * Executes the command, confirms that a CommandException is thrown and that * the result message is correct. Both the 'taskboss' and the 'last shown * list' are verified to be unchanged. * * @see #assertCommandBehavior(boolean, String, String, ReadOnlyTaskBoss, * List) */ private void assertCommandFailure(String inputCommand, String expectedMessage) { TaskBoss expectedTaskBoss = new TaskBoss(model.getTaskBoss()); List<ReadOnlyTask> expectedShownList = new ArrayList<>(model.getFilteredTaskList()); assertCommandBehavior(true, inputCommand, expectedMessage, expectedTaskBoss, expectedShownList); } /** * Executes the command, confirms that the result message is correct and * that a CommandException is thrown if expected and also confirms that the * following three parts of the LogicManager object's state are as * expected:<br> * - the internal TaskBoss data are same as those in the * {@code expectedTaskBoss} <br> * - the backing list shown by UI matches the {@code shownList} <br> * - {@code expectedTaskBoss} was saved to the storage file. <br> */ private void assertCommandBehavior(boolean isCommandExceptionExpected, String inputCommand, String expectedMessage, ReadOnlyTaskBoss expectedTaskBoss, List<? extends ReadOnlyTask> expectedShownList) { try { CommandResult result = logic.execute(inputCommand); assertFalse("CommandException expected but was not thrown.", isCommandExceptionExpected); assertEquals(expectedMessage, result.feedbackToUser); } catch (CommandException e) { assertTrue("CommandException not expected but was thrown.", isCommandExceptionExpected); assertEquals(expectedMessage, e.getMessage()); } // Confirm the ui display elements should contain the right data assertEquals(expectedShownList, model.getFilteredTaskList()); // Confirm the state of data (saved and in-memory) is as expected assertEquals(expectedTaskBoss, model.getTaskBoss()); assertEquals(expectedTaskBoss, latestSavedTaskBoss); } @Test public void execute_unknownCommandWord() { String unknownCommand = "uicfhmowqewca"; assertCommandFailure(unknownCommand, MESSAGE_UNKNOWN_COMMAND); } @Test public void execute_help() { assertCommandSuccess("help", HelpCommand.SHOWING_HELP_MESSAGE, new TaskBoss(), Collections.emptyList()); assertTrue(helpShown); } @Test public void execute_exit() { assertCommandSuccess("exit", ExitCommand.MESSAGE_EXIT_ACKNOWLEDGEMENT, new TaskBoss(), Collections.emptyList()); } @Test public void execute_clear() throws Exception { TestDataHelper helper = new TestDataHelper(); model.addTask(helper.generateTask(1)); model.addTask(helper.generateTask(2)); model.addTask(helper.generateTask(3)); assertCommandSuccess("clear", ClearCommand.MESSAGE_SUCCESS, new TaskBoss(), Collections.emptyList()); } @Test public void execute_add_invalidArgsFormat() { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, AddCommand.MESSAGE_USAGE); assertCommandFailure("add n/wrong args wrong args", expectedMessage); assertCommandFailure("add n/Valid Name 12345 sd/today ed/tomorrow " + "i/validInformation.butNoPriorityLevelPrefix", expectedMessage); assertCommandFailure("add n/Valid Name p/1 sd/today ed/tomorrow " + "validInformation.butNoInformationPrefix", expectedMessage); } @Test public void execute_add_invalidTaskData() { assertCommandFailure("add n/[]\\[;] p/1 sd/today ed/tomorrow i/valid, information", Name.MESSAGE_NAME_CONSTRAINTS); assertCommandFailure("add n/Valid Name p/not_numbers sd/today ed/tomorrow i/valid, information", PriorityLevel.MESSAGE_PRIORITY_CONSTRAINTS); assertCommandFailure("add n/Valid Name p/1 sd/today ed/tomorrow " + "i/valid, information c/invalid_-[.category", Category.MESSAGE_CATEGORY_CONSTRAINTS); assertCommandFailure("add n/Valid Name p/1 sd/today to next week ed/tomorrow i/valid, information", DateParser.getStartDateMultipleDatesError()); assertCommandFailure("add n/Valid Name p/1 sd/invalid date ed/monday to friday i/valid, information", DateParser.getStartDateInvalidDateError()); } @Test public void execute_add_successful() throws Exception { // setup expectations TestDataHelper helper = new TestDataHelper(); Task toBeAdded = helper.adam(); TaskBoss expectedAB = new TaskBoss(); expectedAB.addTask(toBeAdded); // execute command and verify result assertCommandSuccess(helper.generateAddCommand(toBeAdded), String.format(AddCommand.MESSAGE_SUCCESS, toBeAdded), expectedAB, expectedAB.getTaskList()); } @Test public void execute_addDuplicate_notAllowed() throws Exception { // setup expectations TestDataHelper helper = new TestDataHelper(); Task toBeAdded = helper.adam(); // setup starting state model.addTask(toBeAdded); // task already in internal TaskBoss // execute command and verify result assertCommandFailure(helper.generateAddCommand(toBeAdded), AddCommand.MESSAGE_DUPLICATE_TASK); } @Test public void execute_list_showsAllTasks() throws Exception { // prepare expectations TestDataHelper helper = new TestDataHelper(); TaskBoss expectedAB = helper.generateTaskBoss(2); List<? extends ReadOnlyTask> expectedList = expectedAB.getTaskList(); // prepare TaskBoss state helper.addToModel(model, 2); assertCommandSuccess("list", ListCommand.MESSAGE_SUCCESS, expectedAB, expectedList); } /** * Confirms the 'invalid argument index number behaviour' for the given * command targeting a single task in the shown list, using visible index. * * @param commandWord to test assuming it targets a single task in the last shown * list based on visible index. */ private void assertIncorrectIndexFormatBehaviorForCommand(String commandWord, String expectedMessage) throws Exception { assertCommandFailure(commandWord, expectedMessage); // index missing assertCommandFailure(commandWord + " +1", expectedMessage); // index should be unsigned assertCommandFailure(commandWord + " -1", expectedMessage); // index should be unsigned assertCommandFailure(commandWord + " 0", expectedMessage); assertCommandFailure(commandWord + " not_a_number", expectedMessage); } /** * Confirms the 'invalid argument index number behaviour' for the given * command targeting a single task in the shown list, using visible index. * * @param commandWord * to test assuming it targets a single task in the last shown * list based on visible index. */ private void assertIndexNotFoundBehaviorForCommand(String commandWord) throws Exception { String expectedMessage = MESSAGE_INVALID_TASK_DISPLAYED_INDEX; TestDataHelper helper = new TestDataHelper(); List<Task> taskList = helper.generateTaskList(2); // set AB state to 2 tasks model.resetData(new TaskBoss()); for (Task p : taskList) { model.addTask(p); } assertCommandFailure(commandWord + " 3", expectedMessage); } @Test public void execute_selectInvalidArgsFormat_errorMessageShown() throws Exception { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, SelectCommand.MESSAGE_USAGE); assertIncorrectIndexFormatBehaviorForCommand("select", expectedMessage); } @Test public void execute_selectIndexNotFound_errorMessageShown() throws Exception { assertIndexNotFoundBehaviorForCommand("select"); } @Test public void execute_select_jumpsToCorrectTask() throws Exception { TestDataHelper helper = new TestDataHelper(); List<Task> threeTasks = helper.generateTaskList(3); TaskBoss expectedAB = helper.generateTaskBoss(threeTasks); helper.addToModel(model, threeTasks); assertCommandSuccess("select 2", String.format(SelectCommand.MESSAGE_SELECT_TASK_SUCCESS, 2), expectedAB, expectedAB.getTaskList()); assertEquals(1, targetedJumpIndex); assertEquals(model.getFilteredTaskList().get(1), threeTasks.get(1)); } @Test public void execute_deleteInvalidArgsFormat_errorMessageShown() throws Exception { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, DeleteCommand.MESSAGE_USAGE); assertIncorrectIndexFormatBehaviorForCommand("delete", expectedMessage); } @Test public void execute_deleteIndexNotFound_errorMessageShown() throws Exception { assertIndexNotFoundBehaviorForCommand("delete"); } @Test public void execute_delete_removesCorrectTask() throws Exception { TestDataHelper helper = new TestDataHelper(); List<Task> threeTasks = helper.generateTaskList(3); TaskBoss expectedAB = helper.generateTaskBoss(threeTasks); expectedAB.removeTask(threeTasks.get(1)); helper.addToModel(model, threeTasks); assertCommandSuccess("delete 2", String.format(DeleteCommand.MESSAGE_DELETE_TASK_SUCCESS, threeTasks.get(1)), expectedAB, expectedAB.getTaskList()); } @Test public void execute_find_invalidArgsFormat() { String expectedMessage = String.format(MESSAGE_INVALID_COMMAND_FORMAT, FindCommand.MESSAGE_USAGE); assertCommandFailure("find ", expectedMessage); } @Test public void execute_find_onlyMatchesFullWordsInNames() throws Exception { TestDataHelper helper = new TestDataHelper(); Task pTarget1 = helper.generateTaskWithName("bla bla KEY bla"); Task pTarget2 = helper.generateTaskWithName("bla KEY bla bceofeia"); Task p1 = helper.generateTaskWithName("KE Y"); Task p2 = helper.generateTaskWithName("KEYKEYKEY sduauo"); List<Task> fourTasks = helper.generateTaskList(p1, pTarget1, p2, pTarget2); TaskBoss expectedAB = helper.generateTaskBoss(fourTasks); List<Task> expectedList = helper.generateTaskList(pTarget1, pTarget2); helper.addToModel(model, fourTasks); assertCommandSuccess("find n/KEY", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedAB, expectedList); } @Test public void execute_find_isNotCaseSensitive() throws Exception { TestDataHelper helper = new TestDataHelper(); Task p1 = helper.generateTaskWithName("bla bla KEY bla"); Task p2 = helper.generateTaskWithName("bla KEY bla bceofeia"); Task p3 = helper.generateTaskWithName("key key"); Task p4 = helper.generateTaskWithName("KEy sduauo"); List<Task> fourTasks = helper.generateTaskList(p3, p1, p4, p2); TaskBoss expectedAB = helper.generateTaskBoss(fourTasks); List<Task> expectedList = fourTasks; helper.addToModel(model, fourTasks); assertCommandSuccess("find n/KEY", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedAB, expectedList); } @Test public void execute_find_matchesIfAnyKeywordPresent() throws Exception { TestDataHelper helper = new TestDataHelper(); Task pTarget1 = helper.generateTaskWithName("bla bla KEY bla"); Task pTarget2 = helper.generateTaskWithName("bla rAnDoM bla bceofeia"); Task pTarget3 = helper.generateTaskWithName("key key"); Task p1 = helper.generateTaskWithName("sduauo"); List<Task> fourTasks = helper.generateTaskList(pTarget1, p1, pTarget2, pTarget3); TaskBoss expectedAB = helper.generateTaskBoss(fourTasks); List<Task> expectedList = helper.generateTaskList(pTarget1, pTarget2, pTarget3); helper.addToModel(model, fourTasks); assertCommandSuccess("find n/key rAnDoM", Command.getMessageForTaskListShownSummary(expectedList.size()), expectedAB, expectedList); } /** * A utility class to generate test data. */ class TestDataHelper { Task adam() throws Exception { Name name = new Name("Adam Brown"); PriorityLevel privatePriorityLevel = new PriorityLevel("1"); DateTime startDateTime = new DateTime(ParserUtil.parseStartDate("today 5pm")); DateTime endDateTime = new DateTime(ParserUtil.parseEndDate("tomorrow 8pm")); Information privateInformation = new Information("111, alpha street"); Category category1 = new Category("category1"); Category category2 = new Category("longercategory2"); UniqueCategoryList categories = new UniqueCategoryList(category1, category2); return new Task(name, privatePriorityLevel, startDateTime, endDateTime, privateInformation, categories); } /** * Generates a valid task using the given seed. Running this function * with the same parameter values guarantees the returned task will have * the same state. Each unique seed will generate a unique Task object. * * @param seed * used to generate the task data field values */ Task generateTask(int seed) throws Exception { return new Task( new Name("Task " + seed), new PriorityLevel("" + Math.abs(seed)), new DateTime("Feb 19 10am, 2017"), new DateTime("Feb 20 10am, 2017"), new Information("House of " + seed), new UniqueCategoryList(new Category("category" + Math.abs(seed)), new Category("category" + Math.abs(seed + 1))) ); } private String generateAddCommand(Task p) throws IllegalValueException { StringBuffer cmd = new StringBuffer(); cmd.append("add "); cmd.append(" n/").append(p.getName().toString()); cmd.append(" p/").append(p.getPriorityLevel()); cmd.append(" sd/").append(ParserUtil.parseStartDate(p.getStartDateTime().toString())); cmd.append(" ed/").append(ParserUtil.parseEndDate(p.getEndDateTime().toString())); cmd.append(" i/").append(p.getInformation()); UniqueCategoryList categories = p.getCategories(); for (Category t : categories) { cmd.append(" c/").append(t.categoryName); } System.out.println(cmd.toString()); return cmd.toString(); } /** * Generates an TaskBoss with auto-generated tasks. */ TaskBoss generateTaskBoss(int numGenerated) throws Exception { TaskBoss taskBoss = new TaskBoss(); addToTaskBoss(taskBoss, numGenerated); return taskBoss; } /** * Generates an TaskBoss based on the list of Tasks given. */ TaskBoss generateTaskBoss(List<Task> tasks) throws Exception { TaskBoss taskBoss = new TaskBoss(); addToTaskBoss(taskBoss, tasks); return taskBoss; } /** * Adds auto-generated Task objects to the given TaskBoss * * @param taskBoss * The TaskBoss to which the Tasks will be added */ void addToTaskBoss(TaskBoss taskBoss, int numGenerated) throws Exception { addToTaskBoss(taskBoss, generateTaskList(numGenerated)); } /** * Adds the given list of Tasks to the given TaskBoss */ void addToTaskBoss(TaskBoss taskBoss, List<Task> tasksToAdd) throws Exception { for (Task t : tasksToAdd) { taskBoss.addTask(t); } } /** * Adds auto-generated Task objects to the given model * * @param model * The model to which the Tasks will be added */ void addToModel(Model model, int numGenerated) throws Exception { addToModel(model, generateTaskList(numGenerated)); } /** * Adds the given list of Tasks to the given model */ void addToModel(Model model, List<Task> tasksToAdd) throws Exception { for (Task t : tasksToAdd) { model.addTask(t); } } /** * Generates a list of Tasks based on the flags. */ List<Task> generateTaskList(int numGenerated) throws Exception { List<Task> tasks = new ArrayList<>(); for (int i = 1; i <= numGenerated; i++) { tasks.add(generateTask(i)); } return tasks; } List<Task> generateTaskList(Task... tasks) { return Arrays.asList(tasks); } /** * Generates a Task object with given name. Other fields will have some * dummy values. */ Task generateTaskWithName(String name) throws Exception { return new Task( new Name(name), new PriorityLevel("1"), new DateTime("Feb 19 10am, 2017"), new DateTime("Feb 20 10am, 2017"), new Information("House of 1"), new UniqueCategoryList(new Category("category")) ); } } }
package seedu.typed.schedule; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import java.time.Month; import org.junit.Test; import seedu.typed.model.task.DateTime; //@@author A0139379M public class DayInMonthTETest { // Boundary Cases for Last Tuesday // Last Tuesday of March 2017 private DateTime testDate280317 = DateTime.getDateTime(2017, Month.MARCH, 28, 0, 0); // Last Tuesday of April 2017 private DateTime testDate250417 = DateTime.getDateTime(2017, Month.APRIL, 25, 0, 0); // Last Tuesday of April 2018 private DateTime testDate240418 = DateTime.getDateTime(2018, Month.APRIL, 24, 0, 0); // Second Last Tuesday of March 2017 private DateTime testDate210317 = DateTime.getDateTime(2017, Month.MARCH, 21, 0, 0); // Boundary Cases for First Monday // First Monday of March 2017 private DateTime firstMondayOfMarch = DateTime.getDateTime(2017, Month.MARCH, 06, 0, 0); // Second Monday of March 2017 private DateTime secondMondayOfMarch = DateTime.getDateTime(2017, Month.MARCH, 13, 0, 0); // First Monday of April 2017 private DateTime firstMondayOfApril = DateTime.getDateTime(2017, Month.APRIL, 03, 0, 0); // First Monday of April 2018 private DateTime testDate020418 = DateTime.getDateTime(2018, Month.APRIL, 02, 0, 0); // Second Monday of April 20172017 private DateTime testDate100417 = DateTime.getDateTime(2017, Month.APRIL, 10, 0, 0); // First Monday of Jan 2018 private DateTime firstMondayOfJan2018 = DateTime.getDateTime(2018, Month.JANUARY, 01, 0, 0); // First Monday of Dec 2017 private DateTime firstMondayOfDec2017 = DateTime.getDateTime(2017, Month.DECEMBER, 04, 0, 0); // First Tuesday of March 2017 private DateTime firstTuesdayOfMarch = DateTime.getDateTime(2017, Month.MARCH, 07, 0, 0); // Second Tuesday of March 2017 private DateTime secondTuesdayOfMarch = DateTime.getDateTime(2017, Month.MARCH, 14, 0, 0); // First Wednesday of April 2017 private DateTime firstWednesdayOfApril = DateTime.getDateTime(2017, Month.APRIL, 05, 0, 0); // Second Sunday of March 2017 private DateTime secondSundayOfMarch = DateTime.getDateTime(2017, Month.MARCH, 12, 0, 0); // First Sunday of April 2017 private DateTime firstSundayOfApril = DateTime.getDateTime(2017, Month.APRIL, 02, 0, 0); // Some Edge Cases for Last Monday // Last Monday of April 2018, in particular that April has 5 Mondays // In particular, it should also match the 5th week Monday private DateTime testDate300418 = DateTime.getDateTime(2018, Month.APRIL, 30, 0, 0); private DayInMonthTE everyFirstMonday = new DayInMonthTE(1, 1); private DayInMonthTE everyLastTuesday = new DayInMonthTE(-1, 2); private DayInMonthTE everyLastMonday = new DayInMonthTE(-1, 1); private DayInMonthTE everyFifthMonday = new DayInMonthTE(5, 1); private DayInMonthTE everyFirstTuesday = new DayInMonthTE(1, 2); private DayInMonthTE everySecondMonday = new DayInMonthTE(2, 1); private DayInMonthTE everySecondTuesday = new DayInMonthTE(2, 2); private DayInMonthTE everyFirstWednesday = new DayInMonthTE(1, 3); private DayInMonthTE everyFirstSunday = new DayInMonthTE(1, 7); private TimeExpression firstWeek = DayInMonthTE.week(1); private TimeExpression everyMonday = DayInMonthTE.weekly(1); private TimeExpression everyTuesday = DayInMonthTE.weekly(2); private TimeExpression firstMondayEveryMonth = DayInMonthTE.monthly(1, 1); // Testing involves forming a particular TimeExpression like everyFifthMonday and the input 300418 // includes method is very important to work for all cases as every time expression will depends // on it to get the correct recurrence @Test public void includes_300418_everyFifthMonday_true() { assertTrue(everyFifthMonday.includes(testDate300418)); } @Test public void includes_300418_everyLastMonday_true() { assertTrue(everyLastMonday.includes(testDate300418)); } @Test public void includes_280317_everyLastTuesday_true() { assertTrue(everyLastTuesday.includes(testDate280317)); } @Test public void includes_250417_everyLastTuesday_true() { assertTrue(everyLastTuesday.includes(testDate250417)); } @Test public void includes_240418_everyLastTuesday_true() { assertTrue(everyLastTuesday.includes(testDate240418)); } @Test public void includes_210317_everyLastTuesday_false() { assertFalse(everyLastTuesday.includes(testDate210317)); } @Test public void includes_firstMondayOfMarch_everyFirstMonday_true() { assertTrue(everyFirstMonday.includes(firstMondayOfMarch)); } @Test public void includes_030417_everyFirstMonday_true() { assertTrue(everyFirstMonday.includes(firstMondayOfApril)); } @Test public void includes_020418_everyFirstMonday_true() { assertTrue(everyFirstMonday.includes(testDate020418)); } @Test public void includes_100417_everyFirstMonday_true() { assertFalse(everyFirstMonday.includes(testDate100417)); } // Another very important method to test is nextDeadlineOccurrence // we need to ensure that the DateTime returned is the correct and accurate // representation of the next occurrence given the particular recurrence rule // Testing methods are named in this format // nextDeadlineOccurrence_DATE_RECURRENCE_OUTCOME // where next occurrence will be after DATE // Testing various conditions like next occurrence is next year, next month, same month, different weeks etc @Test public void nextDeadlineOccurrence_firstMondayOfMarch_everyFirstMonday_firstMondayOfApril() { assertTrue(everyFirstMonday.nextDeadlineOccurrence(firstMondayOfMarch).equals(firstMondayOfApril)); } @Test public void nextDeadlineOccurrence_firstMondayOfDec2017_everyFirstMonday_firstMondayOfJan2018() { assertTrue(everyFirstMonday.nextDeadlineOccurrence(firstMondayOfDec2017).equals(firstMondayOfJan2018)); } @Test public void nextDeadlineOccurrence_firstMondayOfMarch_everyFirstTuesday_firstTuesdayOfMarch() { assertTrue(everyFirstTuesday.nextDeadlineOccurrence(firstMondayOfMarch).equals(firstTuesdayOfMarch)); } @Test public void nextDeadlineOccurrence_firstMondayOfMarch_everySecondMonday_secondMondayOfMarch() { assertTrue(everySecondMonday.nextDeadlineOccurrence(firstMondayOfMarch).equals(secondMondayOfMarch)); } @Test public void nextDeadlineOccurrence_firstTuesdayOfMarch_everySecondMonday_secondMondayOfMarch() { assertTrue(everySecondMonday.nextDeadlineOccurrence(firstTuesdayOfMarch).equals(secondMondayOfMarch)); } @Test public void nextDeadlineOccurrence_firstMondayOfMarch_everySecondTuesday_secondTuesdayOfMarch() { assertTrue(everySecondTuesday.nextDeadlineOccurrence(firstMondayOfMarch).equals(secondTuesdayOfMarch)); } @Test public void nextDeadlineOccurrence_firstMondayOfMarch_everyFirstWednesday_firstWednesdayOfApril() { assertTrue(everyFirstWednesday.nextDeadlineOccurrence(firstMondayOfMarch).equals(firstWednesdayOfApril)); } @Test public void nextDeadlineOccurrence_secondSundayOfMarch_everyFirstSunday_firstSundayOfApril() { assertTrue(everyFirstSunday.nextDeadlineOccurrence(secondSundayOfMarch).equals(firstSundayOfApril)); } @Test public void nextDeadlineOccurrence_firstMondayOfMarch_everyFirstSunday_firstSundayOfApril() { assertTrue(everyFirstSunday.nextDeadlineOccurrence(firstMondayOfMarch).equals(firstSundayOfApril)); } // Recurrence constructs are shortcuts to give us TimeExpression that // recurs according to common recurring rules like weekly, or the whole week // To test this, we will use include to verify that the date falls within the recurrence // week tests @Test public void week_firstMondayOfMarch_firstWeek_true() { assertTrue(firstWeek.includes(firstMondayOfMarch)); } @Test public void week_firstTuesdayOfMarch_firstWeek_true() { assertTrue(firstWeek.includes(firstTuesdayOfMarch)); } @Test public void week_secondTuesdayOfMarch_firstWeek_false() { assertFalse(firstWeek.includes(secondTuesdayOfMarch)); } // weekly tests @Test public void weekly_secondMondayOfMarch_everyMonday_true() { assertTrue(everyMonday.includes(secondMondayOfMarch)); } @Test public void weekly_firstMondayOfApril_everyMonday_true() { assertTrue(everyMonday.includes(firstMondayOfApril)); } @Test public void weekly_firstTuesdayOfMarch_everyMonday_false() { assertFalse(everyMonday.includes(firstTuesdayOfMarch)); } @Test public void weekly_firstMondayOfJan2018_everyMonday_true() { assertTrue(everyMonday.includes(firstMondayOfJan2018)); } @Test public void weekly_firstTuesdayOfMarch_everyTuesday_true() { assertTrue(everyTuesday.includes(firstTuesdayOfMarch)); } // monthly tests // In particular, recur a given date every month @Test public void monthly_firstMonday_recursEveryFirstMonday() { assertTrue(firstMondayEveryMonth.includes(firstMondayOfApril)); assertTrue(firstMondayEveryMonth.includes(firstMondayOfMarch)); assertTrue(firstMondayEveryMonth.includes(firstMondayOfJan2018)); assertFalse(firstMondayEveryMonth.includes(firstTuesdayOfMarch)); } @Test public void isLeapYear_2000_true() { assertTrue(DayInMonthTE.isLeapYear(2000)); } @Test public void isLeapYear_1900_true() { assertFalse(DayInMonthTE.isLeapYear(1900)); } }
package aQute.bnd.build; import static java.util.Objects.requireNonNull; import static org.osgi.framework.Constants.FRAMEWORK_BEGINNING_STARTLEVEL; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLClassLoader; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.concurrent.Executor; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.jar.Manifest; import java.util.regex.Pattern; import org.osgi.framework.launch.FrameworkFactory; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import aQute.bnd.header.Attrs; import aQute.bnd.header.OSGiHeader; import aQute.bnd.header.Parameters; import aQute.bnd.help.instructions.BuilderInstructions; import aQute.bnd.help.instructions.LauncherInstructions; import aQute.bnd.osgi.Constants; import aQute.bnd.osgi.Domain; import aQute.bnd.osgi.Jar; import aQute.bnd.osgi.Processor; import aQute.bnd.osgi.Verifier; import aQute.bnd.service.Strategy; import aQute.lib.io.IO; import aQute.lib.startlevel.StartLevelRuntimeHandler; import aQute.lib.watcher.FileWatcher; import aQute.lib.watcher.FileWatcher.Builder; import aQute.libg.command.Command; import aQute.libg.generics.Create; /** * A Project Launcher is a base class to be extended by launchers. Launchers are * JARs that launch a framework and install a number of bundles and then run the * framework. A launcher jar must specify a Launcher-Class manifest header. This * class is instantiated and cast to a LauncherPlugin. This plug in is then * asked to provide a ProjectLauncher. This project launcher is then used by the * project to run the code. Launchers must extend this class. */ public abstract class ProjectLauncher extends Processor { public static final String EMBEDDED_ACTIVATOR = "Embedded-Activator"; final static Logger logger = LoggerFactory.getLogger(ProjectLauncher.class); private final Project project; private long timeout = 0; private final List<String> classpath = new ArrayList<>(); private List<String> runbundles = Create.list(); private final List<String> runvm = new ArrayList<>(); private final List<String> runprogramargs = new ArrayList<>(); private Map<String, String> runproperties; private Command java; private Parameters runsystempackages; private Parameters runsystemcapabilities; private final List<String> activators = Create.list(); private File storageDir; protected BuilderInstructions builderInstrs; protected LauncherInstructions launcherInstrs; private boolean trace; private boolean keep; private int framework; private File cwd; private Collection<String> agents = new ArrayList<>(); private Set<NotificationListener> listeners = Collections.newSetFromMap(new IdentityHashMap<>()); protected Appendable out = System.out; protected Appendable err = System.err; protected InputStream in = System.in; public final static int SERVICES = 10111; public final static int NONE = 20123; // MUST BE ALIGNED WITH LAUNCHER public final static int OK = 0; public final static int WARNING = 126 - 1; public final static int ERROR = 126 - 2; public final static int TIMEDOUT = 126 - 3; public final static int UPDATE_NEEDED = 126 - 4; public final static int CANCELED = 126 - 5; public final static int DUPLICATE_BUNDLE = 126 - 6; public final static int RESOLVE_ERROR = 126 - 7; public final static int ACTIVATOR_ERROR = 126 - 8; public final static int STOPPED = 126 - 9; public ProjectLauncher(Project project) throws Exception { this.project = project; builderInstrs = project.getInstructions(BuilderInstructions.class); launcherInstrs = project.getInstructions(LauncherInstructions.class); } /** * Collect all the aspect from the project and set the local fields from * them. Should be called after constructor has been called. * * @throws Exception */ protected void updateFromProject() throws Exception { setCwd(getProject().getBase()); // pkr: could not use this because this is killing the runtests. // getProject().refresh(); runbundles.clear(); Collection<Container> run = getProject().getRunbundles(); for (Container container : run) { File file = container.getFile(); if (file != null && (file.isFile() || file.isDirectory())) { addRunBundle(IO.absolutePath(file)); } else { getProject().error("Bundle file \"%s\" does not exist, given error is %s", file, container.getError()); } } if (getProject().getRunBuilds()) { File[] builds = getProject().getBuildFiles(true); if (builds != null) for (File file : builds) addRunBundle(IO.absolutePath(file)); } Collection<Container> runpath = getProject().getRunpath(); runsystempackages = new Parameters(getProject().mergeProperties(Constants.RUNSYSTEMPACKAGES), getProject()); runsystemcapabilities = new Parameters(getProject().mergeProperties(Constants.RUNSYSTEMCAPABILITIES), getProject()); framework = getRunframework(getProject().getProperty(Constants.RUNFRAMEWORK)); timeout = Processor.getDuration(getProject().getProperty(Constants.RUNTIMEOUT), 0); trace = getProject().isRunTrace(); runpath.addAll(getProject().getRunFw()); for (Container c : runpath) { addClasspath(c); } runvm.addAll(getProject().getRunVM()); runprogramargs.addAll(getProject().getRunProgramArgs()); runproperties = getProject().getRunProperties(); storageDir = getProject().getRunStorage(); setKeep(getProject().getRunKeep()); calculatedProperties(runproperties); } private int getRunframework(String property) { if (Constants.RUNFRAMEWORK_NONE.equalsIgnoreCase(property)) return NONE; else if (Constants.RUNFRAMEWORK_SERVICES.equalsIgnoreCase(property)) return SERVICES; return SERVICES; } public void addClasspath(Container container) throws Exception { addClasspath(container, classpath); } protected void addClasspath(Container container, List<String> pathlist) throws Exception { if (container.getError() != null) { getProject().error("Cannot launch because %s has reported %s", container.getProject(), container.getError()); } else { Collection<Container> members = container.getMembers(); for (Container m : members) { String path = IO.absolutePath(m.getFile()); if (!pathlist.contains(path)) { Manifest manifest = m.getManifest(); if (manifest != null) { // We are looking for any agents, used if // -javaagent=true is set String agentClassName = manifest.getMainAttributes() .getValue("Premain-Class"); if (agentClassName != null) { String agent = path; if (container.getAttributes() .get("agent") != null) { agent += "=" + container.getAttributes() .get("agent"); } agents.add(agent); } Parameters exports = getProject().parseHeader(manifest.getMainAttributes() .getValue(Constants.EXPORT_PACKAGE)); for (Entry<String, Attrs> e : exports.entrySet()) { if (!runsystempackages.containsKey(e.getKey())) runsystempackages.put(e.getKey(), e.getValue()); } // Allow activators on the runpath. They are called // after the framework is completely initialized // with the system context. String activator = manifest.getMainAttributes() .getValue(EMBEDDED_ACTIVATOR); if (activator != null) activators.add(activator); } pathlist.add(path); } } } } protected void addClasspath(Collection<Container> path) throws Exception { for (Container c : Container.flatten(path)) { addClasspath(c); } } public void addRunBundle(String path) { path = IO.normalizePath(path); if (!runbundles.contains(path)) { runbundles.add(path); } } public Collection<String> getRunBundles() { return runbundles; } public void addRunVM(String arg) { runvm.add(arg); } public void addRunProgramArgs(String arg) { runprogramargs.add(arg); } public List<String> getRunpath() { return classpath; } public Collection<String> getClasspath() { return classpath; } public Collection<String> getRunVM() { return runvm; } @Deprecated public Collection<String> getArguments() { return getRunProgramArgs(); } public Collection<String> getRunProgramArgs() { return runprogramargs; } public Map<String, String> getRunProperties() { return runproperties; } public File getStorageDir() { return storageDir; } public abstract String getMainTypeName(); public void update() throws Exception { getProject().refresh(); } @Override public String getJavaExecutable(String java) { return getProject().getJavaExecutable(java); } public int launch() throws Exception { prepare(); java = new Command(); // Handle the environment Map<String, String> env = getRunEnv(); for (Map.Entry<String, String> e : env.entrySet()) { java.var(e.getKey(), e.getValue()); } java.add(getJavaExecutable("java")); if (getProject().is(Constants.JAVAAGENT)) { for (String agent : agents) { java.add("-javaagent:" + agent); } } String jdb = getRunJdb(); if (jdb != null) { int port = 1044; try { port = Integer.parseInt(jdb); } catch (Exception e) { // ok, value can also be ok, or on, or true } String suspend = port > 0 ? "y" : "n"; java.add("-Xrunjdwp:server=y,transport=dt_socket,address=" + Math.abs(port) + ",suspend=" + suspend); } java.addAll(split(System.getenv("JAVA_OPTS"), "\\s+")); java.add("-cp"); java.add(join(getClasspath(), File.pathSeparator)); java.addAll(getRunVM()); java.add(getMainTypeName()); java.addAll(getRunProgramArgs()); if (getTimeout() != 0) { java.setTimeout(getTimeout() + 1000, TimeUnit.MILLISECONDS); } File cwd = getCwd(); if (cwd != null) java.setCwd(cwd); logger.debug("cmd line {}", java); try { int result = java.execute(in, out, err); if (result == Integer.MIN_VALUE) return TIMEDOUT; reportResult(result); return result; } finally { cleanup(); listeners.clear(); } } /** * launch a framework internally. I.e. do not start a separate process. */ final static Pattern IGNORE = Pattern.compile("org[./]osgi[./]resource.*"); public int start(ClassLoader parent) throws Exception { // FIXME This seems kinda broken. I think ProjectLauncherImpl will need // to implement this since only it will know the main class name of the // non-pre jar prepare(); // Intermediate class loader to not load osgi framework packages // from bnd's loader. Unfortunately, bnd uses some osgi classes // itself that would unnecessarily constrain the framework. ClassLoader fcl = new ClassLoader(parent) { @Override protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException { if (IGNORE.matcher(name) .matches()) throw new ClassNotFoundException(); return super.loadClass(name, resolve); } }; // Load the class that would have gone to the class path // i.e. the framework etc. List<URL> cp = new ArrayList<>(); for (String path : getRunpath()) { cp.add(new File(path).toURI() .toURL()); } @SuppressWarnings("resource") URLClassLoader cl = new URLClassLoader(cp.toArray(new URL[0]), fcl) { @Override public void addURL(URL url) { super.addURL(url); } }; String[] args = getRunProgramArgs().toArray(new String[0]); Class<?> main = cl.loadClass(getMainTypeName()); return invoke(main, args); } protected int invoke(Class<?> main, String args[]) throws Exception { throw new UnsupportedOperationException(); } /** * Is called after the process exists. Can you be used to cleanup the * properties file. */ public void cleanup() { // do nothing by default } protected void reportResult(int result) { switch (result) { case OK : logger.debug("Command terminated normal {}", java); break; case TIMEDOUT : getProject().error("Launch timedout: %s", java); break; case ERROR : getProject().error("Launch errored: %s", java); break; case WARNING : getProject().warning("Launch had a warning %s", java); break; default : getProject().error("Exit code remote process %d: %s", result, java); break; } } public void setTimeout(long timeout, TimeUnit unit) { this.timeout = unit.convert(timeout, TimeUnit.MILLISECONDS); } public long getTimeout() { return this.timeout; } public void cancel() throws Exception { java.cancel(); } public Map<String, ? extends Map<String, String>> getSystemPackages() { return runsystempackages.asMapMap(); } public String getSystemCapabilities() { return runsystemcapabilities.isEmpty() ? null : runsystemcapabilities.toString(); } public Parameters getSystemCapabilitiesParameters() { return runsystemcapabilities; } public void setKeep(boolean keep) { this.keep = keep; } public boolean isKeep() { return keep; } @Override public void setTrace(boolean level) { this.trace = level; } public boolean getTrace() { return this.trace; } /** * Should be called when all the changes to the launchers are set. Will * calculate whatever is necessary for the launcher. * * @throws Exception */ public void prepare() throws Exception { // noop } public Project getProject() { return project; } public boolean addActivator(String e) { return activators.add(e); } public Collection<String> getActivators() { return Collections.unmodifiableCollection(activators); } /** * Either NONE or SERVICES to indicate how the remote end launches. NONE * means it should not use the classpath to run a framework. This likely * requires some dummy framework support. SERVICES means it should load the * framework from the claspath. */ public int getRunFramework() { return framework; } public void setRunFramework(int n) { assert n == NONE || n == SERVICES; this.framework = n; } /** * Add the specification for a set of bundles the runpath if it does not * already is included. This can be used by subclasses to ensure the proper * jars are on the classpath. * * @param defaultSpec The default spec for default jars */ public void addDefault(String defaultSpec) throws Exception { Collection<Container> deflts = getProject().getBundles(Strategy.HIGHEST, defaultSpec, null); for (Container c : deflts) addClasspath(c); } /** * Create a self executable. */ public Jar executable() throws Exception { throw new UnsupportedOperationException(); } public File getCwd() { return cwd; } public void setCwd(File cwd) { this.cwd = cwd; } public String getRunJdb() { return getProject().getProperty(Constants.RUNJDB); } public Map<String, String> getRunEnv() { String runenv = getProject().getProperty(Constants.RUNENV); if (runenv != null) { return OSGiHeader.parseProperties(runenv); } return Collections.emptyMap(); } public interface NotificationListener { void notify(NotificationType type, String notification); } public enum NotificationType { ERROR, WARNING, INFO; } public void registerForNotifications(NotificationListener listener) { listeners.add(listener); } public Set<NotificationListener> getNotificationListeners() { return Collections.unmodifiableSet(listeners); } /** * Set the stderr and stdout streams for the output process. The debugged * process must append its output (i.e. write operation in the process under * debug) to the given appendables. * * @param out std out * @param err std err */ public void setStreams(Appendable out, Appendable err) { this.out = out; this.err = err; } /** * Write text to the debugged process as if it came from stdin. * * @param text the text to write * @throws Exception */ public void write(String text) throws Exception { } /** * Get the run sessions. If this return null, then launch on this object * should be used, otherwise each returned object provides a remote session. * * @throws Exception */ public List<? extends RunSession> getRunSessions() throws Exception { return null; } /** * Utility to calculate the final framework properties from settings */ public void calculatedProperties(Map<String, String> properties) throws Exception { if (getTrace()) properties.put(Constants.LAUNCH_TRACE, "true"); boolean eager = launcherInstrs.runoptions() .contains(LauncherInstructions.RunOption.eager); if (eager) properties.put(Constants.LAUNCH_ACTIVATION_EAGER, Boolean.toString(eager)); Collection<String> activators = getActivators(); if (!activators.isEmpty()) properties.put(Constants.LAUNCH_ACTIVATORS, join(activators, ",")); if (!keep) properties.put(org.osgi.framework.Constants.FRAMEWORK_STORAGE_CLEAN, org.osgi.framework.Constants.FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT); if (!runsystemcapabilities.isEmpty()) properties.put(org.osgi.framework.Constants.FRAMEWORK_SYSTEMCAPABILITIES_EXTRA, runsystemcapabilities.toString()); if (!runsystempackages.isEmpty()) properties.put(org.osgi.framework.Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, runsystempackages.toString()); setupStartlevels(properties); } /** * Calculate the start level properties. This code is matched to the * aQute.lib class {@link StartLevelRuntimeHandler} that handles the runtime * details. * <p> * The -runbundles instruction can carry a `startlevel` attribute. If any * bundle has this start level attribute we control the startlevel process. * If no bundle has this attribute, then the start level handling is not * doing anything. The remaining section assumes that there is at least 1 * bundle with a set startlevel attribute. * <p> * The {@link StartLevelRuntimeHandler#LAUNCH_STARTLEVEL_DEFAULT} is then * set to the maximum startlevel + 1. This signals that the * {@link StartLevelRuntimeHandler} class handles the runtime aspects. * <p> * The {@link Constants#RUNSTARTLEVEL_BEGIN} controls the beginning start * level of the framework after the framework itself is started. The user * can set this or else it is set to the maxmum startlevel+2. * <p> * During runtime, the handler must be created with * {@link StartLevelRuntimeHandler#create(aQute.lib.startlevel.Trace, Map)} * before the framework is created since it may change the properties. I.e. * the properties given to the {@link FrameworkFactory} must be the same * object as given to the create method. One thing is that it will set the * {@link Constants#RUNSTARTLEVEL_BEGIN} to ensure that all bundles are * installed at level 1. * <p> * After the framework is created, the runtime handler * {@link StartLevelRuntimeHandler#beforeStart(org.osgi.framework.launch.Framework)} * must be called. This will prepare that bundles will get their proper * start level when installed. * <p> * After the set of bundles is installed, the * {@link StartLevelRuntimeHandler#afterStart()} is called to raise the * start level to the desired level. Either the set * {@link Constants#RUNSTARTLEVEL_BEGIN} or the maximum level + 2. */ private void setupStartlevels(Map<String, String> properties) throws Exception, IOException { Parameters runbundles = new Parameters(); int maxLevel = -1; for (Container c : project.getRunbundles()) { Map<String, String> attrs = c.getAttributes(); if (attrs == null) continue; if (c.getBundleSymbolicName() == null) continue; if (c.getError() != null) continue; if (c.getFile() == null || !c.getFile() .isFile()) continue; Attrs runtimeAttrs; if (attrs instanceof Attrs) { runtimeAttrs = new Attrs((Attrs) attrs); } else { runtimeAttrs = new Attrs(attrs); } String startLevelString = attrs.get(Constants.RUNBUNDLES_STARTLEVEL_ATTRIBUTE); if (startLevelString == null) continue; int startlevel = -1; if (!Verifier.isNumber(startLevelString)) { error("Invalid start level on -runbundles. bsn=%s, version=%s, startlevel=%s, not a number", c.getBundleSymbolicName(), c.getVersion(), startLevelString); continue; } else { startlevel = Integer.parseInt(startLevelString); if (startlevel > 0) { if (startlevel > maxLevel) maxLevel = startlevel; } Domain domain = Domain.domain(c.getFile()); String bsn = domain.getBundleSymbolicName() .getKey(); String bundleVersion = domain.getBundleVersion(); if (!Verifier.isVersion(bundleVersion)) { error("Invalid version on -runbundles. bsn=%s, version=%s", c.getBundleSymbolicName(), c.getVersion(), startLevelString); continue; } else { runtimeAttrs.put("version", bundleVersion); } runbundles.put(bsn, runtimeAttrs); } } boolean areStartlevelsEnabled = maxLevel > 0; String beginningLevelString = properties.get(FRAMEWORK_BEGINNING_STARTLEVEL); if (!runbundles.isEmpty()) { properties.put(Constants.LAUNCH_RUNBUNDLES_ATTRS, runbundles.toString()); if (areStartlevelsEnabled) { int defaultLevel = maxLevel + 1; int beginningLevel = maxLevel + 2; if (!properties.containsKey(LAUNCH_STARTLEVEL_DEFAULT)) properties.put(LAUNCH_STARTLEVEL_DEFAULT, Integer.toString(defaultLevel)); if (beginningLevelString == null) { properties.put(FRAMEWORK_BEGINNING_STARTLEVEL, Integer.toString(beginningLevel)); } } } if (beginningLevelString != null) { if (!Verifier.isNumber(beginningLevelString)) { error("%s set to %s, not a valid startlevel (is not a number)", beginningLevelString); } else { int beginningStartLevel = Integer.parseInt(beginningLevelString); if (beginningStartLevel < 1) { error("%s set to %s, must be > 0", beginningLevelString); } } } } public LiveCoding liveCoding(Executor executor, ScheduledExecutorService scheduledExecutor) throws Exception { return new LiveCoding(executor, scheduledExecutor); } public class LiveCoding implements Closeable { private final Semaphore semaphore = new Semaphore(1); private final AtomicBoolean propertiesChanged = new AtomicBoolean(false); private final Executor executor; private final ScheduledExecutorService scheduledExecutor; private volatile FileWatcher fw; LiveCoding(Executor executor, ScheduledExecutorService scheduledExecutor) throws Exception { this.executor = requireNonNull(executor); this.scheduledExecutor = requireNonNull(scheduledExecutor); watch(); } @Override public void close() { FileWatcher old = fw; if (old != null) { old.close(); } } private void watch() throws IOException { Builder builder = new FileWatcher.Builder().executor(executor) .changed(this::changed) .file(getProject().getPropertiesFile()) .files(getProject().getIncluded()); for (String runpath : getRunpath()) { builder.file(new File(runpath)); } for (String runbundle : getRunBundles()) { builder.file(new File(runbundle)); } FileWatcher old = fw; fw = builder.build(); if (old != null) { old.close(); } logger.debug("[LiveCoding] Watching for changes..."); } private void changed(File file, String kind) { logger.info("[LiveCoding] Detected change to {}.", file); propertiesChanged.compareAndSet(false, getProject().getPropertiesFile() .equals(file) || getProject().getIncluded() .contains(file)); if (semaphore.tryAcquire()) { scheduledExecutor.schedule(() -> { try { logger.info("[LiveCoding] Updating ProjectLauncher."); update(); } catch (Exception e) { logger.error("[LiveCoding] Error on ProjectLauncher update", e); } finally { semaphore.release(); if (propertiesChanged.compareAndSet(true, false)) { logger.info("[LiveCoding] Detected changes to bnd properties file. Replacing watcher."); try { watch(); } catch (IOException e) { logger.error("[LiveCoding] Error replacing watcher {}", e); } } } }, 600, TimeUnit.MILLISECONDS); } } } }
package signature.chemistry; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.ArrayList; import java.util.Collections; import java.util.List; import junit.framework.Assert; import org.junit.Test; import signature.chemistry.Molecule; import signature.chemistry.MoleculeSignature; public class LargeMoleculeTest { public void addRing(int atomToAttachTo, int ringSize, Molecule molecule) { int numberOfAtoms = molecule.getAtomCount(); int previous = atomToAttachTo; for (int i = 0; i < ringSize; i++) { molecule.addAtom("C"); int current = numberOfAtoms + i; molecule.addSingleBond(previous, current); previous = current; } molecule.addSingleBond(numberOfAtoms, numberOfAtoms + (ringSize - 1)); } public Molecule makeMinimalMultiRing(int ringCount, int ringSize) { Molecule mol = new Molecule(); mol.addAtom("C"); for (int i = 0; i < ringCount; i++) { addRing(0, ringSize, mol); } return mol; } public Molecule makeTetrakisTriphenylPhosphoranylRhodium() { Molecule ttpr = new Molecule(); ttpr.addAtom("Rh"); int phosphateCount = 2; for (int i = 1; i <= phosphateCount; i++) { ttpr.addAtom("P"); ttpr.addSingleBond(0, i); } int phenylCount = 3; for (int j = 1; j <= phosphateCount; j++) { for (int k = 0; k < phenylCount; k++) { addRing(j, 6, ttpr); } } return ttpr; } @Test public void ttprTest() { Molecule ttpr = makeTetrakisTriphenylPhosphoranylRhodium(); MoleculeSignature molSig = new MoleculeSignature(ttpr); // String sigString = molSig.toCanonicalString(); String sigString = molSig.signatureStringForVertex(0); System.out.println(sigString); } @Test public void testMinimalMol() { Molecule mol = makeMinimalMultiRing(5, 3); MoleculeSignature molSig = new MoleculeSignature(mol); // String sigString = molSig.toCanonicalString(); String sigString = molSig.signatureStringForVertex(0); System.out.println(sigString); System.out.println(mol); System.out.println("result " + sigString); } public Molecule makeChain(int length) { Molecule chain = new Molecule(); int previous = -1; for (int i = 0; i < length; i++) { chain.addAtom("C"); if (previous != -1) { chain.addSingleBond(previous, i); } previous = i; } return chain; } @Test public void testLongChains() { int length = 10; Molecule chain = makeChain(length); MoleculeSignature molSig = new MoleculeSignature(chain); String sigString = molSig.toCanonicalString(); System.out.println(sigString); } @Test public void buckyballTest() { Molecule molecule = MoleculeReader.readMolfile("data/buckyball.mol"); MoleculeQuotientGraph mqg = new MoleculeQuotientGraph(molecule); System.out.println(mqg); Assert.assertEquals(32, mqg.getVertexCount()); Assert.assertEquals(49, mqg.getEdgeCount()); Assert.assertEquals(6, mqg.numberOfLoopEdges()); } @Test public void buckyballWithoutMultipleBonds() { Molecule molecule = MoleculeReader.readMolfile("data/buckyball.mol"); for (Molecule.Bond bond : molecule.bonds()) { bond.order = 1; } MoleculeQuotientGraph mqg = new MoleculeQuotientGraph(molecule); System.out.println(mqg); Assert.assertEquals(1, mqg.getVertexCount()); Assert.assertEquals(1, mqg.getEdgeCount()); Assert.assertEquals(1, mqg.numberOfLoopEdges()); } @Test public void faulonsBuckySignatures() { Molecule mol = MoleculeReader.readMolfile("data/buckyball.mol"); try { // String filename = "data/buckysigs.txt"; String filename = "data/buckysigs3.txt"; List<String> sigs = readSigs2(filename); MoleculeQuotientGraph mqg = new MoleculeQuotientGraph(mol, sigs); System.out.println(mqg); Assert.assertEquals(32, mqg.getVertexCount()); Assert.assertEquals(49, mqg.getEdgeCount()); Assert.assertEquals(6, mqg.numberOfLoopEdges()); } catch (Exception e) { System.out.println(e); return; } } public List<String> readSigs(String filename) throws Exception { File file = new File(filename); BufferedReader reader = new BufferedReader(new FileReader(file)); String line; List<String> sigs = new ArrayList<String>(); while ((line = reader.readLine()) != null) { int index = line.indexOf(" ") + 1; int count = Integer.parseInt(line.substring(0, index - 1)); String sig = line.substring(index); System.out.println(count); sigs.add(sig); } return sigs; } public List<String> readSigs2(String filename) throws Exception { File file = new File(filename); BufferedReader reader = new BufferedReader(new FileReader(file)); String line; List<String> sigs = new ArrayList<String>(); while ((line = reader.readLine()) != null) { String[] bits = line.split("\\s+"); String sig = bits[3]; sigs.add(sig); } Collections.reverse(sigs); return sigs; } public static void main(String[] args) { new LargeMoleculeTest().testMinimalMol(); // new LargeMoleculeTest().ttprTest(); } }
package uk.org.cinquin.mutinack.statistics; import java.io.Serializable; import java.util.Collection; import java.util.Comparator; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.TreeSet; import java.util.function.Predicate; import java.util.stream.Collectors; import javax.jdo.annotations.PersistenceCapable; import org.eclipse.jdt.annotation.NonNull; import org.eclipse.jdt.annotation.Nullable; import com.fasterxml.jackson.annotation.JsonIgnore; import gnu.trove.map.hash.THashMap; import uk.org.cinquin.final_annotation.Final; import uk.org.cinquin.mutinack.SequenceLocation; import uk.org.cinquin.mutinack.misc_util.Pair; import uk.org.cinquin.mutinack.misc_util.SerializablePredicate; import uk.org.cinquin.mutinack.misc_util.SerializableSupplier; @PersistenceCapable public class MultiCounter<T> implements ICounterSeqLoc, Serializable, Actualizable { @JsonIgnore private static final long serialVersionUID = 8621583719293625759L; @JsonIgnore protected boolean on = true; @JsonIgnore private final transient @Nullable SerializableSupplier<@NonNull ICounter<T>> factory1; @JsonIgnore private final transient @Nullable SerializableSupplier<@NonNull ICounterSeqLoc> factory2; private final THashMap<String, Pair<SerializablePredicate<SequenceLocation>, ICounter<T>>> counters = new THashMap<>(); private final THashMap<String, Pair<SerializablePredicate<SequenceLocation>, ICounterSeqLoc>> seqLocCounters = new THashMap<>(); @JsonIgnore private final DoubleAdderFormatter adderForTotal = new DoubleAdderFormatter(); @JsonIgnore private static final transient @NonNull SerializablePredicate<SequenceLocation> yes = l -> true; @SuppressWarnings("rawtypes") private interface SerializableComparator extends Comparator<Entry<String, Pair<Predicate<SequenceLocation>, Comparable>>>, Serializable { } @SuppressWarnings({ "unchecked", "rawtypes" }) private static final SerializableComparator byKeySorter = (e, f) -> ((Comparable) e.getKey()).compareTo(f.getKey()); @SuppressWarnings({ "unchecked" }) private static final SerializableComparator byValueSorter = (e, f) -> { int result = - e.getValue().snd.compareTo(f.getValue().snd); if (result == 0) { result = e.getKey().compareTo(f.getKey()); } return result; }; @JsonIgnore @SuppressWarnings("rawtypes") private @Final transient Comparator<? super Entry<String, Pair<Predicate<SequenceLocation>, Comparable>>> printingSorter; public MultiCounter(@Nullable SerializableSupplier<@NonNull ICounter<T>> factory1, @Nullable SerializableSupplier<@NonNull ICounterSeqLoc> factory2) { this(factory1, factory2, false); } public MultiCounter(@Nullable SerializableSupplier<@NonNull ICounter<T>> factory1, @Nullable SerializableSupplier<@NonNull ICounterSeqLoc> factory2, boolean sortByValue) { if (sortByValue) { printingSorter = byValueSorter; } else { printingSorter = byKeySorter; } this.factory1 = factory1; this.factory2 = factory2; addPredicate("All", yes); } public Map<String, Pair<SerializablePredicate<SequenceLocation>, ICounterSeqLoc>> getSeqLocCounters() { return seqLocCounters; } public void addPredicate(String name, @NonNull SerializablePredicate<SequenceLocation> predicate) { if (factory1 != null) { counters.put(name, new Pair<>(predicate, factory1.get())); } if (factory2 != null) { seqLocCounters.put(name, new Pair<>(predicate, factory2.get())); } } public void addPredicate(String name, @NonNull SerializablePredicate<SequenceLocation> predicate, @NonNull ICounterSeqLoc counter) { if (seqLocCounters.put(name, new Pair<>(predicate, counter)) != null) { throw new IllegalArgumentException("Counter with name " + name + " already exists"); } } @Override public void accept(@NonNull SequenceLocation loc) { if (on) accept(loc, 1d); } @Override public void accept(@NonNull SequenceLocation loc, double d) { if (!on) { return; } adderForTotal.add(d); seqLocCounters.forEachValue(c -> { if (c.fst.test(loc)) { c.snd.accept(loc, d); } return true; }); } public void accept(@NonNull SequenceLocation loc, @NonNull T t, double d) { if (!on) { return; } adderForTotal.add(d); seqLocCounters.forEachValue(c -> { if (c.fst.test(loc)) { c.snd.accept(loc, d); } return true; }); counters.forEachValue(c -> { if (c.fst.test(loc)) { c.snd.accept(t, d); } return true; }); } public void accept(@NonNull SequenceLocation loc, @NonNull T t) { if (on) accept(loc, t, 1d); } @SuppressWarnings("unchecked") @Override public String toString() { StringBuilder b = new StringBuilder(); for (Entry<String, Pair<SerializablePredicate<SequenceLocation>, ICounter<T>>> e: counters.entrySet(). stream().sorted((Comparator<? super Entry<String, Pair<SerializablePredicate<SequenceLocation>, ICounter<T>>>>) printingSorter).collect(Collectors.toList())) { b.append(e.getKey()).append(": ").append(e.getValue().snd.toString()). append("; total: ").append(DoubleAdderFormatter.formatDouble(e.getValue().snd.sum())). append('\n'); } for (Entry<String, Pair<SerializablePredicate<SequenceLocation>, ICounterSeqLoc>> e: seqLocCounters.entrySet(). stream().sorted((Comparator<? super Entry<String, Pair<SerializablePredicate<SequenceLocation>, ICounterSeqLoc>>>) printingSorter).collect(Collectors.toList())) { b.append(e.getKey()).append(": ").append(e.getValue().snd.toString()).append('\n'); /*b.append(e.getKey()).append(": total ").append(e.getValue().snd.totalSum()). append("; ").append(e.getValue().snd.toString()).append("\n");*/ } return b.toString(); } public long sum() { return (long) adderForTotal.sum(); } @Override public double totalSum() { return adderForTotal.sum(); } @Override public void accept(@NonNull SequenceLocation loc, long l) { if (on) accept(loc, (double) l); } public void acceptSkip0(@NonNull SequenceLocation loc, long l) { if (l == 0) { return; } if (on) accept(loc, (double) l); } public double getSum(String predicateName) { if (counters.containsKey(predicateName)) { return counters.get(predicateName).getSnd().sum(); } else if (seqLocCounters.containsKey(predicateName)) { return seqLocCounters.get(predicateName).getSnd().totalSum(); } else { return Double.NaN; } } public Set<String> getCounterNames() { Set<String> result = new TreeSet<>(); result.addAll(counters.keySet()); seqLocCounters.forEachEntry((k , v) -> { if (!(v.snd instanceof CounterWithBedFeatureBreakdown)) { result.add(k); } return true; }); return result; } @Override public @NonNull Map<Object, @NonNull Object> getCounts() { throw new RuntimeException("Not implemented"); } @Override public void turnOff() { on = false; } @Override public void turnOn() { on = true; } @Override public boolean isOn() { return on; } @Override public int compareTo(Object o) { return Double.compare(totalSum(), ((ICounterSeqLoc) o).totalSum()); } @Override public boolean equals(Object o) { throw new RuntimeException("Unimplemented"); } @Override public int hashCode() { throw new RuntimeException("Unimplemented"); } @Override public void actualize() { actualizeValues(counters.values()); actualizeValues(seqLocCounters.values()); } @SuppressWarnings("unchecked") private static void actualizeValues(@SuppressWarnings("rawtypes") Collection values) { values.forEach(o -> { Pair<?, ?> p = (Pair<?, ?>) o; if (p.snd instanceof Actualizable) { ((Actualizable) p.snd).actualize(); } }); } }
package src.usi.gui.functionality; import java.util.ArrayList; import java.util.List; import src.usi.configuration.ConfigurationManager; import src.usi.gui.functionality.instance.Instance_GUI_pattern; import src.usi.gui.structure.Action_widget; import src.usi.gui.structure.GUI; import src.usi.gui.structure.Input_widget; import src.usi.gui.structure.Option_input_widget; import src.usi.gui.structure.Selectable_widget; import src.usi.gui.structure.Window; import src.usi.semantic.FunctionalitySemantics; import src.usi.semantic.SpecificSemantics; import src.usi.semantic.alloy.AlloyUtil; import src.usi.semantic.alloy.Alloy_Model; import src.usi.semantic.alloy.structure.Fact; import src.usi.testcase.AlloyTestCaseGenerator; import src.usi.testcase.GUITestCaseResult; import src.usi.testcase.TestCaseRunner; import src.usi.testcase.structure.Click; import src.usi.testcase.structure.Fill; import src.usi.testcase.structure.GUIAction; import src.usi.testcase.structure.GUITestCase; import src.usi.testcase.structure.Select; import com.google.common.collect.HashBasedTable; import com.google.common.collect.Table; public class GUIFunctionality_validate { private final Instance_GUI_pattern instancePattern; private final GUI gui; private List<String> windows_to_visit = new ArrayList<>(); private final List<String> aw_to_click; private final List<String> iw_to_fill; private final List<String> sw_to_select; private final List<GUITestCaseResult> completely_executed_tcs; private SpecificSemantics working_sem; protected List<String> semantic_cases; private List<String> semantic_pairwaise_cases; private final Table<String, String, String> pairwise; // number of times a run command can be executed final int MAX_RUN = 1; final int batch_size = ConfigurationManager.getMultithreadingBatchSize(); public GUIFunctionality_validate(final Instance_GUI_pattern instancePattern, final GUI gui) throws Exception { this.completely_executed_tcs = new ArrayList<>(); this.instancePattern = instancePattern; this.gui = gui; this.windows_to_visit = new ArrayList<>(); this.aw_to_click = new ArrayList<>(); this.iw_to_fill = new ArrayList<>(); this.sw_to_select = new ArrayList<>(); this.semantic_pairwaise_cases = new ArrayList<>(); this.init(); final List<String> edges = new ArrayList<>(); for (final Action_widget aw : instancePattern.getGui().getAction_widgets()) { if (instancePattern.getPAW_for_AW(aw.getId()) == null) { continue; } for (final Window w : instancePattern.getGui().getDynamicForwardLinks(aw.getId())) { final String edge = aw.getId() + " -> " + w.getId(); edges.add(edge); } for (final Window w : instancePattern.getGui().getStaticForwardLinks(aw.getId())) { final String edge = aw.getId() + " -> " + w.getId(); edges.add(edge); } } this.generate_run_commands(instancePattern.getSemantics()); this.pairwise = HashBasedTable.create(); for (int x = 0; x < edges.size(); x++) { final String edge1 = edges.get(x); final String dest1 = edge1.split(" -> ")[1]; final String aw1 = edge1.split(" -> ")[0]; for (int y = x; y < edges.size(); y++) { final String edge2 = edges.get(y); final String dest2 = edge2.split(" -> ")[1]; final String aw2 = edge2.split(" -> ")[0]; String run = "run {System and (some t1,t2: Time | not(t1=t2) and #Track.op.(T/next[t1]) = 1 and Track.op.(T/next[t1]) in Click and #Track.op.(T/next[t2]) = 1 and Track.op.(T/next[t2]) in Click and "; run += "Track.op.(T/next[t1]).clicked = Action_widget_" + aw1 + " and Track.op.(T/next[t2]).clicked = Action_widget_" + aw2 + " and Current_window.is_in.(T/next[t1]) = Window_" + dest1 + " and Current_window.is_in.(T/next[t2]) = Window_" + dest2 + " and click_semantics[Action_widget_" + aw1 + ", t1] and click_semantics[Action_widget_" + aw2 + ", t2])}"; this.pairwise.put(edge1, edge2, run); // run = // "run {System and (some t1,t2: Time | t1 in T/nexts[t2] and #Track.op.(T/next[t1]) = 1 and Track.op.(T/next[t1]) in Click and #Track.op.(T/next[t2]) = 1 and Track.op.(T/next[t2]) in Click and "; // run += "Track.op.(T/next[t1]).clicked = Action_widget_" + aw1 // + " and Track.op.(T/next[t2]).clicked = Action_widget_" + aw2 // + " and Current_window.is_in.(T/next[t1]) = Window_" + dest1 // + " and Current_window.is_in.(T/next[t2]) = Window_" + dest2 // + " and click_semantics[Action_widget_" + aw1 // + ", t1] and click_semantics[Action_widget_" + aw2 + // this.pairwise.put(edge2, edge1, run); } } } protected void init() { for (final Window w : this.instancePattern.getGui().getWindows()) { this.windows_to_visit.add(w.getId()); for (final Action_widget aw : w.getActionWidgets()) { if (this.instancePattern.getPAW_for_AW(aw.getId()) != null) { this.aw_to_click.add(aw.getId()); } } for (final Input_widget iw : w.getInputWidgets()) { if (iw instanceof Option_input_widget) { final Option_input_widget oiw = (Option_input_widget) iw; if (oiw.getSize() == 0) { continue; } } if (this.instancePattern.getPIW_for_IW(iw.getId()) != null) { this.iw_to_fill.add(iw.getId()); } } for (final Selectable_widget sw : w.getSelectableWidgets()) { if (this.instancePattern.getPSW_for_SW(sw.getId()) != null) { this.sw_to_select.add(sw.getId()); } } } } private List<GUITestCaseResult> runTestCases(final List<GUITestCase> testcases) throws Exception { final TestCaseRunner runner = new TestCaseRunner(this.gui); final List<GUITestCaseResult> results = new ArrayList<>(); for (final GUITestCase tc : testcases) { final GUITestCaseResult res = runner.runTestCase(tc); // final GUITestCaseResult res2 = // this.instancePattern.updateTCResult(res); // if (res2 != null) { // res = res2; results.add(res); } return results; } private List<GUITestCaseResult> execute(final boolean minimal) throws Exception { final List<GUITestCaseResult> out = new ArrayList<>(); SpecificSemantics working_sem_bis = new SpecificSemantics(this.working_sem.getSignatures(), this.working_sem.getFacts(), this.working_sem.getPredicates(), this.working_sem.getFunctions(), this.working_sem.getOpenStatements()); for (final String run : this.working_sem.getRun_commands()) { working_sem_bis.addRun_command(run); } final Instance_GUI_pattern work_instance = this.instancePattern.clone(); work_instance.setSpecificSemantics(working_sem_bis); for (int cont = 0; cont < this.MAX_RUN; cont++) { List<GUITestCase> testcases = null; if (minimal) { final List<String> runs = working_sem_bis.getRun_commands(); testcases = new ArrayList<>(); for (final String run : runs) { working_sem_bis.clearRunCommands(); working_sem_bis.addRun_command(run); final AlloyTestCaseGenerator generator = new AlloyTestCaseGenerator( work_instance); testcases.addAll(generator.generateMinimalTestCases(ConfigurationManager .getTestcaseLength())); } } else { final AlloyTestCaseGenerator generator = new AlloyTestCaseGenerator(work_instance); testcases = generator.generateTestCases(); } final List<GUITestCase> testcases_filtered = new ArrayList<>(); final List<GUITestCaseResult> results = new ArrayList<>(); // we dont need the alloy result final List<GUITestCase> tests = new ArrayList<>(); for (final GUITestCase tc : testcases) { if (tc != null) { final GUITestCase tc2 = new GUITestCase(null, tc.getActions(), tc.getRunCommand()); tests.add(tc2); } } testcases = tests; final List<GUITestCase> already = new ArrayList<>(); // we filter out the already run test cases for (final GUITestCase tc : testcases) { final GUITestCaseResult res = this.wasTestCasePreviouslyExecuted(tc); if (res != null) { already.add(tc); } else { testcases_filtered.add(tc); } } if (already.size() > 0) { System.out.println("RE-EXECUTING ALREADY RUN TEST CASES:"); for (final GUITestCase tc : already) { final Instance_GUI_pattern work_instance2 = this.instancePattern.clone(); final Alloy_Model working_sem_tris = AlloyUtil.getTCaseModelOpposite( working_sem_bis, tc.getActions()); working_sem_tris.clearRunCommands(); working_sem_tris.addRun_command(tc.getRunCommand()); final AlloyTestCaseGenerator generator = new AlloyTestCaseGenerator( work_instance2); work_instance2.setSpecificSemantics(SpecificSemantics .instantiate(working_sem_tris)); List<GUITestCase> testcases2 = null; if (minimal) { testcases2 = generator.generateMinimalTestCases(ConfigurationManager .getTestcaseLength()); } else { testcases2 = generator.generateTestCases(); } for (final GUITestCase tcc : testcases2) { if (tc != null) { final GUITestCase tc2 = new GUITestCase(null, tcc.getActions(), tcc.getRunCommand()); testcases_filtered.add(tc2); } } } } final List<GUITestCaseResult> r = this.runTestCases(testcases_filtered); results.addAll(r); out.addAll(r); final List<GUITestCaseResult> to_rerun = new ArrayList<>(); for (final GUITestCaseResult res : results) { if (res.getActions_executed().size() < res.getTc().getActions().size()) { // if the testcase is not run completely to_rerun.add(res); // we don't need the result final GUITestCase tc = new GUITestCase(null, res.getActions_executed(), res .getTc().getRunCommand()); final GUITestCaseResult new_res = new GUITestCaseResult(tc, res.getActions_executed(), res.getResults(), res.getActions_actually_executed()); // working_sem_bis = SpecificSemantics.instantiate(AlloyUtil // .getTCaseModelOpposite(working_sem_bis, // res.getTc().getActions())); this.completely_executed_tcs.add(new_res); } else { this.completely_executed_tcs.add(res); } } if (to_rerun.size() == 0) { break; } System.out.println(to_rerun.size() + " TESTCASES WERE NOT RUN COMPLETELY."); working_sem_bis = new SpecificSemantics(working_sem_bis.getSignatures(), working_sem_bis.getFacts(), working_sem_bis.getPredicates(), working_sem_bis.getFunctions(), working_sem_bis.getOpenStatements()); for (final GUITestCaseResult run : to_rerun) { working_sem_bis.addRun_command(run.getTc().getRunCommand()); } work_instance.setSpecificSemantics(working_sem_bis); } return out; } public List<GUITestCaseResult> validate() throws Exception { final long beginTime = System.currentTimeMillis(); // we add a fact to filter redundant actions final List<Fact> facts = this.instancePattern.getSemantics().getFacts(); // final Fact new_fact = new Fact( // "filter_redundant_actions", // "no t: Time | #Track.op.t = 1 and Track.op.t in Select and Track.op.(T/prev[t]) in Select and Track.op.(T/prev[t]).wid = Track.op.t.wid" // // + System.lineSeparator() // "no t: Time | #Track.op.t = 1 and Track.op.t in Fill and Track.op.(T/prev[t]) in Fill and Track.op.(T/prev[t]).filled = Track.op.t.filled" // + System.lineSeparator() // "no t: Time | #Track.op.t = 1 and Track.op.t in Click and Track.op.(T/prev[t]) in Click and Track.op.t.clicked = Track.op.(T/prev[t]).clicked"); // facts.add(new_fact); final SpecificSemantics sem = new SpecificSemantics(this.instancePattern.getSemantics() .getSignatures(), facts, this.instancePattern.getSemantics().getPredicates(), this.instancePattern.getSemantics().getFunctions(), this.instancePattern .getSemantics().getOpenStatements()); this.instancePattern.setSpecificSemantics(sem); final List<GUITestCaseResult> out = new ArrayList<>(); this.working_sem = new SpecificSemantics(this.instancePattern.getSemantics() .getSignatures(), facts, this.instancePattern.getSemantics().getPredicates(), this.instancePattern.getSemantics().getFunctions(), this.instancePattern .getSemantics().getOpenStatements()); System.out.println("COVERING SEMANTIC CASES."); List<String> run_commands = this.semantic_cases; for (int x = 0; x < run_commands.size(); x++) { System.out.println((x + 1) + " " + run_commands.get(x)); } System.out.println(run_commands.size() + " TESTCASES. RUNNING THEM IN BATCHES OF " + this.batch_size + "."); int batch_num = 0; while (((batch_num * this.batch_size)) < run_commands.size()) { System.out.println("BATCH " + (batch_num + 1)); this.working_sem = new SpecificSemantics(this.working_sem.getSignatures(), this.working_sem.getFacts(), this.working_sem.getPredicates(), this.working_sem.getFunctions(), this.working_sem.getOpenStatements()); for (int cont = 0; ((batch_num * this.batch_size) + cont) < run_commands.size() && cont < this.batch_size; cont++) { final String run = run_commands.get(((batch_num * this.batch_size) + cont)); this.working_sem.addRun_command(run); } final List<GUITestCaseResult> results = this.execute(true); for (final GUITestCaseResult r : results) { this.working_sem = SpecificSemantics.instantiate(AlloyUtil.getTCaseModelOpposite( this.working_sem, r.getActions_executed())); } out.addAll(results); batch_num++; } System.out.println("COVERING NEGATIVE CASES."); run_commands = this.semantic_pairwaise_cases; for (int x = 0; x < run_commands.size(); x++) { System.out.println((x + 1) + " " + run_commands.get(x)); } System.out.println(run_commands.size() + " TESTCASES. RUNNING THEM IN BATCHES OF " + this.batch_size + "."); batch_num = 0; while (((batch_num * this.batch_size)) < run_commands.size()) { System.out.println("BATCH " + (batch_num + 1)); this.working_sem = new SpecificSemantics(this.working_sem.getSignatures(), this.working_sem.getFacts(), this.working_sem.getPredicates(), this.working_sem.getFunctions(), this.working_sem.getOpenStatements()); for (int cont = 0; ((batch_num * this.batch_size) + cont) < run_commands.size() && cont < this.batch_size; cont++) { final String run = run_commands.get(((batch_num * this.batch_size) + cont)); this.working_sem.addRun_command(run); } final List<GUITestCaseResult> results = this.execute(true); for (final GUITestCaseResult r : results) { this.working_sem = SpecificSemantics.instantiate(AlloyUtil.getTCaseModelOpposite( this.working_sem, r.getActions_executed())); } out.addAll(results); batch_num++; } if (ConfigurationManager.getPairwiseTestcase()) { System.out.println("COVERING PAIRWISE."); batch_num = 0; System.out.println(this.pairwise.values().size() + " TESTCASES. RUNNING THEM IN BATCHES OF " + this.batch_size + "."); while (true) { this.filterPairwise(out); run_commands = this.getNPairwiseTests(this.batch_size); if (run_commands.size() == 0) { break; } for (int x = 0; x < run_commands.size(); x++) { System.out.println((x + 1) + " " + run_commands.get(x)); } System.out.println("BATCH " + (batch_num + 1)); this.working_sem = new SpecificSemantics(this.working_sem.getSignatures(), this.working_sem.getFacts(), this.working_sem.getPredicates(), this.working_sem.getFunctions(), this.working_sem.getOpenStatements()); for (final String run : run_commands) { this.working_sem.addRun_command(run); } final List<GUITestCaseResult> results = this.execute(false); for (final GUITestCaseResult r : results) { this.working_sem = SpecificSemantics.instantiate(AlloyUtil .getTCaseModelOpposite(this.working_sem, r.getActions_executed())); } out.addAll(results); batch_num++; } } System.out.println("COVERING REMAINING STRUCTURAL ELEMENTS."); // ConfigurationManager.setTestcaseLength(old_tc_size); run_commands = this.getAdditionalRunCommands(this.completely_executed_tcs); for (int x = 0; x < run_commands.size(); x++) { System.out.println((x + 1) + " " + run_commands.get(x)); } System.out.println(run_commands.size() + " TESTCASES. RUNNING THEM IN BATCHES OF " + this.batch_size + "."); batch_num = 0; while (((batch_num * this.batch_size)) < run_commands.size()) { System.out.println("BATCH " + (batch_num + 1)); this.working_sem = new SpecificSemantics(this.working_sem.getSignatures(), this.working_sem.getFacts(), this.working_sem.getPredicates(), this.working_sem.getFunctions(), this.working_sem.getOpenStatements()); for (int cont = 0; ((batch_num * this.batch_size) + cont) < run_commands.size() && cont < this.batch_size; cont++) { final String run = run_commands.get(((batch_num * this.batch_size) + cont)); this.working_sem.addRun_command(run); } final List<GUITestCaseResult> results = this.execute(false); for (final GUITestCaseResult r : results) { this.working_sem = SpecificSemantics.instantiate(AlloyUtil.getTCaseModelOpposite( this.working_sem, r.getActions_executed())); } out.addAll(results); batch_num++; } final long tottime = (System.currentTimeMillis() - beginTime) / 1000; System.out.println("VALIDATION ELAPSED TIME: " + tottime); return out; } // function that returns additional run commands to cover uncovered // structural elements private List<String> getAdditionalRunCommands(final List<GUITestCaseResult> testcases) { for (final GUITestCaseResult tcr : testcases) { final GUITestCase tc = tcr.getTc(); for (final GUIAction act : tc.getActions()) { if (act.getWindow() != null && this.windows_to_visit.contains(act.getWindow().getId())) { this.windows_to_visit.remove(act.getWindow().getId()); } if (act instanceof Click) { final Click click = (Click) act; if (this.aw_to_click.contains(click.getWidget().getId())) { this.aw_to_click.remove(click.getWidget().getId()); } } else if (act instanceof Fill) { final Fill fill = (Fill) act; if (this.iw_to_fill.contains(fill.getWidget().getId())) { this.iw_to_fill.remove(fill.getWidget().getId()); } } else if (act instanceof Select) { final Select select = (Select) act; if (this.sw_to_select.contains(select.getWidget().getId())) { this.sw_to_select.remove(select.getWidget().getId()); } } } } final List<String> new_run_commands = new ArrayList<>(); for (final String winid : this.windows_to_visit) { String new_run = "run{System and "; new_run += "(some t:Time| Current_window.is_in.t = Window_" + winid + ")"; new_run += "}"; new_run_commands.add(new_run); } for (final String awid : this.aw_to_click) { String new_run = "run{System and "; new_run += "(some t:Time| Track.op.t in Click and Track.op.t.clicked = Action_widget_" + awid + ")"; new_run += "}"; new_run_commands.add(new_run); } for (final String iwid : this.iw_to_fill) { String new_run = "run{System and "; new_run += "(some t:Time| Track.op.t in Fill and Track.op.t.filled = Input_widget_" + iwid + ")"; new_run += "}"; new_run_commands.add(new_run); } for (final String swid : this.sw_to_select) { String new_run = "run{System and "; new_run += "(some t:Time| Track.op.t in Select and Track.op.t.wid = Selectable_widget_" + swid + ")"; new_run += "}"; new_run_commands.add(new_run); } return new_run_commands; } protected void generate_run_commands(final FunctionalitySemantics sem) throws Exception { final List<String> commands = new ArrayList<>(); this.semantic_pairwaise_cases = new ArrayList<>(); this.semantic_cases = new ArrayList<>(); final String click = "some t: Time | #Track.op.(T/next[t]) = 1 and Track.op.(T/next[t]) in Click and"; final String click_edge = "click [Track.op.(T/next[t]).clicked, t, T/next[t], Track.op.(T/next[t])] and"; for (final String prec : sem.getClickSemantics().getCases().keySet()) { final String negative_edge = click_edge + " (" + prec + ") and not(click_semantics[Track.op.(T/next[t]).clicked, t])"; final String positive_edge = click_edge + " (" + prec + ") and (click_semantics[Track.op.(T/next[t]).clicked, t])"; commands.add(negative_edge); commands.add(positive_edge); final String pred = click + " (" + prec + ") and ("; // the number of possible combinations final List<String> cases = sem.getClickSemantics().getCases().get(prec); if (cases.size() == 1 && cases.get(0).trim().equals("2=(1+1)")) { final String run_command = "run {System and {" + click + " (" + prec + ")} }"; this.semantic_cases.add(run_command); continue; } final double n = Math.pow(2, cases.size()); for (int cont = 0; cont < n; cont++) { String binary = Integer.toBinaryString(cont); for (int c = 0; c < (cases.size() - binary.length()); c++) { binary = "0" + binary; } String sem_pred = ""; for (int cont2 = cases.size() - 1; cont2 >= 0; cont2 if (cont2 > (binary.length() - 1) || binary.charAt(cont2) == '0') { sem_pred = sem_pred + "not (" + cases.get(cont2) + ")"; } else { sem_pred = sem_pred + cases.get(cont2); } if (cont2 > 0) { sem_pred = sem_pred + " and "; } } final String run_command = "run {System and {" + pred + sem_pred + ")} }"; this.semantic_cases.add(run_command); } } final String fill = "some t: Time | #Track.op.(T/next[t]) = 1 and Track.op.(T/next[t]) in Fill and"; final String fill_edge = "fill [Track.op.(T/next[t]).filled, t, T/next[t], Track.op.(T/next[t]).with, Track.op.(T/next[t])] and"; for (final String prec : sem.getFillSemantics().getCases().keySet()) { final String negative_edge = fill_edge + " (" + prec + ") and not(fill_semantics[Track.op.(T/next[t]).filled, t, Track.op.(T/next[t]).with])"; final String positive_edge = fill_edge + " (" + prec + ") and (fill_semantics[Track.op.(T/next[t]).filled, t, Track.op.(T/next[t]).with])"; commands.add(negative_edge); commands.add(positive_edge); final String pred = fill + " (" + prec + ") and ("; // the number of possible combinations final List<String> cases = sem.getFillSemantics().getCases().get(prec); if (cases.size() == 1 && cases.get(0).trim().equals("2=(1+1)")) { final String run_command = "run {System and {" + click + " (" + prec + ")} }"; this.semantic_cases.add(run_command); continue; } final double n = Math.pow(2, cases.size()); for (int cont = 0; cont < n; cont++) { String binary = Integer.toBinaryString(cont); for (int c = 0; c < (cases.size() - binary.length()); c++) { binary = "0" + binary; } String sem_pred = ""; for (int cont2 = cases.size() - 1; cont2 >= 0; cont2 if (cont2 > (binary.length() - 1) || binary.charAt(cont2) == '0') { sem_pred = sem_pred + "not (" + cases.get(cont2) + ")"; } else { sem_pred = sem_pred + cases.get(cont2); } if (cont2 > 0) { sem_pred = sem_pred + " and "; } } final String run_command = "run {System and {" + pred + sem_pred + ")} }"; this.semantic_cases.add(run_command); } } final String select = "some t: Time | #Track.op.(T/next[t]) = 1 and Track.op.(T/next[t]) in Select and"; final String select_edge = "select [Track.op.(T/next[t]).wid, t, T/next[t], Track.op.(T/next[t]).selected_o, Track.op.(T/next[t])] and"; for (final String prec : sem.getSelectSemantics().getCases().keySet()) { final String negative_edge = select_edge + " (" + prec + ") and not(select_semantics[Track.op.(T/next[t]).wid, t, Track.op.(T/next[t]).selected_o])"; final String positive_edge = select_edge + " (" + prec + ") and (select_semantics[Track.op.(T/next[t]).wid, t, Track.op.(T/next[t]).selected_o])"; commands.add(negative_edge); commands.add(positive_edge); final String pred = select + " (" + prec + ") and ("; // the number of possible combinations final List<String> cases = sem.getSelectSemantics().getCases().get(prec); if (cases.size() == 1 && cases.get(0).trim().equals("2=(1+1)")) { final String run_command = "run {System and {" + click + " (" + prec + ")} }"; this.semantic_cases.add(run_command); continue; } final double n = Math.pow(2, cases.size()); for (int cont = 0; cont < n; cont++) { String binary = Integer.toBinaryString(cont); for (int c = 0; c < (cases.size() - binary.length()); c++) { binary = "0" + binary; } String sem_pred = ""; for (int cont2 = cases.size() - 1; cont2 >= 0; cont2 if (cont2 > (binary.length() - 1) || binary.charAt(cont2) == '0') { sem_pred = sem_pred + "not (" + cases.get(cont2) + ")"; } else { sem_pred = sem_pred + cases.get(cont2); } if (cont2 > 0) { sem_pred = sem_pred + " and "; } } final String run_command = "run {System and {" + pred + sem_pred + ")} }"; this.semantic_cases.add(run_command); } } final List<String> edges = new ArrayList<>(); for (final Action_widget aw : this.instancePattern.getGui().getAction_widgets()) { if (this.instancePattern.getPAW_for_AW(aw.getId()) == null) { continue; } for (final Window w : this.instancePattern.getGui().getDynamicForwardLinks(aw.getId())) { final String edge = aw.getId() + " -> " + w.getId(); edges.add(edge); } } for (int x = 0; x < commands.size(); x++) { for (int y = x; y < commands.size(); y++) { final String edge1 = commands.get(x); String edge2 = commands.get(y); edge2 = edge2.replace("[t]", "[t2]"); edge2 = edge2.replace(".t ", ".t2 "); edge2 = edge2.replace(" t]", " t2]"); edge2 = edge2.replace(", t,", ", t2,"); final String run = "run {System and {some t,t2: Time | not(t=t2) and " + edge1 + " and " + edge2 + "}}"; this.semantic_pairwaise_cases.add(run); } } } private GUITestCaseResult wasTestCasePreviouslyExecuted(final GUITestCase tc) { for (final GUITestCaseResult tc2 : this.completely_executed_tcs) { if (tc.isSame(tc2.getTc())) { return tc2; } } return null; } private void filterPairwise(final List<GUITestCaseResult> ress) { for (final GUITestCaseResult res : ress) { final List<String> covered_edges = new ArrayList<>(); for (final GUIAction act : res.getActions_executed()) { if (!(act instanceof Click)) { continue; } final Click c = (Click) act; final String aw = c.getWidget().getId(); final String sw = c.getWindow().getId(); final String dw = c.getOracle().getId(); covered_edges.add(aw + " -> " + dw); if (sw.equals(dw)) { covered_edges.add("!" + aw); } } for (int x = 0; x < covered_edges.size(); x++) { final String edge1 = covered_edges.get(x); for (int y = x + 1; y < covered_edges.size(); y++) { final String edge2 = covered_edges.get(y); this.pairwise.remove(edge1, edge2); this.pairwise.remove(edge2, edge1); } } } } private List<String> getNPairwiseTests(final int n) throws Exception { final List<String> to_remove = new ArrayList<>(); final List<String> out = new ArrayList<>(); loop: for (final String c : this.pairwise.columnKeySet()) { for (final String r : this.pairwise.rowKeySet()) { if (this.pairwise.get(r, c) != null) { out.add(this.pairwise.get(r, c)); to_remove.add(r + " if (out.size() == n) { break loop; } } } } for (final String rem : to_remove) { // System.out.println(rem.split(" // System.out.println(rem.split(" if (this.pairwise.remove(rem.split(" throw new Exception("GUIFuncitonality_validate: error in getNPairwiseTests."); } } return out; } }
import java.io.*; import org.apache.commons.net.ftp.FTPClient; import org.apache.commons.net.ftp.FTPFile; import org.apache.commons.net.ftp.FTPReply; public class ftp_client { private static Console console = System.console(); private static BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); private static FTPClient ftpClient = new FTPClient(); private static FileInputStream fileInputStream = null; public static void main(String[] args) { setupFTPClient(args); String command; String localDir = System.getProperty("user.dir"); while(ftpClient.isConnected()) { command = getVar("command"); switch(command) { case "list remote": case "lsr": listRemote(null); break; case "list local": case "lsl": listLocal(localDir); break; case "exit": case "logout": exit(); break; case "help": help(); break; case "cls": case "clear": clear(); break; default: //REGEX Matching //change directory - cd local/cdl if(command.matches("cd local (.*)") || command.matches("cdl (.*)")) { localDir = changeDirectory(localDir, command); } else //put file - put/p if(command.matches("put (.*)") || command.matches("cdl (.*)")) { //put the given file in the given location putFile(localDir, command); } else { System.out.println("\tCommand not found. For help input \"help\""); } } } logout(); System.exit(0); } //Puts the specified file from the local server to the specified location on the remote server private static boolean putFile(String localDir, String input) { //The file to put, the location to put File file; String outFile; String location = ftpClient.getLocalAddress().toString(); //remove "put"/"p" from input, get rid of blank spaces input = input.replace("put",""); input = input.replace("p",""); input = input.trim(); //split on whitespaces String[] inputList = input.split(" "); //need to change, should match more than one whitespace //if provided, the location to put the file if (inputList.length == 2) { location = location.concat(inputList[1]); } //get the provided file outFile = localDir; outFile = outFile.concat("/"); outFile = outFile.concat(inputList[0]); file = new File(outFile); //check the file actually exists try { if (file.exists()) { //if so, put the file out fileInputStream = new FileInputStream(outFile); ftpClient.storeFile(outFile, fileInputStream); //verify the file is there FTPFile[] remoteFile = ftpClient.listFiles(inputList[0]); if(remoteFile.length == 1) return true; else return false; } else { System.out.println("File not found :("); return false; } } catch(Exception e) { System.out.println("Something went wrong :("); return false; } } //Lists the remote files/folders in the provided directory private static boolean listRemote(String dir) { try { FTPFile[] fileList = ftpClient.listFiles(dir); //get the full path before printing dir = ftpClient.getLocalAddress().toString(); System.out.println("Remote Directory: " + dir); for (int i = 0; i < fileList.length; ++i) { if(fileList[i].isFile()) { System.out.println("\t" + fileList[i].getName()); } else if(fileList[i].isDirectory()) { System.out.println("\t" + fileList[i].getName()); } } } catch (IOException e) { return false; //e.printStackTrace(); } return true; } //Lists the local files/folders in the provided directory private static boolean listLocal(String dir) { System.out.println(); try { File folder = new File(dir); File[] fileList = folder.listFiles(); System.out.println("Current Directory: " + dir); for (int i = 0; i < fileList.length; ++i) { if(fileList[i].isFile()) { System.out.println("\t" + fileList[i].getName()); } else if(fileList[i].isDirectory()) { System.out.println("\t" + fileList[i].getName()); } } System.out.println(); } catch(Exception e) { return false; } return true; } private static String changeDirectory(String dir, String input) { input = input.replace("cdl",""); input = input.replace("cd local",""); input = input.trim(); File newDir = new File(dir, input); try { if (newDir.exists()) { System.out.println("Changed Directory to: " + newDir.toPath().normalize().toString()); return newDir.toPath().normalize().toString(); } else { System.out.println("Folder not found :("); return dir; } } catch(Exception e) { System.out.println("Something went wrong :("); return dir; } } //Prints the help menu private static void help() { System.out.println("RTFM"); //fix me System.out.println(); } //Clears the console private static void clear() { System.out.print("\033[H\033[2J"); //clear then home System.out.flush(); } //Logoff and exit private static void exit() { logout(); } //gets reply from the server private static void showServerReply(FTPClient ftpClient) { String[] replies = ftpClient.getReplyStrings(); //if there are messages, display each one in order if (replies != null && replies.length > 0) for (String reply : replies) System.out.println("SERVER: " + reply); } //Gets input from user or args and calls login private static void setupFTPClient(String[] args) { //shouldn't be more than 3 args - error if(args.length > 3) System.out.println("RTFM!"); //Yes, I know there is no manual String server = (args.length < 1) ? getVar("Server") : args[0]; int port = 21; String username = (args.length < 2) ? getVar("User") : args[1]; String password = (args.length < 3) ? getPrivateVar("Password") : args[2]; login(server,port,username,password); } private static boolean login(String server, int port, String user, String password) { try { ftpClient.connect(server, port); showServerReply(ftpClient); if(!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) { System.out.println("Could not connect"); return false; } return ftpClient.login(user, password); } catch(Exception ex) { System.out.println("Something went wrong :( - couldn't connect to the server"); return false; } } private static boolean logout() { if(ftpClient.isConnected()) { try { System.out.println("Logging out..."); ftpClient.logout(); ftpClient.disconnect(); System.out.println("Succesfully Disconnected"); return true; } catch(Exception ex) { System.out.println("Something went wrong :( - Couldn't logout and disconnect correctly"); return false; } } return false; } //Prompts user and returns a string //Bugfix for eclipse? private static String getVar(String request) { System.out.print(request + ": "); if(console != null) { return console.readLine(); } else { try { return in.readLine(); } catch(Exception ex) { return null; } } } //Prompts user and returns a string w/o outputing it //Does not work in eclipse so redirects to getVar() private static String getPrivateVar(String request) { if(console != null) { System.out.print(request + ": "); return new String(console.readPassword()); } else return getVar(request); } }
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.LinkedHashMap; 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 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.primitive.IntegerDecimal; 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.Node; import org.jetel.graph.Result; import org.jetel.graph.TransformationGraph; import org.jetel.graph.dictionary.Dictionary; 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.ExceptionUtils; 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.formatter.TimeZoneProvider; import org.jetel.util.primitive.TypedProperties; import org.jetel.util.property.PropertiesUtilsTest; import org.jetel.util.string.CloverString; import org.jetel.util.string.StringUtils; import org.joda.time.DateTime; import org.joda.time.Years; import org.junit.FixMethodOrder; import org.junit.runners.MethodSorters; import junit.framework.AssertionFailedError; @FixMethodOrder(MethodSorters.NAME_ASCENDING) 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; protected Node node; 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 check(String varName, double expectedResult, double delta) { assertEquals(varName, expectedResult, (double) getVariable(varName), delta); } @SuppressWarnings({ "unchecked", "rawtypes" }) protected void checkEqualValue(String varName, Object expectedResult) { assertTrue(varName, ((Comparable)expectedResult).compareTo(getVariable(varName))==0); } 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 en.US to prevent various parsing errors Locale.setDefault(new Locale("en", "US")); initEngine(); } @Override protected void tearDown() throws Exception { super.tearDown(); inputRecords = null; outputRecords = null; graph = null; node = 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("integerList", "list", Arrays.asList(1, 2, null, 4)); g.getDictionary().setContentType("integerList", "integer"); 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"); g.getDictionary().setValue("stringMap", "map", new LinkedHashMap<String,String>()); g.getDictionary().setContentType("stringMap", "string"); g.getDictionary().setValue("integerMap", "map", new LinkedHashMap<String,Integer>()); g.getDictionary().setContentType("integerMap", "integer"); } 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); 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); 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); 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; } else { expStr = "//#CTL2:INTERPRET\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 = createCompiler(graph, inMetadata, outMetadata); // 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.\n" + messages); } // CLVFStart parseTree = compiler.getStart(); // parseTree.dump(""); executeCode(compiler); } protected ITLCompiler createCompiler(TransformationGraph graph, DataRecordMetadata[] inMetadata, DataRecordMetadata[] outMetadata) { return TLCompilerFactory.createCompiler(graph, inMetadata, outMetadata, "UTF-8"); } protected void doCompileExpectError(TransformationGraph graph, String expStr, String testIdentifier, List<String> errCodes) { this.graph = graph; 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; } else { expStr = "//#CTL2:INTERPRET\n" + expStr; } print_code(expStr); ITLCompiler compiler = createCompiler(graph, inMetadata, outMetadata); 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 expStr, String testIdentifier, List<String> errCodes) { doCompileExpectError(createDefaultGraph(), expStr, testIdentifier, errCodes); } 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"); } } 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"); } } 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"); check("ret3", "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 } try { doCompile("function integer transform(){firstInput fi = null; string str = fi.getFieldType(\"XYZABC\"); return 0;}","test_dynamiclib_getFieldType_expect_error"); fail(); } catch (Exception e) { // do nothing } doCompileExpectError("function integer transform(){firstInput fi; fi.getFieldType(null); return 0;}","test_dynamiclib_getFieldType_expect_error",Arrays.asList("Function 'getFieldType' is ambiguous")); } public void test_dynamiclib_getFieldProperties(){ doCompile("test_dynamiclib_getFieldProperties"); Map<String, String> expected = new LinkedHashMap<>(); expected.clear(); expected.put("name", "Name"); expected.put("label", "Name"); expected.put("type", "string"); expected.put("delimiter", "|"); expected.put("nullable", "true"); expected.put("nullValue", ""); expected.put("trim", "false"); expected.put("locale", "en.US"); expected.put("timeZone", "'java:Europe/Prague';'joda:Europe/Prague'"); for (String key: new String[] {"length", "scale", "containerType", "default", "description", "format", "size"}) { expected.put(key, null); } check("ret1", expected); expected.clear(); expected.put("name", "Age"); expected.put("label", "Age"); expected.put("type", "number"); expected.put("delimiter", "|"); expected.put("nullable", "true"); expected.put("nullValue", ""); expected.put("trim", "true"); expected.put("locale", "en.US"); expected.put("timeZone", "'java:Europe/Prague';'joda:Europe/Prague'"); for (String key: new String[] {"length", "scale", "containerType", "default", "description", "format", "size"}) { expected.put(key, null); } check("ret2", expected); expected.clear(); expected.put("name", "Currency"); expected.put("label", "Currency"); expected.put("type", "decimal"); expected.put("delimiter", "\n"); expected.put("length", "7"); expected.put("scale", "3"); expected.put("nullable", "true"); expected.put("nullValue", ""); expected.put("trim", "true"); expected.put("locale", "en.US"); expected.put("timeZone", "'java:Europe/Prague';'joda:Europe/Prague'"); for (String key: new String[] {"containerType", "default", "description", "format", "size"}) { expected.put(key, null); } check("lastField", expected); } public void test_dynamiclib_getFieldProperties_CLO_6293() { TransformationGraph graph = createDefaultGraph(); TypedProperties recordProperties = graph.getDataRecordMetadata(INPUT_1).getRecordProperties(); recordProperties.setProperty("previewAttachment", "previewAttachment"); recordProperties.setProperty("previewAttachmentCharset", "previewAttachmentCharset"); recordProperties.setProperty("previewAttachmentMetadataRow", "previewAttachmentMetadataRow"); recordProperties.setProperty("previewAttachmentSampleDataRow", "previewAttachmentSampleDataRow"); graph.getDataRecordMetadata(INPUT_1).getField("Born").setFormatStr("joda:yyyy-MM-dd HH:mm:ss;yyyy-MM-dd HH:mm:ss"); 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("string format; map[string, string] recordProperties; map[string, string] fieldProperties; function integer transform(){format = getFieldProperties($in.0, 'Born')['format']; recordProperties = getRecordProperties($in.0); fieldProperties = getFieldProperties($in.0, 'Born'); return 0;}", "test_dynamiclib_getFieldProperties", graph, inRecords, outRecords); check("format", "joda:yyyy-MM-dd HH:mm:ss;yyyy-MM-dd HH:mm:ss"); Map<?, ?> recordPropertiesValue = (Map<?, ?>) getVariable("recordProperties"); assertFalse(recordPropertiesValue.containsKey("previewAttachment")); assertFalse(recordPropertiesValue.containsKey("previewAttachmentCharset")); assertFalse(recordPropertiesValue.containsKey("previewAttachmentMetadataRow")); assertFalse(recordPropertiesValue.containsKey("previewAttachmentSampleDataRow")); String expectedTimeZone = new TimeZoneProvider().toString(); assertFalse(StringUtils.isEmpty(expectedTimeZone)); assertEquals("en.US", recordPropertiesValue.get("locale")); assertEquals(expectedTimeZone, recordPropertiesValue.get("timeZone")); Map<?, ?> fieldPropertiesValue = (Map<?, ?>) getVariable("fieldProperties"); assertEquals("en.US", fieldPropertiesValue.get("locale")); assertEquals(expectedTimeZone, fieldPropertiesValue.get("timeZone")); } public void test_dynamiclib_getFieldProperties_expect_error(){ // ambiguity doCompileExpectError("function integer transform(){getFieldProperties($in.0, null); return 0;}","test_dynamiclib_getFieldProperties_expect_error", Arrays.asList("Function 'getFieldProperties' is ambiguous")); // null record try { doCompile("function integer transform(){firstInput r = null; getFieldProperties(r, 0); return 0;}","test_dynamiclib_getFieldProperties_expect_error"); fail(); } catch (Exception e) { assertTrue(isCausedBy(e, NullPointerException.class)); } try { doCompile("function integer transform(){firstInput r = null; getFieldProperties(r, 'Name'); return 0;}","test_dynamiclib_getFieldProperties_expect_error"); fail(); } catch (Exception e) { assertTrue(isCausedBy(e, NullPointerException.class)); } // null string try { doCompile("function integer transform(){string s = null; getFieldProperties($in.0, s); return 0;}","test_dynamiclib_getFieldProperties_expect_error"); fail(); } catch (Exception e) { assertTrue(isCausedBy(e, NullPointerException.class)); } // null integer try { doCompile("function integer transform(){integer i = null; getFieldProperties($in.0, i); return 0;}","test_dynamiclib_getFieldProperties_expect_error"); fail(); } catch (Exception e) { assertTrue(isCausedBy(e, NullPointerException.class)); } // invalid string try { doCompile("function integer transform(){string s = null; getFieldProperties($in.0, 'NoSuchField'); return 0;}","test_dynamiclib_getFieldProperties_expect_error"); fail(); } catch (Exception e) { assertTrue(isCausedBy(e, IllegalArgumentException.class)); } // index out of bounds try { doCompile("function integer transform(){string s = null; getFieldProperties($in.0, -1); return 0;}","test_dynamiclib_getFieldProperties_expect_error"); fail(); } catch (Exception e) { assertTrue(isCausedBy(e, IndexOutOfBoundsException.class)); } try { doCompile("function integer transform(){string s = null; getFieldProperties($in.0, 100); return 0;}","test_dynamiclib_getFieldProperties_expect_error"); fail(); } catch (Exception e) { assertTrue(isCausedBy(e, IndexOutOfBoundsException.class)); } } public void test_dynamiclib_getRecordProperties(){ doCompile("test_dynamiclib_getRecordProperties"); Map<String, String> expected = new LinkedHashMap<>(); expected.clear(); expected.put("name", "firstInput"); expected.put("label", "firstInput"); expected.put("type", "mixed"); expected.put("quotedStrings", "false"); expected.put("eofAsDelimiter", "false"); expected.put("nullValue", ""); expected.put("locale", "en.US"); expected.put("timeZone", "'java:Europe/Prague';'joda:Europe/Prague'"); for (String key: new String[] {"recordDelimiter", "fieldDelimiter", "quoteChar", "description"}) { expected.put(key, null); } check("ret1", expected); expected.clear(); expected.put("name", "secondInput"); expected.put("label", "secondInput"); expected.put("type", "mixed"); expected.put("quotedStrings", "false"); expected.put("eofAsDelimiter", "false"); expected.put("nullValue", ""); expected.put("locale", "en.US"); expected.put("timeZone", "'java:Europe/Prague';'joda:Europe/Prague'"); for (String key: new String[] {"recordDelimiter", "fieldDelimiter", "quoteChar", "description"}) { expected.put(key, null); } check("ret2", expected); } public void test_dynamiclib_getRecordProperties_expect_error(){ // null record try { doCompile("function integer transform(){getRecordProperties(null); return 0;}","test_dynamiclib_getRecordProperties_expect_error"); fail(); } catch (Exception e) { assertTrue(isCausedBy(e, NullPointerException.class)); } try { doCompile("function integer transform(){firstInput r = null; getRecordProperties(r); return 0;}","test_dynamiclib_getRecordProperties_expect_error"); fail(); } catch (Exception e) { assertTrue(isCausedBy(e, NullPointerException.class)); } try { doCompile("function integer transform(){firstInput r = null; getRecordProperties(r); return 0;}","test_dynamiclib_getRecordProperties_expect_error"); fail(); } catch (Exception e) { assertTrue(isCausedBy(e, NullPointerException.class)); } } 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() { // no error expected doCompile("test_ambiguous_working"); // 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"); // swapped arguments (internal and external function) doCompileExpectError("test_ambiguous_swapped_combined", "Function 'charAt' 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_import_CLO10313() { TransformationGraph graph = createDefaultGraph(); String url = getClass().getSuperclass().getResource("test_import_CLO10313.ctl").toString(); url = url.substring(0, url.lastIndexOf('/')); graph.getGraphParameters().getGraphParameter("PROJECT").setValue(url); String testIdentifier = "test_import_CLO10313"; String expStr = loadSourceCode(testIdentifier); doCompile(expStr, testIdentifier, graph, new DataRecord[0], new DataRecord[0]); check("int", 87); check("str", "87"); } 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("literalParserTest1", "some // string"); check("literalParserTest2", "some /* string */"); check("literalParserTest3", "some \" string"); check("literalParserTest4", "some \\ string"); check("literalParserTest5", "some \\\" string"); check("literalParserTest6", "some \\\\\" string"); check("literalParserTest7", "some \\\\\\\" 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"); doCompileExpectError("string promenna = \"^\\..*\"; function integer transform() { return 0;}", "test_type_string", Arrays.asList("Invalid escape sequence: \\.")); doCompileExpectError("string promenna = \"\\uaxax\"; function integer transform() { return 0;}", "test_type_string", Arrays.asList("Invalid escape character at line 2 column 21.")); doCompileExpectError("string \ffff = \"\\uaaaa\"; function integer transform() { return 0;}", "test_type_string", Arrays.asList("Syntax error on token ' '")); } 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("Expected " + o1 + " but was " + o2, (o1 == null) == (o2 == null)); if (o1 instanceof DataRecord) { DataRecord r1 = (DataRecord) o1; DataRecord r2 = (DataRecord) o2; assertEquals(r1.getMetadata(), r2.getMetadata()); 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()); check("incrementTest", "newValue"); check("incrementTestList", Arrays.asList("newValue")); check("incrementCounter", 1); } } /** * Tests examples from the User Guide. */ public void test_assignment_compound() { doCompile("test_assignment_compound"); check("i", 9); check("ni", 5); check("s", "hello world 123"); check("ns", "hello"); check("ns2", "nullhello"); check("list1", Arrays.asList(1, 2, 3, 4, 5)); { Map<String, Integer> expected = new HashMap<>(); expected.put("1", 1); expected.put("2", 22); expected.put("3", 3); check("map1", expected); } check("l", 6L); check("d", new BigDecimal("24.68")); check("n", 4.1, 0.0000001); check("r", 7L); } public void test_assignment_compound_plus() { doCompile("test_assignment_compound_plus"); check("int1", 3); check("intList1", Arrays.asList(3)); check("intList2", Arrays.asList(1, 4)); check("cnt1", 1); check("str1", "str1_append"); check("str2", "str22"); check("str3", "str3true"); check("str4", "str4[1, 2]"); check("str5", "str5" + inputRecords[0]); check("strList1", Arrays.asList("strList1_append")); check("strList2", Arrays.asList("strList2", "strList3_1", "strList3_2")); check("strList4", Arrays.asList("strList4_strList4append")); check("cnt2", 1); check("strList5", Arrays.asList("strList5", "l1", "l2")); { Map<String, String> expected = new LinkedHashMap<String, String>(); expected.put("strMap1_key1", "strMap1_value1_strMap1_append"); expected.put("strMap1_key2", "strMap1_value2_overwritten"); expected.put("strMap2_key1", "strMap2_value1"); expected.put("strMap2_key2", "strMap2_value2"); check("strMap1", expected); } check("long1", 3L); check("long2", 5L); check("decimal1", new BigDecimal(3)); check("decimal2", new BigDecimal(4)); check("decimal3", new BigDecimal(5)); check("decimal4", new BigDecimal("6.5")); check("num1", 3.0); check("num2", 4.0); check("num3", 5.0); Dictionary dictionary = graph.getDictionary(); assertEquals("Verdon_sVerdonAppend", dictionary.getValue("sVerdon")); assertEquals(213, dictionary.getValue("i211")); assertEquals(454L, dictionary.getValue("l452")); assertEquals(new BigDecimal("623.5"), dictionary.getValue("d621")); assertEquals(936.2, dictionary.getValue("n9342")); assertEquals(Arrays.asList("aa_1", "bb_2", "_3", "cc", "dictionary.stringList_1", "dictionary.stringList_2"), dictionary.getValue("stringList")); check("cnt3", 1); { Map<String, String> expected = new LinkedHashMap<>(); expected.put("key1", "value1"); expected.put("key2", "value2_dictionaryMap_append"); expected.put("nonExistingKey", "newValue"); assertEquals(expected, dictionary.getValue("stringMap")); } check("cnt4", 1); { DataRecord r = outputRecords[0]; assertEquals(NAME_VALUE + "_out0Name_append", r.getField("Name").getValue().toString()); assertEquals(AGE_VALUE + 2, r.getField("Age").getValue()); assertEquals(BORN_MILLISEC_VALUE + 2, r.getField("BornMillisec").getValue()); assertEquals(VALUE_VALUE + 2, r.getField("Value").getValue()); assertEquals(CURRENCY_VALUE.add(new BigDecimal(2)), ((Decimal) r.getField("Currency").getValue()).getBigDecimal()); } { DataRecord r = (DataRecord) getVariable("myRecord1"); assertEquals(NAME_VALUE + "_myRecord1_append", r.getField("Name").getValue().toString()); assertEquals(AGE_VALUE + 2, r.getField("Age").getValue()); assertEquals(BORN_MILLISEC_VALUE + 2, r.getField("BornMillisec").getValue()); assertEquals(VALUE_VALUE + 2, r.getField("Value").getValue()); assertEquals(CURRENCY_VALUE.add(new BigDecimal(2)), ((Decimal) r.getField("Currency").getValue()).getBigDecimal()); } { DataRecord r = (DataRecord) ((List<?>) getVariable("recordList1")).get(0); assertEquals(NAME_VALUE + "_recordList1_append", r.getField("Name").getValue().toString()); assertEquals(AGE_VALUE + 2, r.getField("Age").getValue()); assertEquals(BORN_MILLISEC_VALUE + 2, r.getField("BornMillisec").getValue()); assertEquals(VALUE_VALUE + 2, r.getField("Value").getValue()); assertEquals(CURRENCY_VALUE.add(new BigDecimal(2)), ((Decimal) r.getField("Currency").getValue()).getBigDecimal()); check("cnt5", 1); } { DataRecord r = (DataRecord) ((Map<?, ?>) getVariable("recordMap1")).get("key"); assertEquals(NAME_VALUE + "_recordMap1_append", r.getField("Name").getValue().toString()); assertEquals(AGE_VALUE + 2, r.getField("Age").getValue()); assertEquals(BORN_MILLISEC_VALUE + 2, r.getField("BornMillisec").getValue()); assertEquals(VALUE_VALUE + 2, r.getField("Value").getValue()); assertEquals(CURRENCY_VALUE.add(new BigDecimal(2)), ((Decimal) r.getField("Currency").getValue()).getBigDecimal()); check("cnt6", 1); } { // check that tmpRecord is unmodified DataRecord r = (DataRecord) getVariable("tmpRecord"); assertNull(r.getField("Name").getValue()); assertNull(r.getField("Age").getValue()); assertNull(r.getField("BornMillisec").getValue()); assertNull(r.getField("Value").getValue()); assertNull(r.getField("Currency").getValue()); } { Map<String, String> expected = new LinkedHashMap<>(); expected.put("key", "val555"); check("singleEvaluationTest", expected); check("cnt7", 2); } { Map<?, ?> singleEvaluationMap = (Map<?, ?>) getVariable("singleEvaluationMap"); DataRecord record = (DataRecord) singleEvaluationMap.get("key"); assertEquals("singleEvaluationMap123", record.getField("Name").getValue().toString()); check("cnt8", 2); } check("nullAppend", "nullAppend_null"); check("mergeTest", Arrays.asList("mergeTest_mergeTestAppend")); { List<?> stringListField = (List<?>) outputRecords[4].getField("stringListField").getValue(); assertEquals(stringListField.get(0).toString(), "stringListField_stringListFieldAppend"); check("cnt9", 2); } check("stringInit", "stringInit"); check("integerInit", 5); check("longInit", 77L); check("numberInit", 5.4); check("decimalInit", new BigDecimal("7.8")); check("listInit1", Arrays.asList(null, null, "listInit1")); check("listInit2", Arrays.asList(null, "listInit2tmp")); { Map<String, String> expected = new HashMap<>(1); expected.put("key", "mapInit1"); check("mapInit1", expected); } { Map<String, String> expected = new HashMap<>(1); expected.put("key", "mapInit2tmp"); check("mapInit2", expected); } { DataRecord expected = DataRecordFactory.newRecord(graph.getDataRecordMetadata(INPUT_1)); expected.getField("Name").setValue("recordInit1"); assertDeepEquals(expected, getVariable("recordInit1")); } { DataRecord expected = DataRecordFactory.newRecord(graph.getDataRecordMetadata("multivalueInput")); expected.getField("stringListField").setValue(Arrays.asList(null, null, "recordInit3")); Map<String, String> map = new HashMap<>(1); map.put("key", "recordInit3"); expected.getField("stringMapField").setValue(map); assertDeepEquals(expected, getVariable("recordInit3")); } { DataRecord r = DataRecordFactory.newRecord(graph.getDataRecordMetadata("multivalueInput")); r.getField("stringListField").setValue(Arrays.asList(null, null, "recordListInit")); assertDeepEquals(Arrays.asList(null, null, r), getVariable("recordListInit")); } assertEquals("dictStringInit", dictionary.getValue("s")); assertEquals(5, dictionary.getValue("i")); assertEquals(77L, dictionary.getValue("l")); assertEquals(new BigDecimal("7.8"), dictionary.getValue("d")); assertEquals(5.4, dictionary.getValue("n")); { DataRecord expected = DataRecordFactory.newRecord(graph.getDataRecordMetadata(OUTPUT_2)); expected.getField("Name").setValue("_out1Name_append"); expected.getField("Age").setValue(2); expected.getField("BornMillisec").setValue(2L); expected.getField("Value").setValue(2.0); expected.getField("Currency").setValue(new BigDecimal("2.0")); assertDeepEquals(expected, outputRecords[1]); expected.getField("Name").setValue("_out2Name_append"); assertDeepEquals(expected, outputRecords[2]); } } public void test_assignment_compound_minus() { doCompile("test_assignment_compound_minus"); check("int1", -1); check("intList1", Arrays.asList(-1)); check("intList2", Arrays.asList(1, -2)); check("cnt1", 1); check("intList3", Arrays.asList(-1, 2)); check("cnt2", 1); { Map<String, Integer> expected = new LinkedHashMap<String, Integer>(); expected.put("intMap1_key1", 3); expected.put("intMap1_key2", 8); check("intMap1", expected); } check("long1", -1L); check("long2", -1L); check("decimal1", new BigDecimal(-1)); check("decimal2", new BigDecimal(0)); check("decimal3", new BigDecimal(1)); check("decimal4", new BigDecimal("1.5")); check("num1", -1.0); check("num2", 0.0); check("num3", 1.0); Dictionary dictionary = graph.getDictionary(); assertEquals(209, dictionary.getValue("i211")); assertEquals(450L, dictionary.getValue("l452")); assertEquals(new BigDecimal("618.5"), dictionary.getValue("d621")); assertEquals(932.2, dictionary.getValue("n9342")); assertEquals(Arrays.asList(-2, -3, -8, 4), dictionary.getValue("integerList")); check("cnt3", 1); { Map<String, Integer> expected = new LinkedHashMap<>(); expected.put("key2", -9); expected.put("nonExistingKey", -7); assertEquals(expected, dictionary.getValue("integerMap")); } check("cnt4", 1); { DataRecord r = outputRecords[0]; assertEquals(AGE_VALUE - 2, r.getField("Age").getValue()); assertEquals(BORN_MILLISEC_VALUE - 2, r.getField("BornMillisec").getValue()); assertEquals(VALUE_VALUE - 2, r.getField("Value").getValue()); assertEquals(CURRENCY_VALUE.add(new BigDecimal(-2)), ((Decimal) r.getField("Currency").getValue()).getBigDecimal()); } { DataRecord r = (DataRecord) getVariable("myRecord1"); assertEquals(AGE_VALUE - 2, r.getField("Age").getValue()); assertEquals(BORN_MILLISEC_VALUE - 2, r.getField("BornMillisec").getValue()); assertEquals(VALUE_VALUE - 2, r.getField("Value").getValue()); assertEquals(CURRENCY_VALUE.add(new BigDecimal(-2)), ((Decimal) r.getField("Currency").getValue()).getBigDecimal()); } { DataRecord r = (DataRecord) ((List<?>) getVariable("recordList1")).get(0); assertEquals(AGE_VALUE - 2, r.getField("Age").getValue()); assertEquals(BORN_MILLISEC_VALUE - 2, r.getField("BornMillisec").getValue()); assertEquals(VALUE_VALUE - 2, r.getField("Value").getValue()); assertEquals(CURRENCY_VALUE.add(new BigDecimal(-2)), ((Decimal) r.getField("Currency").getValue()).getBigDecimal()); check("cnt5", 1); } { DataRecord r = (DataRecord) ((Map<?, ?>) getVariable("recordMap1")).get("key"); assertEquals(AGE_VALUE - 2, r.getField("Age").getValue()); assertEquals(BORN_MILLISEC_VALUE - 2, r.getField("BornMillisec").getValue()); assertEquals(VALUE_VALUE - 2, r.getField("Value").getValue()); assertEquals(CURRENCY_VALUE.add(new BigDecimal(-2)), ((Decimal) r.getField("Currency").getValue()).getBigDecimal()); check("cnt6", 1); } { // check that tmpRecord is unmodified DataRecord r = (DataRecord) getVariable("tmpRecord"); assertNull(r.getField("Age").getValue()); assertNull(r.getField("BornMillisec").getValue()); assertNull(r.getField("Value").getValue()); assertNull(r.getField("Currency").getValue()); } { Map<String, Integer> expected = new LinkedHashMap<>(); expected.put("key", -333); check("singleEvaluationTest", expected); check("cnt7", 2); } { Map<?, ?> singleEvaluationMap = (Map<?, ?>) getVariable("singleEvaluationMap"); DataRecord record = (DataRecord) singleEvaluationMap.get("key"); assertEquals(531, record.getField("Value").getValue()); check("cnt8", 2); } { List<?> integerListField = (List<?>) outputRecords[4].getField("integerListField").getValue(); assertEquals(integerListField.get(0), 543); check("cnt9", 2); } check("integerInit", -5); check("longInit", -77L); check("numberInit", -5.4); check("decimalInit", new BigDecimal("-7.8")); check("listInit1", Arrays.asList(null, null, -12L)); { Map<String, BigDecimal> expected = new HashMap<>(1); expected.put("key", new BigDecimal(-987)); check("mapInit1", expected); } { DataRecord expected = DataRecordFactory.newRecord(graph.getDataRecordMetadata(INPUT_1)); expected.getField("Age").setValue(-12.34); assertDeepEquals(expected, getVariable("recordInit1")); } { DataRecord expected = DataRecordFactory.newRecord(graph.getDataRecordMetadata("multivalueInput")); expected.getField("integerListField").setValue(Arrays.asList(null, null, -42)); Map<String, BigDecimal> map = new HashMap<>(1); map.put("key", new BigDecimal("-88.8")); expected.getField("decimalMapField").setValue(map); assertDeepEquals(expected, getVariable("recordInit3")); } { DataRecord r = DataRecordFactory.newRecord(graph.getDataRecordMetadata("multivalueInput")); r.getField("integerListField").setValue(Arrays.asList(null, null, -24)); assertDeepEquals(Arrays.asList(null, null, r), getVariable("recordListInit")); } assertEquals(-5, dictionary.getValue("i")); assertEquals(-77L, dictionary.getValue("l")); assertEquals(new BigDecimal("-7.8"), dictionary.getValue("d")); assertEquals(-5.4, dictionary.getValue("n")); { DataRecord expected = DataRecordFactory.newRecord(graph.getDataRecordMetadata(OUTPUT_2)); expected.getField("Age").setValue(-2); expected.getField("BornMillisec").setValue(-2L); expected.getField("Value").setValue(-2.0); expected.getField("Currency").setValue(new BigDecimal("-2.0")); assertDeepEquals(expected, outputRecords[1]); assertDeepEquals(expected, outputRecords[2]); } } public void test_assignment_compound_multiply() { doCompile("test_assignment_compound_multiply"); check("int1", 2); check("intList1", Arrays.asList(2)); check("intList2", Arrays.asList(1, 8)); check("cnt1", 1); check("intList3", Arrays.asList(2, 2)); check("cnt2", 1); { Map<String, Integer> expected = new LinkedHashMap<String, Integer>(); expected.put("intMap1_key1", 10); expected.put("intMap1_key2", 8); check("intMap1", expected); } check("long1", 2L); check("long2", 6L); check("decimal1", new BigDecimal(2)); check("decimal2", new BigDecimal(4)); check("decimal3", new BigDecimal(6)); check("decimal4", new BigDecimal("10.0")); check("num1", 2.0); check("num2", 4.0); check("num3", 6.0); Dictionary dictionary = graph.getDictionary(); assertEquals(422, dictionary.getValue("i211")); assertEquals(904L, dictionary.getValue("l452")); assertEquals(new BigDecimal("1552.5"), dictionary.getValue("d621")); assertEquals(1868.4, dictionary.getValue("n9342")); assertEquals(Arrays.asList(3, 10, 0, 4), dictionary.getValue("integerList")); check("cnt3", 1); { Map<String, Integer> expected = new LinkedHashMap<>(); expected.put("key2", 0); expected.put("nonExistingKey", 0); assertEquals(expected, dictionary.getValue("integerMap")); } check("cnt4", 1); { DataRecord r = outputRecords[0]; assertEquals(AGE_VALUE * 2, r.getField("Age").getValue()); assertEquals(BORN_MILLISEC_VALUE * 2, r.getField("BornMillisec").getValue()); assertEquals(VALUE_VALUE * 2, r.getField("Value").getValue()); assertEquals(CURRENCY_VALUE.multiply(new BigDecimal(2)), ((Decimal) r.getField("Currency").getValue()).getBigDecimal()); } { DataRecord r = (DataRecord) getVariable("myRecord1"); assertEquals(AGE_VALUE * 2, r.getField("Age").getValue()); assertEquals(BORN_MILLISEC_VALUE * 2, r.getField("BornMillisec").getValue()); assertEquals(VALUE_VALUE * 2, r.getField("Value").getValue()); assertEquals(CURRENCY_VALUE.multiply(new BigDecimal(2)), ((Decimal) r.getField("Currency").getValue()).getBigDecimal()); } { DataRecord r = (DataRecord) ((List<?>) getVariable("recordList1")).get(0); assertEquals(AGE_VALUE * 2, r.getField("Age").getValue()); assertEquals(BORN_MILLISEC_VALUE * 2, r.getField("BornMillisec").getValue()); assertEquals(VALUE_VALUE * 2, r.getField("Value").getValue()); assertEquals(CURRENCY_VALUE.multiply(new BigDecimal(2)), ((Decimal) r.getField("Currency").getValue()).getBigDecimal()); check("cnt5", 1); } { DataRecord r = (DataRecord) ((Map<?, ?>) getVariable("recordMap1")).get("key"); assertEquals(AGE_VALUE * 2, r.getField("Age").getValue()); assertEquals(BORN_MILLISEC_VALUE * 2, r.getField("BornMillisec").getValue()); assertEquals(VALUE_VALUE * 2, r.getField("Value").getValue()); assertEquals(CURRENCY_VALUE.multiply(new BigDecimal(2)), ((Decimal) r.getField("Currency").getValue()).getBigDecimal()); check("cnt6", 1); } { // check that tmpRecord is unmodified DataRecord r = (DataRecord) getVariable("tmpRecord"); assertNull(r.getField("Age").getValue()); assertNull(r.getField("BornMillisec").getValue()); assertNull(r.getField("Value").getValue()); assertNull(r.getField("Currency").getValue()); } { Map<String, Integer> expected = new LinkedHashMap<>(); expected.put("key", 123210); check("singleEvaluationTest", expected); check("cnt7", 2); } { Map<?, ?> singleEvaluationMap = (Map<?, ?>) getVariable("singleEvaluationMap"); DataRecord record = (DataRecord) singleEvaluationMap.get("key"); assertEquals(80442, record.getField("Value").getValue()); check("cnt8", 2); } { List<?> integerListField = (List<?>) outputRecords[4].getField("integerListField").getValue(); assertEquals(integerListField.get(0), 72594); check("cnt9", 2); } check("integerInit", 0); check("longInit", 0L); check("numberInit", 0.0); check("decimalInit", new BigDecimal("0.0")); check("listInit1", Arrays.asList(null, null, 0L)); { Map<String, BigDecimal> expected = new HashMap<>(1); expected.put("key", new BigDecimal("0")); check("mapInit1", expected); } { DataRecord expected = DataRecordFactory.newRecord(graph.getDataRecordMetadata(INPUT_1)); expected.getField("Age").setValue(0.0); assertDeepEquals(expected, getVariable("recordInit1")); } { DataRecord expected = DataRecordFactory.newRecord(graph.getDataRecordMetadata("multivalueInput")); expected.getField("integerListField").setValue(Arrays.asList(null, null, 0)); Map<String, BigDecimal> map = new HashMap<>(1); map.put("key", new BigDecimal("0")); expected.getField("decimalMapField").setValue(map); assertDeepEquals(expected, getVariable("recordInit3")); } { DataRecord r = DataRecordFactory.newRecord(graph.getDataRecordMetadata("multivalueInput")); r.getField("integerListField").setValue(Arrays.asList(null, null, 0)); assertDeepEquals(Arrays.asList(null, null, r), getVariable("recordListInit")); } assertEquals(0, dictionary.getValue("i")); assertEquals(0L, dictionary.getValue("l")); assertEquals(new BigDecimal("0.0"), dictionary.getValue("d")); assertEquals(0.0, dictionary.getValue("n")); { DataRecord expected = DataRecordFactory.newRecord(graph.getDataRecordMetadata(OUTPUT_2)); expected.getField("Age").setValue(0.0); expected.getField("BornMillisec").setValue(0L); expected.getField("Value").setValue(0); expected.getField("Currency").setValue(new BigDecimal("0.0")); assertDeepEquals(expected, outputRecords[1]); assertDeepEquals(expected, outputRecords[2]); } } public void test_assignment_compound_divide() { doCompile("test_assignment_compound_divide"); check("int1", 5); check("intList1", Arrays.asList(5)); check("intList2", Arrays.asList(11, 3)); check("cnt1", 1); check("intList3", Arrays.asList(5, 12)); check("cnt2", 1); { Map<String, Integer> expected = new LinkedHashMap<String, Integer>(); expected.put("intMap1_key1", 2); expected.put("intMap1_key2", 8); check("intMap1", expected); } check("long1", 2L); check("long2", 3L); check("decimal1", new BigDecimal("0.5")); check("decimal2", new BigDecimal(1)); check("decimal3", new BigDecimal("1.5")); check("decimal4", new BigDecimal("1.6")); check("num1", 0.5); check("num2", 1.0); check("num3", 1.5); Dictionary dictionary = graph.getDictionary(); assertEquals(105, dictionary.getValue("i211")); assertEquals(226L, dictionary.getValue("l452")); assertEquals(new BigDecimal("248.4"), dictionary.getValue("d621")); assertEquals(467.1, dictionary.getValue("n9342")); assertEquals(Arrays.asList(0, 0, 0, 4), dictionary.getValue("integerList")); check("cnt3", 1); { Map<String, Integer> expected = new LinkedHashMap<>(); expected.put("key2", 0); expected.put("nonExistingKey", 0); assertEquals(expected, dictionary.getValue("integerMap")); } check("cnt4", 1); { DataRecord r = outputRecords[0]; assertEquals(AGE_VALUE / 2, r.getField("Age").getValue()); assertEquals(BORN_MILLISEC_VALUE / 2, r.getField("BornMillisec").getValue()); assertEquals(VALUE_VALUE / 2, r.getField("Value").getValue()); compareDecimals(CURRENCY_VALUE.divide(new BigDecimal("2.0"), 3, RoundingMode.DOWN), ((Decimal) r.getField("Currency").getValue()).getBigDecimal()); } { DataRecord r = (DataRecord) getVariable("myRecord1"); assertEquals(AGE_VALUE / 2, r.getField("Age").getValue()); assertEquals(BORN_MILLISEC_VALUE / 2, r.getField("BornMillisec").getValue()); assertEquals(VALUE_VALUE / 2, r.getField("Value").getValue()); compareDecimals(CURRENCY_VALUE.divide(new BigDecimal("2.0"), 3, RoundingMode.DOWN), ((Decimal) r.getField("Currency").getValue()).getBigDecimal()); } { DataRecord r = (DataRecord) ((List<?>) getVariable("recordList1")).get(0); assertEquals(AGE_VALUE / 2, r.getField("Age").getValue()); assertEquals(BORN_MILLISEC_VALUE / 2, r.getField("BornMillisec").getValue()); assertEquals(VALUE_VALUE / 2, r.getField("Value").getValue()); compareDecimals(CURRENCY_VALUE.divide(new BigDecimal("2.0"), 3, RoundingMode.DOWN), ((Decimal) r.getField("Currency").getValue()).getBigDecimal()); check("cnt5", 1); } { DataRecord r = (DataRecord) ((Map<?, ?>) getVariable("recordMap1")).get("key"); assertEquals(AGE_VALUE / 2, r.getField("Age").getValue()); assertEquals(BORN_MILLISEC_VALUE / 2, r.getField("BornMillisec").getValue()); assertEquals(VALUE_VALUE / 2, r.getField("Value").getValue()); compareDecimals(CURRENCY_VALUE.divide(new BigDecimal("2.0"), 3, RoundingMode.DOWN), ((Decimal) r.getField("Currency").getValue()).getBigDecimal()); check("cnt6", 1); } { // check that tmpRecord is unmodified DataRecord r = (DataRecord) getVariable("tmpRecord"); assertNull(r.getField("Age").getValue()); assertNull(r.getField("BornMillisec").getValue()); assertNull(r.getField("Value").getValue()); assertNull(r.getField("Currency").getValue()); } { Map<String, Integer> expected = new LinkedHashMap<>(); expected.put("key", 4); check("singleEvaluationTest", expected); check("cnt7", 2); } { Map<?, ?> singleEvaluationMap = (Map<?, ?>) getVariable("singleEvaluationMap"); DataRecord record = (DataRecord) singleEvaluationMap.get("key"); assertEquals(10, record.getField("Value").getValue()); check("cnt8", 2); } { List<?> integerListField = (List<?>) outputRecords[4].getField("integerListField").getValue(); assertEquals(integerListField.get(0), 5); check("cnt9", 2); } check("integerInit", 0); check("longInit", 0L); check("numberInit", 0.0); checkEqualValue("decimalInit", BigDecimal.ZERO); check("listInit1", Arrays.asList(null, null, 0L)); { Map<String, BigDecimal> expected = new HashMap<>(1); expected.put("key", new BigDecimal("0")); check("mapInit1", expected); } { DataRecord expected = DataRecordFactory.newRecord(graph.getDataRecordMetadata(INPUT_1)); expected.getField("Age").setValue(0.0); assertDeepEquals(expected, getVariable("recordInit1")); } { DataRecord expected = DataRecordFactory.newRecord(graph.getDataRecordMetadata("multivalueInput")); expected.getField("integerListField").setValue(Arrays.asList(null, null, 0)); Map<String, BigDecimal> map = new HashMap<>(1); map.put("key", BigDecimal.ZERO); expected.getField("decimalMapField").setValue(map); assertDeepEquals(expected, getVariable("recordInit3")); } { DataRecord r = DataRecordFactory.newRecord(graph.getDataRecordMetadata("multivalueInput")); r.getField("integerListField").setValue(Arrays.asList(null, null, 0)); assertDeepEquals(Arrays.asList(null, null, r), getVariable("recordListInit")); } assertEquals(0, dictionary.getValue("i")); assertEquals(0L, dictionary.getValue("l")); compareDecimals(BigDecimal.ZERO, (BigDecimal) dictionary.getValue("d")); assertEquals(0.0, dictionary.getValue("n")); { DataRecord expected = DataRecordFactory.newRecord(graph.getDataRecordMetadata(OUTPUT_2)); expected.getField("Age").setValue(0.0); expected.getField("BornMillisec").setValue(0L); expected.getField("Value").setValue(0); expected.getField("Currency").setValue(BigDecimal.ZERO); assertDeepEquals(expected, outputRecords[1]); assertDeepEquals(expected, outputRecords[2]); } } public void test_assignment_compound_modulo() { doCompile("test_assignment_compound_modulo"); check("int1", 1); check("intList1", Arrays.asList(2)); check("intList2", Arrays.asList(12, 3)); check("cnt1", 1); check("intList3", Arrays.asList(2, 12)); check("cnt2", 1); { Map<String, Integer> expected = new LinkedHashMap<String, Integer>(); expected.put("intMap1_key1", 2); expected.put("intMap1_key2", 8); check("intMap1", expected); } check("long1", 2L); check("long2", 1L); check("decimal1", BigDecimal.ONE); check("decimal2", new BigDecimal(2)); check("decimal3", BigDecimal.ZERO); check("decimal4", new BigDecimal("0.5")); check("num1", 1.0); check("num2", 2.0); check("num3", 0.0); Dictionary dictionary = graph.getDictionary(); assertEquals(3, dictionary.getValue("i211")); assertEquals(4L, dictionary.getValue("l452")); assertEquals(new BigDecimal("0.5"), dictionary.getValue("d621")); assertEquals(6.2, (Double) dictionary.getValue("n9342"), 0.0001); assertEquals(Arrays.asList(1, 2, 0, 4), dictionary.getValue("integerList")); check("cnt3", 1); { Map<String, Integer> expected = new LinkedHashMap<>(); expected.put("key2", 0); expected.put("nonExistingKey", 0); assertEquals(expected, dictionary.getValue("integerMap")); } check("cnt4", 1); { DataRecord r = outputRecords[0]; assertEquals(AGE_VALUE % 3, r.getField("Age").getValue()); assertEquals(BORN_MILLISEC_VALUE % 3, r.getField("BornMillisec").getValue()); assertEquals(VALUE_VALUE % 3, r.getField("Value").getValue()); compareDecimals(CURRENCY_VALUE.remainder(new BigDecimal("3.0")), ((Decimal) r.getField("Currency").getValue()).getBigDecimal()); } { DataRecord r = (DataRecord) getVariable("myRecord1"); assertEquals(AGE_VALUE % 3, r.getField("Age").getValue()); assertEquals(BORN_MILLISEC_VALUE % 3, r.getField("BornMillisec").getValue()); assertEquals(VALUE_VALUE % 3, r.getField("Value").getValue()); compareDecimals(CURRENCY_VALUE.remainder(new BigDecimal("3.0")), ((Decimal) r.getField("Currency").getValue()).getBigDecimal()); } { DataRecord r = (DataRecord) ((List<?>) getVariable("recordList1")).get(0); assertEquals(AGE_VALUE % 3, r.getField("Age").getValue()); assertEquals(BORN_MILLISEC_VALUE % 3, r.getField("BornMillisec").getValue()); assertEquals(VALUE_VALUE % 3, r.getField("Value").getValue()); compareDecimals(CURRENCY_VALUE.remainder(new BigDecimal("3.0")), ((Decimal) r.getField("Currency").getValue()).getBigDecimal()); check("cnt5", 1); } { DataRecord r = (DataRecord) ((Map<?, ?>) getVariable("recordMap1")).get("key"); assertEquals(AGE_VALUE % 3, r.getField("Age").getValue()); assertEquals(BORN_MILLISEC_VALUE % 3, r.getField("BornMillisec").getValue()); assertEquals(VALUE_VALUE % 3, r.getField("Value").getValue()); compareDecimals(CURRENCY_VALUE.remainder(new BigDecimal("3.0")), ((Decimal) r.getField("Currency").getValue()).getBigDecimal()); check("cnt6", 1); } { // check that tmpRecord is unmodified DataRecord r = (DataRecord) getVariable("tmpRecord"); assertNull(r.getField("Age").getValue()); assertNull(r.getField("BornMillisec").getValue()); assertNull(r.getField("Value").getValue()); assertNull(r.getField("Currency").getValue()); } { Map<String, Integer> expected = new LinkedHashMap<>(); expected.put("key", 22); check("singleEvaluationTest", expected); check("cnt7", 2); } { Map<?, ?> singleEvaluationMap = (Map<?, ?>) getVariable("singleEvaluationMap"); DataRecord record = (DataRecord) singleEvaluationMap.get("key"); assertEquals(54, record.getField("Value").getValue()); check("cnt8", 2); } { List<?> integerListField = (List<?>) outputRecords[4].getField("integerListField").getValue(); assertEquals(integerListField.get(0), 99); check("cnt9", 2); } check("integerInit", 0); check("longInit", 0L); check("numberInit", 0.0); checkEqualValue("decimalInit", BigDecimal.ZERO); check("listInit1", Arrays.asList(null, null, 0L)); { Map<String, BigDecimal> expected = new HashMap<>(1); expected.put("key", new BigDecimal("0")); check("mapInit1", expected); } { DataRecord expected = DataRecordFactory.newRecord(graph.getDataRecordMetadata(INPUT_1)); expected.getField("Age").setValue(0.0); assertDeepEquals(expected, getVariable("recordInit1")); } { DataRecord expected = DataRecordFactory.newRecord(graph.getDataRecordMetadata("multivalueInput")); expected.getField("integerListField").setValue(Arrays.asList(null, null, 0)); Map<String, BigDecimal> map = new HashMap<>(1); map.put("key", BigDecimal.ZERO); expected.getField("decimalMapField").setValue(map); assertDeepEquals(expected, getVariable("recordInit3")); } { DataRecord r = DataRecordFactory.newRecord(graph.getDataRecordMetadata("multivalueInput")); r.getField("integerListField").setValue(Arrays.asList(null, null, 0)); assertDeepEquals(Arrays.asList(null, null, r), getVariable("recordListInit")); } assertEquals(0, dictionary.getValue("i")); assertEquals(0L, dictionary.getValue("l")); compareDecimals(BigDecimal.ZERO, (BigDecimal) dictionary.getValue("d")); assertEquals(0.0, dictionary.getValue("n")); { DataRecord expected = DataRecordFactory.newRecord(graph.getDataRecordMetadata(OUTPUT_2)); expected.getField("Age").setValue(0.0); expected.getField("BornMillisec").setValue(0L); expected.getField("Value").setValue(0); expected.getField("Currency").setValue(BigDecimal.ZERO); assertDeepEquals(expected, outputRecords[1]); assertDeepEquals(expected, outputRecords[2]); } } public void test_assignment_compound_expect_error() { doCompileExpectError("function integer transform(){" + "integer i;" + "i += null;" + "return 0;}","test_assignment_compound_expect_error", Arrays.asList("Operator '+' is not defined for types: 'integer' and 'null'")); doCompileExpectError("function integer transform(){" + "integer i;" + "i -= 'aaa';" + "return 0;}","test_assignment_compound_expect_error", Arrays.asList("Operator '-' is not defined for types: 'integer' and 'string'")); doCompileExpectError("function integer transform(){" + "integer i;" + "i -= 0L;" + "return 0;}","test_assignment_compound_expect_error", Arrays.asList("Type mismatch: cannot convert from 'long' to 'integer'")); try { doCompile("function integer transform(){" + "integer i;" + "i /= 0;" + "return 0;}","test_assignment_compound_expect_error"); fail(); } catch (RuntimeException ex) { if (!isCausedBy(ex, ArithmeticException.class)) { throw ex; } } try { doCompile("function integer transform(){" + "long l;" + "l /= 0;" + "return 0;}","test_assignment_compound_expect_error"); fail(); } catch (RuntimeException ex) { if (!isCausedBy(ex, ArithmeticException.class)) { throw ex; } } } public void test_assignment_list_initialization() { doCompile("test_assignment_list_initialization"); check("stringList", Arrays.asList(null, null, null, "test")); check("integerList", Arrays.asList(null, null, null, 8)); check("longList", Arrays.asList(null, null, null, 77L)); check("numberList", Arrays.asList(null, null, null, 5.4)); check("booleanList", Arrays.asList(null, null, null, true)); check("decimalList", Arrays.asList(null, null, null, new BigDecimal("8.7"))); { List<byte[]> expected = Arrays.asList(null, null, null, new byte[] {(byte) 0xFF}); assertDeepEquals(expected, getVariable("byteList")); } check("recordList1", Arrays.asList(null, null, null, inputRecords[0])); { DataRecord r = DataRecordFactory.newRecord(inputRecords[0].getMetadata()); r.getField(0).setValue("test"); List<DataRecord> expected = Arrays.asList(null, null, null, r); assertDeepEquals(expected, getVariable("recordList2")); } } // CLO-5789 public void test_assignment_increment() { doCompile("test_assignment_increment"); check("incrementCounter", 1); check("incrementTest", "newValue"); check("incrementTestList", Arrays.asList("newValue")); } // CLO-403 public void test_container_assignment_initialization() { doCompile("test_container_assignment_initialization"); //list Object val = ((List<?>) outputRecords[5].getField("stringListField").getValue()).get(1); assertEquals(val.toString(), "value"); val = ((List<?>) outputRecords[4].getField("stringListField").getValue()).get(0); assertEquals(val.toString(), "value"); List<?> dictList = (List<?>) graph.getDictionary().getEntry("stringList").getValue(); assertDeepEquals(dictList, Arrays.asList(null, "value")); check("listNull", true); check("arrayString", Arrays.asList("value")); //map val = ((Map<?,?>) outputRecords[5].getField("stringMapField").getValue()).get("key"); assertEquals(val.toString(), "value"); val = ((Map<?,?>) outputRecords[4].getField("stringMapField").getValue()).get("key"); assertEquals(val.toString(), "value"); Map<?,?> dictMap = (Map<?,?>) graph.getDictionary().getEntry("stringMap").getValue(); LinkedHashMap<String,String> expectedmap = new LinkedHashMap<>(); expectedmap.put("key", "value"); assertDeepEquals(dictMap, expectedmap); check("mapNull", true); check("mapString", expectedmap); } /** * Answers <code>true</code> if given throwable is or is caused by given cause type. * @param throwable * @param causeType * @return */ public static boolean isCausedBy(Throwable throwable, Class<? extends Throwable> causeType) { while (throwable != null) { if (causeType.isAssignableFrom(throwable.getClass())) { return true; } throwable = throwable.getCause(); } return false; } public void test_container_assignment_initialization_expect_error() { try { doCompile("function string[] getStringList() {return $out.firstMultivalueOutput.stringListField;} function integer transform(){getStringList()[0] = 'test'; return 0;}", "test_container_assignment_initialization_expect_error"); fail(); } catch (NullPointerException npe) { } catch (TransformLangExecutorRuntimeException ex) { if (!isCausedBy(ex, NullPointerException.class)) { throw ex; } } try { doCompile("function map[string, string] getStringMap() {return $out.firstMultivalueOutput.stringMapField;} function integer transform(){getStringMap()['key'] = 'value'; return 0;}", "test_container_assignment_initialization_expect_error"); fail(); } catch (NullPointerException npe) { } catch (TransformLangExecutorRuntimeException ex) { if (!isCausedBy(ex, NullPointerException.class)) { throw ex; } } } // CLO-5423 public void test_cast_null() { doCompile("test_cast_null"); } @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_regex_CLO6907() { try { doCompile("function integer transform(){" + "string regex = null;" + "boolean b = 'a' ~= regex;" + "return 0;}","test_regex_CLO6907"); fail(); } catch (Exception e) { Throwable cause = ExceptionUtils.getRootCause(e); assertTrue(cause instanceof NullPointerException); NullPointerException npe = (NullPointerException) cause; assertEquals("Regular expression is null", npe.getMessage()); } } public void test_regex_CLO7369() { doCompileExpectError("function integer transform(){" + "boolean b = 'a' ~= null;" + "return 0;}", "test_regex_CLO7369", Arrays.asList("Incompatible types 'string' and 'null' for regexp operator")); } 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])); } // CLO-4532: public void test_mapping_whitespace() { doCompileExpectError("test_mapping_whitespace", "Invalid member access expression"); } public void test_mappinglib_field_parsing(){ try { // mapping code can not be null doCompile("function integer transform(){\n" + "getMappedSourceFields(null, \"name\", 0);" + "\nreturn 0;}", "test_mappinglib_field_parsing"); fail(); } catch (RuntimeException e) { if (!isCausedBy(e, NullPointerException.class)) { throw e; } } try { // index can not be null doCompile("function integer transform(){\n" + "getMappedSourceFields(\"$name=$name;$name=$firstName;$countryName=$countryName;#$phone=$field1;\", \"name\", null);" + "\nreturn 0;}", "test_mappinglib_field_parsing"); fail(); } catch (RuntimeException e) { if (!isCausedBy(e, NullPointerException.class)) { throw e; } } try { // index out of bound doCompile("function integer transform(){\n" + "getMappedSourceFields(\"$name=$name;$name=$firstName;$countryName=$countryName;#$phone=$field1;\", \"name\", 2);" + "\nreturn 0;}", "test_mappinglib_field_parsing"); fail(); } catch (RuntimeException e) { if (!isCausedBy(e, IndexOutOfBoundsException.class)) { throw e; } } try { // invalid fieldname "" doCompile("function integer transform(){\n" + "getMappedSourceFields(\"$name=$name;$name=;$countryName=$countryName;#$phone=$field1;\", \"name\", 0);" + "\nreturn 0;}", "test_mappinglib_field_parsing"); fail(); } catch (RuntimeException e) { if (!isCausedBy(e, IllegalArgumentException.class)) { throw e; } if (e instanceof IllegalArgumentException) { assertEquals(e.getMessage(), "field name \"\" is not valid."); } } try { // invalid fieldname "$01myName" doCompile("function integer transform(){\n" + "getMappedSourceFields(\"$name=$name;$name=$01myName;$countryName=$countryName;#$phone=$field1;\", \"name\", 0);" + "\nreturn 0;}", "test_mappinglib_field_parsing"); fail(); } catch (RuntimeException e) { if (!isCausedBy(e, IllegalArgumentException.class)) { throw e; } if (e instanceof IllegalArgumentException) { assertEquals(e.getMessage(), "field name \"$01myName\" is not valid."); } } try { // invalid fieldname "$name(i)" - ordering allowed only on target fields doCompile("function integer transform(){\n" + "getMappedSourceFields(\"$name=$name(i);#$phone=$field1;\", \"name\", 0);" + "\nreturn 0;}", "test_mappinglib_field_parsing"); fail(); } catch (RuntimeException e) { if (!isCausedBy(e, IllegalArgumentException.class)) { throw e; } if (e instanceof IllegalArgumentException) { assertEquals(e.getMessage(), "field name \"$name(i)\" is not valid."); } } doCompile("test_mappinglib_field_parsing"); check("sourceFields_nullTarget", Collections.EMPTY_LIST); check("sourceFields1", Arrays.asList("name", "firstName")); check("sourceFields2", Arrays.asList()); check("sourceFields3", Arrays.asList("a", "b", "c")); check("sourceFields4", Arrays.asList("name", "firstName")); check("sourceFields5", Arrays.asList("name", "firstName", "countryName")); check("sourceFields6", Arrays.asList("name", "firstName", "countryName")); check("targetFields_nullSource", Collections.EMPTY_LIST); check("targetFields", Arrays.asList("name", "countryName")); check("targetFields1", Arrays.asList("name")); check("targetFields2", Arrays.asList("field1", "field2")); check("targetFields3", Arrays.asList("field1", "field2", "field3")); check("isSourceMapped1", true); check("isSourceMapped2", false); check("isSourceMapped3", true); check("isTargetMapped", true); check("sourceMapped_nullTarget", false); check("targetMapped_nullSource", false); // examples from the User Guide check("example_getMappedSourceFields1", Arrays.asList("srcB4")); check("example_getMappedSourceFields2", Arrays.asList("source1", "source3")); check("example_getMappedSourceFields3", Arrays.asList("source1", "source3", "source4")); check("example_getMappedTargetFields1", Arrays.asList("target2")); check("example_getMappedTargetFields2", Arrays.asList("target1", "target3", "target2")); check("example_getMappedTargetFields3", Arrays.asList("target1", "target3")); check("example_isSourceFieldMapped1", true); check("example_isSourceFieldMapped2", false); check("example_isSourceFieldMapped3", true); check("example_isSourceFieldMapped4", false); check("example_isTargetFieldMapped1", true); check("example_isTargetFieldMapped2", false); } 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()); // CLO-637: DataRecord outRecord1 = (DataRecord) getVariable("outRecord1"); DataRecord outRecord2 = (DataRecord) getVariable("outRecord2"); assertEquals(outRecord1.getField("Name").getValue(), null); assertEquals(outRecord2.getField("Name").getValue().toString(), "some value"); } 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_copyByName_assignment_containers() { TransformationGraph g = createEmptyGraph(); DataRecordMetadata m1 = new DataRecordMetadata("metadata1"); m1.addField(new DataFieldMetadata("field1", DataFieldType.STRING, "|")); m1.addField(new DataFieldMetadata("field2", DataFieldType.STRING, "|")); m1.addField(new DataFieldMetadata("field3", DataFieldType.STRING, "|")); m1.addField(new DataFieldMetadata("yyy", DataFieldType.STRING, "|")); g.addDataRecordMetadata(m1); DataRecordMetadata m2 = new DataRecordMetadata("metadata2"); DataFieldMetadata field; m2.addField(new DataFieldMetadata("field1", DataFieldType.STRING, "|")); m2.addField(field = new DataFieldMetadata("field2", DataFieldType.STRING, "|")); field.setContainerType(DataFieldContainerType.LIST); m2.addField(field = new DataFieldMetadata("field3", DataFieldType.STRING, "|")); field.setContainerType(DataFieldContainerType.MAP); m2.addField(new DataFieldMetadata("xxx", DataFieldType.STRING, "|")); g.addDataRecordMetadata(m2); DataRecord input1 = DataRecordFactory.newRecord(m1); DataRecord input2 = DataRecordFactory.newRecord(m2); DataRecord output1 = DataRecordFactory.newRecord(m2); DataRecord output2 = DataRecordFactory.newRecord(m1); input1.getField("field1").setValue("abc"); input1.getField("field2").setValue("def"); input1.getField("field3").setValue("ghi"); input1.getField("yyy").setValue("jkl"); input2.getField("field1").setValue("abc"); input2.getField("field2").setValue(Arrays.asList("def", "ghi")); Map<String, String> map = new HashMap<String, String>(); map.put("jkl", "mno"); map.put("pqr", "stu"); input2.getField("field3").setValue(map); input2.getField("xxx").setValue("jkl"); String testIdentifier = "test_copyByName_assignment_containers"; doCompile(loadSourceCode(testIdentifier), testIdentifier, g, new DataRecord[] {input1, input2}, new DataRecord[] {output1, output2}); assertEquals("abc", output1.getField("field1").getValue().toString()); assertEquals(null, output1.getField("field2").getValue()); assertEquals(null, output1.getField("field3").getValue()); assertEquals(null, output1.getField("xxx").getValue()); assertEquals("abc", output2.getField("field1").getValue().toString()); assertEquals(null, output2.getField("field2").getValue()); assertEquals(null, output2.getField("field3").getValue()); assertEquals(null, output2.getField("yyy").getValue()); } public void test_copyByName_assignment_caseInsensitive() { TransformationGraph g = createEmptyGraph(); DataRecordMetadata m1 = new DataRecordMetadata("metadata1"); m1.addField(new DataFieldMetadata("a", DataFieldType.STRING, "|")); m1.addField(new DataFieldMetadata("b", DataFieldType.STRING, "|")); m1.addField(new DataFieldMetadata("c", DataFieldType.STRING, "|")); m1.addField(new DataFieldMetadata("noexactmatch", DataFieldType.STRING, "|")); m1.addField(new DataFieldMetadata("ambiguous", DataFieldType.STRING, "|")); m1.addField(new DataFieldMetadata("AMBIGUOUS", DataFieldType.STRING, "|")); m1.addField(new DataFieldMetadata("aMBIGUOUs", DataFieldType.STRING, "|")); m1.addField(new DataFieldMetadata("AmbiguouS", DataFieldType.STRING, "|")); m1.addField(new DataFieldMetadata("exactMATCH", DataFieldType.STRING, "|")); m1.addField(new DataFieldMetadata("exactMatch", DataFieldType.STRING, "|")); m1.addField(new DataFieldMetadata("EXACTMATCH", DataFieldType.STRING, "|")); g.addDataRecordMetadata(m1); DataRecordMetadata m2 = new DataRecordMetadata("metadata2"); m2.addField(new DataFieldMetadata("D", DataFieldType.STRING, "|")); m2.addField(new DataFieldMetadata("B", DataFieldType.STRING, "|")); m2.addField(new DataFieldMetadata("A", DataFieldType.STRING, "|")); m2.addField(new DataFieldMetadata("NOEXACTMATCH", DataFieldType.STRING, "|")); m2.addField(new DataFieldMetadata("noExactMatch", DataFieldType.STRING, "|")); m2.addField(new DataFieldMetadata("noEXACTmatch", DataFieldType.STRING, "|")); m2.addField(new DataFieldMetadata("ambiGUOUS", DataFieldType.STRING, "|")); m2.addField(new DataFieldMetadata("AMBIguous", DataFieldType.STRING, "|")); m2.addField(new DataFieldMetadata("ambiguouS", DataFieldType.STRING, "|")); m2.addField(new DataFieldMetadata("Ambiguous", DataFieldType.STRING, "|")); m2.addField(new DataFieldMetadata("ExactMatch", DataFieldType.STRING, "|")); m2.addField(new DataFieldMetadata("EXACTMATCH", DataFieldType.STRING, "|")); m2.addField(new DataFieldMetadata("ExactMATCH", DataFieldType.STRING, "|")); m2.addField(new DataFieldMetadata("Exactmatch", DataFieldType.STRING, "|")); g.addDataRecordMetadata(m2); DataRecordMetadata m3 = new DataRecordMetadata("metadata3"); m3.addField(new DataFieldMetadata("singleInputField", DataFieldType.STRING, "|")); g.addDataRecordMetadata(m3); DataRecordMetadata m4 = new DataRecordMetadata("metadata4"); m4.addField(new DataFieldMetadata("outputField1", DataFieldType.STRING, "|")); // must not match "singleInputField" g.addDataRecordMetadata(m4); String testIdentifier = "test_copyByName_assignment_caseInsensitive"; doCompile(loadSourceCode(testIdentifier), testIdentifier, g, new DataRecord[0], new DataRecord[0]); DataRecord r2 = (DataRecord) getVariable("r2"); assertEquals("a", r2.getField("A").getValue().toString()); assertEquals("b", r2.getField("B").getValue().toString()); assertEquals(null, r2.getField("D").getValue()); assertEquals("noexactmatch", r2.getField("NOEXACTMATCH").getValue().toString()); // assigned to the first matching field assertEquals(null, r2.getField("noExactMatch").getValue()); assertEquals(null, r2.getField("noEXACTmatch").getValue()); assertEquals("ambiguous", r2.getField("ambiGUOUS").getValue().toString()); // first unmapped input field selected assertEquals("AMBIGUOUS", r2.getField("AMBIguous").getValue().toString()); // first unmapped input field selected assertEquals("aMBIGUOUs", r2.getField("ambiguouS").getValue().toString()); // first unmapped input field selected assertEquals("AmbiguouS", r2.getField("Ambiguous").getValue().toString()); // first unmapped input field selected assertEquals("exactMATCH", r2.getField("ExactMatch").getValue().toString()); // first unmapped input field selected assertEquals("EXACTMATCH", r2.getField("EXACTMATCH").getValue().toString()); // exact match (has priority) assertEquals("exactMatch", r2.getField("ExactMATCH").getValue().toString()); // first unmapped input field selected assertEquals(null, r2.getField("Exactmatch").getValue()); // no remaining unmapped input field DataRecord r4 = (DataRecord) getVariable("r4"); assertEquals(null, r4.getField("outputField1").getValue()); // CLO-637 } 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_cast_possible_null_values_CLO5762(){ doCompile("test_cast_possible_null_values_CLO5762"); final Integer ZERO_AS_INT = Integer.valueOf(0); check("integerResult", ZERO_AS_INT); check("integerCurrent", ZERO_AS_INT); final Long ZERO_AS_LONG = Long.valueOf(0); check("longResult", ZERO_AS_LONG); check("longCurrent", ZERO_AS_LONG); check("unspecifiedResult", ZERO_AS_LONG); check("unspecifiedCurrent", ZERO_AS_LONG); check("unspecifiedResult", ZERO_AS_LONG); final double ZERO_AS_DOUBLE = Double.valueOf(0.0); check("doubleResult1", ZERO_AS_DOUBLE); check("doubleResult2", ZERO_AS_DOUBLE); check("doubleCurrent1", ZERO_AS_DOUBLE); check("doubleCurrent2", ZERO_AS_DOUBLE); check("decimalResult1", new BigDecimal("0.000")); check("decimalResult2", new BigDecimal("1.000")); check("decimalResult3", new BigDecimal("2.000")); check("decimalResult4", new BigDecimal("3.000")); check("decimalResult5", new BigDecimal("4.000")); check("decimalResult6", new BigDecimal("5.000")); check("decimalResult7", new BigDecimal("6.000")); final BigDecimal ZERO_AS_DECIMAL = new BigDecimal(0.0); check("decimalCurrent3", ZERO_AS_DECIMAL); check("decimalCurrent4", ZERO_AS_DECIMAL); check("decimalCurrent5", ZERO_AS_DECIMAL); check("decimalCurrent6", ZERO_AS_DECIMAL); check("decimalCurrent7", ZERO_AS_DECIMAL); } public void test_sequence(){ doCompile("test_sequence"); check("intRes", Arrays.asList(0, 1, 2, 3, 4, 5)); check("longRes", Arrays.asList(Long.valueOf(0), Long.valueOf(1), Long.valueOf(2), Long.valueOf(3), Long.valueOf(4), Long.valueOf(5))); check("stringRes", Arrays.asList("0", "1", "2", "3", "4", "5")); check("intCurrent", Integer.valueOf(5)); check("longCurrent", Long.valueOf(5)); check("stringCurrent", "5"); } //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","Chomutov","Chodov","Chamonix","Chomutov","Chodov")); 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<?>)(getVariable("copyEmptyList"))).isEmpty()); assertTrue(((List<?>)(getVariable("returnedEmptyList"))).isEmpty()); Map<String, String> emptyMap = new HashMap<String, String>(); check("copyEmptyMap", emptyMap); check("returnedEmptyMap", emptyMap); assertTrue(((HashMap<?,?>)(getVariable("copyEmptyMap"))).isEmpty()); assertTrue(((HashMap<?,?>)(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); check("emptyString",true); check("fullString",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 } doCompileExpectError( "function integer transform(){reverse(null); return 0;}", "test_containerlib_reverse_expect_error", Arrays.asList("Function 'reverse' is ambiguous")); 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()); check("retNull1", Arrays.asList("Kennen", "Renector", null, null)); check("retNull2", Arrays.asList(false, true, true, null, null, null)); cal.clear(); cal.set(2001,0,20,0,0,0); cal.set(Calendar.MILLISECOND, 0); cal2.clear(); cal2.set(2003,4,12,0,0,0); cal2.set(Calendar.MILLISECOND, 0); check("retNull3", Arrays.asList(cal.getTime(), cal2.getTime(), null, null)); check("retNull4", Arrays.asList(1,8,10,12,null,null,null)); check("retNull5", Arrays.asList(1l, 12l, 15l, null, null, null)); check("retNull6", Arrays.asList(12.1d, 12.3d, 12.4d, null, null)); check("retNull7", Arrays.asList(new BigDecimal("11"), new BigDecimal("11.1"), new BigDecimal("11.2"), null, null, null)); } public void test_containerlib_sort_expect_error(){ 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", true); // disabled - CLO-4979 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); check("listResults", Arrays.asList(true, false, false, true, false, false, true, false)); check("listEmptyTest1", false); check("listEmptyTest2", false); check("listEmptyTest3", false); check("listTest1", true); check("listTest2", true); check("listTest3", false); check("listTest4", true); check("listTest5", true); check("listTest6", false); //check("listTest7", true); // disabled - CLO-4979 check("listTest8", true); check("listTest9", true); check("listTest10", false); check("listTest11", true); check("listTest12", true); check("listTest13", false); check("listTest14", true); check("listTest15", true); check("listTest16", false); check("integerToLongTest", true); check("listTest17", true); check("listTest18", true); check("listTest19", false); check("listTest20", true); check("listTest21", true); check("listTest22", false); check("listTest23", true); check("listTest24", true); check("listTest25", false); check("listEmptyTest4", false); } public void test_containerlib_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 } try { doCompile("function integer transform(){long[] nullList = null; boolean b = nullList.containsValue(18L); return 0;}","test_convertlib_containsValue_expect_error"); fail(); } catch (Exception e) { // do nothing } doCompileExpectError("function integer transform(){boolean b = containsValue(null, 18L); return 0;}","test_convertlib_containsValue_expect_error", Arrays.asList("Function 'containsValue' is ambiguous")); } public void test_containerlib_binarySearch() { doCompile("test_containerlib_binarySearch"); check("listResults", Arrays.asList(2, -4, -4, 0, -1, -1, 1, -4)); check("listEmptyTest2", -1); check("listEmptyTest3", -1); check("listTest2", 1); check("listTest3", 0); check("listTest8", 1); check("listTest9", 0); check("listTest10", -3); check("listTest11", 1); check("listTest12", 0); check("listTest13", -5); check("listTest14", 0); check("listTest15", 2); check("listTest16", -4); check("integerToLongTest", 1); check("listTest17", 1); check("listTest18", 0); check("listTest19", -5); check("listTest20", 0); check("listTest21", 1); check("listTest22", -5); check("listTest23", 1); check("listTest24", 0); check("listTest25", -5); check("listEmptyTest4", -1); } public void test_containerlib_binarySearch_expect_error(){ try { doCompile("function integer transform(){long[] nullList = null; integer i = nullList.binarySearch(18L); return 0;}","test_containerlib_binarySearch_expect_error"); fail(); } catch (Exception e) { assertTrue(isCausedBy(e, NullPointerException.class)); } try { doCompile("function integer transform(){long nullValue = null; [5L, 15L].binarySearch(nullValue); return 0;}","test_containerlib_binarySearch_expect_error"); fail(); } catch (Exception e) { assertTrue(isCausedBy(e, NullPointerException.class)); } try { doCompile("function integer transform(){long[] emptyList; long nullValue = null; emptyList.binarySearch(nullValue); return 0;}","test_containerlib_binarySearch_expect_error"); fail(); } catch (Exception e) { assertTrue(isCausedBy(e, NullPointerException.class)); } try { doCompile("function integer transform(){byte[] byteList = [hex2byte('00')]; byteList.binarySearch(hex2byte('FF')); return 0;}","test_containerlib_binarySearch_expect_error"); fail(); } catch (Exception e) { assertTrue(isCausedBy(e, IllegalArgumentException.class)); } } 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_containerlib_getValues() { doCompile("test_containerlib_getValues"); 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_getValues_expect_error(){ try { doCompile("function integer transform(){map[string,string] strMap = null; string[] str = strMap.getValues(); return 0;}","test_containerlib_getValues_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){map[string,string] strMap = null; string[] str = getValues(strMap); return 0;}","test_containerlib_getValues_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_containerlib_toMap() { doCompile("test_containerlib_toMap"); { Map<Integer, Boolean> expected = new HashMap<>(); expected.put(5, true); expected.put(8, false); check("integerBooleanMap", expected); } { Map<Integer, Boolean> expected = new HashMap<>(); expected.put(5, null); expected.put(8, null); check("integerBooleanMapNull", expected); } { Map<Integer, Boolean> expected = new HashMap<>(); expected.put(5, true); expected.put(8, true); check("integerBooleanMapTrue", expected); } check("emptyMap", new HashMap<BigDecimal, Long>(0)); { Map<Double, byte[]> expected = new HashMap<>(); expected.put(null, null); check("nullMap", expected); } { Map<Date, String> expected = new HashMap<>(); expected.put(new Date(7), "C"); expected.put(null, "D"); expected.put(new Date(46), "E"); check("duplicateMap", expected); } { List<String> upperCase = Arrays.asList("A", "B", "C", "D", "E", "F", "G"); List<String> lowerCase = Arrays.asList("a", "b", "c", "d", "e", "f", "g"); check("keys1", upperCase); check("keys2", upperCase); check("values", lowerCase); } } public void test_containerlib_toMap_expect_error() { doCompileExpectError("function integer transform(){map[string,string] strMap = toMap(null, null); return 0;}","test_containerlib_toMap_expect_error", Arrays.asList("Function 'toMap' is ambiguous")); doCompileExpectError("function integer transform(){map[string,string] strMap = toMap(['a', 'b'], null); return 0;}","test_containerlib_toMap_expect_error", Arrays.asList("Function 'toMap' is ambiguous")); doCompileExpectError("function integer transform(){string[] values = null; map[string,string] strMap = toMap(null, values); return 0;}","test_containerlib_toMap_expect_error", Arrays.asList("Type mismatch: cannot convert from 'map[?,string]' to 'map[string,string]'")); try { doCompile("function integer transform(){string[] keys = ['A']; string[] values = null; map[string,string] strMap = toMap(keys, values); return 0;}","test_containerlib_toMap_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string[] keys = null; string[] values = ['A']; map[string,string] strMap = toMap(keys, values); return 0;}","test_containerlib_toMap_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string[] keys = ['x', 'y']; string[] values = ['A']; map[string,string] strMap = toMap(keys, values); return 0;}","test_containerlib_toMap_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 } try { doCompile("integer test;function integer transform() {integer input = null; test = editDistance('Talon','Ahri', input);return 0;}","test_stringlib_editDistance_expect_error"); } catch ( Exception e) { // do nothing } try { doCompile("integer test;function integer transform() {integer input = null; test = editDistance('Talon','Ahri', input, 'cs.CZ');return 0;}","test_stringlib_editDistance_expect_error"); } catch ( Exception e) { // do nothing } try { doCompile("integer test;function integer transform() {integer input = null; test = editDistance('Talon','Ahri', input, input);return 0;}","test_stringlib_editDistance_expect_error"); } catch ( Exception e) { // do nothing } try { doCompile("integer test;function integer transform() {integer input = null; test = editDistance('Talon','Ahri', input, 'cs.CZ', input);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('mark.twain@javlin.eu','(^[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('mark.twain@javlin.eu','(^[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('mark.twain@javlin.eu',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", null); check("test9", "abc"); check("test10", "abc"); check("test11", ""); check("test12", null); check("test13", null); check("test14", ""); check("test15", ""); } public void test_stringlib_left_expect_error(){ try { doCompile("function integer transform(){string s = left('Lux', -7, false); return 0;}","test_stringlib_left_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string s = left('Darius', -7, true); return 0;}","test_stringlib_left_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string s = left('Darius', null, true); return 0;}","test_stringlib_left_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer int = null; string s = left('Darius', int, true); return 0;}","test_stringlib_left_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){boolean b = null; string s = left('Darius', 9, b); return 0;}","test_stringlib_left_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string s = left('Darius', 7, null); return 0;}","test_stringlib_left_expect_error"); fail(); } catch (Exception e) { // do nothing } } 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("split2", Arrays.asList("The quick br", "wn f", "", " jumps " , "ver the lazy d", "g")); check("split3", Arrays.asList("The quick br", "wn f", "", " jumps " , "ver the lazy d", "g")); // limit check("limit1", Arrays.asList("The quick brown fox jumps over the lazy dog")); check("limit2", Arrays.asList("The quick br", "wn fox jumps over the lazy dog")); check("limit3", Arrays.asList("The quick br", "wn f", "x jumps over the lazy dog")); check("limit4", Arrays.asList("The quick br", "wn f", "", " jumps over the lazy dog")); check("limit20", 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")); check("test_empty3", Arrays.asList("")); check("test_empty4", Arrays.asList("","a","a")); check("test_empty5", Arrays.asList("")); check("test_empty6", Arrays.asList("","a","a", "")); // regex is an empty string => trailing empty string check("test_null", Collections.EMPTY_LIST); check("removeTrailing1", Collections.EMPTY_LIST); check("removeTrailing2", Collections.EMPTY_LIST); check("removeTrailing3", Arrays.asList("", "a", "", "b")); check("removeTrailing4", Arrays.asList("", "a", "", "b")); check("keepTrailing1", Arrays.asList("", "", "", "", "")); check("keepTrailing2", Arrays.asList("", "a", "", "b", "", "", "")); } public void test_stringlib_split_expect_error(){ //test: regexp null literal 1 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 literal 2 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 literal 3 try { doCompile("function integer transform(){string[] s = split(null,null); return 0;}","test_stringlib_split_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: regexp null variable try { doCompile("function integer transform(){string regexp = null; string[] s = split(null,regexp); return 0;}","test_stringlib_split_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: limit null try { doCompile("function integer transform(){split('a','a',null); return 0;}","test_stringlib_split_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: limit null variable try { doCompile("function integer transform(){integer limit = null; split('a','a',limit); 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", ""); check("nullLiteral", null); check("nullVariable", null); check("subs2", "UICk !!$ broWn fox juMPS over the lazy DOG "); check("test2", "aaa"); check("test3", ""); check("test_empty2", ""); check("nullLiteral2", null); check("nullVariable2", null); check("result1", "abcdefghi"); check("result2", "fghi"); check("result3", ""); check("result4", ""); check("result5", ""); check("result6", "abcdefghi"); check("result7", ""); check("result8", "f"); check("result9", "fghi"); check("result10", ""); check("result11", "i"); check("result12", "i"); } public void test_stringlib_substring_expect_error(){ 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(null,2,-3);return 0;}","test_stringlib_substring_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string test = substring(null,-5,7);return 0;}","test_stringlib_substring_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string test = substring('arabela',-5);return 0;}","test_stringlib_substring_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string test = substring(null,-5);return 0;}","test_stringlib_substring_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string test = substring('arabela',null);return 0;}","test_stringlib_substring_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string test = substring('arabela',null,5);return 0;}","test_stringlib_substring_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string test = substring('arabela',5,null);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_reverse() { doCompile("test_stringlib_reverse"); check("reversed1", "hgfedcba"); check("reversed2", "a"); check("reversed3", null); check("czechString", "\u017Elu\u0165ou\u010Dk\u00FD k\u016F\u0148 \u00FAp\u011Bl \u010F\u00E1belsk\u00E9 \u00F3dy"); // contains 3 non-BMP code points (those which consist of 2 chars) String nonBMP = "\u4DB5\u4E26\u4E27\u4E21\u3402\uD840\uDC0B\u5345\u4E94\u4E92\u4E30\u4E0D\u29EC\u29ED\u29F0\u29EF\uD83D\uDE04\uD835\uDC9E"; check("nonBMP", nonBMP); check("compositeCharacters1", "\u00E9\u00E1o"); // reverse called on composed characters check("compositeCharacters2", "e\u0301a\u0301o"); // reverse called on decomposed characters check("compositeCharacters3", "ea\u0301o\u0301"); // reverse called on canonical composition, then decomposed again check("emptyStr", ""); check("singleChar", "c"); } 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("isNumber9", false); check("isInteger", false); check("isInteger1", false); check("isInteger2", false); check("isInteger3", true); check("isInteger4", false); check("isInteger5", false); check("isInteger6", false); check("isLong", true); check("isLong1", false); check("isLong2", false); check("isLong3", false); check("isLong4", false); check("isLong5", 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", true); check("isDate23", false); check("isDate24", true); check("isDate25", false); check("isDate26", true); check("isDate27", true); // CLO-6601 check("isDate28", false); check("isDate29", false); check("isDate30", false); check("isDate31", false); check("isDate32", false); check("isDate33", false); check("isDate34", false); check("isDate35", true); check("isDate36", true); check("isDate37", true); check("isDate38", true); check("isDecimal", false); check("isDecimal1", false); check("isDecimal2", true); check("isDecimal3", true); check("isDecimal4", false); check("isDecimal5", true); check("isDecimal6", true); check("isDecimal7", false); check("isDecimal8", 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); check("nullInput1", -1); check("nullInput2", -1); check("nullInputVariable1", -1); check("nullInputVariable2", -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 } //test: third arg is null try { doCompile("integer index;function integer transform() {index = indexOf('a','a',null); return 0;}","test_stringlib_indexOf_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_stringlib_lastIndexOf() { doCompile("test_stringlib_lastIndexOf"); check("index1", 9); check("index2", 9); check("index3", 3); check("index4", 12); check("index5", 12); // check("index6", -1); // check("index7", -1); check("index8", 0); check("index9", 0); check("index10", -1); check("nullLiteral1", -1); check("nullLiteral2", -1); check("nullVariable1", -1); check("nullVariable2", -1); } public void test_stringlib_lastIndexOf_expect_error() { //test: fromIndex is null - test1 try { doCompile("integer index;function integer transform() {index = lastIndexOf('hello world','b', null); return 0;}","test_stringlib_lastIndexOf_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: fromIndex is null - test2 try { doCompile("integer index;function integer transform() {integer from = null;index = lastIndexOf('hello world','b', from); return 0;}","test_stringlib_lastIndexOf_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: null searchStr - test1 try { doCompile("integer index;function integer transform() {index = lastIndexOf('hello world',null); return 0;}","test_stringlib_lastIndexOf_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: null variable searchStr - test2 try { doCompile("integer index;function integer transform() {string searchStr = null;index = lastIndexOf('hello world',searchStr); return 0;}","test_stringlib_lastIndexOf_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: null searchStr - test3 try { doCompile("integer index;function integer transform() {index = lastIndexOf('hello world',null,0); return 0;}","test_stringlib_lastIndexOf_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: null variable searchStr - test4 try { doCompile("integer index;function integer transform() {string searchStr = null;index = lastIndexOf('hello world',searchStr,0); return 0;}","test_stringlib_lastIndexOf_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_stringlib_capitalizeWords() { // doCompile("test_stringlib_capitalizeWords"); // check("word", "Word"); // check("twoWords", "Two Words"); // check("sentence", "A Full Sentence."); // check("clock", "8 O'clock"); // check("underscore", "Do _not_ Capitalize Me"); // check("titleCase", "A Full Sentence"); // check("slovak", "\u010Cerven\u00FD \u013Dadoborec"); // check("russian", "\u041F\u0440\u043E\u043B\u0435\u0442\u0430\u0440\u0438\u0438 \u0412\u0441\u0435\u0445 \u0421\u0442\u0440\u0430\u043D, \u0421\u043E\u0435\u0434\u0438\u043D\u044F\u0439\u0442\u0435\u0441\u044C!"); // check("japanese", "\u673A\u306E\u4E0A\u306B\u306F\u30B1\u30FC\u30AD\u304C\u3042\u308A\u307E\u3059\u3002"); // check("german", "\u00DCberwald"); // check("nullValue", null); // check("emptyString", ""); // public void test_stringlib_uncapitalizeWords() { // doCompile("test_stringlib_uncapitalizeWords"); // check("leaveMe", "lEAVE mE aLONE"); // check("correct", "this is correct"); // check("clock", "7 o'Clock"); // check("russian", "\u043F\u0440\u043E\u043B\u0435\u0442\u0430\u0440\u0438\u0438 \u0432\u0441\u0435\u0445 \u0441\u0442\u0440\u0430\u043D, \u0441\u043E\u0435\u0434\u0438\u043D\u044F\u0439\u0442\u0435\u0441\u044C!"); // check("japanese", "\u673A\u306E\u4E0A\u306B\u306F\u30B1\u30FC\u30AD\u304C\u3042\u308A\u307E\u3059\u3002"); // check("german", "\u00FCberwald"); // check("nullValue", null); // check("emptyString", ""); public void test_stringlib_startsWith() { doCompile("test_stringlib_startsWith"); check("b1", true); check("b2", false); check("b3", true); check("b4", false); check("b5", false); check("b6", false); check("b7", true); } public void test_stringlib_startsWith_expect_error() { // null literal prefix try { doCompile("function integer transform(){startsWith('bla bla',null);return 0;}","test_stringlib_startsWith_expect_error"); fail(); } catch (Exception e) { // do nothing } // null variable prefix try { doCompile("function integer transform(){string prefix = null; startsWith('bla bla',prefix);return 0;}","test_stringlib_startsWith_expect_error"); fail(); } catch (Exception e) { // do nothing } // both nulls try { doCompile("function integer transform(){startsWith(null,null);return 0;}","test_stringlib_startsWith_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_stringlib_endsWith() { doCompile("test_stringlib_endsWith"); check("b1", true); check("b2", false); check("b3", true); check("b4", false); check("b5", false); check("b6", false); check("b7", true); } public void test_stringlib_endsWith_expect_error() { // null literal prefix try { doCompile("function integer transform(){endsWith('bla bla',null);return 0;}","test_stringlib_endsWith_expect_error"); fail(); } catch (Exception e) { // do nothing } // null variable prefix try { doCompile("function integer transform(){string prefix = null; endsWith('bla bla',prefix);return 0;}","test_stringlib_endsWith_expect_error"); fail(); } catch (Exception e) { // do nothing } // both nulls try { doCompile("function integer transform(){endsWith(null,null);return 0;}","test_stringlib_endsWith_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_stringlib_lpad() { doCompile("test_stringlib_lpad"); check("result1", "---abc"); check("result2", "abc"); check("result3", " abc"); check("result4", "abc"); check("result5", null); check("result6", null); check("result7", "xxx "); check("result8", " "); check("zeroLength1", "abc"); check("zeroLength2", "abc"); } public void test_stringlib_lpad_expect_error() { //test: null filler try { doCompile("string test;function integer transform() {test = lpad(null, 10, null);return 0;}","test_stringlib_lpad_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: null filler variable try { doCompile("string test;function integer transform() {string filler = null; test = lpad(null, 10, filler);return 0;}","test_stringlib_lpad_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("string test;function integer transform() {test = lpad('x', 10, 'filler');return 0;}","test_stringlib_lpad_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: negative target length 1 try { doCompile("function integer transform() {lpad(null, -1, ' ');return 0;}","test_stringlib_lpad_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: negative target length 2 try { doCompile("function integer transform() {lpad(null, -1);return 0;}","test_stringlib_lpad_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: negative target length 3 try { doCompile("function integer transform() {lpad('abc', -1, ' ');return 0;}","test_stringlib_lpad_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: negative target length 4 try { doCompile("function integer transform() {lpad('abc', -1);return 0;}","test_stringlib_lpad_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: null target length 1 try { doCompile("string test;function integer transform() {test = lpad('x', null);return 0;}","test_stringlib_lpad_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: null target length 1 (variable) try { doCompile("string test;function integer transform() {integer input = null;test = lpad('x', input);return 0;}","test_stringlib_lpad_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: null target length 2 try { doCompile("string test;function integer transform() {test = lpad('x', null, '-');return 0;}","test_stringlib_lpad_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: null target length 2 (variable) try { doCompile("string test;function integer transform() {integer input = null;test = lpad('x', input, '-');return 0;}","test_stringlib_lpad_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_stringlib_rpad() { doCompile("test_stringlib_rpad"); check("result1", "abc check("result2", "abc"); check("result3", "abc "); check("result4", "abc"); check("result5", null); check("result6", null); check("result7", " xxx"); check("result8", " "); check("zeroLength1", "abc"); check("zeroLength2", "abc"); } public void test_stringlib_rpad_expect_error() { //test: null filler try { doCompile("string test;function integer transform() {test = rpad(null, 10, null);return 0;}","test_stringlib_rpad_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: null filler variable try { doCompile("string test;function integer transform() {string filler = null; test = rpad(null, 10, filler);return 0;}","test_stringlib_rpad_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("string test;function integer transform() {test = rpad('x', 10, 'filler');return 0;}","test_stringlib_rpad_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: negative target length 1 try { doCompile("function integer transform() {rpad(null, -1, ' ');return 0;}","test_stringlib_rpad_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: negative target length 2 try { doCompile("function integer transform() {rpad(null, -1);return 0;}","test_stringlib_rpad_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: negative target length 3 try { doCompile("function integer transform() {rpad('abc', -1, ' ');return 0;}","test_stringlib_rpad_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: negative target length 4 try { doCompile("function integer transform() {rpad('abc', -1);return 0;}","test_stringlib_rpad_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: null target length 1 try { doCompile("string test;function integer transform() {test = rpad('x', null);return 0;}","test_stringlib_rpad_expect_error"); fail(); } catch (Exception e) { // do nothing e.printStackTrace(); } //test: null target length 1 (variable) try { doCompile("string test;function integer transform() {integer input = null;test = rpad('x', input);return 0;}","test_stringlib_rpad_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: null target length 2 try { doCompile("string test;function integer transform() {test = rpad('x', null, '-');return 0;}","test_stringlib_rpad_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: null target length 2 (variable) try { doCompile("string test;function integer transform() {integer input = null;test = rpad('x', input, '-');return 0;}","test_stringlib_rpad_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_stringlib_concatWithSeparator() { doCompile("test_stringlib_concatWithSeparator"); check("result1", "a,b,c"); check("result2", "a, b, c"); check("result3", "ab"); check("result4", "x, y, z"); check("result5", "a#a,b,c#b#c"); check("blank", ""); check("variables", "a, b, c"); check("oneElement", "a"); } public void test_stringlib_concatWithSeparator_expect_error() { //test: null separator try { doCompile("string test;function integer transform() {test = concatWithSeparator(null, 'a', 'b');return 0;}","test_stringlib_concatWithSeparator_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_stringlib_escapeUrlFragment() { doCompile("test_stringlib_escapeUrlFragment"); String expected = "nothing_interesting"; check("noCharset", expected); check("utf8", "%C5%BElu%C5%A5ou%C4%8Dk%C3%BD_k%C5%AF%C5%88_%C3%BAp%C4%9Bl_%C4%8F%C3%A1belsk%C3%A9_%C3%B3dy"); check("cp1250", "%9Elu%9Dou%E8k%FD_k%F9%F2_%FAp%ECl_%EF%E1belsk%E9_%F3dy"); // UTF-8 check("defaultCharset", "%C5%BElu%C5%A5ou%C4%8Dk%C3%BD_k%C5%AF%C5%88_%C3%BAp%C4%9Bl_%C4%8F%C3%A1belsk%C3%A9_%C3%B3dy"); check("keyValue", "name%3Dvalue"); check("keyValueSpace", "name%3Dlong+value"); check("emptyString", ""); check("nullValue1", null); check("nullValue2", null); // CLO-2367 check("emailAddressLogin1", "http%3A%2F%2Fsome.user%40gooddata.com%3Apassword%40secure.bestdata.com"); check("emailAddressLogin2", "http://some.user%40gooddata.com:password@secure.bestdata.com"); check("hashLogin1", "http%3A%2F%2Fac%23dsds.dsz%3Apassword%40server.goooddata.com%2Fnice"); check("hashLogin2", "http://ac%23dsds.dsz:password@server.goooddata.com/nice"); check("plusLogin1", "http%3A%2F%2Fac%25%2Bdsds.dsz%3Apassword%40server.goooddata.com%2Fnice"); check("plusLogin2", "http://ac%25%2Bdsds.dsz:password@server.goooddata.com/nice"); } public void test_stringlib_escapeUrlFragment_expect_error() { //test: null literal encoding try { doCompile("function integer transform() {escapeUrlFragment('test', null);return 0;}","test_stringlib_escapeUrlFragment_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: null variable encoding try { doCompile("function integer transform() {string encoding = null; escapeUrlFragment('test', encoding);return 0;}","test_stringlib_escapeUrlFragment_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: empty encoding try { doCompile("function integer transform() {escapeUrlFragment('test', '');return 0;}","test_stringlib_escapeUrlFragment_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: Unsupported encoding try { doCompile("string test;function integer transform() {test = escapeUrlFragment('test', 'not a charset');return 0;}","test_stringlib_escapeUrlFragment_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_stringlib_unescapeUrlFragment() { doCompile("test_stringlib_unescapeUrlFragment"); String expected = "nothing_interesting"; check("noCharset", expected); String kun = "\u017Elu\u0165ou\u010Dk\u00FD_k\u016F\u0148_\u00FAp\u011Bl_\u010F\u00E1belsk\u00E9_\u00F3dy"; check("utf8", kun); check("cp1250", kun); check("defaultCharset", kun); check("keyValue", "name=value"); check("keyValueSpace1", "name=long value"); check("keyValueSpace2", "name=long value"); check("emptyString", ""); check("nullValue1", null); check("nullValue2", null); } public void test_stringlib_unescapeUrlFragment_expect_error() { //test: null literal encoding try { doCompile("function integer transform() {unescapeUrlFragment('%20', null);return 0;}","test_stringlib_unescapeUrlFragment_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: null variable encoding try { doCompile("function integer transform() {string encoding = null; unescapeUrlFragment('%20', encoding);return 0;}","test_stringlib_unescapeUrlFragment_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: empty encoding try { doCompile("function integer transform() {unescapeUrlFragment('%20', '');return 0;}","test_stringlib_unescapeUrlFragment_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: Unsupported encoding try { doCompile("string test;function integer transform() {test = unescapeUrlFragment('%20', 'not a charset');return 0;}","test_stringlib_unescapeUrlFragment_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_stringlib_codePointToChar() { doCompile("test_stringlib_codePointToChar"); check("a", "a"); check("c_caron", "\u010D"); check("Ryo", "\u826F"); check("S", "\uD835\uDD4A"); // double-struck S } public void test_stringlib_codePointToChar_expect_error() { //test: negative code point try { doCompile("string test;function integer transform() {test = codePointToChar(-1);return 0;}","test_stringlib_codePointToChar_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: null try { doCompile("string test;function integer transform() {test = codePointToChar(null);return 0;}","test_stringlib_codePointToChar_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: null variable try { doCompile("string test;function integer transform() {integer input = null;test = codePointToChar(input);return 0;}","test_stringlib_codePointToChar_expect_error"); fail(); } catch (Exception e) { // do nothing } } @SuppressWarnings("unchecked") public void test_stringlib_codePointAt() { doCompile("test_stringlib_codePointAt"); check("russian", 0x0445); check("slovak", (int) 'd'); List<Integer> japanese = (List<Integer>) getVariable("japanese"); StringBuilder sb = new StringBuilder(japanese.size()); for (Integer i: japanese) { sb.appendCodePoint(i); } assertEquals(sb.toString(), "\u673A\u306E\u4E0A\u306B\u306F\u30B1\u30FC\u30AD\u304C\u3042\u308A\u307E\u3059\u3002"); List<Integer> equation = (List<Integer>) getVariable("equation"); StringBuilder actualEquation = new StringBuilder(equation.size()); for (Integer i: equation) { actualEquation.appendCodePoint(i); } StringBuilder expectedEquation = new StringBuilder(); // A = {x, y} (in mathematical script) expectedEquation.appendCodePoint(0x01D49C).append(" = {").appendCodePoint(0x01D465).append(", ").appendCodePoint(0x01D4CE).append("}"); assertEquals(expectedEquation.toString(), actualEquation.toString()); } public void test_stringlib_codePointAt_expect_error() { //test: negative index try { doCompile("integer test;function integer transform() {test = 'abc'.codePointAt(-1);return 0;}","test_stringlib_codePointAt_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: index out of bounds try { doCompile("integer test;function integer transform() {test = 'abc'.codePointAt(3);return 0;}","test_stringlib_codePointAt_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: null try { doCompile("integer test;function integer transform() {test = 'abc'.codePointAt(null);return 0;}","test_stringlib_codePointAt_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: null variable try { doCompile("integer test;function integer transform() {integer input = null;test = 'abc'.codePointAt(input);return 0;}","test_stringlib_codePointAt_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_stringlib_codePointLength() { doCompile("test_stringlib_codePointLength"); check("maxJapanese", 1); check("equation", Arrays.asList("\uD835\uDC9C", "\uD835\uDC65", "\uD835\uDCCE")); } public void test_stringlib_codePointLength_expect_error() { //test: null try { doCompile("integer test;function integer transform() {test = codePointLength(null);return 0;}","test_stringlib_codePointLength_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: null variable try { doCompile("integer test;function integer transform() {integer input = null;test = codePointLength(input);return 0;}","test_stringlib_codePointLength_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_stringlib_isValidCodePoint() { doCompile("test_stringlib_isValidCodePoint"); check("negative", false); check("minCodePoint", true); check("maxCodePoint", true); check("tooHigh", false); check("a", true); check("c_caron", true); check("Ryo", true); check("S", true); } public void test_stringlib_isValidCodePoint_expect_error() { //test: null try { doCompile("boolean test;function integer transform() {test = isValidCodePoint(null);return 0;}","test_stringlib_codePointLength_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: null variable try { doCompile("boolean test;function integer transform() {integer input = null;test = isValidCodePoint(input);return 0;}","test_stringlib_codePointLength_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_stringlib_unicodeNormalize() { doCompile("test_stringlib_unicodeNormalize"); check("nullValue1", null); check("nullValue2", null); check("emptyString", ""); check("nfd", "A\u030AA\u030AA\u030A\u0132c\u030Cc\u030C"); check("nfc", "\u00C5\u00C5\u00C5\u0132\u010D\u010D"); check("nfkd", "A\u030AA\u030AA\u030AIJc\u030Cc\u030C"); check("nfkc", "\u00C5\u00C5\u00C5IJ\u010D\u010D"); check("NFD", "A\u030AA\u030AA\u030A\u0132c\u030Cc\u030C"); check("NFC", "\u00C5\u00C5\u00C5\u0132\u010D\u010D"); check("NFKD", "A\u030AA\u030AA\u030AIJc\u030Cc\u030C"); check("NFKC", "\u00C5\u00C5\u00C5IJ\u010D\u010D"); } public void test_stringlib_unicodeNormalize_expect_error() { //test: null try { doCompile("function integer transform() {unicodeNormalize('sample input', null);return 0;}","test_stringlib_unicodeNormalize_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: null variable try { doCompile("function integer transform() {string input = null;unicodeNormalize('sample input', input);return 0;}","test_stringlib_unicodeNormalize_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: invalid algorithm try { doCompile("function integer transform() {string input = 'not a valid algorithm';unicodeNormalize('sample input', input);return 0;}","test_stringlib_unicodeNormalize_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_stringlib_isUnicodeNormalized() { doCompile("test_stringlib_isUnicodeNormalized"); check("nullValue1", true); check("nullValue2", true); check("emptyString", true); check("nfd", true); check("nfc", true); check("nfkd", true); check("nfkc", true); check("NFD", true); check("NFC", true); check("NFKD", true); check("NFKC", true); Boolean[] results = new Boolean[8]; Arrays.fill(results, Boolean.FALSE); check("results", Arrays.asList(results)); } public void test_stringlib_isUnicodeNormalized_expect_error() { //test: null try { doCompile("function integer transform() {isUnicodeNormalized('sample input', null);return 0;}","test_stringlib_isUnicodeNormalized_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: null variable try { doCompile("function integer transform() {string input = null;isUnicodeNormalized('sample input', input);return 0;}","test_stringlib_isUnicodeNormalized_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: invalid algorithm try { doCompile("function integer transform() {string input = 'not a valid algorithm';isUnicodeNormalized('sample input', input);return 0;}","test_stringlib_isUnicodeNormalized_expect_error"); fail(); } catch (Exception e) { // do nothing } } private void checkEqualVariables(String var1, String var2) { Object value1 = getVariable(var1); Object value2 = getVariable(var2); assertEquals("Variables '" + var1 + "' and '" + var2 + "' have different values", value1, value2); } public void test_stringlib_contains() { doCompile("test_stringlib_contains"); check("contains1", true); check("contains2", true); check("contains3", false); check("contains4", true); check("contains_empty1", false); check("contains_empty2", true); check("contains_null1", false); check("contains_null2", false); check("self", true); // check consistency with indexOf() for (int i = 1; i <= 4; i++) { checkEqualVariables("contains" + i, "indexOf" + i); } for (int i = 1; i <= 2; i++) { checkEqualVariables("contains_empty" + i, "indexOf_empty" + i); } for (int i = 1; i <= 2; i++) { checkEqualVariables("contains_null" + i, "indexOf_null" + i); } } public void test_stringlib_contains_expect_error() { //test: null try { doCompile("function integer transform() {contains('sample input', null);return 0;}","test_stringlib_contains_expect_error"); fail(); } catch (Exception e) { // do nothing } //test: null variable try { doCompile("function integer transform() {string input = null;contains('sample input', input);return 0;}","test_stringlib_contains_expect_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); checkArray("resultByte1", new byte[] {0x01, (byte) 0xF1, (byte) 0xFF}); checkArray("resultByte2", new byte[] {(byte) 0xF1, (byte) 0xF1, (byte) 0xFF}); checkArray("resultByte3", new byte[] {0x71, 0x73, (byte) 0xFF}); checkArray("resultByte4", new byte[] {(byte) 0xF1, (byte) 0xF3, (byte) 0xFF}); checkArray("resultByteDifferentLength", new byte[] {(byte) 0xFF, (byte) 0xF0, (byte) 0xF7}); } 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 } try { doCompile("function integer transform(){\n" + "byte a = hex2byte('FF'); byte b = null;\n" + "byte i = bitOr(a,b);\n" + "return 0;}", "test_bitwise_or_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){\n" + "byte a = null; byte b = hex2byte('FF');\n" + "byte i = bitOr(a,b);\n" + "return 0;}", "test_bitwise_or_expect_error"); fail(); } catch (Exception e) { // do nothing } doCompileExpectError("function integer transform(){long i = bitOr(null, null); return 0;}","test_bitwise_or_expect_error", Arrays.asList("Function 'bitOr' is ambiguous")); } 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); checkArray("resultByte1", new byte[] {0x00, 0x00, 0x01}); checkArray("resultByte2", new byte[] {0x00, 0x01, (byte) 0xF1}); checkArray("resultByte3", new byte[] {0x00, 0x70, 0x71}); checkArray("resultByte4", new byte[] {0x00, (byte) 0xF1, (byte) 0xF1}); checkArray("resultByteDifferentLength", new byte[] {(byte) 0xF0, 0x00, 0x70}); } 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 } try { doCompile("function integer transform(){\n" + "byte a = hex2byte('FF'); byte b = null;\n" + "byte i = bitAnd(a,b);\n" + "return 0;}", "test_bitwise_and_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){\n" + "byte a = null; byte b = hex2byte('FF');\n" + "byte i = bitAnd(a,b);\n" + "return 0;}", "test_bitwise_and_expect_error"); fail(); } catch (Exception e) { // do nothing } doCompileExpectError("function integer transform(){long i = bitAnd(null, null); return 0;}","test_bitwise_and_expect_error", Arrays.asList("Function 'bitAnd' is ambiguous")); } 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); checkArray("resultByte1", new byte[] {0x01, (byte) 0xF1, (byte) 0xFE}); checkArray("resultByte2", new byte[] {(byte) 0xF1, (byte) 0xF0, (byte) 0x0E}); checkArray("resultByte3", new byte[] {0x71, 0x03, (byte) 0x8E}); checkArray("resultByte4", new byte[] {(byte) 0xF1, 0x02, (byte) 0x0E}); checkArray("resultByteDifferentLength", new byte[] {0x0F, (byte) 0xF0, (byte) 0x87}); } 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 } try { doCompile("function integer transform(){\n" + "byte a = hex2byte('FF'); byte b = null;\n" + "byte i = bitXor(a,b);\n" + "return 0;}", "test_bitwise_xor_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){\n" + "byte a = null; byte b = hex2byte('FF');\n" + "byte i = bitXor(a,b);\n" + "return 0;}", "test_bitwise_xor_expect_error"); fail(); } catch (Exception e) { // do nothing } doCompileExpectError("function integer transform(){long i = bitXor(null, null); return 0;}","test_bitwise_xor_expect_error", Arrays.asList("Function 'bitXor' is ambiguous")); } 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); check("test_mixed1", 176l); check("test_mixed2", 616l); } 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", 30l); check("test_mix2", 39l); } 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); checkArray("resultByte", new byte[] {0b00110101, 0b01101100}); byte[] testZeroByte = new byte[4]; Arrays.fill(testZeroByte, (byte) 0xFF); checkArray("testZeroByte", testZeroByte); } 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 } try { doCompile("function integer transform(){byte input = null; byte i = bitNegate(input); return 0;}","test_bitwise_negate_expect_error"); fail(); } catch (Exception e) { // do nothing } doCompileExpectError("function integer transform(){long i = bitNegate(null); return 0;}","test_bitwise_negate_expect_error", Arrays.asList("Function 'bitNegate' is ambiguous")); } 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(new BigDecimal(3.0), new BigDecimal(-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; decimal 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(new BigDecimal("2"), new BigDecimal("-4"))); } 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; decimal 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(new BigDecimal("8"), new BigDecimal("8"), new BigDecimal("8"), new BigDecimal("8"))); check("longResult", Arrays.asList(new BigDecimal("8"), new BigDecimal("8"), new BigDecimal("8"), new BigDecimal("8"))); check("doubleResult", Arrays.asList(new BigDecimal("8"), new BigDecimal("8"), new BigDecimal("8"), new BigDecimal("8"))); check("decimalResult", Arrays.asList(new BigDecimal("8.000"), new BigDecimal("8.000"), new BigDecimal("8.000"), new BigDecimal("8.000"))); } 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; decimal 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; decimal n = pow(var1, var2); return 0;}","test_mathlib_pow_expect_error"); fail(); } catch (Exception e) { // do nothing } } private void compareDecimals(String variableName, BigDecimal expected) { BigDecimal actual = (BigDecimal) getVariable(variableName); compareDecimals(expected, actual); } private void compareDecimals(BigDecimal expected, BigDecimal actual) { assertTrue("Expected: " + expected + ", actual: " + actual, expected.compareTo(actual) == 0); } /* * The equals() method also takes the scale into account, * CTL uses compareTo() instead. */ private void compareDecimals(List<BigDecimal> expected, List<BigDecimal> actual) { assertEquals(expected.size(), actual.size()); for (int i = 0; i < actual.size(); i++) { compareDecimals(expected.get(i), actual.get(i)); } } @SuppressWarnings("unchecked") 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, 3l, 4l)); //CLO-1835 check("decimalResult", Arrays.asList(new BigDecimal("2"), new BigDecimal("3"), new BigDecimal("4"))); // negative precision means the number of places after the decimal point // positive precision before the decimal point List<BigDecimal> expected = Arrays.asList( new BigDecimal("0"), new BigDecimal("1000000"), new BigDecimal("1200000"), new BigDecimal("1230000"), new BigDecimal("1235000"), // rounded up new BigDecimal("1234600"), // rounded up new BigDecimal("1234570"), // rounded up new BigDecimal("1234567"), new BigDecimal("1234567.1"), new BigDecimal("1234567.12"), new BigDecimal("1234567.123"), new BigDecimal("1234567.1235"), // rounded up new BigDecimal("1234567.12346"), // rounded up new BigDecimal("1234567.123457"), // rounded up new BigDecimal("1234567.1234567") ); //CLO-1835 compareDecimals(expected, (List<BigDecimal>) getVariable("decimal2Result")); //CLO-1832 check("intWithPrecisionResult", 1000); check("longWithPrecisionResult", 123456l); check("ret1", 1200); check("ret2", 10000l); List<Double> expectedDouble = Arrays.asList(0.0d, 1000000.0d, 1200000.0d, 1230000.0d, 1235000.0d, 1234600.0d, 1234570.0d, 1234567.0d, 1234567.1d, 1234567.12d, 1234567.123d, 1234567.1235d, 1234567.12346d, 1234567.123457d, 1234567.1234567d ); check("double2Result", expectedDouble); check("documentationExample1", 100); check("documentationExample2", 123); check("documentationExample3", 123.12d); // CLO-2346 compareDecimals("hundredsDecimalUp", new BigDecimal("300")); check("hundredsLongUp", 300L); check("hundredsIntegerUp", 300); compareDecimals("hundredsDecimalNegativeUp", new BigDecimal("-300")); check("hundredsLongNegativeUp", -300L); check("hundredsIntegerNegativeUp", -300); compareDecimals("hundredsDecimalDown", new BigDecimal("200")); check("hundredsLongDown", 200L); check("hundredsIntegerDown", 200); compareDecimals("hundredsDecimalNegativeDown", new BigDecimal("-200")); check("hundredsLongNegativeDown", -200L); check("hundredsIntegerNegativeDown", -200); // no overflow should occur check("minInt", -2000000000); check("maxInt", 2000000000); check("minLong", -9000000000000000000L); check("maxLong", 9000000000000000000L); check("zeroPrecisionInteger", Integer.MIN_VALUE); check("zeroPrecisionLong", Long.MIN_VALUE); } 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; decimal l = round(input);return 0;}","test_mathlib_round_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){number input = null; number l = round(input, 2);return 0;}","test_mathlib_round_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){decimal input = null; decimal l = round(input, 9); return 0;}","test_mathlib_round_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer input = null; integer l = round(input, 9); return 0;}","test_mathlib_round_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long input = null; long l = round(input, 9); return 0;}","test_mathlib_round_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long input = null; long l = round(input); return 0;}","test_mathlib_round_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer input = null; long l = round(input); return 0;}","test_mathlib_round_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer input = 7012; integer l = round(input, null); return 0;}","test_mathlib_round_expect_error"); fail(); } catch (Exception e) { // do nothing } } @SuppressWarnings("unchecked") public void test_mathlib_roundHalfToEven() { doCompile("test_mathlib_roundHalfToEven"); check("round1", new BigDecimal(-4)); check("intResult", Arrays.asList(new BigDecimal(2), new BigDecimal(3))); check("longResult", Arrays.asList(new BigDecimal(2), new BigDecimal(3))); check("doubleResult", Arrays.asList(new BigDecimal(2), new BigDecimal(2), new BigDecimal(4))); //CLO-1835 check("decimalResult", Arrays.asList(new BigDecimal(2), new BigDecimal(2), new BigDecimal(4), new BigDecimal(4), new BigDecimal(5))); // negative precision means the number of places after the decimal point // positive precision before the decimal point List<BigDecimal> expected = Arrays.asList( new BigDecimal("0"), new BigDecimal("1000000"), new BigDecimal("1200000"), new BigDecimal("1230000"), new BigDecimal("1235000"), // rounded up new BigDecimal("1234600"), // rounded up new BigDecimal("1234570"), // rounded up new BigDecimal("1234567"), new BigDecimal("1234567.1"), new BigDecimal("1234567.12"), new BigDecimal("1234567.123"), new BigDecimal("1234567.1235"), // rounded up new BigDecimal("1234567.12346"), // rounded up new BigDecimal("1234567.123457"), // rounded up new BigDecimal("1234567.1234567") ); //CLO-1835 compareDecimals(expected, (List<BigDecimal>) getVariable("decimal2Result")); //CLO-1832 compareDecimals("intWithPrecisionResult", new BigDecimal(1000)); compareDecimals("longWithPrecisionResult", new BigDecimal(123456)); compareDecimals("ret1", new BigDecimal(1200)); compareDecimals("ret2", new BigDecimal(10000)); compareDecimals(expected, (List<BigDecimal>) getVariable("double2Result")); expected = Arrays.asList( new BigDecimal("44.44"), new BigDecimal("55.56"), new BigDecimal("66.66"), new BigDecimal("44.444"), new BigDecimal("55.556"), new BigDecimal("66.666"), new BigDecimal("444000"), new BigDecimal("556000"), new BigDecimal("666000"), new BigDecimal("4444"), new BigDecimal("5556"), new BigDecimal("6666") ); compareDecimals(expected, (List<BigDecimal>) getVariable("decimal3result")); } public void test_mathlib_roundHalfToEven_expect_error(){ try { doCompile("function integer transform(){decimal d = roundHalfToEven(null);return 0;}","test_mathlib_roundHalfToEven_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){decimal input = null;decimal d = roundHalfToEven(input);return 0;}","test_mathlib_roundHalfToEven_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer precision = null; decimal d = roundHalfToEven(1D, precision);return 0;}","test_mathlib_roundHalfToEven_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){decimal d = roundHalfToEven(1D, null);return 0;}","test_mathlib_roundHalfToEven_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_mathlib_setRandomSeed_expect_error(){ try { doCompile("function integer transform(){long l = null; setRandomSeed(l); return 0;}","test_mathlib_setRandomSeed_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer i = null; setRandomSeed(i); return 0;}","test_mathlib_setRandomSeed_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_mathlib_max() throws UnsupportedEncodingException{ doCompile("test_mathlib_max"); check("retInt", Arrays.asList(7,545,15,11,67,-43)); check("retIntNull", Arrays.asList(4,-4, null, null, 12, 54, 11, 11)); check("retLong", Arrays.asList(23L, 58L, 45l, 75L, 89L, -11L)); check("retLongNull", Arrays.asList(40L, 89L, null, null, 44L, 56L, 89L, 78l, 89L, 78L, 23L)); check("retDec", Arrays.asList(new BigDecimal("56.3"), new BigDecimal("87.3"), new BigDecimal("65.1"), new BigDecimal("56.3"), new BigDecimal("65.1"), new BigDecimal("-11.1"))); check("retDecNull", Arrays.asList(new BigDecimal("65.9"), new BigDecimal("-12.6"), null, null, new BigDecimal("32.4"), new BigDecimal("21.5"), new BigDecimal("11.3"), new BigDecimal("56.3"), new BigDecimal("78.1"), new BigDecimal("45.3"), new BigDecimal("87.9"), new BigDecimal("12.3"), new BigDecimal("13.4"), new BigDecimal("78"), new BigDecimal("59.6"), new BigDecimal("78.6"), new BigDecimal("12.3"), new BigDecimal("58.6"), new BigDecimal("48.6"), new BigDecimal("65.1"))); check("retNum", Arrays.asList(54.89d, 0d, 89.7d, 89.7d, 23.6d, -12.5)); check("retNumNull", Arrays.asList(56.4d, 98.3d, null, null, 56.9d, 45.7d, -78.6d, -11.2d, 78d, 45.6d, 89.6d, 56.9d, 123.3d, 45.9d, 48.5d, 67.8d)); check("retString", Arrays.asList("Kennen", "Zac")); check("retStringNull", Arrays.asList("Warwick", "Quinn", null)); check("retBool", Arrays.asList(true, true)); check("retBoolNull", Arrays.asList(true, true, null)); Calendar cal = Calendar.getInstance(); cal.set(2013, 1, 24, 0, 0, 0); cal.set(Calendar.MILLISECOND, 0); check("retDate", Arrays.asList(cal.getTime(), cal.getTime())); check("retDateNull", Arrays.asList(cal.getTime(), cal.getTime(), null)); } public void test_mathlib_max_expect_error(){ try { doCompile("function integer transform(){long[] my_list = null; max(my_list); return 0;}","test_mathlib_max_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long[] my_list; max(my_list); return 0;}","test_mathlib_max_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){byte[] my_list = [str2byte('Lux', 'utf-8'), str2byte('Tresh', 'utf-8')]; max(my_list); return 0;}","test_mathlib_max_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_mathlib_min(){ doCompile("test_mathlib_min"); check("retInt", Arrays.asList(-5, 14, 17, 15, -9, -48)); check("retIntNull", Arrays.asList(-3, -9, null, 19, 12, null, 15, 56)); check("retLong", Arrays.asList(-76l, 12l, 156l, -6l, 76l, -6l)); check("retLongNull", Arrays.asList(-30L, 12L, null, 13L, 12L, null, 89L, -4L, 12L, -9l, -5L, -89L)); check("retNum", Arrays.asList(0.99d, -90.1d, 56.9d, 56.9d, 45.1d, -1.11d)); check("retNumNull", Arrays.asList(11.3d, -11.1d, null, null, null, 12.3d, 11.2d, 11.6d, 12.6d, 12.3d, 17d, 12.6d, 12d, null, 12.3d, -23.6d, 36.9d, 23d, null)); check("retDec", Arrays.asList(new BigDecimal("-7.8"), new BigDecimal("-1.11"), new BigDecimal("56.7"), new BigDecimal("32.1"), new BigDecimal("56.7"), new BigDecimal("-12.4"))); check("retDecNull", Arrays.asList(new BigDecimal("34.2"), new BigDecimal("-1.6"), null, null, null, new BigDecimal("12.3"), new BigDecimal("11.2"), new BigDecimal("1.11"), new BigDecimal("-13.5"), new BigDecimal("2.11"), new BigDecimal("-23.9"), new BigDecimal("89.7"), new BigDecimal("16"), null, new BigDecimal("23.6"), new BigDecimal("78.9"), new BigDecimal("45.3"), new BigDecimal("458"), null, new BigDecimal("36.9"), new BigDecimal("-89.6"), new BigDecimal("78.9"), new BigDecimal("0"), null)); check("retStr", Arrays.asList("Jax", "Sivir")); check("retStrNull", Arrays.asList("Lulu", "Fizz", null, null)); check("retBool", Arrays.asList(false, false)); check("retBoolNull", Arrays.asList(false, false, null)); Calendar cal = Calendar.getInstance(); cal.set(2003, 10, 17, 0, 0, 0); cal.set(Calendar.MILLISECOND, 0); check("retDate", Arrays.asList(cal.getTime(), cal.getTime())); check("retDateNull", Arrays.asList(cal.getTime(), cal.getTime(), null)); } public void test_mathlib_min_expect_error(){ try { doCompile("function integer transform(){integer[] myList = null; min(myList); return 0;}","test_mathlib_min_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer[] myList; min(myList); return 0;}","test_mathlib_min_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){min([str2byte('Renektor', 'utf-8'), str2byte('Kayle', 'utf-16')]); return 0;}","test_mathlib_min_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_mathlib_cos(){ doCompile("test_mathlib_cos"); check("ret", Arrays.asList(Math.cos(12.6d), Math.cos(0d), Math.cos(-1456.8d), Math.cos(1.6d), Math.cos(12.6d), Math.cos(-19.3d), Math.cos(12d), Math.cos(23d), Math.cos(0d), Math.cos(0d))); } public void test_mathlib_cos_expect_error(){ try { doCompile("function integer transform(){double input = null; double d = cos(input); return 0;}","test_mathlib_cos_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){decimal input = null; double d = cos(input); return 0;}","test_mathlib_cos_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_mathlib_sin(){ doCompile("test_mathlib_sin"); check("ret", Arrays.asList(Math.sin(1d), Math.sin(25.9d), Math.sin(256d), Math.sin(123d), Math.sin(0d), Math.sin(0d))); } public void test_mathlib_sin_expect_error(){ try { doCompile("function integer transform(){double input = null; double d = sin(input); return 0;}","test_mathlib_sin_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){decimal input = null; double d = sin(input); return 0;}","test_mathlib_sin_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_mathlib_tan(){ doCompile("test_mathlib_tan"); check("ret", Arrays.asList(Math.tan(Math.PI/2), Math.tan(2*Math.PI), Math.tan(Math.PI), Math.tan(0d), Math.tan(12.44d), Math.tan(78d), Math.tan(725d), Math.tan(0d), Math.tan(0d))); } public void test_mathlib_tan_expect_error(){ try { doCompile("function integer transform(){double input = null; double dd = tan(input); return 0;}","test_mathlib_tan_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){decimal input = null; double dd = tan(input); return 0;}","test_mathlib_tan_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_mathlib_acos(){ doCompile("test_mathlib_acos"); check("ret", Arrays.asList(Math.acos(Math.PI), Math.acos(Math.PI*2), Math.acos(Math.PI/2), Math.acos(180), Math.acos(90), Math.acos(0), Math.acos(123))); } public void test_mathlib_acos_expect_error(){ try { doCompile("function integer transform(){double input = null; acos(input);return 0;}"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){decimal input = null; acos(input);return 0;}"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long input = null; acos(input);return 0;}"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer input = null; acos(input);return 0;}"); fail(); } catch (Exception e) { // do nothing } } public void test_mathlib_asin(){ doCompile("test_mathlib_asin"); check("ret", Arrays.asList(Math.asin(Math.PI), Math.asin(Math.PI*2), Math.asin(Math.PI/2), Math.asin(1236), Math.asin(0))); } public void test_mathlib_asin_expect_error(){ try { doCompile("function integer transform(){number input = null; asin(input); return 0;}","test_mathlib_asin_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){decimal input = null; asin(input); return 0;}","test_mathlib_asin_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long input = null; asin(input); return 0;}","test_mathlib_asin_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer input = null; asin(input); return 0;}","test_mathlib_asin_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_mathlib_atan(){ doCompile("test_mathlib_atan"); check("ret", Arrays.asList(Math.atan(Math.PI), Math.atan(Math.PI*2), Math.atan(Math.PI/2), Math.atan(45), Math.atan(0))); } public void test_mathlib_atan_expect_error(){ try { doCompile("function integer transform(){number input = null; atan(input); return 0;}","test_mathlib_atan_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){decimal input = null; atan(input); return 0;}","test_mathlib_atan_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long input = null; atan(input); return 0;}","test_mathlib_atan_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer input = null; atan(input); return 0;}","test_mathlib_atan_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")); Calendar cal = Calendar.getInstance(); cal.set(1997,10,12,0,0,0); cal.set(Calendar.MILLISECOND,0); check("ret3", cal.getTime()); cal.clear(); cal.set(1970,0,1,1,0,12); cal.set(Calendar.MILLISECOND, 0); check("ret4", cal.getTime()); } 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"))); check("nullLiteralOutput", null); check("nullVariableOutput", null); } public void test_convertlib_bits2str() { doCompile("test_convertlib_bits2str"); check("bitsAsString1", "00000000"); check("bitsAsString2", "11111111"); check("bitsAsString3", "010100000100110110100000"); check("nullLiteralOutput", null); check("nullVariableOutput", null); } 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); check("nullLiteralOutput", null); check("nullVariableOutput", null); check("nullLiteralOutputWrapped", null); check("nullVariableOutputWrapped", null); check("nullLiteralOutputNowrap", null); check("nullVariableOutputNowrap", null); } public void test_convertlib_byte2base64_expect_error(){ 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); check("week1", 6); check("week2", 7); } 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})); check("nullLiteralOutput", null); check("nullVariableOutput", null); } 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)); check("nullLiteralOutput", null); check("nullVariableOutput", null); } 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[] {})); check("nullLiteralOutput", null); check("nullVariableOutput", null); } public void test_convertlib_str2bits_expect_error() { try { doCompile("function integer transform(){byte b = str2bits('abcd'); 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); // CLO-6306: cal.clear(); cal.setTimeZone(TimeZone.getTimeZone("GMT+8")); cal.set(2015, 04, 04, 11, 04, 13); check("CLO_6306_1", cal.getTime()); check("CLO_6306_3", cal.getTime()); cal.clear(); cal.setTimeZone(TimeZone.getTimeZone("GMT+5")); cal.set(2015, 04, 04, 11, 04, 13); check("CLO_6306_2", cal.getTime()); check("CLO_6306_4", cal.getTime()); // CLO-5961: cal.clear(); cal.setTimeZone(TimeZone.getDefault()); cal.set(2015, 4, 25, 0, 0, 0); check("CLO_5961_1", cal.getTime()); check("CLO_5961_2", cal.getTime()); cal.set(2015, 10, 25); check("CLO_5961_3", cal.getTime()); check("CLO_5961_4", cal.getTime()); } 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, false); 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, false); return 0;}","test_convertlib_str2date_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){date d = str2date('1924011', 'yyyyMMdd', true); return 0;}","test_convertlib_str2date_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){date d = str2date('2015-001-012', 'yyyy-MM-dd', true); return 0;}","test_convertlib_str2date_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){date d = str2date('2015-1-12', 'yyyy-MM-dd', true); return 0;}","test_convertlib_str2date_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){date d = str2date('2015-November-12', 'yyyy-MMM-dd', 'en.US', true); return 0;}","test_convertlib_str2date_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){date d = str2date('2015-Nov-12', 'yyyy-MMMM-dd', 'en.US', true); return 0;}","test_convertlib_str2date_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){date d = str2date('2015-Nov-12', 'yyyy-MM-dd', 'en.US', true); return 0;}","test_convertlib_str2date_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){date d = str2date('2015-November-12', 'yyyy-MM-dd', 'en.US', true); 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("booleanString", "true"); 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 }); check("nullLiteralOutput", null); check("nullVariableOutput", null); } public void test_convertlib_str2byte_expect_error(){ 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); check("nullLiteralOutput", null); check("nullVariableOutput", null); } public void test_convertlib_byte2str_expect_error(){ 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_conditional_fail_CLO_4566() { doCompile("test_conditional_fail_CLO-4566"); } 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_read_CLO6850() { String testIdentifier = "test_dictionary_read_CLO6850"; 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)) }; Dictionary dictionary = graph.getDictionary(); CloverString cs = new CloverString("hello"); Decimal d = new IntegerDecimal(10, 2); d.setValue(123); try { dictionary.setValue("stringEntry", "string", cs); dictionary.setValue("stringListEntry", "list", new ArrayList<>(Arrays.asList(cs))); dictionary.setContentType("stringListEntry", "string"); Map<String, Object> map = new HashMap<>(); map.put("key", cs); dictionary.setValue("stringMapEntry", "map", map); dictionary.setContentType("stringMapEntry", "string"); dictionary.setValue("decimalEntry", "decimal", d); dictionary.setValue("decimalListEntry", "list", new ArrayList<>(Arrays.asList(d))); dictionary.setContentType("decimalListEntry", "decimal"); map = new HashMap<>(); map.put("key", d); dictionary.setValue("decimalMapEntry", "map", map); dictionary.setContentType("decimalMapEntry", "decimal"); dictionary.setValue("stringListEntry2", "list", new ArrayList<>(Arrays.asList(cs))); dictionary.setContentType("stringListEntry2", "string"); dictionary.setValue("stringListEntry3", "list", new ArrayList<>(Arrays.asList(cs))); dictionary.setContentType("stringListEntry3", "string"); map = new HashMap<>(); map.put("key", cs); dictionary.setValue("stringMapEntry2", "map", map); dictionary.setContentType("stringMapEntry2", "string"); map = new HashMap<>(); map.put("key", cs); dictionary.setValue("stringMapEntry3", "map", map); dictionary.setContentType("stringMapEntry3", "string"); } catch (ComponentNotReadyException e) { throw new RuntimeException("Error init default dictionary", e); } String sourceCode = loadSourceCode(testIdentifier); doCompile(sourceCode, testIdentifier, graph, inRecords, outRecords); Boolean[] expected = new Boolean[14]; Arrays.fill(expected, true); check("results", Arrays.asList(expected)); // implementation detail, may change in the future assertTrue(((List<?>) dictionary.getValue("stringListEntry3")).get(0) == cs); assertTrue(((Map<?, ?>) dictionary.getValue("stringMapEntry3")).get("key") == cs); } public void test_dictionary_expect_error() throws Exception { // CLO-2283 TransformationGraph graph = createEmptyGraph(); graph.getDictionary().setValue("listEntry", "list", new ArrayList<String>()); graph.getDictionary().setContentType("listEntry", "object"); graph.getDictionary().setValue("mapEntry", "map", new HashMap<String, String>()); graph.getDictionary().setContentType("mapEntry", "object"); doCompileExpectError(graph, "function integer transform(){append(dictionary.listEntry, \"newValue\"); return 0;}", "test_dictionary_expect_error", Arrays.asList("Dictionary entry 'listEntry' has invalid content type: 'object'")); doCompileExpectError(graph, "function integer transform(){containsKey(dictionary.mapEntry, \"myKey\"); return 0;}", "test_dictionary_expect_error", Arrays.asList("Dictionary entry 'mapEntry' has invalid content type: 'object'")); } 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_dictionary_keywords_CLO6866() { String ident = "test_dictionary_keywords_CLO6866"; TransformationGraph g = createEmptyGraph(); try { g.getDictionary().setValue("year", "integer", 10); g.getDictionary().setValue("month", "integer", 10); g.getDictionary().setValue("week", "integer", 10); g.getDictionary().setValue("day", "integer", 10); g.getDictionary().setValue("hour", "integer", 10); g.getDictionary().setValue("minute", "integer", 10); g.getDictionary().setValue("second", "integer", 10); g.getDictionary().setValue("millisec", "integer", 10); } catch (ComponentNotReadyException e) { throw new RuntimeException(e); } doCompile(loadSourceCode("test_dictionary_keywords_CLO6866"), ident, g, new DataRecord[0], new DataRecord[0]); } 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_utillib_byteAt() { doCompile("test_utillib_byteAt"); check("ret0", 0x00); check("ret1", 0xFF); check("ret2", 0xF0); check("ret3", 0x0F); check("ret4", 0x01); check("ret5", 0x00); } public void test_utillib_byteAt_expect_error() { try { doCompile("function integer transform(){byte b = hex2byte('00'); b.byteAt(-1); return 0;}","test_utillib_byteAt_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){byte b = hex2byte('00'); b.byteAt(1); return 0;}","test_utillib_byteAt_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){byte b = hex2byte(''); b.byteAt(0); return 0;}","test_utillib_byteAt_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){byte b = null; b.byteAt(0); return 0;}","test_utillib_byteAt_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){byteAt(null, 0); return 0;}","test_utillib_byteAt_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){byte b = hex2byte('00'); integer i = null; b.byteAt(i); return 0;}","test_utillib_byteAt_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){byte b = hex2byte('00'); b.byteAt(null); return 0;}","test_utillib_byteAt_expect_error"); fail(); } catch (Exception e) { // do nothing } } 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_randomString_expect_error(){ try { doCompile("function integer transform(){randomString(-5, 1); return 0;}","test_stringlib_randomString_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){randomString(15, 2); return 0;}","test_stringlib_randomString_expect_error"); fail(); } catch (Exception e) { // do nothing } } 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); check("ret1", null); // CLO-1700 // check("ret2", null); // check("ret3", null); } public void test_utillib_getComponentProperty() { final String expected = "expectedValue"; this.node = new Node("TEST", graph) { @Override protected Result execute() throws Exception { // TODO Auto-generated method stub return null; } @Override public Properties getAttributes() { Properties attributes = new Properties(); attributes.put("transform", expected); return attributes; } }; doCompile("test_utillib_getComponentProperty"); check("transform", expected); } public void test_utillib_getComponentProperty_expect_error() { try { doCompile("test_utillib_getComponentProperty"); fail(); } catch (Exception ex) {} } 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); check("ret1", null); // CLO-1700 // check("ret2", null); // check("ret3", null); } 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); check("ret1", null); check("ret2", null); check("ret3", null); } 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); check("ret1", null); check("ret2", null); } public void test_utillib_getRawParamValues() { doCompile("test_utillib_getRawParamValues"); Map<String, String> params = new HashMap<String, String>(); params.put("PROJECT", "."); params.put("DATAIN_DIR", "${PROJECT}/data-in"); params.put("COUNT", "`1+2`"); params.put("NEWLINE", "\\n"); // special characters should NOT be resolved check("params", params); check("ret1", null); check("ret2", null); check("ret3", null); } public void test_utillib_getRawParamValue() { doCompile("test_utillib_getRawParamValue"); Map<String, String> params = new HashMap<String, String>(); params.put("PROJECT", "."); params.put("DATAIN_DIR", "${PROJECT}/data-in"); params.put("COUNT", "`1+2`"); params.put("NEWLINE", "\\n"); // special characters should NOT be resolved params.put("NONEXISTING", null); check("params", params); check("ret1", null); check("ret2", null); } public void test_stringlib_getUrlParts() { doCompile("test_stringlib_getUrlParts"); List<Boolean> isUrl = Arrays.asList(true, true, true, 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", "/share/dir/file.txt", "/dir/file.txt", "/bucketname/dir/file.txt", null); List<String> protocol = Arrays.asList("sftp", "sandbox", "ftp", "https", "smb", "hdfs", "s3", null); List<String> host = Arrays.asList( "ava-fileManipulator1-devel.getgooddata.com", "cloveretl.test.scenarios", "ftp.test.com", "www.test.com", "hostname", "HADOOP0", "s3.amazonaws.com", null); List<Integer> port = Arrays.asList(-1, -1, 21, 80, 445, -1, -1, -2); List<String> userInfo = Arrays.asList( "user%40gooddata.com:password", "", "test:test", "test:test", "user:password", "", "ACCESSKEY:secretkey", 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_stringlib_getPathParts() { doCompile("test_stringlib_getPathParts"); { List<String> expected = Arrays.asList( null, "", "txt", "xlsx", "dat", "cdf", "xml", "jpg", "", "", "dbf", "", "gz", "Z", "", "", "txt" ); List<?> extensions = (List<?>) getVariable("extensions"); assertEquals(expected.size(), extensions.size()); for (int i = 0; i < expected.size(); i++) { assertEquals(String.valueOf(i), expected.get(i), extensions.get(i)); } } { List<String> expected = Arrays.asList( null, "", "out5.txt", "input.xlsx", "file.dat", "c.cdf", "c.xml", "c.ab.jpg", "", "", "c.dbf", "b", "c.gz", "c.Z", "b", "", "file_with_query?and#hash.txt" ); List<?> filenames = (List<?>) getVariable("filenames"); assertEquals(expected.size(), filenames.size()); for (int i = 0; i < expected.size(); i++) { assertEquals(String.valueOf(i), expected.get(i), filenames.get(i)); } } { List<String> expected = Arrays.asList( null, "", "out5", "input", "file", "c", "c", "c.ab", "", "", "c", "b", "c", "c", "b", "", "file_with_query?and#hash" ); List<?> filenamesWithoutExtension = (List<?>) getVariable("filenamesWithoutExtension"); assertEquals(expected.size(), filenamesWithoutExtension.size()); for (int i = 0; i < expected.size(); i++) { assertEquals(String.valueOf(i), expected.get(i), filenamesWithoutExtension.get(i)); } } { List<String> expected = Arrays.asList( null, "", "/foo/../bar/../baz/", "/cloveretl.test.scenarios/./data-in/fileOperation/", "/data/", "C:/a/b/", "C:/a/b/", "a/b/", "file:/C:/Users/krivanekm/workspace/Experiments/", "sandbox://cloveretl.test.scenarios/", "sandbox://cloveretl.test.scenarios/a/b/", "ftp://user:password@hostname.com/a/", "ftp://user:password@hostname.com/a/../b/", "s3://user:password@hostname.com/a/b/", "sftp://user:password@hostname.com/../a/", "sandbox://cloveretl.test.scenarios", "sandbox://cloveretl.test.scenarios/" ); List<?> filepaths = (List<?>) getVariable("filepaths"); assertEquals(expected.size(), filepaths.size()); for (int i = 0; i < expected.size(); i++) { assertEquals(String.valueOf(i), expected.get(i), filepaths.get(i)); } } { List<String> expected = Arrays.asList( null, "", "/baz/out5.txt", "/cloveretl.test.scenarios/data-in/fileOperation/input.xlsx", "/data/file.dat", "C:/a/b/c.cdf", "C:/a/b/c.xml", "a/b/c.ab.jpg", "file:/C:/Users/krivanekm/workspace/Experiments/", "sandbox://cloveretl.test.scenarios/", "sandbox://cloveretl.test.scenarios/a/b/c.dbf", "ftp://user:password@hostname.com/a/b", "ftp://user:password@hostname.com/b/c.gz", "s3://user:password@hostname.com/a/b/c.Z", null, "sandbox://cloveretl.test.scenarios", "sandbox://cloveretl.test.scenarios/file_with_query?and#hash.txt" ); List<?> normalized = (List<?>) getVariable("normalized"); assertEquals(expected.size(), normalized.size()); for (int i = 0; i < expected.size(); i++) { assertEquals(String.valueOf(i), expected.get(i), normalized.get(i)); } } } 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 } //CLO-1701 try { doCompile("function integer transform(){string str = iif(null, '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); check("ret17", "Shaco"); check("ret18", 12); check("ret19", 18.1d); check("ret20", 15L); check("ret21", new BigDecimal("18.1")); } public void test_utillib_toAbsolutePath(){ doCompile("test_utillib_toAbsolutePath"); assertNotNull(getVariable("ret1")); assertNotNull(getVariable("ret2")); check("ret3", null); } public void test_utillib_toAbsolutePath_expect_error(){ try { doCompile("function integer transform(){string str = toAbsolutePath(null); return 0;}","test_utillib_toAbsolutePath_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string s = null; string str = toAbsolutePath(s); return 0;}","test_utillib_toAbsolutePath_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_stringlib_toProjectUrl() throws IOException { doCompile("test_stringlib_toProjectUrl"); String result; result = (String) getVariable("ret1"); assertTrue(result.startsWith("file:") || result.startsWith("sandbox:")); result = (String) getVariable("ret2"); assertTrue(result.startsWith("file:") || result.startsWith("sandbox:")); check("ret3", "ftp://kennen_ftp/home"); check("ret4", null); check("ret5", "file:/home/user/workspace/myproject"); check("ret6", "sandbox://mysandbox/user/workspace/myproject"); } public void test_stringlib_toProjectUrl_expect_error(){ try { doCompile("function integer transform(){string str = toProjectUrl('https://user@gooddata.com:password@secure-di.gooddata.com/'); return 0;}","test_stringlib_toProjectUrl_expect_error"); fail(); } catch (Exception e) { // do nothing } } /** * @see PropertiesUtilsTest#testDeserialize() */ @SuppressWarnings("serial") public void test_stringlib_parseProperties() { doCompile("test_stringlib_parseProperties"); Map<String, String> expected = new HashMap<String, String>(); expected.put("xxx", "1"); expected.put("kkk", "2"); expected.put("aaa", "3"); expected.put("bbb", "4"); Map<?, ?> actual = (Map<?, ?>) getVariable("ret1"); List<?> keys = new ArrayList<>(actual.keySet()); assertEquals(Arrays.asList("xxx", "kkk", "aaa", "bbb"), keys); // check order check("ret1", expected); expected = new HashMap<String, String>(); check("ret2", expected); // empty string check("ret3", expected); // blank string check("ret4", expected); // null string check("ret5", new HashMap<String, String>() {{ put("include", "aaa"); }}); // include not ignored } }
package com.stanfy.app; import java.lang.ref.WeakReference; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.view.KeyEvent; import android.view.Menu; import android.view.MenuItem; import com.stanfy.DebugFlags; import com.stanfy.serverapi.request.RequestExecutor; import com.stanfy.stats.StatsManager; import com.stanfy.utils.ApiMethodsSupport; import com.stanfy.utils.AppUtils; import com.stanfy.utils.LocationMethodsSupport; public class BaseActivityBehavior implements RequestExecutorProvider { /** Logging tag. */ private static final String TAG = "ActibityBehavior"; /** Debug flag. */ private static final boolean DEBUG = DebugFlags.DEBUG_GUI; /** Activity reference. */ private final WeakReference<Activity> activityRef; /** Action bar support. */ private ActionBarSupport actionBarSupport; /** Server API support. */ private ApiMethodsSupport serverApiSupport; /** Location support. */ private LocationMethodsSupport locationSupport; /** Flag that indicates an attempt to bind API. */ private boolean apiBindAttemptDone = false, locationBindAttemptDone = false; /** First start flag. */ private boolean firstStart = true; /** Stats manager. */ private final StatsManager statsManager; public BaseActivityBehavior(final Activity activity) { activityRef = new WeakReference<Activity>(activity); statsManager = ((Application)activity.getApplication()).getStatsManager(); } /** * @return action bar support */ private ActionBarSupport createActionBarSupport() { final Activity a = activityRef.get(); final Application app = (Application)a.getApplication(); return app.createActionBarSupport(); } /** * @return activity instance, can be null */ protected final Activity getActivity() { return activityRef.get(); } /** * @see Activity#onContentChanged() */ public void onContentChanged() { if (actionBarSupport != null) { actionBarSupport.destroy(); } actionBarSupport = createActionBarSupport(); actionBarSupport.doInitialize(activityRef.get()); } /** * @see Activity#onCreate(Bundle) * @param savedInstanceState saved state bundle * @param serverApiSupport server API support */ public void onCreate(final Bundle savedInstanceState, final ApiMethodsSupport serverApiSupport) { if (DEBUG) { Log.v(TAG, "create " + activityRef.get()); } if (serverApiSupport != null) { if (DEBUG) { Log.i(TAG, "has api support"); } this.serverApiSupport = serverApiSupport; } } /** * @see Activity#onRestart() */ public void onRestart() { if (DEBUG) { Log.v(TAG, "restart " + activityRef.get()); } firstStart = false; } /** * @see Activity#onStart() */ public void onStart() { if (DEBUG) { Log.v(TAG, "start " + activityRef.get()); } // server API bindAPI(); // location bindLocation(); // statistics final Activity a = getActivity(); if (a == null) { return; } statsManager.onStartSession(a); if (firstStart) { statsManager.onStartScreen(a); } statsManager.onComeToScreen(a); } /** * @see Activity#onResume() */ public void onResume() { if (DEBUG) { Log.v(TAG, "resume " + activityRef.get()); } } /** * @see Activity#onSaveInstanceState(Bundle) * @param outState result bundle */ public void onSaveInstanceState(final Bundle outState) { } /** * @see Activity#onRestoreInstanceState(Bundle) * @param savedInstanceState saved state bundle */ public void onRestoreInstanceState(final Bundle savedInstanceState) { } /** * @see Activity#onPause() */ public void onPause() { if (DEBUG) { Log.v(TAG, "pause " + activityRef.get()); } ((Application)getActivity().getApplication()).dispatchCrucialGUIOperationFinish(); } /** * @see Activity#onStop() */ public void onStop() { if (DEBUG) { Log.v(TAG, "stop " + activityRef.get()); } // server API unbindAPI(); // location unbindLocation(); // statistics final Activity a = getActivity(); if (a == null) { return; } statsManager.onLeaveScreen(a); statsManager.onEndSession(a); } /** * @see Activity#onDestroy() */ public void onDestroy() { if (DEBUG) { Log.v(TAG, "destroy " + activityRef.get()); } if (actionBarSupport != null) { actionBarSupport.destroy(); } } /** @return the actionBarSupport */ public ActionBarSupport getActionBarSupport() { return actionBarSupport; } /** @return the locationSupport */ public LocationMethodsSupport getLocationSupport() { return locationSupport; } /** * @see Activity#onKeyDown(int, KeyEvent) */ boolean onKeyDown(final int keyCode, final KeyEvent event) { return false; } @Override public RequestExecutor getRequestExecutor() { return serverApiSupport; } protected void bindAPI() { if (serverApiSupport != null) { if (DEBUG) { Log.v(TAG, "bind to API methods"); } serverApiSupport.bind(); serverApiSupport.registerListener(); } apiBindAttemptDone = true; } protected void unbindAPI() { if (serverApiSupport != null) { serverApiSupport.removeListener(); serverApiSupport.unbind(); } apiBindAttemptDone = false; } protected void bindLocation() { if (locationSupport != null) { locationSupport.bind(); } locationBindAttemptDone = true; } protected void unbindLocation() { if (locationSupport != null) { locationSupport.unbind(); } locationBindAttemptDone = false; } /** * @param apiSupport API support instance */ public void forceAPIBinding(final ApiMethodsSupport apiSupport) { if (serverApiSupport == null) { this.serverApiSupport = apiSupport; if (apiBindAttemptDone) { bindAPI(); } } } /** * Setup location support. */ public void setupLocationSupport() { if (locationSupport == null) { locationSupport = new LocationMethodsSupport(getActivity()); if (locationBindAttemptDone) { bindLocation(); } } } public boolean ensureRoot() { final Activity a = activityRef.get(); if (!a.isTaskRoot() && AppUtils.isStartedFromLauncher(a)) { a.finish(); return false; } return true; } /** @return the serverApiSupport */ public ApiMethodsSupport getServerApiSupport() { return serverApiSupport; } /** * @see Activity#onOptionsItemSelected(MenuItem) * @return true if event was processed */ public boolean onOptionsItemSelected(final MenuItem item) { return false; } /** * @see Activity#onCreateOptionsMenu(Menu) * @return true if event was processed */ public boolean onCreateOptionsMenu(final Menu menu) { return false; } /** * @see Activity#onOptionsMenuClosed(Menu) */ public void onOptionsMenuClosed(final Menu menu) { // nothing } }
package snowballmadness; import com.google.common.base.*; import org.bukkit.*; import org.bukkit.block.*; import org.bukkit.entity.*; /** * This logic takes in a material to place and possibly a second material (for * placing in the air block just above the material) and a number specifying how * many blocks down the embedding is to go. If nothing is specified, we assume 1 * block. Higher numbers attempt to place that many blocks under the point of * impact. -1 means we go down to void. * * * @author christopherjohnson, somewhat */ public class BlockEmbedSnowballLogic extends SnowballLogic { private final Material toPlace; private final Material toCap; private final float embedDepth; public BlockEmbedSnowballLogic(Material toPlace, Material toCap, float embedDepth) { this.toPlace = Preconditions.checkNotNull(toPlace); this.toCap = Preconditions.checkNotNull(toCap); this.embedDepth = embedDepth; } /** * This method creates a logic for a material that you supply; we have many * special cases here! * * @param material The material being used with the snowball. * @return The new logic. */ public static BlockEmbedSnowballLogic fromMaterial(Material material) { switch (material) { case QUARTZ: return new BlockEmbedSnowballLogic(Material.OBSIDIAN, Material.PORTAL, 1); case COAL: return new BlockEmbedSnowballLogic(Material.COAL_BLOCK, Material.FIRE, 1); case COAL_BLOCK: return new BlockEmbedSnowballLogic(Material.COAL_ORE, Material.AIR, 256); case REDSTONE_BLOCK: return new BlockEmbedSnowballLogic(Material.COAL_BLOCK, Material.REDSTONE_BLOCK, 1) { @Override protected void placeCapBlock(Block block) { //if boosted, in this case we want to spawn a creeper //or perhaps just spawn the creeper and then hit him with the lightning block.getWorld().strikeLightning(block.getLocation()); } }; case NETHERRACK: return new BlockEmbedSnowballLogic(Material.NETHERRACK, Material.FIRE, 1); case LADDER: return new BlockEmbedSnowballLogic(material, material, 256) { @Override protected void placeShaftBlock(Block block) { if (!(block.getType().isSolid())) { if (block.getRelative(BlockFace.SOUTH).getType().isSolid()) { super.placeCapBlock(block); block.setData((byte) 2); } if (block.getRelative(BlockFace.NORTH).getType().isSolid()) { super.placeCapBlock(block); block.setData((byte) 3); } if (block.getRelative(BlockFace.EAST).getType().isSolid()) { super.placeCapBlock(block); block.setData((byte) 4); } if (block.getRelative(BlockFace.WEST).getType().isSolid()) { super.placeCapBlock(block); block.setData((byte) 5); } } } protected void placeCapBlock(Block block) { if (block.getRelative(BlockFace.SOUTH).getType().isSolid()) { super.placeCapBlock(block); block.setData((byte) 2); } if (block.getRelative(BlockFace.NORTH).getType().isSolid()) { super.placeCapBlock(block); block.setData((byte) 3); } if (block.getRelative(BlockFace.EAST).getType().isSolid()) { super.placeCapBlock(block); block.setData((byte) 4); } if (block.getRelative(BlockFace.WEST).getType().isSolid()) { super.placeCapBlock(block); block.setData((byte) 5); } //if none of the above, we haven't placed a block //worst case we repeatedly place it, which is probably fine // ladders need a special case to place them on the side of // the shaft! 2 = north, 3 = south, 4 = west, 5 = east. // There has to be a better way than this! } }; case DIAMOND_ORE: return new BlockEmbedSnowballLogic(Material.AIR, Material.AIR, 256) { @Override protected void placeShaftBlock(Block block) { if (block.getRelative(BlockFace.DOWN).getType() == Material.BEDROCK) { block.setType(Material.STATIONARY_WATER); } else { super.placeShaftBlock(block); } } }; case DIAMOND_BLOCK: return new BlockEmbedSnowballLogic(Material.AIR, Material.AIR, -1); default: return new BlockEmbedSnowballLogic(material, material, 1); } } @Override public void hit(Snowball snowball, SnowballInfo info) { super.hit(snowball, info); Location loc = snowball.getLocation().clone(); Block block = loc.getBlock(); if (block.getType() == Material.AIR && block.getY() > 1) { loc.setY(loc.getY() - 1); block = loc.getBlock(); } if (block.getType() != Material.AIR) { loc.setY(loc.getY() + 1); block = loc.getBlock(); } if (block.getType() == Material.AIR) { placeCapBlock(block);//we set the cap and prepare to step downward loc.setY(loc.getY() - 1); block = loc.getBlock(); } float decrement = embedDepth; while (!((loc.getY() < 0) || (decrement == 0) || (decrement > 0 && block.getType() == Material.BEDROCK))) { //bail if: loc.Y is less than zero OR embedDepth is exactly zero // OR (embedDepth > 0 and the block type is bedrock) placeShaftBlock(block); //just stepped down, it's above zero and either a replaceable block //or bedrock with embedDepth negative. place that sucker! decrement = decrement - 1; loc.setY(loc.getY() - 1); block = loc.getBlock(); //step down and go back to re-check the while } } /** * This method applies the cap block; you can override it do something * different though, like strike with lightning. * * @param block The block to be updated. */ protected void placeCapBlock(Block block) { block.setType(toCap); } /** * This method applies the shaft block; you can override it to do something * fancier. * * @param block The block to be updated. */ protected void placeShaftBlock(Block block) { block.setType(toPlace); } }
package net.minecraft.src; import java.util.EnumSet; import cpw.mods.fml.common.FMLCommonHandler; import cpw.mods.fml.common.ITickHandler; import cpw.mods.fml.common.TickType; import net.minecraft.client.Minecraft; public class mod_testMod extends BaseMod implements ITickHandler { private long ts; private long tsg; @Override public String getVersion() { return "test"; } @Override public void load() { ModLoader.setInGameHook(this, true, true); ModLoader.setInGUIHook(this, true, false); FMLCommonHandler.instance().registerTickHandler(this); ts=System.currentTimeMillis(); tsg=ts; } @Override public boolean onTickInGame(float time, Minecraft minecraftInstance) { long now = System.currentTimeMillis(); long del=now-ts; ts=now; System.out.printf("%d %d %d %d MLTICK\n",del, ts, tsg, now); return true; } @Override public boolean onTickInGUI(float tick, Minecraft game, GuiScreen gui) { System.out.printf("%d MLGUITICK\n",System.currentTimeMillis()); return true; } @Override public void tickStart(EnumSet<TickType> type, Object... tickData) { } @Override public void tickEnd(EnumSet<TickType> type, Object... tickData) { long now = System.currentTimeMillis(); long del=now-tsg; tsg=now; System.out.printf("%d %d %d %d GAMETICK\n",del, ts, tsg, now); } @Override public EnumSet<TickType> ticks() { return EnumSet.of(TickType.GAME); } /* (non-Javadoc) * @see cpw.mods.fml.common.ITickHandler#getLabel() */ @Override public String getLabel() { // TODO Auto-generated method stub return "TickTester"; } }
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 checkEqualValue(String varName, Object expectedResult) { assertTrue(varName, ((Comparable)expectedResult).compareTo(getVariable(varName))==0); } 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()); check("retNull1", Arrays.asList("Kennen", "Renector", null, null)); check("retNull2", Arrays.asList(false, true, true, null, null, null)); cal.clear(); cal.set(2001,0,20,0,0,0); cal.set(Calendar.MILLISECOND, 0); cal2.clear(); cal2.set(2003,4,12,0,0,0); cal2.set(Calendar.MILLISECOND, 0); check("retNull3", Arrays.asList(cal.getTime(), cal2.getTime(), null, null)); check("retNull4", Arrays.asList(1,8,10,12,null,null,null)); check("retNull5", Arrays.asList(1l, 12l, 15l, null, null, null)); check("retNull6", Arrays.asList(12.1d, 12.3d, 12.4d, null, null)); check("retNull7", Arrays.asList(new BigDecimal("11"), new BigDecimal("11.1"), new BigDecimal("11.2"), null, null, null)); } public void test_containerlib_sort_expect_error(){ 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('mark.twain@javlin.eu','(^[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('mark.twain@javlin.eu','(^[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('mark.twain@javlin.eu',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", null); check("test9", "abc"); check("test10", "abc"); check("test11", ""); check("test12", null); check("test13", null); check("test14", ""); check("test15", ""); } public void test_stringlib_left_expect_error(){ try { doCompile("function integer transform(){string s = left('Lux', -7, false); return 0;}","test_stringlib_left_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string s = left('Darius', -7, true); return 0;}","test_stringlib_left_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string s = left('Darius', null, true); return 0;}","test_stringlib_left_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer int = null; string s = left('Darius', int, true); return 0;}","test_stringlib_left_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){boolean b = null; string s = left('Darius', 9, b); return 0;}","test_stringlib_left_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string s = left('Darius', 7, null); return 0;}","test_stringlib_left_expect_error"); fail(); } catch (Exception e) { // do nothing } } 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", true); check("isDate23", false); check("isDate24", true); check("isDate25", false); check("isDate26", true); check("isDate27", true); } 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); check("test_mixed1", 176l); check("test_mixed2", 616l); } 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", 30l); check("test_mix2", 39l); } 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(new BigDecimal(3.0), new BigDecimal(-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; decimal 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(new BigDecimal("2"), new BigDecimal("-4"))); } 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; decimal 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(new BigDecimal("8"), new BigDecimal("8"), new BigDecimal("8"), new BigDecimal("8"))); check("longResult", Arrays.asList(new BigDecimal("8"), new BigDecimal("8"), new BigDecimal("8"), new BigDecimal("8"))); check("doubleResult", Arrays.asList(new BigDecimal("8"), new BigDecimal("8"), new BigDecimal("8"), new BigDecimal("8"))); check("decimalResult", Arrays.asList(new BigDecimal("8.000"), new BigDecimal("8.000"), new BigDecimal("8.000"), new BigDecimal("8.000"))); } 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; decimal 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; decimal n = pow(var1, var2); return 0;}","test_mathlib_pow_expect_error"); fail(); } catch (Exception e) { // do nothing } } /* * The equals() method also takes the scale into account, * CTL uses compareTo() instead. */ private void compareDecimals(List<BigDecimal> expected, List<BigDecimal> actual) { assertEquals(expected.size(), actual.size()); for (int i = 0; i < actual.size(); i++) { assertTrue("Expected: " + expected.get(i) + ", actual: " + actual.get(i), expected.get(i).compareTo(actual.get(i)) == 0); } } @SuppressWarnings("unchecked") 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)); //CLO-1835 // check("decimalResult", Arrays.asList(new BigDecimal("2"), new BigDecimal("4"))); // negative precision means the number of places after the decimal point // positive precision before the decimal point List<BigDecimal> expected = Arrays.asList( new BigDecimal("0"), new BigDecimal("1000000"), new BigDecimal("1200000"), new BigDecimal("1230000"), new BigDecimal("1235000"), // rounded up new BigDecimal("1234600"), // rounded up new BigDecimal("1234570"), // rounded up new BigDecimal("1234567"), new BigDecimal("1234567.1"), new BigDecimal("1234567.12"), new BigDecimal("1234567.123"), new BigDecimal("1234567.1235"), // rounded up new BigDecimal("1234567.12346"), // rounded up new BigDecimal("1234567.123457"), // rounded up new BigDecimal("1234567.1234567") ); //CLO-1835 compareDecimals(expected, (List<BigDecimal>) getVariable("decimal2Result")); //CLO-1832 check("intWithPrecisionResult", 1000); check("longWithPrecisionResult", 123456l); check("ret1", 1200); check("ret2", 10000l); List<Double> expectedDouble = Arrays.asList(0.0d, 1000000.0d, 1200000.0d, 1230000.0d, 1235000.0d, 1234600.0d, 1234570.0d, 1234567.0d, 1234567.1d, 1234567.12d, 1234567.123d, 1234567.1235d, 1234567.12346d, 1234567.123457d, 1234567.1234567d ); check("double2Result", expectedDouble); } 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; decimal l = round(input);return 0;}","test_mathlib_round_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){number input = null; number l = round(input, 2);return 0;}","test_mathlib_round_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){decimal input = null; decimal l = round(input, 9); return 0;}","test_mathlib_round_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer input = null; number l = round(input, 9); return 0;}","test_mathlib_round_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long input = null; number l = round(input, 9); return 0;}","test_mathlib_round_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long input = null; number l = round(input); return 0;}","test_mathlib_round_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer input = null; number 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_mathlib_setRandomSeed_expect_error(){ try { doCompile("function integer transform(){long l = null; setRandomSeed(l); return 0;}","test_mathlib_setRandomSeed_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer i = null; setRandomSeed(i); return 0;}","test_mathlib_setRandomSeed_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_mathlib_max() throws UnsupportedEncodingException{ doCompile("test_mathlib_max"); check("retInt", Arrays.asList(7,545,15,11,67,-43)); check("retIntNull", Arrays.asList(4,-4, null, null, 12, 54, 11, 11)); check("retLong", Arrays.asList(23L, 58L, 45l, 75L, 89L, -11L)); check("retLongNull", Arrays.asList(40L, 89L, null, null, 44L, 56L, 89L, 78l, 89L, 78L, 23L)); check("retDec", Arrays.asList(new BigDecimal("56.3"), new BigDecimal("87.3"), new BigDecimal("65.1"), new BigDecimal("56.3"), new BigDecimal("65.1"), new BigDecimal("-11.1"))); check("retDecNull", Arrays.asList(new BigDecimal("65.9"), new BigDecimal("-12.6"), null, null, new BigDecimal("32.4"), new BigDecimal("21.5"), new BigDecimal("11.3"), new BigDecimal("56.3"), new BigDecimal("78.1"), new BigDecimal("45.3"), new BigDecimal("87.9"), new BigDecimal("12.3"), new BigDecimal("13.4"), new BigDecimal("78"), new BigDecimal("59.6"), new BigDecimal("78.6"), new BigDecimal("12.3"), new BigDecimal("58.6"), new BigDecimal("48.6"), new BigDecimal("65.1"))); check("retNum", Arrays.asList(54.89d, 0d, 89.7d, 89.7d, 23.6d, -12.5)); check("retNumNull", Arrays.asList(56.4d, 98.3d, null, null, 56.9d, 45.7d, -78.6d, -11.2d, 78d, 45.6d, 89.6d, 56.9d, 123.3d, 45.9d, 48.5d, 67.8d)); check("retString", Arrays.asList("Kennen", "Zac")); check("retStringNull", Arrays.asList("Warwick", "Quinn", null)); check("retBool", Arrays.asList(true, true)); check("retBoolNull", Arrays.asList(true, true, null)); Calendar cal = Calendar.getInstance(); cal.set(2013, 1, 24, 0, 0, 0); cal.set(Calendar.MILLISECOND, 0); check("retDate", Arrays.asList(cal.getTime(), cal.getTime())); check("retDateNull", Arrays.asList(cal.getTime(), cal.getTime(), null)); } public void test_mathlib_max_expect_error(){ try { doCompile("function integer transform(){long[] my_list = null; max(my_list); return 0;}","test_mathlib_max_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long[] my_list; max(my_list); return 0;}","test_mathlib_max_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){byte[] my_list = [str2byte('Lux', 'utf-8'), str2byte('Tresh', 'utf-8')]; max(my_list); return 0;}","test_mathlib_max_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_mathlib_min(){ doCompile("test_mathlib_min"); check("retInt", Arrays.asList(-5, 14, 17, 15, -9, -48)); check("retIntNull", Arrays.asList(-3, -9, null, 19, 12, null, 15, 56)); check("retLong", Arrays.asList(-76l, 12l, 156l, -6l, 76l, -6l)); check("retLongNull", Arrays.asList(-30L, 12L, null, 13L, 12L, null, 89L, -4L, 12L, -9l, -5L, -89L)); check("retNum", Arrays.asList(0.99d, -90.1d, 56.9d, 56.9d, 45.1d, -1.11d)); check("retNumNull", Arrays.asList(11.3d, -11.1d, null, null, null, 12.3d, 11.2d, 11.6d, 12.6d, 12.3d, 17d, 12.6d, 12d, null, 12.3d, -23.6d, 36.9d, 23d, null)); check("retDec", Arrays.asList(new BigDecimal("-7.8"), new BigDecimal("-1.11"), new BigDecimal("56.7"), new BigDecimal("32.1"), new BigDecimal("56.7"), new BigDecimal("-12.4"))); check("retDecNull", Arrays.asList(new BigDecimal("34.2"), new BigDecimal("-1.6"), null, null, null, new BigDecimal("12.3"), new BigDecimal("11.2"), new BigDecimal("1.11"), new BigDecimal("-13.5"), new BigDecimal("2.11"), new BigDecimal("-23.9"), new BigDecimal("89.7"), new BigDecimal("16"), null, new BigDecimal("23.6"), new BigDecimal("78.9"), new BigDecimal("45.3"), new BigDecimal("458"), null, new BigDecimal("36.9"), new BigDecimal("-89.6"), new BigDecimal("78.9"), new BigDecimal("0"), null)); check("retStr", Arrays.asList("Jax", "Sivir")); check("retStrNull", Arrays.asList("Lulu", "Fizz", null, null)); check("retBool", Arrays.asList(false, false)); check("retBoolNull", Arrays.asList(false, false, null)); Calendar cal = Calendar.getInstance(); cal.set(2003, 10, 17, 0, 0, 0); cal.set(Calendar.MILLISECOND, 0); check("retDate", Arrays.asList(cal.getTime(), cal.getTime())); check("retDateNull", Arrays.asList(cal.getTime(), cal.getTime(), null)); } public void test_mathlib_min_expect_error(){ try { doCompile("function integer transform(){integer[] myList = null; min(myList); return 0;}","test_mathlib_min_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer[] myList; min(myList); return 0;}","test_mathlib_min_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){min([str2byte('Renektor', 'utf-8'), str2byte('Kayle', 'utf-16')]); return 0;}","test_mathlib_min_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_mathlib_cos(){ doCompile("test_mathlib_cos"); check("ret", Arrays.asList(Math.cos(12.6d), Math.cos(0d), Math.cos(-1456.8d), Math.cos(1.6d), Math.cos(12.6d), Math.cos(-19.3d), Math.cos(12d), Math.cos(23d), Math.cos(0d), Math.cos(0d))); } public void test_mathlib_cos_expect_error(){ try { doCompile("function integer transform(){double input = null; double d = cos(input); return 0;}","test_mathlib_cos_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){decimal input = null; double d = cos(input); return 0;}","test_mathlib_cos_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_mathlib_sin(){ doCompile("test_mathlib_sin"); check("ret", Arrays.asList(Math.sin(1d), Math.sin(25.9d), Math.sin(256d), Math.sin(123d), Math.sin(0d), Math.sin(0d))); } public void test_mathlib_sin_expect_error(){ try { doCompile("function integer transform(){double input = null; double d = sin(input); return 0;}","test_mathlib_sin_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){decimal input = null; double d = sin(input); return 0;}","test_mathlib_sin_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_mathlib_tan(){ doCompile("test_mathlib_tan"); check("ret", Arrays.asList(Math.tan(Math.PI/2), Math.tan(2*Math.PI), Math.tan(Math.PI), Math.tan(0d), Math.tan(12.44d), Math.tan(78d), Math.tan(725d), Math.tan(0d), Math.tan(0d))); } public void test_mathlib_tan_expect_error(){ try { doCompile("function integer transform(){double input = null; double dd = tan(input); return 0;}","test_mathlib_tan_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){decimal input = null; double dd = tan(input); return 0;}","test_mathlib_tan_expect_error"); fail(); } catch (Exception e) { // do nothing } } public void test_mathlib_acos(){ doCompile("test_mathlib_acos"); check("ret", Arrays.asList(Math.acos(Math.PI), Math.acos(Math.PI*2), Math.acos(Math.PI/2), Math.acos(180), Math.acos(90), Math.acos(0), Math.acos(123))); } public void test_mathlib_acos_expect_error(){ try { doCompile("function integer transform(){double input = null; acos(input);return 0;}"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){decimal input = null; acos(input);return 0;}"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){long input = null; acos(input);return 0;}"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){integer input = null; acos(input);return 0;}"); 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")); Calendar cal = Calendar.getInstance(); cal.set(1997,10,12,0,0,0); cal.set(Calendar.MILLISECOND,0); check("ret3", cal.getTime()); cal.clear(); cal.set(1970,0,1,1,0,12); cal.set(Calendar.MILLISECOND, 0); check("ret4", cal.getTime()); } 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"))); check("nullLiteralOutput", null); check("nullVariableOutput", null); } public void test_convertlib_bits2str() { doCompile("test_convertlib_bits2str"); check("bitsAsString1", "00000000"); check("bitsAsString2", "11111111"); check("bitsAsString3", "010100000100110110100000"); check("nullLiteralOutput", null); check("nullVariableOutput", null); } 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); check("nullLiteralOutput", null); check("nullVariableOutput", null); check("nullLiteralOutputWrapped", null); check("nullVariableOutputWrapped", null); check("nullLiteralOutputNowrap", null); check("nullVariableOutputNowrap", null); } public void test_convertlib_byte2base64_expect_error(){ 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})); check("nullLiteralOutput", null); check("nullVariableOutput", null); } 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)); check("nullLiteralOutput", null); check("nullVariableOutput", null); } 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[] {})); check("nullLiteralOutput", null); check("nullVariableOutput", null); } 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 }); check("nullLiteralOutput", null); check("nullVariableOutput", null); } public void test_convertlib_str2byte_expect_error(){ 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); check("nullLiteralOutput", null); check("nullVariableOutput", null); } public void test_convertlib_byte2str_expect_error(){ 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_randomString_expect_error(){ try { doCompile("function integer transform(){randomString(-5, 1); return 0;}","test_stringlib_randomString_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){randomString(15, 2); return 0;}","test_stringlib_randomString_expect_error"); fail(); } catch (Exception e) { // do nothing } } 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); check("ret1", null); // CLO-1700 // check("ret2", null); // check("ret3", null); } 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); check("ret1", null); // CLO-1700 // check("ret2", null); // check("ret3", null); } 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); check("ret1", null); check("ret2", null); check("ret3", null); } 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); check("ret1", null); check("ret2", null); } 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 } //CLO-1701 try { doCompile("function integer transform(){string str = iif(null, '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); check("ret17", "Shaco"); check("ret18", 12); check("ret19", 18.1d); check("ret20", 15L); check("ret21", new BigDecimal("18.1")); } public void test_utillib_toAbsolutePath(){ doCompile("test_utillib_toAbsolutePath"); assertNotNull(getVariable("ret1")); assertNotNull(getVariable("ret2")); check("ret3", null); } public void test_utillib_toAbsolutePath_expect_error(){ try { doCompile("function integer transform(){string str = toAbsolutePath(null); return 0;}","test_utillib_toAbsolutePath_expect_error"); fail(); } catch (Exception e) { // do nothing } try { doCompile("function integer transform(){string s = null; string str = toAbsolutePath(s); return 0;}","test_utillib_toAbsolutePath_expect_error"); fail(); } catch (Exception e) { // do nothing } } }
package com.mindoo.domino.jna; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.io.StringWriter; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.Collections; import java.util.Date; import java.util.EnumSet; import java.util.HashMap; import java.util.List; import java.util.Map; import com.mindoo.domino.jna.NotesNote.IItemCallback.Action; import com.mindoo.domino.jna.compoundtext.RichTextBuilder; import com.mindoo.domino.jna.constants.CDRecord; import com.mindoo.domino.jna.constants.Compression; import com.mindoo.domino.jna.constants.ItemType; import com.mindoo.domino.jna.constants.NoteClass; import com.mindoo.domino.jna.constants.OpenNote; import com.mindoo.domino.jna.constants.UpdateNote; import com.mindoo.domino.jna.errors.INotesErrorConstants; import com.mindoo.domino.jna.errors.NotesError; import com.mindoo.domino.jna.errors.NotesErrorUtils; import com.mindoo.domino.jna.errors.UnsupportedItemValueError; import com.mindoo.domino.jna.gc.IRecyclableNotesObject; import com.mindoo.domino.jna.gc.NotesGC; import com.mindoo.domino.jna.html.CommandId; import com.mindoo.domino.jna.html.IHtmlApiReference; import com.mindoo.domino.jna.html.IHtmlApiUrlTargetComponent; import com.mindoo.domino.jna.html.IHtmlConversionResult; import com.mindoo.domino.jna.html.IHtmlImageRef; import com.mindoo.domino.jna.html.ReferenceType; import com.mindoo.domino.jna.html.TargetType; import com.mindoo.domino.jna.internal.CollationDecoder; import com.mindoo.domino.jna.internal.ItemDecoder; import com.mindoo.domino.jna.internal.NotesCAPI; import com.mindoo.domino.jna.internal.NotesCAPI.b32_CWFErrorProc; import com.mindoo.domino.jna.internal.NotesCAPI.b64_CWFErrorProc; import com.mindoo.domino.jna.internal.NotesJNAContext; import com.mindoo.domino.jna.internal.ViewFormatDecoder; import com.mindoo.domino.jna.internal.WinNotesCAPI; import com.mindoo.domino.jna.structs.NoteIdStruct; import com.mindoo.domino.jna.structs.NotesBlockIdStruct; import com.mindoo.domino.jna.structs.NotesCDFieldStruct; import com.mindoo.domino.jna.structs.NotesFileObjectStruct; import com.mindoo.domino.jna.structs.NotesNumberPairStruct; import com.mindoo.domino.jna.structs.NotesObjectDescriptorStruct; import com.mindoo.domino.jna.structs.NotesOriginatorIdStruct; import com.mindoo.domino.jna.structs.NotesRangeStruct; import com.mindoo.domino.jna.structs.NotesTimeDatePairStruct; import com.mindoo.domino.jna.structs.NotesTimeDateStruct; import com.mindoo.domino.jna.structs.NotesUniversalNoteIdStruct; import com.mindoo.domino.jna.structs.html.HTMLAPIReference32Struct; import com.mindoo.domino.jna.structs.html.HTMLAPIReference64Struct; import com.mindoo.domino.jna.structs.html.HtmlApi_UrlTargetComponentStruct; import com.mindoo.domino.jna.utils.LegacyAPIUtils; import com.mindoo.domino.jna.utils.NotesDateTimeUtils; import com.mindoo.domino.jna.utils.NotesStringUtils; import com.mindoo.domino.jna.utils.StringUtil; import com.sun.jna.Memory; import com.sun.jna.Native; import com.sun.jna.Pointer; import com.sun.jna.StringArray; import com.sun.jna.ptr.ByteByReference; import com.sun.jna.ptr.DoubleByReference; import com.sun.jna.ptr.IntByReference; import com.sun.jna.ptr.LongByReference; import com.sun.jna.ptr.ShortByReference; import lotus.domino.Database; import lotus.domino.Document; import lotus.domino.NotesException; /** * Object wrapping a Notes document / note * * @author Karsten Lehmann */ public class NotesNote implements IRecyclableNotesObject { private int m_hNote32; private long m_hNote64; private boolean m_noRecycle; private NotesDatabase m_parentDb; private Document m_legacyDocRef; private EnumSet<NoteClass> m_noteClass; /** * Creates a new instance * * @param parentDb parent database * @param hNote handle */ NotesNote(NotesDatabase parentDb, int hNote) { if (NotesJNAContext.is64Bit()) throw new IllegalStateException("Constructor is 32bit only"); m_parentDb = parentDb; m_hNote32 = hNote; } /** * Creates a new instance * * @param parentDb parent database * @param hNote handle */ NotesNote(NotesDatabase parentDb, long hNote) { if (!NotesJNAContext.is64Bit()) throw new IllegalStateException("Constructor is 64bit only"); m_parentDb = parentDb; m_hNote64 = hNote; } /** * Creates a new NotesDatabase * * @param adaptable adaptable providing enough information to create the database */ public NotesNote(IAdaptable adaptable) { Document legacyDoc = adaptable.getAdapter(Document.class); if (legacyDoc!=null) { if (isRecycled(legacyDoc)) throw new NotesError(0, "Legacy database already recycled"); long docHandle = LegacyAPIUtils.getDocHandle(legacyDoc); if (docHandle==0) throw new NotesError(0, "Could not read db handle"); if (NotesJNAContext.is64Bit()) { m_hNote64 = docHandle; } else { m_hNote32 = (int) docHandle; } NotesGC.__objectCreated(NotesNote.class, this); setNoRecycle(); m_legacyDocRef = legacyDoc; Database legacyDb; try { legacyDb = legacyDoc.getParentDatabase(); } catch (NotesException e1) { throw new NotesError(0, "Could not read parent legacy db from document", e1); } long dbHandle = LegacyAPIUtils.getDBHandle(legacyDb); try { if (NotesJNAContext.is64Bit()) { m_parentDb = (NotesDatabase) NotesGC.__b64_checkValidObjectHandle(NotesDatabase.class, dbHandle); } else { m_parentDb = (NotesDatabase) NotesGC.__b32_checkValidObjectHandle(NotesDatabase.class, (int) dbHandle); } } catch (NotesError e) { m_parentDb = LegacyAPIUtils.toNotesDatabase(legacyDb); } } else { throw new NotesError(0, "Unsupported adaptable parameter"); } } private boolean isRecycled(Document doc) { try { //call any method to check recycled state doc.hasItem("~-~-~-~-~-~"); } catch (NotesException e) { if (e.id==4376 || e.id==4466) return true; } return false; } /** * Converts a legacy {@link lotus.domino.Document} to a * {@link NotesNote}. * * @param parentDb parent database * @param doc document to convert * @return note */ public static NotesNote toNote(NotesDatabase parentDb, Document doc) { long handle = LegacyAPIUtils.getDocHandle(doc); NotesNote note; if (NotesJNAContext.is64Bit()) { note = new NotesNote(parentDb, handle); } else { note = new NotesNote(parentDb, (int) handle); } note.setNoRecycle(); return note; } /** * Converts this note to a legacy {@link Document} * * @param db parent database * @return document */ public Document toDocument(Database db) { if (NotesJNAContext.is64Bit()) { return LegacyAPIUtils.createDocument(db, m_hNote64); } else { return LegacyAPIUtils.createDocument(db, m_hNote32); } } /** * Returns the parent database * * @return database */ public NotesDatabase getParent() { return m_parentDb; } /** * Returns the note id of the note * * @return note id */ public int getNoteId() { checkHandle(); Memory retNoteId = new Memory(4); retNoteId.clear(); NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); if (NotesJNAContext.is64Bit()) { notesAPI.b64_NSFNoteGetInfo(m_hNote64, NotesCAPI._NOTE_ID, retNoteId); } else { notesAPI.b32_NSFNoteGetInfo(m_hNote32, NotesCAPI._NOTE_ID, retNoteId); } return retNoteId.getInt(0); } /** * Returns the note class of the note * * @return note class */ public EnumSet<NoteClass> getNoteClass() { if (m_noteClass==null) { checkHandle(); Memory retNoteClass = new Memory(2); retNoteClass.clear(); NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); if (NotesJNAContext.is64Bit()) { notesAPI.b64_NSFNoteGetInfo(m_hNote64, NotesCAPI._NOTE_CLASS, retNoteClass); } else { notesAPI.b32_NSFNoteGetInfo(m_hNote32, NotesCAPI._NOTE_CLASS, retNoteClass); } int noteClassMask = retNoteClass.getShort(0); m_noteClass = NoteClass.toNoteClasses(noteClassMask); } return m_noteClass; } /** * Converts the value of {@link #getNoteId()} to a hex string in uppercase * format * * @return note id as hex string */ public String getNoteIdAsString() { return Integer.toString(getNoteId(), 16).toUpperCase(); } @Override public String toString() { if (isRecycled()) { return "NotesNote [recycled]"; } else { return "NotesNote [handle="+(NotesJNAContext.is64Bit() ? m_hNote64 : m_hNote32)+", noteid="+getNoteId()+"]"; } } /** * Returns the UNID of the note * * @return UNID */ public String getUNID() { NotesOriginatorIdStruct oid = getOIDStruct(); String unid = oid.getUNIDAsString(); return unid; } /** * Internal method to get the populated {@link NotesOriginatorIdStruct} object * for this note * * @return oid structure */ private NotesOriginatorIdStruct getOIDStruct() { checkHandle(); Memory retOid = new Memory(NotesCAPI.oidSize); retOid.clear(); NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); if (NotesJNAContext.is64Bit()) { notesAPI.b64_NSFNoteGetInfo(m_hNote64, NotesCAPI._NOTE_OID, retOid); } else { notesAPI.b32_NSFNoteGetInfo(m_hNote32, NotesCAPI._NOTE_OID, retOid); } NotesOriginatorIdStruct oidStruct = NotesOriginatorIdStruct.newInstance(retOid); oidStruct.read(); return oidStruct; } /** * Returns the {@link NotesOriginatorId} for this note * * @return oid */ public NotesOriginatorId getOID() { NotesOriginatorIdStruct oidStruct = getOIDStruct(); NotesOriginatorId oid = new NotesOriginatorId(oidStruct); return oid; } /** * Sets a new UNID in the {@link NotesOriginatorId} for this note * * @param newUnid new universal id */ public void setUNID(String newUnid) { checkHandle(); Memory retOid = new Memory(NotesCAPI.oidSize); retOid.clear(); NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); if (NotesJNAContext.is64Bit()) { notesAPI.b64_NSFNoteGetInfo(m_hNote64, NotesCAPI._NOTE_OID, retOid); } else { notesAPI.b32_NSFNoteGetInfo(m_hNote32, NotesCAPI._NOTE_OID, retOid); } NotesOriginatorIdStruct oidStruct = NotesOriginatorIdStruct.newInstance(retOid); oidStruct.read(); oidStruct.setUNID(newUnid); if (NotesJNAContext.is64Bit()) { notesAPI.b64_NSFNoteSetInfo(m_hNote64, NotesCAPI._NOTE_OID, retOid); } else { notesAPI.b32_NSFNoteSetInfo(m_hNote32, NotesCAPI._NOTE_OID, retOid); } } /** * Returns the last modified date of the note * * @return last modified date */ public Calendar getLastModified() { checkHandle(); Memory retModified = new Memory(NotesCAPI.timeDateSize); retModified.clear(); NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); if (NotesJNAContext.is64Bit()) { notesAPI.b64_NSFNoteGetInfo(m_hNote64, NotesCAPI._NOTE_MODIFIED, retModified); } else { notesAPI.b32_NSFNoteGetInfo(m_hNote32, NotesCAPI._NOTE_MODIFIED, retModified); } NotesTimeDateStruct td = NotesTimeDateStruct.newInstance(retModified); td.read(); Calendar cal = td.toCalendar(); return cal; } /** * Returns the creation date of this note * * @return creation date */ public Calendar getCreationDate() { checkHandle(); Calendar creationDate = getItemValueDateTime("$CREATED"); if (creationDate!=null) { return creationDate; } NotesOriginatorIdStruct oidStruct = getOIDStruct(); NotesTimeDateStruct creationDateStruct = oidStruct.Note; return creationDateStruct.toCalendar(); } /** * Returns the last access date of the note * * @return last access date */ public Calendar getLastAccessed() { checkHandle(); Memory retModified = new Memory(NotesCAPI.timeDateSize); retModified.clear(); NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); if (NotesJNAContext.is64Bit()) { notesAPI.b64_NSFNoteGetInfo(m_hNote64, NotesCAPI._NOTE_ACCESSED, retModified); } else { notesAPI.b32_NSFNoteGetInfo(m_hNote32, NotesCAPI._NOTE_ACCESSED, retModified); } NotesTimeDateStruct td = NotesTimeDateStruct.newInstance(retModified); td.read(); Calendar cal = td.toCalendar(); return cal; } /** * Returns the last access date of the note * * @return last access date */ public Calendar getAddedToFileTime() { checkHandle(); Memory retModified = new Memory(NotesCAPI.timeDateSize); retModified.clear(); NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); if (NotesJNAContext.is64Bit()) { notesAPI.b64_NSFNoteGetInfo(m_hNote64, NotesCAPI._NOTE_ADDED_TO_FILE, retModified); } else { notesAPI.b32_NSFNoteGetInfo(m_hNote32, NotesCAPI._NOTE_ADDED_TO_FILE, retModified); } NotesTimeDateStruct td = NotesTimeDateStruct.newInstance(retModified); td.read(); Calendar cal = td.toCalendar(); return cal; } /** * The NOTE_FLAG_READONLY bit indicates that the note is Read-Only for the current user.<br> * If a note contains an author names field, and the name of the user opening the * document is not included in the author names field list, then the NOTE_FLAG_READONLY * bit is set in the note header data when that user opens the note. * * @return TRUE if document cannot be updated */ public boolean isReadOnly() { int flags = getFlags(); return (flags & NotesCAPI.NOTE_FLAG_READONLY) == NotesCAPI.NOTE_FLAG_READONLY; } /** * The NOTE_FLAG_ABSTRACTED bit indicates that the note has been abstracted (truncated).<br> * This bit may be set if the database containing the note has replication settings set to * "Truncate large documents and remove attachments". * * @return true if truncated */ public boolean isTruncated() { int flags = getFlags(); return (flags & NotesCAPI.NOTE_FLAG_ABSTRACTED) == NotesCAPI.NOTE_FLAG_ABSTRACTED; } /** * Reads the note flags (e.g. {@link NotesCAPI#NOTE_FLAG_READONLY}) * * @return flags */ private short getFlags() { checkHandle(); Memory retFlags = new Memory(2); retFlags.clear(); NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); if (NotesJNAContext.is64Bit()) { notesAPI.b64_NSFNoteGetInfo(m_hNote64, NotesCAPI._NOTE_FLAGS, retFlags); } else { notesAPI.b32_NSFNoteGetInfo(m_hNote32, NotesCAPI._NOTE_FLAGS, retFlags); } short flags = retFlags.getShort(0); return flags; } public void setNoRecycle() { m_noRecycle=true; } @Override public boolean isNoRecycle() { return m_noRecycle; } @Override public void recycle() { if (m_noRecycle || isRecycled()) return; NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); short result; if (NotesJNAContext.is64Bit()) { result = notesAPI.b64_NSFNoteClose(m_hNote64); NotesErrorUtils.checkResult(result); NotesGC.__objectBeeingBeRecycled(NotesNote.class, this); m_hNote64=0; } else { result = notesAPI.b32_NSFNoteClose(m_hNote32); NotesErrorUtils.checkResult(result); NotesGC.__objectBeeingBeRecycled(NotesNote.class, this); m_hNote32=0; } } @Override public boolean isRecycled() { if (NotesJNAContext.is64Bit()) { return m_hNote64==0; } else { return m_hNote32==0; } } @Override public int getHandle32() { return m_hNote32; } @Override public long getHandle64() { return m_hNote64; } void checkHandle() { if (m_legacyDocRef!=null && isRecycled(m_legacyDocRef)) throw new NotesError(0, "Wrapped legacy document already recycled"); if (NotesJNAContext.is64Bit()) { if (m_hNote64==0) throw new NotesError(0, "Note already recycled"); NotesGC.__b64_checkValidObjectHandle(NotesNote.class, m_hNote64); } else { if (m_hNote32==0) throw new NotesError(0, "Note already recycled"); NotesGC.__b32_checkValidObjectHandle(NotesNote.class, m_hNote32); } } /** * Unsigns the note. This function removes the $Signature item from the note. */ public void unsign() { checkHandle(); NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); if (NotesJNAContext.is64Bit()) { short result = notesAPI.b64_NSFNoteUnsign(m_hNote64); NotesErrorUtils.checkResult(result); } else { short result = notesAPI.b32_NSFNoteUnsign(m_hNote32); NotesErrorUtils.checkResult(result); } } /** * This function writes the in-memory version of a note to its database.<br> * <br> * Prior to issuing this call, a new note (or changes to a note) are not a part * of the on-disk database.<br> * <br> * This function allows using extended 32-bit DWORD update options, as described * in the entry {@link UpdateNote}.<br> * <br> * You should also consider updating the collections associated with other Views * in a database via the function {@link NotesCollection#update()}, * if you have added and/or deleted a substantial number of documents.<br> * <br> * If the Server's Indexer Task does not rebuild the collections associated with the database's Views, * the first user to access a View in the modified database might experience an inordinant * delay, while the collection is rebuilt by the Notes Workstation (locally) or * Server Application (remotely). * @param updateFlags flags */ public void update(EnumSet<UpdateNote> updateFlags) { checkHandle(); int updateFlagsBitmask = UpdateNote.toBitMaskForUpdateExt(updateFlags); NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); if (NotesJNAContext.is64Bit()) { short result = notesAPI.b64_NSFNoteUpdateExtended(m_hNote64, updateFlagsBitmask); NotesErrorUtils.checkResult(result); } else { short result = notesAPI.b32_NSFNoteUpdateExtended(m_hNote32, updateFlagsBitmask); NotesErrorUtils.checkResult(result); } } /** * This function writes the in-memory version of a note to its database.<br> * Prior to issuing this call, a new note (or changes to a note) are not a part of * the on-disk database.<br> * <br> * You should also consider updating the collections associated with other Views in a database * via the function * {@link NotesCollection#update()}, if you have added and/or deleted a substantial number of documents.<br> * If the Server's Indexer Task does not rebuild the collections associated with * the database's Views, the first user to access a View in the modified database * might experience an inordinant delay, while the collection is rebuilt by the * Notes Workstation (locally) or Server Application (remotely).<br> * <br> * Do not update notes to disk that contain invalid items.<br> * An example of an invalid item is a view design note that has a $Collation item * whose BufferSize member is set to zero.<br> * This update method may return an error for an invalid item that was not caught * in a previous release of Domino or Notes.<br> * Note: if you have enabled IMAP on a database, in the case of the * special NoteID "NOTEID_ADD_OR_REPLACE", a new note is always created. * */ public void update() { update(EnumSet.noneOf(UpdateNote.class)); } /** * The method checks whether an item exists * * @param itemName item name * @return true if the item exists */ public boolean hasItem(String itemName) { checkHandle(); Memory itemNameMem = NotesStringUtils.toLMBCS(itemName, false); NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); short result; if (NotesJNAContext.is64Bit()) { result = notesAPI.b64_NSFItemInfo(m_hNote64, itemNameMem, (short) (itemNameMem.size() & 0xffff), null, null, null, null); } else { result = notesAPI.b32_NSFItemInfo(m_hNote32, itemNameMem, (short) (itemNameMem.size() & 0xffff), null, null, null, null); } return result == 0; } /** * The function NSFNoteHasComposite returns TRUE if the given note contains any TYPE_COMPOSITE items. * * @return true if composite */ public boolean hasComposite() { checkHandle(); NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); if (NotesJNAContext.is64Bit()) { return notesAPI.b64_NSFNoteHasComposite(m_hNote64) == 1; } else { return notesAPI.b32_NSFNoteHasComposite(m_hNote32) == 1; } } /** * The function NSFNoteHasMIME returns TRUE if the given note contains either TYPE_RFC822_TEXT * items or TYPE_MIME_PART items. * * @return true if mime */ public boolean hasMIME() { checkHandle(); NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); if (NotesJNAContext.is64Bit()) { return notesAPI.b64_NSFNoteHasMIME(m_hNote64) == 1; } else { return notesAPI.b32_NSFNoteHasMIME(m_hNote32) == 1; } } /** * The function NSFNoteHasMIMEPart returns TRUE if the given note contains any TYPE_MIME_PART items. * * @return true if mime part */ public boolean hasMIMEPart() { checkHandle(); NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); if (NotesJNAContext.is64Bit()) { return notesAPI.b64_NSFNoteHasMIMEPart(m_hNote64) == 1; } else { return notesAPI.b32_NSFNoteHasMIMEPart(m_hNote32) == 1; } } /** * This function deletes this note from the specified database with default flags (0).<br> * <br> * This function allows using extended 32-bit DWORD update options, as described in the entry {@link UpdateNote}.<br> * <br> * It deletes the specified note by updating it with a nil body, and marking the note as a deletion stub.<br> * The deletion stub identifies the deleted note to other replica copies of the database.<br> * This allows the replicator to delete copies of the note from replica databases. * <br> * The deleted note may be of any NOTE_CLASS_xxx. The active user ID must have sufficient user access * in the databases's Access Control List (ACL) to carry out a deletion on the note or the function * will return an error code. */ public void delete() { delete(EnumSet.noneOf(UpdateNote.class)); } /** * This function deletes this note from the specified database.<br> * <br> * This function allows using extended 32-bit DWORD update options, as described in the entry {@link UpdateNote}.<br> * <br> * It deletes the specified note by updating it with a nil body, and marking the note as a deletion stub.<br> * The deletion stub identifies the deleted note to other replica copies of the database.<br> * This allows the replicator to delete copies of the note from replica databases. * <br> * The deleted note may be of any NOTE_CLASS_xxx. The active user ID must have sufficient user access * in the databases's Access Control List (ACL) to carry out a deletion on the note or the function * will return an error code. * * @param flags flags */ public void delete(EnumSet<UpdateNote> flags) { checkHandle(); if (m_parentDb.isRecycled()) throw new NotesError(0, "Parent database already recycled"); int flagsAsInt = UpdateNote.toBitMaskForUpdateExt(flags); NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); short result; if (NotesJNAContext.is64Bit()) { result = notesAPI.b64_NSFNoteDeleteExtended(m_parentDb.getHandle64(), getNoteId(), flagsAsInt); } else { result = notesAPI.b32_NSFNoteDeleteExtended(m_parentDb.getHandle32(), getNoteId(), flagsAsInt); } NotesErrorUtils.checkResult(result); } /** * Method to remove an item from a note * * @param itemName item name */ public void removeItem(String itemName) { checkHandle(); Memory itemNameMem = NotesStringUtils.toLMBCS(itemName, false); NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); short result; if (NotesJNAContext.is64Bit()) { result = notesAPI.b64_NSFItemDelete(m_hNote64, itemNameMem, (short) (itemNameMem.size() & 0xffff)); } else { result = notesAPI.b32_NSFItemDelete(m_hNote32, itemNameMem, (short) (itemNameMem.size() & 0xffff)); } if (result==INotesErrorConstants.ERR_ITEM_NOT_FOUND) { return; } NotesErrorUtils.checkResult(result); } //shared memory buffer for text item values private static Memory MAX_TEXT_ITEM_VALUE = new Memory(65535); static { MAX_TEXT_ITEM_VALUE.clear(); } /** * Use this function to read the value of a text item.<br> * <br> * If the item does not exist, the method returns an empty string. Use {@link #hasItem(String)} * to check for item existence. * * @param itemName item name * @return text value */ public String getItemValueString(String itemName) { checkHandle(); NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); Memory itemNameMem = NotesStringUtils.toLMBCS(itemName, true); synchronized (MAX_TEXT_ITEM_VALUE) { try { short length; if (NotesJNAContext.is64Bit()) { length = notesAPI.b64_NSFItemGetText(m_hNote64, itemNameMem, MAX_TEXT_ITEM_VALUE, (short) (MAX_TEXT_ITEM_VALUE.size() & 0xffff)); } else { length = notesAPI.b32_NSFItemGetText(m_hNote32, itemNameMem, MAX_TEXT_ITEM_VALUE, (short) (MAX_TEXT_ITEM_VALUE.size() & 0xffff)); } int lengthAsInt = (int) length & 0xffff; if (lengthAsInt==0) { return ""; } String strVal = NotesStringUtils.fromLMBCS(MAX_TEXT_ITEM_VALUE, lengthAsInt); return strVal; } finally { MAX_TEXT_ITEM_VALUE.clear(); } } } /** * This function writes an item of type TEXT to the note.<br> * If an item of that name already exists, it deletes the existing item first, * then appends the new item.<br> * <br> * Note 1: Use \n as line break in your string. The method internally converts these line breaks * to null characters ('\0'), because that's what the Notes API expects as line break delimiter.<br> * <br> * Note 2: If the Summary parameter of is set to TRUE, the ITEM_SUMMARY flag in the item will be set. * Items with the ITEM_SUMMARY flag set are stored in the note's summary buffer. These items may * be used in view columns, selection formulas, and @-functions. The maximum size of the summary * buffer is 32K per note.<br> * If you append more than 32K bytes of data in items that have the ITEM_SUMMARY flag set, * this method call will succeed, but {@link #update(EnumSet)} will return ERR_SUMMARY_TOO_BIG (ERR 561). * To avoid this, decide which fields are not used in view columns, selection formulas, * or @-functions. For these "non-computed" fields, use this method with the Summary parameter set to FALSE.<br> * <br> * API program may read, modify, and write items that do not have the summary flag set, but they * must open the note first. Items that do not have the summary flag set can not be accessed * in the summary buffer.<br> * * @param itemName item name * @param itemValue item value * @param isSummary true to set summary flag */ public void setItemValueString(String itemName, String itemValue, boolean isSummary) { checkHandle(); NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); Memory itemNameMem = NotesStringUtils.toLMBCS(itemName, true); Memory itemValueMem = NotesStringUtils.toLMBCS(itemValue, false); if (NotesJNAContext.is64Bit()) { short result = notesAPI.b64_NSFItemSetTextSummary(m_hNote64, itemNameMem, itemValueMem, itemValueMem==null ? 0 : ((short) (itemValueMem.size() & 0xffff)), isSummary); NotesErrorUtils.checkResult(result); } else { short result = notesAPI.b32_NSFItemSetTextSummary(m_hNote32, itemNameMem, itemValueMem, itemValueMem==null ? 0 : ((short) (itemValueMem.size() & 0xffff)), isSummary); NotesErrorUtils.checkResult(result); } } /** * This function writes a number to an item in the note. * * @param itemName item name * @param value new value */ public void setItemValueDouble(String itemName, double value) { checkHandle(); NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); Memory itemNameMem = NotesStringUtils.toLMBCS(itemName, true); Memory doubleMem = new Memory(Native.getNativeSize(Double.TYPE)); doubleMem.setDouble(0, value); if (NotesJNAContext.is64Bit()) { short result = notesAPI.b64_NSFItemSetNumber(m_hNote64, itemNameMem, doubleMem); NotesErrorUtils.checkResult(result); } else { short result = notesAPI.b32_NSFItemSetNumber(m_hNote32, itemNameMem, doubleMem); NotesErrorUtils.checkResult(result); } } /** * Writes a {@link Calendar} value in an item * * @param itemName item name * @param cal new value */ public void setItemValueDateTime(String itemName, Calendar cal) { if (cal==null) { removeItem(itemName); return; } checkHandle(); NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); Memory itemNameMem = NotesStringUtils.toLMBCS(itemName, true); NotesTimeDate timeDate = NotesDateTimeUtils.calendarToTimeDate(cal); NotesTimeDateStruct timeDateStruct = timeDate==null ? null : timeDate.getAdapter(NotesTimeDateStruct.class); if (NotesJNAContext.is64Bit()) { short result = notesAPI.b64_NSFItemSetTime(m_hNote64, itemNameMem, timeDateStruct); NotesErrorUtils.checkResult(result); } else { short result = notesAPI.b32_NSFItemSetTime(m_hNote32, itemNameMem, timeDateStruct); NotesErrorUtils.checkResult(result); } } /** * Writes a {@link Date} value in an item * * @param itemName item name * @param dt new value * @param hasDate true to save the date of the specified {@link Date} object * @param hasTime true to save the time of the specified {@link Date} object */ public void setItemValueDateTime(String itemName, Date dt, boolean hasDate, boolean hasTime) { if (dt==null) { removeItem(itemName); return; } Calendar cal = Calendar.getInstance(); cal.setTime(dt); if (!hasDate) { NotesDateTimeUtils.setAnyDate(cal); } if (!hasTime) { NotesDateTimeUtils.setAnyTime(cal); } setItemValueDateTime(itemName, cal); } /** * Reads the value of a text list item * * @param itemName item name * @return list of strings; empty if item does not exist */ public List<String> getItemValueStringList(String itemName) { checkHandle(); NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); Memory itemNameMem = NotesStringUtils.toLMBCS(itemName, true); synchronized (MAX_TEXT_ITEM_VALUE) { try { short nrOfValues; if (NotesJNAContext.is64Bit()) { nrOfValues = notesAPI.b64_NSFItemGetTextListEntries(m_hNote64, itemNameMem); } else { nrOfValues = notesAPI.b32_NSFItemGetTextListEntries(m_hNote32, itemNameMem); } int nrOfValuesAsInt = (int) (nrOfValues & 0xffff); if (nrOfValuesAsInt==0) { return Collections.emptyList(); } List<String> strList = new ArrayList<String>(nrOfValuesAsInt); short retBufferSize = (short) (MAX_TEXT_ITEM_VALUE.size() & 0xffff); for (int i=0; i<nrOfValuesAsInt; i++) { short length; if (NotesJNAContext.is64Bit()) { length = notesAPI.b64_NSFItemGetTextListEntry(m_hNote64, itemNameMem, (short) (i & 0xffff), MAX_TEXT_ITEM_VALUE, retBufferSize); } else { length = notesAPI.b32_NSFItemGetTextListEntry(m_hNote32, itemNameMem, (short) (i & 0xffff), MAX_TEXT_ITEM_VALUE, retBufferSize); } int lengthAsInt = (int) length & 0xffff; if (lengthAsInt==0) { strList.add(""); } String strVal = NotesStringUtils.fromLMBCS(MAX_TEXT_ITEM_VALUE, lengthAsInt); strList.add(strVal); } return strList; } finally { MAX_TEXT_ITEM_VALUE.clear(); } } } /** * This is a very powerful function that converts many kinds of Domino fields (items) into * text strings.<br> * * If there is more than one item with the same name, this function will always return the first of these. * This function, therefore, is not useful if you want to retrieve multiple instances of the same * field name. For these situations, use NSFItemConvertValueToText.<br> * <br> * The item value may be any one of these supported Domino data types:<br> * <ul> * <li>TYPE_TEXT - Text is returned unmodified.</li> * <li>TYPE_TEXT_LIST - A text list items will merged into a single text string, with the separator between them.</li> * <li>TYPE_NUMBER - the FLOAT number will be converted to text.</li> * <li>TYPE_NUMBER_RANGE -- the FLOAT numbers will be converted to text, with the separator between them.</li> * <li>TYPE_TIME - the binary Time/Date will be converted to text.</li> * <li>TYPE_TIME_RANGE -- the binary Time/Date values will be converted to text, with the separator between them.</li> * <li>TYPE_COMPOSITE - The text portion of the rich text field will be returned.</li> * <li>TYPE_USERID - The user name portion will be converted to text.</li> * <li>TYPE_ERROR - the binary Error value will be converted to "ERROR: ".</li> * <li>TYPE_UNAVAILABLE - the binary Unavailable value will be converted to "UNAVAILABLE: ".</li> * </ul> * * @param itemName item name * @param multiValueDelimiter delimiter character for value lists; should be an ASCII character, since no encoding is done * @return string value */ public String getItemValueAsText(String itemName, char multiValueDelimiter) { checkHandle(); NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); Memory itemNameMem = NotesStringUtils.toLMBCS(itemName, true); synchronized (MAX_TEXT_ITEM_VALUE) { try { //API docs: The maximum buffer size allowed is 60K. short retBufferSize = (short) (Math.min(60*1024, MAX_TEXT_ITEM_VALUE.size()) & 0xffff); short length; if (NotesJNAContext.is64Bit()) { length = notesAPI.b64_NSFItemConvertToText(m_hNote64, itemNameMem, MAX_TEXT_ITEM_VALUE, retBufferSize, multiValueDelimiter); } else { length = notesAPI.b32_NSFItemConvertToText(m_hNote32, itemNameMem, MAX_TEXT_ITEM_VALUE, retBufferSize, multiValueDelimiter); } int lengthAsInt = (int) length & 0xffff; if (lengthAsInt==0) { return ""; } for (int i=0; i<lengthAsInt; i++) { //replace null bytes with newlines byte currByte = MAX_TEXT_ITEM_VALUE.getByte(i); if (currByte==0) { MAX_TEXT_ITEM_VALUE.setByte(i, (byte) '\n'); } } String strVal = NotesStringUtils.fromLMBCS(MAX_TEXT_ITEM_VALUE, lengthAsInt); return strVal; } finally { MAX_TEXT_ITEM_VALUE.clear(); } } } /** * Use this function to read the value of a number item as double.<br> * <br> * If the item does not exist, the method returns 0. Use {@link #hasItem(String)} * to check for item existence. * * @param itemName item name * @return double value */ public double getItemValueDouble(String itemName) { checkHandle(); NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); Memory itemNameMem = NotesStringUtils.toLMBCS(itemName, true); DoubleByReference retNumber = new DoubleByReference(); if (NotesJNAContext.is64Bit()) { boolean exists = notesAPI.b64_NSFItemGetNumber(m_hNote64, itemNameMem, retNumber); if (!exists) { return 0; } } else { boolean exists = notesAPI.b32_NSFItemGetNumber(m_hNote32, itemNameMem, retNumber); if (!exists) { return 0; } } return retNumber.getValue(); } /** * Use this function to read the value of a number item as long.<br> * <br> * If the item does not exist, the method returns 0. Use {@link #hasItem(String)} * to check for item existence. * * @param itemName item name * @return long value */ public long getItemValueLong(String itemName) { List<?> values = getItemValue(itemName); if (values.size()==0) return 0; Object firstVal = values.get(0); if (firstVal instanceof Number) { return ((Number)firstVal).longValue(); } return 0; } /** * Use this function to read the value of a number item as integer.<br> * <br> * If the item does not exist, the method returns 0. Use {@link #hasItem(String)} * to check for item existence. * * @param itemName item name * @return int value */ public int getItemValueInteger(String itemName) { List<?> values = getItemValue(itemName); if (values.size()==0) return 0; Object firstVal = values.get(0); if (firstVal instanceof Number) { return ((Number)firstVal).intValue(); } return 0; } /** * Use this function to read the value of a timedate item as {@link Calendar}.<br> * <br> * If the item does not exist, the method returns null. * * @param itemName item name * @return time date value or null */ public Calendar getItemValueDateTime(String itemName) { checkHandle(); NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); Memory itemNameMem = NotesStringUtils.toLMBCS(itemName, true); NotesTimeDateStruct td_item_value = NotesTimeDateStruct.newInstance(); if (NotesJNAContext.is64Bit()) { boolean exists = notesAPI.b64_NSFItemGetTime(m_hNote64, itemNameMem, td_item_value); if (!exists) { return null; } } else { boolean exists = notesAPI.b32_NSFItemGetTime(m_hNote32, itemNameMem, td_item_value); if (!exists) { return null; } } return td_item_value.toCalendar(); } /** * Decodes an item value * * @param itemName item name (for logging purpose) * @param valueBlockId value block id * @param valueLength item value length plus 2 bytes for the data type WORD * @return item value as list */ List<Object> getItemValue(String itemName, NotesBlockIdStruct itemBlockId, NotesBlockIdStruct valueBlockId, int valueLength) { NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); Pointer poolPtr; if (NotesJNAContext.is64Bit()) { poolPtr = notesAPI.b64_OSLockObject((long) valueBlockId.pool); } else { poolPtr = notesAPI.b32_OSLockObject(valueBlockId.pool); } int block = (valueBlockId.block & 0xffff); long poolPtrLong = Pointer.nativeValue(poolPtr) + block; Pointer valuePtr = new Pointer(poolPtrLong); try { List<Object> values = getItemValue(itemName, itemBlockId, valuePtr, valueLength); return values; } finally { if (NotesJNAContext.is64Bit()) { notesAPI.b64_OSUnlockObject((long) valueBlockId.pool); } else { notesAPI.b32_OSUnlockObject(valueBlockId.pool); } } } /** * Decodes an item value * * @param notesAPI Notes API * @param itemName item name (for logging purpose) * @param NotesBlockIdStruct itemBlockId item block id * @param valuePtr pointer to the item value * @param valueLength item value length plus 2 bytes for the data type WORD * @return item value as list */ List<Object> getItemValue(String itemName, NotesBlockIdStruct itemBlockId, Pointer valuePtr, int valueLength) { NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); short dataType = valuePtr.getShort(0); int dataTypeAsInt = (int) (dataType & 0xffff); boolean supportedType = false; if (dataTypeAsInt == NotesItem.TYPE_TEXT) { supportedType = true; } else if (dataTypeAsInt == NotesItem.TYPE_TEXT_LIST) { supportedType = true; } else if (dataTypeAsInt == NotesItem.TYPE_NUMBER) { supportedType = true; } else if (dataTypeAsInt == NotesItem.TYPE_TIME) { supportedType = true; } else if (dataTypeAsInt == NotesItem.TYPE_NUMBER_RANGE) { supportedType = true; } else if (dataTypeAsInt == NotesItem.TYPE_TIME_RANGE) { supportedType = true; } else if (dataTypeAsInt == NotesItem.TYPE_OBJECT) { supportedType = true; } else if (dataTypeAsInt == NotesItem.TYPE_NOTEREF_LIST) { supportedType = true; } else if (dataTypeAsInt == NotesItem.TYPE_COLLATION) { supportedType = true; } else if (dataTypeAsInt == NotesItem.TYPE_VIEW_FORMAT) { supportedType = true; } else if (dataTypeAsInt == NotesItem.TYPE_FORMULA) { supportedType = true; } else if (dataTypeAsInt == NotesItem.TYPE_UNAVAILABLE) { supportedType = true; } if (!supportedType) { throw new UnsupportedItemValueError("Data type for value of item "+itemName+" is currently unsupported: "+dataTypeAsInt); } int checkDataType = valuePtr.getShort(0) & 0xffff; Pointer valueDataPtr = valuePtr.share(2); int valueDataLength = valueLength - 2; if (checkDataType!=dataTypeAsInt) { throw new IllegalStateException("Value data type does not meet expected date type: found "+checkDataType+", expected "+dataTypeAsInt); } if (dataTypeAsInt == NotesItem.TYPE_TEXT) { String txtVal = (String) ItemDecoder.decodeTextValue(notesAPI, valueDataPtr, valueDataLength, false); return txtVal==null ? Collections.emptyList() : Arrays.asList((Object) txtVal); } else if (dataTypeAsInt == NotesItem.TYPE_TEXT_LIST) { List<Object> textList = valueDataLength==0 ? Collections.emptyList() : ItemDecoder.decodeTextListValue(notesAPI, valueDataPtr, false); return textList==null ? Collections.emptyList() : textList; } else if (dataTypeAsInt == NotesItem.TYPE_NUMBER) { double numVal = ItemDecoder.decodeNumber(notesAPI, valueDataPtr, valueDataLength); return Arrays.asList((Object) Double.valueOf(numVal)); } else if (dataTypeAsInt == NotesItem.TYPE_NUMBER_RANGE) { List<Object> numberList = ItemDecoder.decodeNumberList(notesAPI, valueDataPtr, valueDataLength); return numberList==null ? Collections.emptyList() : numberList; } else if (dataTypeAsInt == NotesItem.TYPE_TIME) { boolean useDayLight = NotesDateTimeUtils.isDaylightTime(); int gmtOffset = NotesDateTimeUtils.getGMTOffset(); Calendar cal = ItemDecoder.decodeTimeDate(notesAPI, valueDataPtr, valueDataLength, useDayLight, gmtOffset); return cal==null ? Collections.emptyList() : Arrays.asList((Object) cal); } else if (dataTypeAsInt == NotesItem.TYPE_TIME_RANGE) { boolean useDayLight = NotesDateTimeUtils.isDaylightTime(); int gmtOffset = NotesDateTimeUtils.getGMTOffset(); List<Object> calendarValues = ItemDecoder.decodeTimeDateList(notesAPI, valueDataPtr, useDayLight, gmtOffset); return calendarValues==null ? Collections.emptyList() : calendarValues; } else if (dataTypeAsInt == NotesItem.TYPE_OBJECT) { NotesObjectDescriptorStruct objDescriptor = NotesObjectDescriptorStruct.newInstance(valueDataPtr); objDescriptor.read(); int rrv = objDescriptor.RRV; if (objDescriptor.ObjectType == NotesCAPI.OBJECT_FILE) { Pointer fileObjectPtr = valueDataPtr; NotesFileObjectStruct fileObject = NotesFileObjectStruct.newInstance(fileObjectPtr); fileObject.read(); short compressionType = fileObject.CompressionType; NotesTimeDateStruct fileCreated = fileObject.FileCreated; NotesTimeDateStruct fileModified = fileObject.FileModified; NotesTimeDate fileCreatedWrap = fileCreated==null ? null : new NotesTimeDate(fileCreated); NotesTimeDate fileModifiedWrap = fileModified==null ? null : new NotesTimeDate(fileModified); short fileNameLength = fileObject.FileNameLength; int fileSize = fileObject.FileSize; short flags = fileObject.Flags; Compression compression = null; for (Compression currComp : Compression.values()) { if (compressionType == currComp.getValue()) { compression = currComp; break; } } Pointer fileNamePtr = fileObjectPtr.share(NotesCAPI.fileObjectSize); String fileName = NotesStringUtils.fromLMBCS(fileNamePtr, fileNameLength); NotesAttachment attInfo = new NotesAttachment(fileName, compression, flags, fileSize, fileCreatedWrap, fileModifiedWrap, this, itemBlockId, rrv); return Arrays.asList((Object) attInfo); } //TODO add support for other object types return Arrays.asList((Object) objDescriptor); } else if (dataTypeAsInt == NotesItem.TYPE_NOTEREF_LIST) { //skip LIST structure NotesUniversalNoteIdStruct unidStruct = NotesUniversalNoteIdStruct.newInstance(valueDataPtr.share(2)); NotesUniversalNoteId unid = new NotesUniversalNoteId(unidStruct); return Arrays.asList((Object) unid); } else if (dataTypeAsInt == NotesItem.TYPE_COLLATION) { NotesCollationInfo colInfo = CollationDecoder.decodeCollation(valueDataPtr); return Arrays.asList((Object) colInfo); } else if (dataTypeAsInt == NotesItem.TYPE_VIEW_FORMAT) { NotesViewFormat viewFormatInfo = ViewFormatDecoder.decodeViewFormat(valueDataPtr, valueDataLength); return Arrays.asList((Object) viewFormatInfo); } else if (dataTypeAsInt == NotesItem.TYPE_FORMULA) { boolean isSelectionFormula = "$FORMULA".equalsIgnoreCase(itemName) && getNoteClass().contains(NoteClass.VIEW); if (NotesJNAContext.is64Bit()) { LongByReference rethFormulaText = new LongByReference(); ShortByReference retFormulaTextLength = new ShortByReference(); short result = notesAPI.b64_NSFFormulaDecompile(valueDataPtr, isSelectionFormula, rethFormulaText, retFormulaTextLength); NotesErrorUtils.checkResult(result); Pointer formulaPtr = notesAPI.b64_OSLockObject(rethFormulaText.getValue()); try { int textLen = (int) (retFormulaTextLength.getValue() & 0xffff); String formula = NotesStringUtils.fromLMBCS(formulaPtr, textLen); return Arrays.asList((Object) formula); } finally { notesAPI.b64_OSUnlockObject(rethFormulaText.getValue()); notesAPI.b64_OSMemFree(rethFormulaText.getValue()); } } else { IntByReference rethFormulaText = new IntByReference(); ShortByReference retFormulaTextLength = new ShortByReference(); short result = notesAPI.b32_NSFFormulaDecompile(valueDataPtr, isSelectionFormula, rethFormulaText, retFormulaTextLength); NotesErrorUtils.checkResult(result); Pointer formulaPtr = notesAPI.b32_OSLockObject(rethFormulaText.getValue()); try { int textLen = (int) (retFormulaTextLength.getValue() & 0xffff); String formula = NotesStringUtils.fromLMBCS(formulaPtr, textLen); return Arrays.asList((Object) formula); } finally { notesAPI.b32_OSUnlockObject(rethFormulaText.getValue()); notesAPI.b32_OSMemFree(rethFormulaText.getValue()); } } } else if (dataTypeAsInt == NotesItem.TYPE_UNAVAILABLE) { return Collections.emptyList(); } else { throw new UnsupportedItemValueError("Data type for value of item "+itemName+" is currently unsupported: "+dataTypeAsInt); } } /** * Attaches a disk file to a note.<br> * <br> * To accomplish this, the function creates an item of TYPE_OBJECT, sub-category OBJECT_FILE, * whose ITEM_xxx flag(s) are set to ITEM_SIGN | ITEM_SEAL.<br> * The item that is built by NSFNoteAttachFile contains all relevant file information and * the compressed file itself.<br> * Since the Item APIs offer no means of dealing with signed, sealed, or compressed item values, * the File Attachment API NSFNoteDetachFile must be used exclusively to access these items. * * @param filePathOnDisk fully qualified file path specification for file being attached * @param fileNameInNote filename that will be stored internally with the attachment, displayed with the attachment icon when the document is viewed in the Notes user interface, and subsequently used when selecting which attachment to Extract or Detach and what path to create for an Extracted file. Note that these operations may be carried out both from the workstation application Attachments dialog box and programmatically, so try to choose meaningful filenames as opposed to attach.001, attach002, etc., whenever possible. If attaching mulitiple files that have the same filename but different content to a single document, make sure this variable is unique in each call to NSFNoteAttachFile(). * @param compression compression to use */ public void attachFile(String filePathOnDisk, String fileNameInNote, Compression compression) { checkHandle(); NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); Memory $fileItemName = NotesStringUtils.toLMBCS("$FILE", true); Memory filePathOnDiskMem = NotesStringUtils.toLMBCS(filePathOnDisk, true); Memory fileNameInNoteMem = NotesStringUtils.toLMBCS(fileNameInNote, true); short compressionAsShort = (short) (compression.getValue() & 0xffff); if (NotesJNAContext.is64Bit()) { short result = notesAPI.b64_NSFNoteAttachFile(m_hNote64, $fileItemName, (short) (($fileItemName.size()-1) & 0xffff), filePathOnDiskMem, fileNameInNoteMem, compressionAsShort); NotesErrorUtils.checkResult(result); } else { short result = notesAPI.b32_NSFNoteAttachFile(m_hNote32, $fileItemName, (short) (($fileItemName.size()-1) & 0xffff), filePathOnDiskMem, fileNameInNoteMem, compressionAsShort); NotesErrorUtils.checkResult(result); } } /** * The method searches for a note attachment with the specified filename * * @param fileName filename to search for (case-insensitive) * @return attachment or null if not found */ public NotesAttachment getAttachment(final String fileName) { final NotesAttachment[] foundAttInfo = new NotesAttachment[1]; getItems("$file", new IItemCallback() { @Override public void itemNotFound() { } @Override public Action itemFound(NotesItem item) { List<Object> values = item.getValues(); if (values!=null && !values.isEmpty() && values.get(0) instanceof NotesAttachment) { NotesAttachment attInfo = (NotesAttachment) values.get(0); if (attInfo.getFileName().equalsIgnoreCase(fileName)) { foundAttInfo[0] = attInfo; return Action.Stop; } } return Action.Continue; } }); return foundAttInfo[0]; } /** * Decodes the value(s) of the first item with the specified item name<br> * <br> * The supported data types are documented here: {@link NotesItem#getValues()} * * @param itemName item name * @return value(s) as list, not null * @throws UnsupportedItemValueError if item type is not supported yet */ public List<Object> getItemValue(String itemName) { checkHandle(); NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); NotesItem item = getFirstItem(itemName); if (item==null) { return Collections.emptyList(); } int valueLength = item.getValueLength(); Pointer valuePtr; //lock and decode value NotesBlockIdStruct valueBlockId = item.getValueBlockId(); Pointer poolPtr; if (NotesJNAContext.is64Bit()) { poolPtr = notesAPI.b64_OSLockObject((long) valueBlockId.pool); } else { poolPtr = notesAPI.b32_OSLockObject(valueBlockId.pool); } int block = (int) (valueBlockId.block & 0xffff); long poolPtrLong = Pointer.nativeValue(poolPtr) + block; valuePtr = new Pointer(poolPtrLong); try { List<Object> values = getItemValue(itemName, item.getItemBlockId(), valuePtr, valueLength); return values; } finally { if (NotesJNAContext.is64Bit()) { notesAPI.b64_OSUnlockObject((long) valueBlockId.pool); } else { notesAPI.b32_OSUnlockObject(valueBlockId.pool); } } } /** * Callback interface for {@link NotesNote#getItems(IItemCallback)} * * @author Karsten Lehmann */ public static interface IItemCallback { public static enum Action {Continue, Stop}; /** * Method is called when an item could not be found in the note */ public void itemNotFound(); /** * Method is called for each item in the note. A note may contain the same item name * multiple times. In this case, the method is called for each item instance * * @param item item object with meta data and access method to decode item value * @return next action, either continue or stop scan */ public Action itemFound(NotesItem item); } /** * Utility class to decode the item flag bitmask * * @author Karsten Lehmann */ public static class ItemFlags { private int m_itemFlags; public ItemFlags(int itemFlags) { m_itemFlags = itemFlags; } public int getBitMask() { return m_itemFlags; } public boolean isSigned() { return (m_itemFlags & NotesCAPI.ITEM_SIGN) == NotesCAPI.ITEM_SIGN; } public boolean isSealed() { return (m_itemFlags & NotesCAPI.ITEM_SEAL) == NotesCAPI.ITEM_SEAL; } public boolean isSummary() { return (m_itemFlags & NotesCAPI.ITEM_SUMMARY) == NotesCAPI.ITEM_SUMMARY; } public boolean isReadWriters() { return (m_itemFlags & NotesCAPI.ITEM_READWRITERS) == NotesCAPI.ITEM_READWRITERS; } public boolean isNames() { return (m_itemFlags & NotesCAPI.ITEM_NAMES) == NotesCAPI.ITEM_NAMES; } public boolean isPlaceholder() { return (m_itemFlags & NotesCAPI.ITEM_PLACEHOLDER) == NotesCAPI.ITEM_PLACEHOLDER; } public boolean isProtected() { return (m_itemFlags & NotesCAPI.ITEM_PROTECTED) == NotesCAPI.ITEM_PROTECTED; } public boolean isReaders() { return (m_itemFlags & NotesCAPI.ITEM_READERS) == NotesCAPI.ITEM_READERS; } public boolean isUnchanged() { return (m_itemFlags & NotesCAPI.ITEM_UNCHANGED) == NotesCAPI.ITEM_UNCHANGED; } } /** * Scans through all items of this note * * @param callback callback is called for each item found */ public void getItems(final IItemCallback callback) { getItems((String) null, callback); } /** * Scans through all items of this note that have the specified name * * @param searchForItemName item name to search for or null to scan through all items * @param callback callback is called for each scan result */ public void getItems(final String searchForItemName, final IItemCallback callback) { checkHandle(); final NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); Memory itemNameMem = StringUtil.isEmpty(searchForItemName) ? null : NotesStringUtils.toLMBCS(searchForItemName, false); NotesBlockIdStruct.ByReference itemBlockId = NotesBlockIdStruct.ByReference.newInstance(); NotesBlockIdStruct.ByReference valueBlockId = NotesBlockIdStruct.ByReference.newInstance(); ShortByReference retDataType = new ShortByReference(); IntByReference retValueLen = new IntByReference(); short result; if (NotesJNAContext.is64Bit()) { result = notesAPI.b64_NSFItemInfo(m_hNote64, itemNameMem, itemNameMem==null ? 0 : (short) (itemNameMem.size() & 0xffff), itemBlockId, retDataType, valueBlockId, retValueLen); } else { result = notesAPI.b32_NSFItemInfo(m_hNote32, itemNameMem, itemNameMem==null ? 0 : (short) (itemNameMem.size() & 0xffff), itemBlockId, retDataType, valueBlockId, retValueLen); } if (result == INotesErrorConstants.ERR_ITEM_NOT_FOUND) { callback.itemNotFound(); return; } NotesErrorUtils.checkResult(result); NotesBlockIdStruct itemBlockIdClone = new NotesBlockIdStruct(); itemBlockIdClone.pool = itemBlockId.pool; itemBlockIdClone.block = itemBlockId.block; itemBlockIdClone.write(); NotesBlockIdStruct valueBlockIdClone = new NotesBlockIdStruct(); valueBlockIdClone.pool = valueBlockId.pool; valueBlockIdClone.block = valueBlockId.block; valueBlockIdClone.write(); int dataType = retDataType.getValue(); NotesItem itemInfo = new NotesItem(this, itemBlockIdClone, dataType, valueBlockIdClone); Action action = callback.itemFound(itemInfo); if (action != Action.Continue) { return; } while (true) { IntByReference retNextValueLen = new IntByReference(); NotesBlockIdStruct.ByValue itemBlockIdByVal = NotesBlockIdStruct.ByValue.newInstance(); itemBlockIdByVal.pool = itemBlockId.pool; itemBlockIdByVal.block = itemBlockId.block; if (NotesJNAContext.is64Bit()) { result = notesAPI.b64_NSFItemInfoNext(m_hNote64, itemBlockIdByVal, itemNameMem, itemNameMem==null ? 0 : (short) (itemNameMem.size() & 0xffff), itemBlockId, retDataType, valueBlockId, retNextValueLen); } else { result = notesAPI.b32_NSFItemInfoNext(m_hNote32, itemBlockIdByVal, itemNameMem, itemNameMem==null ? 0 : (short) (itemNameMem.size() & 0xffff), itemBlockId, retDataType, valueBlockId, retNextValueLen); } if (result == INotesErrorConstants.ERR_ITEM_NOT_FOUND) { return; } NotesErrorUtils.checkResult(result); itemBlockIdClone = new NotesBlockIdStruct(); itemBlockIdClone.pool = itemBlockId.pool; itemBlockIdClone.block = itemBlockId.block; itemBlockIdClone.write(); valueBlockIdClone = new NotesBlockIdStruct(); valueBlockIdClone.pool = valueBlockId.pool; valueBlockIdClone.block = valueBlockId.block; valueBlockIdClone.write(); dataType = retDataType.getValue(); itemInfo = new NotesItem(this, itemBlockIdClone, dataType, valueBlockIdClone); action = callback.itemFound(itemInfo); if (action != Action.Continue) { return; } } } /** * Method to enumerate all CD records of a richtext item with the specified name. * If Domino splits the richtext data into multiple items (because it does not fit into 64K), * the method will process all available items. * * @param richTextItemName richtext item name * @param callback callback to call for each record */ public void enumerateRichTextCDRecords(String richTextItemName, final ICDRecordCallback callback) { final boolean[] aborted = new boolean[1]; getItems(richTextItemName, new IItemCallback() { @Override public void itemNotFound() { } @Override public Action itemFound(NotesItem item) { if (item.getType()==NotesItem.TYPE_COMPOSITE) { item.enumerateRichTextCDRecords(new ICDRecordCallback() { @Override public Action recordVisited(ByteBuffer data, CDRecord parsedSignature, short signature, int dataLength, int cdRecordLength) { Action action = callback.recordVisited(data, parsedSignature, signature, dataLength, cdRecordLength); if (action==Action.Stop) { aborted[0] = true; } return action; } }); if (aborted[0]) { return Action.Stop; } } return Action.Continue; } }); } /** * Extracts all text from a richtext item * * @param itemName item name * @return text content */ public String getRichtextContentAsText(String itemName) { final StringWriter sWriter = new StringWriter(); //find all items with this name in case the content got to big to fit into one item alone getItems(itemName, new IItemCallback() { @Override public void itemNotFound() { } @Override public Action itemFound(NotesItem item) { if (item.getType()==NotesItem.TYPE_COMPOSITE) { item.getAllCompositeTextContent(sWriter); } return Action.Continue; } }); return sWriter.toString(); } /** * Returns the first item with the specified name from the note * * @param itemName item name * @return item data or null if not found */ public NotesItem getFirstItem(String itemName) { if (itemName==null) { throw new IllegalArgumentException("Item name cannot be null. Use getItems() instead."); } final NotesItem[] retItem = new NotesItem[1]; getItems(itemName, new IItemCallback() { @Override public void itemNotFound() { retItem[0]=null; } @Override public Action itemFound(NotesItem itemInfo) { retItem[0] = itemInfo; return Action.Stop; } }); return retItem[0]; } /** * Checks whether this note is signed * * @return true if signed */ public boolean isSigned() { checkHandle(); ByteByReference signed_flag_ptr = new ByteByReference(); ByteByReference sealed_flag_ptr = new ByteByReference(); final NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); if (NotesJNAContext.is64Bit()) { notesAPI.b64_NSFNoteIsSignedOrSealed(m_hNote64, signed_flag_ptr, sealed_flag_ptr); byte signed = signed_flag_ptr.getValue(); return signed == 1; } else { notesAPI.b32_NSFNoteIsSignedOrSealed(m_hNote32, signed_flag_ptr, sealed_flag_ptr); byte signed = signed_flag_ptr.getValue(); return signed == 1; } } /** * Checks whether this note is sealed * * @return true if sealed */ public boolean isSealed() { checkHandle(); ByteByReference signed_flag_ptr = new ByteByReference(); ByteByReference sealed_flag_ptr = new ByteByReference(); final NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); if (NotesJNAContext.is64Bit()) { notesAPI.b64_NSFNoteIsSignedOrSealed(m_hNote64, signed_flag_ptr, sealed_flag_ptr); byte sealed = sealed_flag_ptr.getValue(); return sealed == 1; } else { notesAPI.b32_NSFNoteIsSignedOrSealed(m_hNote32, signed_flag_ptr, sealed_flag_ptr); byte sealed = sealed_flag_ptr.getValue(); return sealed == 1; } } /** Possible validation phases for {@link NotesNote#computeWithForm(boolean, ComputeWithFormCallback)} */ public static enum ValidationPhase { /** Error occurred when processing the Default Value formula. */ CWF_DV_FORMULA, /** Error occurred when processing the Translation formula. */ CWF_IT_FORMULA, /** Error occurred when processing the Validation formula. */ CWF_IV_FORMULA, /** Error occurred when processing the computed field Value formula. */ CWF_COMPUTED_FORMULA, /** Error occurred when verifying the data type for the field. */ CWF_DATATYPE_CONVERSION, /** Error occurred when processing the computed field Value formula, during the "load" pass. */ CWF_COMPUTED_FORMULA_LOAD, /** Error occurred when processing the computed field Value formula, during the "save" pass. */ CWF_COMPUTED_FORMULA_SAVE }; /* Possible return values from the callback routine specified in NSFNoteComputeWithForm() */ public static enum CWF_Action { /** End all processing by NSFNoteComputeWithForm() and return the error status to the caller. */ CWF_ABORT((short) 1), /** End validation of the current field and go on to the next. */ CWF_NEXT_FIELD((short) 2), /** Begin the validation process for this field over again. */ CWF_RECHECK_FIELD((short) 3); short actionVal; CWF_Action(short val) { this.actionVal = val; } public short getShortVal() { return actionVal; } } private ValidationPhase decodeValidationPhase(short phase) { ValidationPhase phaseEnum = null; if (phase == NotesCAPI.CWF_DV_FORMULA) { phaseEnum = ValidationPhase.CWF_DV_FORMULA; } else if (phase == NotesCAPI.CWF_IT_FORMULA) { phaseEnum = ValidationPhase.CWF_IT_FORMULA; } else if (phase == NotesCAPI.CWF_IV_FORMULA) { phaseEnum = ValidationPhase.CWF_IV_FORMULA; } else if (phase == NotesCAPI.CWF_COMPUTED_FORMULA) { phaseEnum = ValidationPhase.CWF_COMPUTED_FORMULA; } else if (phase == NotesCAPI.CWF_DATATYPE_CONVERSION) { phaseEnum = ValidationPhase.CWF_DATATYPE_CONVERSION; } else if (phase == NotesCAPI.CWF_COMPUTED_FORMULA_LOAD) { phaseEnum = ValidationPhase.CWF_COMPUTED_FORMULA_LOAD; } else if (phase == NotesCAPI.CWF_COMPUTED_FORMULA_SAVE) { phaseEnum = ValidationPhase.CWF_COMPUTED_FORMULA_SAVE; } return phaseEnum; } private FieldInfo readCDFieldInfo(Pointer ptrCDField) { NotesCDFieldStruct cdField = NotesCDFieldStruct.newInstance(ptrCDField); cdField.read(); Pointer defaultValueFormulaPtr = ptrCDField.share(NotesCAPI.cdFieldSize); Pointer inputTranslationFormulaPtr = defaultValueFormulaPtr.share(cdField.DVLength & 0xffff); Pointer inputValidityCheckFormulaPtr = inputTranslationFormulaPtr.share((cdField.ITLength &0xffff) + (cdField.TabOrder & 0xffff)); // Pointer namePtr = inputValidityCheckFormulaPtr.share(cdField.IVLength & 0xffff); // field.DVLength + field.ITLength + field.IVLength, // field.NameLength Pointer namePtr = ptrCDField.share((cdField.DVLength & 0xffff) + (cdField.ITLength & 0xffff) + (cdField.IVLength & 0xffff)); Pointer descriptionPtr = namePtr.share(cdField.NameLength & 0xffff); String defaultValueFormula = NotesStringUtils.fromLMBCS(defaultValueFormulaPtr, cdField.DVLength & 0xffff); String inputTranslationFormula = NotesStringUtils.fromLMBCS(inputTranslationFormulaPtr, cdField.ITLength & 0xffff); String inputValidityCheckFormula = NotesStringUtils.fromLMBCS(inputValidityCheckFormulaPtr, cdField.IVLength & 0xffff); String name = NotesStringUtils.fromLMBCS(namePtr, cdField.NameLength & 0xffff); String description = NotesStringUtils.fromLMBCS(descriptionPtr, cdField.DescLength & 0xffff); return new FieldInfo(defaultValueFormula, inputTranslationFormula, inputValidityCheckFormula, name, description); } public static class FieldInfo { private String m_defaultValueFormula; private String m_inputTranslationFormula; private String m_inputValidityCheckFormula; private String m_name; private String m_description; public FieldInfo(String defaultValueFormula, String inputTranslationFormula, String inputValidityCheckFormula, String name, String description) { m_defaultValueFormula = defaultValueFormula; m_inputTranslationFormula = inputTranslationFormula; m_inputValidityCheckFormula = inputValidityCheckFormula; m_name = name; m_description = description; } public String getDefaultValueFormula() { return m_defaultValueFormula; } public String getInputTranslationFormula() { return m_inputTranslationFormula; } public String getInputValidityCheckFormula() { return m_inputValidityCheckFormula; } public String getName() { return m_name; } public String getDescription() { return m_description; } @Override public String toString() { return "FieldInfo [name="+getName()+", description="+getDescription()+", default="+getDefaultValueFormula()+ ", inputtranslation="+getInputTranslationFormula()+", validation="+getInputValidityCheckFormula()+"]"; } } public void computeWithForm(boolean continueOnError, final ComputeWithFormCallback callback) { checkHandle(); int dwFlags = 0; if (continueOnError) { dwFlags = NotesCAPI.CWF_CONTINUE_ON_ERROR; } final NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); if (NotesJNAContext.is64Bit()) { b64_CWFErrorProc errorProc; if (notesAPI instanceof WinNotesCAPI) { errorProc = new WinNotesCAPI.b64_CWFErrorProcWin() { @Override public short invoke(Pointer pCDField, short phase, short error, long hErrorText, short wErrorTextSize, Pointer ctx) { String errorTxt; if (hErrorText==0) { errorTxt = ""; } else { Pointer errorTextPtr = notesAPI.b64_OSLockObject(hErrorText); try { //TODO find out where this offset 6 comes from errorTxt = NotesStringUtils.fromLMBCS(errorTextPtr.share(6), (wErrorTextSize & 0xffff)-6); } finally { notesAPI.b64_OSUnlockObject(hErrorText); } } FieldInfo fieldInfo = readCDFieldInfo(pCDField); ValidationPhase phaseEnum = decodeValidationPhase(phase); CWF_Action action; if (callback==null) { action = CWF_Action.CWF_ABORT; } else { action = callback.errorRaised(fieldInfo, phaseEnum, errorTxt, hErrorText); } return action==null ? CWF_Action.CWF_ABORT.getShortVal() : action.getShortVal(); } }; } else { errorProc = new b64_CWFErrorProc() { @Override public short invoke(Pointer pCDField, short phase, short error, long hErrorText, short wErrorTextSize, Pointer ctx) { String errorTxt; if (hErrorText==0) { errorTxt = ""; } else { Pointer errorTextPtr = notesAPI.b64_OSLockObject(hErrorText); System.out.println("ErrorTextPtr: "+errorTextPtr.dump(0, (int) (wErrorTextSize & 0xffff))); try { //TODO find out where this offset 6 comes from errorTxt = NotesStringUtils.fromLMBCS(errorTextPtr.share(6), (wErrorTextSize & 0xffff)-6); } finally { notesAPI.b64_OSUnlockObject(hErrorText); } } FieldInfo fieldInfo = readCDFieldInfo(pCDField); ValidationPhase phaseEnum = decodeValidationPhase(phase); CWF_Action action; if (callback==null) { action = CWF_Action.CWF_ABORT; } else { action = callback.errorRaised(fieldInfo, phaseEnum, errorTxt, hErrorText); } return action==null ? CWF_Action.CWF_ABORT.getShortVal() : action.getShortVal(); } }; } short result = notesAPI.b64_NSFNoteComputeWithForm(m_hNote64, 0, dwFlags, errorProc, null); NotesErrorUtils.checkResult(result); } else { b32_CWFErrorProc errorProc; if (notesAPI instanceof WinNotesCAPI) { errorProc = new WinNotesCAPI.b32_CWFErrorProcWin() { @Override public short invoke(Pointer pCDField, short phase, short error, int hErrorText, short wErrorTextSize, Pointer ctx) { String errorTxt; if (hErrorText==0) { errorTxt = ""; } else { Pointer errorTextPtr = notesAPI.b32_OSLockObject(hErrorText); try { //TODO find out where this offset 6 comes from errorTxt = NotesStringUtils.fromLMBCS(errorTextPtr.share(6), (wErrorTextSize & 0xffff)-6); } finally { notesAPI.b32_OSUnlockObject(hErrorText); } } FieldInfo fieldInfo = readCDFieldInfo(pCDField); ValidationPhase phaseEnum = decodeValidationPhase(phase); CWF_Action action; if (callback==null) { action = CWF_Action.CWF_ABORT; } else { action = callback.errorRaised(fieldInfo, phaseEnum, errorTxt, hErrorText); } return action==null ? CWF_Action.CWF_ABORT.getShortVal() : action.getShortVal(); } }; } else { errorProc = new b32_CWFErrorProc() { @Override public short invoke(Pointer pCDField, short phase, short error, int hErrorText, short wErrorTextSize, Pointer ctx) { String errorTxt; if (hErrorText==0) { errorTxt = ""; } else { Pointer errorTextPtr = notesAPI.b32_OSLockObject(hErrorText); try { //TODO find out where this offset 6 comes from errorTxt = NotesStringUtils.fromLMBCS(errorTextPtr.share(6), (wErrorTextSize & 0xffff)-6); } finally { notesAPI.b32_OSUnlockObject(hErrorText); } } FieldInfo fieldInfo = readCDFieldInfo(pCDField); ValidationPhase phaseEnum = decodeValidationPhase(phase); CWF_Action action; if (callback==null) { action = CWF_Action.CWF_ABORT; } else { action = callback.errorRaised(fieldInfo, phaseEnum, errorTxt, hErrorText); } return action==null ? CWF_Action.CWF_ABORT.getShortVal() : action.getShortVal(); } }; } short result = notesAPI.b32_NSFNoteComputeWithForm(m_hNote32, 0, dwFlags, errorProc, null); NotesErrorUtils.checkResult(result); } } public static interface ComputeWithFormCallback { public CWF_Action errorRaised(FieldInfo fieldInfo, ValidationPhase phase, String errorTxt, long errCode); } public static enum EncryptionMode { /** Encrypt the message with the key in the user's ID. This flag is not for outgoing mail * messages because recipients, other than the sender, will not be able to decrypt * the message. This flag can be useful to encrypt documents in a local database to * keep them secure or to encrypt documents that can only be decrypted by the same user. */ ENCRYPT_WITH_USER_PUBLIC_KEY (NotesCAPI.ENCRYPT_WITH_USER_PUBLIC_KEY), /** * Encrypt SMIME if MIME present */ ENCRYPT_SMIME_IF_MIME_PRESENT (NotesCAPI.ENCRYPT_SMIME_IF_MIME_PRESENT), /** * Encrypt SMIME no sender. */ ENCRYPT_SMIME_NO_SENDER (NotesCAPI.ENCRYPT_SMIME_NO_SENDER), /** * Encrypt SMIME trusting all certificates. */ ENCRYPT_SMIME_TRUST_ALL_CERTS(NotesCAPI.ENCRYPT_SMIME_TRUST_ALL_CERTS); private int m_mode; private EncryptionMode(int mode) { m_mode = mode; } public int getMode() { return m_mode; } }; /** * This function copies and encrypts (seals) the encryption enabled fields in a note * (including the note's file objects), using the current ID file.<br> * <br> * It can encrypt a note in several ways -- by using the Domino public key of the caller, * by using specified secret encryption keys stored in the caller's ID, or by using the * Domino public keys of specified users, if the note does not have any mime parts.<br> * <br> * The method decides which type of encryption to do based upon the setting of the flag * passed to it in its <code>encryptionMode</code> argument.<br> * <br> * If the {@link EncryptionMode#ENCRYPT_WITH_USER_PUBLIC_KEY} flag is set, it uses the * caller's public ID to encrypt the note.<br> * In this case, only the user who encodes the note can decrypt it.<br> * This feature allows an individual to protect information from anyone else.<br> * <br> * If, instead, the {@link EncryptionMode#ENCRYPT_WITH_USER_PUBLIC_KEY} flag is not set, * then the function expects the note to contain a field named "SecretEncryptionKeys" * a field named "PublicEncryptionKeys", or both.<br> * Each field is either a TYPE_TEXT or TYPE_TEXT_LIST field.<br> * <br> * "SecretEncryptionKeys" contains the name(s) of the secret encryption keys in the * calling user's ID to be used to encrypt the note.<br> * This feature is intended to allow a group to encrypt some of the notes in a single * database in a way that only they can decrypt them -- they must share the secret encryption * keys among themselves first for this to work.<br> * <br> * "PublicEncryptionKeys" contains the name(s) of users, in canonical format.<br> * The note will be encrypted with each user's Domino public key.<br> * The user can then decrypt the note with the private key in the user's ID.<br> * This feature provides a way to encrypt documents, such as mail documents, for another user.<br> * <br> * The note must contain at least one encryption enabled item (an item with the ITEM_SEAL flag set) * in order to be encrypted.<br> * If the note has mime parts and flag {@link EncryptionMode#ENCRYPT_SMIME_IF_MIME_PRESENT} * is set, then it is SMIME encrypted.<br> * <br> * If the document is to be signed as well as encrypted, you must sign the document * before using this method. * @param encryptionMode encryption mode * @return encrypted note copy */ public NotesNote copyAndEncrypt(EnumSet<EncryptionMode> encryptionMode) { return copyAndEncrypt(null, encryptionMode); } /** * This function copies and encrypts (seals) the encryption enabled fields in a note * (including the note's file objects), using a handle to an ID file.<br> * <br> * It can encrypt a note in several ways -- by using the Domino public key of the caller, * by using specified secret encryption keys stored in the caller's ID, or by using the * Domino public keys of specified users, if the note does not have any mime parts.<br> * <br> * The method decides which type of encryption to do based upon the setting of the flag * passed to it in its <code>encryptionMode</code> argument.<br> * <br> * If the {@link EncryptionMode#ENCRYPT_WITH_USER_PUBLIC_KEY} flag is set, it uses the * caller's public ID to encrypt the note.<br> * In this case, only the user who encodes the note can decrypt it.<br> * This feature allows an individual to protect information from anyone else.<br> * <br> * If, instead, the {@link EncryptionMode#ENCRYPT_WITH_USER_PUBLIC_KEY} flag is not set, * then the function expects the note to contain a field named "SecretEncryptionKeys" * a field named "PublicEncryptionKeys", or both.<br> * Each field is either a TYPE_TEXT or TYPE_TEXT_LIST field.<br> * <br> * "SecretEncryptionKeys" contains the name(s) of the secret encryption keys in the * calling user's ID to be used to encrypt the note.<br> * This feature is intended to allow a group to encrypt some of the notes in a single * database in a way that only they can decrypt them -- they must share the secret encryption * keys among themselves first for this to work.<br> * <br> * "PublicEncryptionKeys" contains the name(s) of users, in canonical format.<br> * The note will be encrypted with each user's Domino public key.<br> * The user can then decrypt the note with the private key in the user's ID.<br> * This feature provides a way to encrypt documents, such as mail documents, for another user.<br> * <br> * The note must contain at least one encryption enabled item (an item with the ITEM_SEAL flag set) * in order to be encrypted.<br> * If the note has mime parts and flag {@link EncryptionMode#ENCRYPT_SMIME_IF_MIME_PRESENT} * is set, then it is SMIME encrypted.<br> * <br> * If the document is to be signed as well as encrypted, you must sign the document * before using this method. * @param id user id to be used for encryption, use null for current id * @param encryptionMode encryption mode * @return encrypted note copy */ public NotesNote copyAndEncrypt(NotesUserId id, EnumSet<EncryptionMode> encryptionMode) { checkHandle(); NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); int flags = 0; for (EncryptionMode currMode : encryptionMode) { flags = flags | currMode.getMode(); } short flagsShort = (short) (flags & 0xffff); short result; if (NotesJNAContext.is64Bit()) { LongByReference rethDstNote = new LongByReference(); result = notesAPI.b64_NSFNoteCopyAndEncryptExt2(m_hNote64, id==null ? 0 : id.getHandle64(), flagsShort, rethDstNote, 0, null); NotesErrorUtils.checkResult(result); NotesNote copyNote = new NotesNote(m_parentDb, rethDstNote.getValue()); NotesGC.__objectCreated(NotesNote.class, copyNote); return copyNote; } else { IntByReference rethDstNote = new IntByReference(); result = notesAPI.b32_NSFNoteCopyAndEncryptExt2(m_hNote32, id==null ? 0 : id.getHandle32(), flagsShort, rethDstNote, 0, null); NotesErrorUtils.checkResult(result); NotesNote copyNote = new NotesNote(m_parentDb, rethDstNote.getValue()); NotesGC.__objectCreated(NotesNote.class, copyNote); return copyNote; } } public NotesNote copyToDatabase(NotesDatabase targetDb) { checkHandle(); if (targetDb.isRecycled()) { throw new NotesError(0, "Target database already recycled"); } NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); if (NotesJNAContext.is64Bit()) { LongByReference note_handle_dst = new LongByReference(); short result = notesAPI.b64_NSFNoteCopy(m_hNote64, note_handle_dst); NotesErrorUtils.checkResult(result); NotesNote copyNote = new NotesNote(targetDb, note_handle_dst.getValue()); NotesOriginatorId newOid = targetDb.generateOID(); NotesOriginatorIdStruct newOidStruct = newOid.getAdapter(NotesOriginatorIdStruct.class); notesAPI.b64_NSFNoteSetInfo(copyNote.getHandle64(), NotesCAPI._NOTE_ID, null); notesAPI.b64_NSFNoteSetInfo(copyNote.getHandle64(), NotesCAPI._NOTE_OID, newOidStruct.getPointer()); LongByReference targetDbHandle = new LongByReference(); targetDbHandle.setValue(targetDb.getHandle64()); notesAPI.b64_NSFNoteSetInfo(copyNote.getHandle64(), NotesCAPI._NOTE_DB, targetDbHandle.getPointer()); NotesGC.__objectCreated(NotesNote.class, copyNote); return copyNote; } else { IntByReference note_handle_dst = new IntByReference(); short result = notesAPI.b32_NSFNoteCopy(m_hNote32, note_handle_dst); NotesErrorUtils.checkResult(result); NotesNote copyNote = new NotesNote(targetDb, note_handle_dst.getValue()); NotesOriginatorId newOid = targetDb.generateOID(); NotesOriginatorIdStruct newOidStruct = newOid.getAdapter(NotesOriginatorIdStruct.class); notesAPI.b32_NSFNoteSetInfo(copyNote.getHandle32(), NotesCAPI._NOTE_ID, null); notesAPI.b32_NSFNoteSetInfo(copyNote.getHandle32(), NotesCAPI._NOTE_OID, newOidStruct.getPointer()); IntByReference targetDbHandle = new IntByReference(); targetDbHandle.setValue(targetDb.getHandle32()); notesAPI.b32_NSFNoteSetInfo(copyNote.getHandle32(), NotesCAPI._NOTE_DB, targetDbHandle.getPointer()); NotesGC.__objectCreated(NotesNote.class, copyNote); return copyNote; } } /** * This function decrypts an encrypted note, using the current user's ID file.<br> * If the user does not have the appropriate encryption key to decrypt the note, an error is returned.<br> * <br> * This function supports new cryptographic keys and algorithms introduced in Release 8.0.1 as * well as any from releases prior to 8.0.1. * <br> * The current implementation of this function automatically decrypts attachments as well. */ public void decrypt() { decrypt(null); } /** * This function decrypts an encrypted note, using the appropriate encryption key stored * in the user's ID file.<br> * If the user does not have the appropriate encryption key to decrypt the note, an error is returned.<br> * <br> * This function supports new cryptographic keys and algorithms introduced in Release 8.0.1 as * well as any from releases prior to 8.0.1. * <br> * The current implementation of this function automatically decrypts attachments as well. * * @param id user id used for decryption, use null for current id */ public void decrypt(NotesUserId id) { checkHandle(); NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); short decryptFlags = NotesCAPI.DECRYPT_ATTACHMENTS_IN_PLACE; short result; if (NotesJNAContext.is64Bit()) { result = notesAPI.b64_NSFNoteCipherDecrypt(m_hNote64, id==null ? 0 : id.getHandle64(), decryptFlags, null, 0, null); } else { result = notesAPI.b32_NSFNoteCipherDecrypt(m_hNote32, id==null ? 0 : id.getHandle32(), decryptFlags, null, 0, null); } NotesErrorUtils.checkResult(result); } /** * Removes any existing field with the specified name and creates a new one with the specified value, setting the {@link ItemType#SUMMARY}<br> * We support the following value types: * <ul> * <li>String and List&lt;String&gt; (max. 65535 entries)</li> * <li>Double, double, Integer, int, Long, long, Float, float for numbers (will all be converted to double, because that's how Domino stores them)</li> * <li>{@link List} of number types for multiple numbers (max. 65535 entries)</li> * <li>Double[], double[], Integer[], int[], Long[], long[], Float[], float[] with 2 elements (lower/upper) for number ranges (will all be converted to double, because that's how Domino stores them)</li> * <li>{@link List} of number range types for multiple number ranges</li> * <li>Calendar, Date, NotesTimeDate</li> * <li>{@link List} of date types for multiple dates</li> * <li>Calendar[], Date[], NotesTimeDate[] with 2 elements (lower/upper) for date ranges</li> * <li>{@link List} of date range types for multiple date ranges (max. 65535 entries)</li> * </ul> * * @param itemName item name * @param value item value, see method comment for allowed types * @return created item */ public NotesItem replaceItemValue(String itemName, Object value) { return replaceItemValue(itemName, EnumSet.of(ItemType.SUMMARY), value); } /** * Removes any existing field with the specified name and creates a new one with the specified value.<br> * We support the following value types: * <ul> * <li>String and List&lt;String&gt; (max. 65535 entries)</li> * <li>Double, double, Integer, int, Long, long, Float, float for numbers (will all be converted to double, because that's how Domino stores them)</li> * <li>{@link List} of number types for multiple numbers (max. 65535 entries)</li> * <li>Double[], double[], Integer[], int[], Long[], long[], Float[], float[] with 2 elements (lower/upper) for number ranges (will all be converted to double, because that's how Domino stores them)</li> * <li>{@link List} of number range types for multiple number ranges</li> * <li>Calendar, Date, NotesTimeDate</li> * <li>{@link List} of date types for multiple dates</li> * <li>Calendar[], Date[], NotesTimeDate[] with 2 elements (lower/upper) for date ranges</li> * <li>{@link List} of date range types for multiple date ranges (max. 65535 entries)</li> * </ul> * * @param itemName item name * @param flags item flags, e.g. {@link ItemType#SUMMARY} * @param value item value, see method comment for allowed types * @return created item */ public NotesItem replaceItemValue(String itemName, EnumSet<ItemType> flags, Object value) { if (!hasSupportedItemObjectType(value)) { throw new IllegalArgumentException("Unsupported value type: "+(value==null ? "null" : value.getClass().getName())); } while (hasItem(itemName)) { removeItem(itemName); } return appendItemValue(itemName, flags, value); } @SuppressWarnings("rawtypes") private boolean hasSupportedItemObjectType(Object value) { if (value instanceof String) { return true; } else if (value instanceof Number) { return true; } else if (value instanceof Calendar || value instanceof NotesTimeDate || value instanceof Date) { return true; } else if (value instanceof List && ((List)value).isEmpty()) { return true; } else if (value instanceof List && isStringList((List) value)) { return true; } else if (value instanceof List && isNumberOrNumberArrayList((List) value)) { return true; } else if (value instanceof List && isCalendarOrCalendarArrayList((List) value)) { return true; } else if (value instanceof Calendar[] && ((Calendar[])value).length==2) { return true; } else if (value instanceof NotesTimeDate[] && ((NotesTimeDate[])value).length==2) { return true; } else if (value instanceof Date[] && ((Date[])value).length==2) { return true; } else if (value instanceof Number[] && ((Number[])value).length==2) { return true; } else if (value instanceof Double[] && ((Double[])value).length==2) { return true; } else if (value instanceof Integer[] && ((Integer[])value).length==2) { return true; } else if (value instanceof Long[] && ((Long[])value).length==2) { return true; } else if (value instanceof Float[] && ((Float[])value).length==2) { return true; } else if (value instanceof double[] && ((double[])value).length==2) { return true; } else if (value instanceof int[] && ((int[])value).length==2) { return true; } else if (value instanceof long[] && ((long[])value).length==2) { return true; } else if (value instanceof float[] && ((float[])value).length==2) { return true; } else if (value instanceof NotesUniversalNoteId) { return true; } return false; } /** * Creates a new item with the specified value, setting the {@link ItemType#SUMMARY} (does not overwrite items with the same name)<br> * We support the following value types: * <ul> * <li>String and List&lt;String&gt; (max. 65535 entries)</li> * <li>Double, double, Integer, int, Long, long, Float, float for numbers (will all be converted to double, because that's how Domino stores them)</li> * <li>{@link List} of number types for multiple numbers (max. 65535 entries)</li> * <li>Double[], double[], Integer[], int[], Long[], long[], Float[], float[] with 2 elements (lower/upper) for number ranges (will all be converted to double, because that's how Domino stores them)</li> * <li>{@link List} of number range types for multiple number ranges</li> * <li>Calendar, Date, NotesTimeDate</li> * <li>{@link List} of date types for multiple dates</li> * <li>Calendar[], Date[], NotesTimeDate[] with 2 elements (lower/upper) for date ranges</li> * <li>{@link List} of date range types for multiple date ranges (max. 65535 entries)</li> * </ul> * * @param itemName item name * @param value item value, see method comment for allowed types * @return created item */ public NotesItem appendItemValue(String itemName, Object value) { return appendItemValue(itemName, EnumSet.of(ItemType.SUMMARY), value); } /** * Creates a new item with the specified item flags and value<br> * We support the following value types: * <ul> * <li>String and List&lt;String&gt; (max. 65535 entries)</li> * <li>Double, double, Integer, int, Long, long, Float, float for numbers (will all be converted to double, because that's how Domino stores them)</li> * <li>{@link List} of number types for multiple numbers (max. 65535 entries)</li> * <li>Double[], double[], Integer[], int[], Long[], long[], Float[], float[] with 2 elements (lower/upper) for number ranges (will all be converted to double, because that's how Domino stores them)</li> * <li>{@link List} of number range types for multiple number ranges</li> * <li>Calendar, Date, NotesTimeDate</li> * <li>{@link List} of date types for multiple dates</li> * <li>Calendar[], Date[], NotesTimeDate[] with 2 elements (lower/upper) for date ranges</li> * <li>{@link List} of date range types for multiple date ranges (max. 65535 entries)</li> * <li>{@link NotesUniversalNoteId} for $REF like items</li> * </ul> * * @param itemName item name * @param flags item flags * @param value item value, see method comment for allowed types * @return created item */ public NotesItem appendItemValue(String itemName, EnumSet<ItemType> flags, Object value) { checkHandle(); NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); if (value instanceof String) { Memory strValueMem = NotesStringUtils.toLMBCS((String)value, false); int valueSize = (int) (2 + (strValueMem==null ? 0 : strValueMem.size())); if (NotesJNAContext.is64Bit()) { LongByReference rethItem = new LongByReference(); short result = notesAPI.b64_OSMemAlloc((short) 0, valueSize, rethItem); NotesErrorUtils.checkResult(result); Pointer valuePtr = notesAPI.b64_OSLockObject(rethItem.getValue()); try { valuePtr.setShort(0, (short) NotesItem.TYPE_TEXT); valuePtr = valuePtr.share(2); if (strValueMem!=null) { valuePtr.write(0, strValueMem.getByteArray(0, (int) strValueMem.size()), 0, (int) strValueMem.size()); } NotesItem item = appendItemValue(itemName, flags, NotesItem.TYPE_TEXT, (int) rethItem.getValue(), valueSize); return item; } finally { notesAPI.b64_OSUnlockObject(rethItem.getValue()); } } else { IntByReference rethItem = new IntByReference(); short result = notesAPI.b32_OSMemAlloc((short) 0, valueSize, rethItem); NotesErrorUtils.checkResult(result); Pointer valuePtr = notesAPI.b32_OSLockObject(rethItem.getValue()); try { valuePtr.setShort(0, (short) NotesItem.TYPE_TEXT); valuePtr = valuePtr.share(2); if (strValueMem!=null) { valuePtr.write(0, strValueMem.getByteArray(0, (int) strValueMem.size()), 0, (int) strValueMem.size()); } NotesItem item = appendItemValue(itemName, flags, NotesItem.TYPE_TEXT, rethItem.getValue(), valueSize); return item; } finally { notesAPI.b32_OSUnlockObject(rethItem.getValue()); } } } else if (value instanceof Number) { int valueSize = 2 + 8; if (NotesJNAContext.is64Bit()) { LongByReference rethItem = new LongByReference(); short result = notesAPI.b64_OSMemAlloc((short) 0, valueSize, rethItem); NotesErrorUtils.checkResult(result); Pointer valuePtr = notesAPI.b64_OSLockObject(rethItem.getValue()); try { valuePtr.setShort(0, (short) NotesItem.TYPE_NUMBER); valuePtr = valuePtr.share(2); valuePtr.setDouble(0, ((Number)value).doubleValue()); NotesItem item = appendItemValue(itemName, flags, NotesItem.TYPE_NUMBER, (int) rethItem.getValue(), valueSize); return item; } finally { notesAPI.b64_OSUnlockObject(rethItem.getValue()); } } else { IntByReference rethItem = new IntByReference(); short result = notesAPI.b32_OSMemAlloc((short) 0, valueSize, rethItem); NotesErrorUtils.checkResult(result); Pointer valuePtr = notesAPI.b32_OSLockObject(rethItem.getValue()); try { valuePtr.setShort(0, (short) NotesItem.TYPE_NUMBER); valuePtr = valuePtr.share(2); valuePtr.setDouble(0, ((Number)value).doubleValue()); NotesItem item = appendItemValue(itemName, flags, NotesItem.TYPE_NUMBER, rethItem.getValue(), valueSize); return item; } finally { notesAPI.b32_OSUnlockObject(rethItem.getValue()); } } } else if (value instanceof Calendar || value instanceof NotesTimeDate || value instanceof Date) { Calendar calValue; if (value instanceof Calendar) { calValue = (Calendar) value; } else if (value instanceof NotesTimeDate) { calValue = ((NotesTimeDate)value).getTimeAsCalendar(); } else if (value instanceof Date) { calValue = Calendar.getInstance(); calValue.setTime((Date) value); } else { throw new IllegalArgumentException("Unsupported date value type: "+(value==null ? "null" : value.getClass().getName())); } boolean hasDate = NotesDateTimeUtils.hasDate(calValue); boolean hasTime = NotesDateTimeUtils.hasTime(calValue); int[] innards = NotesDateTimeUtils.calendarToInnards(calValue, hasDate, hasTime); int valueSize = 2 + 8; if (NotesJNAContext.is64Bit()) { LongByReference rethItem = new LongByReference(); short result = notesAPI.b64_OSMemAlloc((short) 0, valueSize, rethItem); NotesErrorUtils.checkResult(result); Pointer valuePtr = notesAPI.b64_OSLockObject(rethItem.getValue()); try { valuePtr.setShort(0, (short) NotesItem.TYPE_TIME); valuePtr = valuePtr.share(2); NotesTimeDateStruct timeDate = NotesTimeDateStruct.newInstance(valuePtr); timeDate.Innards[0] = innards[0]; timeDate.Innards[1] = innards[1]; timeDate.write(); NotesItem item = appendItemValue(itemName, flags, NotesItem.TYPE_TIME, (int) rethItem.getValue(), valueSize); return item; } finally { notesAPI.b64_OSUnlockObject(rethItem.getValue()); } } else { IntByReference rethItem = new IntByReference(); short result = notesAPI.b32_OSMemAlloc((short) 0, valueSize, rethItem); NotesErrorUtils.checkResult(result); Pointer valuePtr = notesAPI.b32_OSLockObject(rethItem.getValue()); try { valuePtr.setShort(0, (short) NotesItem.TYPE_TIME); valuePtr = valuePtr.share(2); NotesTimeDateStruct timeDate = NotesTimeDateStruct.newInstance(valuePtr); timeDate.Innards[0] = innards[0]; timeDate.Innards[1] = innards[1]; timeDate.write(); NotesItem item = appendItemValue(itemName, flags, NotesItem.TYPE_TIME, rethItem.getValue(), valueSize); return item; } finally { notesAPI.b32_OSUnlockObject(rethItem.getValue()); } } } else if (value instanceof List && (((List)value).isEmpty() || isStringList((List) value))) { List<String> strList = (List<String>) value; if (strList.size()> 65535) { throw new IllegalArgumentException("String list size must fit in a WORD ("+strList.size()+">65535)"); } short result; if (NotesJNAContext.is64Bit()) { LongByReference rethList = new LongByReference(); ShortByReference retListSize = new ShortByReference(); result = notesAPI.b64_ListAllocate((short) 0, (short) 0, 1, rethList, null, retListSize); NotesErrorUtils.checkResult(result); long hList = rethList.getValue(); notesAPI.b64_OSUnlockObject(hList); for (int i=0; i<strList.size(); i++) { String currStr = strList.get(i); Memory currStrMem = NotesStringUtils.toLMBCS(currStr, false); result = notesAPI.b64_ListAddEntry(hList, 1, retListSize, (short) (i & 0xffff), currStrMem, (short) (currStrMem==null ? 0 : (currStrMem.size() & 0xffff))); NotesErrorUtils.checkResult(result); } int listSize = retListSize.getValue() & 0xffff; @SuppressWarnings("unused") Pointer valuePtr = notesAPI.b64_OSLockObject(hList); try { NotesItem item = appendItemValue(itemName, flags, NotesItem.TYPE_TEXT_LIST, (int) hList, listSize); return item; } finally { notesAPI.b64_OSUnlockObject(hList); } } else { IntByReference rethList = new IntByReference(); ShortByReference retListSize = new ShortByReference(); result = notesAPI.b32_ListAllocate((short) 0, (short) 0, 1, rethList, null, retListSize); NotesErrorUtils.checkResult(result); int hList = rethList.getValue(); notesAPI.b32_OSUnlockObject(hList); for (int i=0; i<strList.size(); i++) { String currStr = strList.get(i); Memory currStrMem = NotesStringUtils.toLMBCS(currStr, false); result = notesAPI.b32_ListAddEntry(hList, 1, retListSize, (short) (i & 0xffff), currStrMem, (short) (currStrMem==null ? 0 : (currStrMem.size() & 0xffff))); NotesErrorUtils.checkResult(result); } int listSize = retListSize.getValue() & 0xffff; @SuppressWarnings("unused") Pointer valuePtr = notesAPI.b32_OSLockObject(hList); try { NotesItem item = appendItemValue(itemName, flags, NotesItem.TYPE_TEXT_LIST, (int) hList, listSize); return item; } finally { notesAPI.b32_OSUnlockObject(hList); } } } else if (value instanceof List && isNumberOrNumberArrayList((List) value)) { List<?> numberOrNumberArrList = toNumberOrNumberArrayList((List<?>) value); List<Number> numberList = new ArrayList<Number>(); List<double[]> numberArrList = new ArrayList<double[]>(); for (int i=0; i<numberOrNumberArrList.size(); i++) { Object currObj = numberOrNumberArrList.get(i); if (currObj instanceof Double) { numberList.add((Number) currObj); } else if (currObj instanceof double[]) { numberArrList.add((double[])currObj); } } if (numberList.size()> 65535) { throw new IllegalArgumentException("Number list size must fit in a WORD ("+numberList.size()+">65535)"); } if (numberArrList.size()> 65535) { throw new IllegalArgumentException("Number range list size must fit in a WORD ("+numberList.size()+">65535)"); } int valueSize = 2 + NotesCAPI.rangeSize + 8 * numberList.size() + NotesCAPI.numberPairSize * numberArrList.size(); if (NotesJNAContext.is64Bit()) { LongByReference rethItem = new LongByReference(); short result = notesAPI.b64_OSMemAlloc((short) 0, valueSize, rethItem); NotesErrorUtils.checkResult(result); Pointer valuePtr = notesAPI.b64_OSLockObject(rethItem.getValue()); try { valuePtr.setShort(0, (short) NotesItem.TYPE_NUMBER_RANGE); valuePtr = valuePtr.share(2); Pointer rangePtr = valuePtr; NotesRangeStruct range = NotesRangeStruct.newInstance(rangePtr); range.ListEntries = (short) (numberList.size() & 0xffff); range.RangeEntries = (short) (numberArrList.size() & 0xffff); range.write(); Pointer doubleListPtr = rangePtr.share(NotesCAPI.rangeSize); for (int i=0; i<numberList.size(); i++) { doubleListPtr.setDouble(0, numberList.get(i).doubleValue()); doubleListPtr = doubleListPtr.share(8); } Pointer doubleArrListPtr = doubleListPtr; for (int i=0; i<numberArrList.size(); i++) { double[] currNumberArr = numberArrList.get(i); NotesNumberPairStruct numberPair = NotesNumberPairStruct.newInstance(doubleArrListPtr); numberPair.Lower = currNumberArr[0]; numberPair.Upper = currNumberArr[1]; numberPair.write(); doubleArrListPtr = doubleArrListPtr.share(NotesCAPI.numberPairSize); } NotesItem item = appendItemValue(itemName, flags, NotesItem.TYPE_NUMBER_RANGE, (int) rethItem.getValue(), valueSize); return item; } finally { notesAPI.b64_OSUnlockObject(rethItem.getValue()); } } else { IntByReference rethItem = new IntByReference(); short result = notesAPI.b32_OSMemAlloc((short) 0, valueSize, rethItem); NotesErrorUtils.checkResult(result); Pointer valuePtr = notesAPI.b32_OSLockObject(rethItem.getValue()); try { valuePtr.setShort(0, (short) NotesItem.TYPE_NUMBER_RANGE); valuePtr = valuePtr.share(2); Pointer rangePtr = valuePtr; NotesRangeStruct range = NotesRangeStruct.newInstance(rangePtr); range.ListEntries = (short) (numberList.size() & 0xffff); range.RangeEntries = (short) (numberArrList.size() & 0xffff); range.write(); Pointer doubleListPtr = rangePtr.share(NotesCAPI.rangeSize); for (int i=0; i<numberList.size(); i++) { doubleListPtr.setDouble(0, numberList.get(i).doubleValue()); doubleListPtr = doubleListPtr.share(8); } Pointer doubleArrListPtr = doubleListPtr; for (int i=0; i<numberArrList.size(); i++) { double[] currNumberArr = numberArrList.get(i); NotesNumberPairStruct numberPair = NotesNumberPairStruct.newInstance(doubleArrListPtr); numberPair.Lower = currNumberArr[0]; numberPair.Upper = currNumberArr[1]; numberPair.write(); doubleArrListPtr = doubleArrListPtr.share(NotesCAPI.numberPairSize); } NotesItem item = appendItemValue(itemName, flags, NotesItem.TYPE_NUMBER_RANGE, rethItem.getValue(), valueSize); return item; } finally { notesAPI.b32_OSUnlockObject(rethItem.getValue()); } } } else if (value instanceof Calendar[]) { return appendItemValue(itemName, flags, Arrays.asList(value)); } else if (value instanceof Date[]) { return appendItemValue(itemName, flags, Arrays.asList(value)); } else if (value instanceof NotesTimeDate[]) { return appendItemValue(itemName, flags, Arrays.asList(value)); } else if (value instanceof List && isCalendarOrCalendarArrayList((List) value)) { List<?> calendarOrCalendarArrList = toCalendarOrCalendarArrayList((List<?>) value); List<Calendar> calendarList = new ArrayList<Calendar>(); List<Calendar[]> calendarArrList = new ArrayList<Calendar[]>(); for (int i=0; i<calendarOrCalendarArrList.size(); i++) { Object currObj = calendarOrCalendarArrList.get(i); if (currObj instanceof Calendar) { calendarList.add((Calendar) currObj); } else if (currObj instanceof Calendar[]) { calendarArrList.add((Calendar[]) currObj); } } if (calendarList.size() > 65535) { throw new IllegalArgumentException("Date list size must fit in a WORD ("+calendarList.size()+">65535)"); } if (calendarArrList.size() > 65535) { throw new IllegalArgumentException("Date range list size must fit in a WORD ("+calendarArrList.size()+">65535)"); } int valueSize = 2 + NotesCAPI.rangeSize + 8 * calendarList.size() + NotesCAPI.timeDatePairSize * calendarArrList.size(); if (NotesJNAContext.is64Bit()) { LongByReference rethItem = new LongByReference(); short result = notesAPI.b64_OSMemAlloc((short) 0, valueSize, rethItem); NotesErrorUtils.checkResult(result); Pointer valuePtr = notesAPI.b64_OSLockObject(rethItem.getValue()); try { valuePtr.setShort(0, (short) NotesItem.TYPE_TIME_RANGE); valuePtr = valuePtr.share(2); Pointer rangePtr = valuePtr; NotesRangeStruct range = NotesRangeStruct.newInstance(rangePtr); range.ListEntries = (short) (calendarList.size() & 0xffff); range.RangeEntries = (short) (calendarArrList.size() & 0xffff); range.write(); Pointer dateListPtr = rangePtr.share(NotesCAPI.rangeSize); for (Calendar currCal : calendarList) { boolean hasDate = NotesDateTimeUtils.hasDate(currCal); boolean hasTime = NotesDateTimeUtils.hasTime(currCal); int[] innards = NotesDateTimeUtils.calendarToInnards(currCal, hasDate, hasTime); dateListPtr.setInt(0, innards[0]); dateListPtr = dateListPtr.share(4); dateListPtr.setInt(0, innards[1]); dateListPtr = dateListPtr.share(4); } Pointer rangeListPtr = dateListPtr; for (int i=0; i<calendarArrList.size(); i++) { Calendar[] currRangeVal = calendarArrList.get(i); boolean hasDateStart = NotesDateTimeUtils.hasDate(currRangeVal[0]); boolean hasTimeStart = NotesDateTimeUtils.hasTime(currRangeVal[0]); int[] innardsStart = NotesDateTimeUtils.calendarToInnards(currRangeVal[0], hasDateStart, hasTimeStart); boolean hasDateEnd = NotesDateTimeUtils.hasDate(currRangeVal[1]); boolean hasTimeEnd = NotesDateTimeUtils.hasTime(currRangeVal[1]); int[] innardsEnd = NotesDateTimeUtils.calendarToInnards(currRangeVal[1], hasDateEnd, hasTimeEnd); NotesTimeDateStruct timeDateStart = NotesTimeDateStruct.newInstance(innardsStart); NotesTimeDateStruct timeDateEnd = NotesTimeDateStruct.newInstance(innardsEnd); NotesTimeDatePairStruct timeDatePair = NotesTimeDatePairStruct.newInstance(rangeListPtr); timeDatePair.Lower = timeDateStart; timeDatePair.Upper = timeDateEnd; timeDatePair.write(); rangeListPtr = rangeListPtr.share(NotesCAPI.timeDatePairSize); } NotesItem item = appendItemValue(itemName, flags, NotesItem.TYPE_TIME_RANGE, (int) rethItem.getValue(), valueSize); return item; } finally { notesAPI.b64_OSUnlockObject(rethItem.getValue()); } } else { IntByReference rethItem = new IntByReference(); short result = notesAPI.b32_OSMemAlloc((short) 0, valueSize, rethItem); NotesErrorUtils.checkResult(result); Pointer valuePtr = notesAPI.b32_OSLockObject(rethItem.getValue()); try { valuePtr.setShort(0, (short) NotesItem.TYPE_TIME_RANGE); valuePtr = valuePtr.share(2); Pointer rangePtr = valuePtr; NotesRangeStruct range = NotesRangeStruct.newInstance(rangePtr); range.ListEntries = (short) (calendarList.size() & 0xffff); range.RangeEntries = (short) (calendarArrList.size() & 0xffff); range.write(); Pointer dateListPtr = rangePtr.share(NotesCAPI.rangeSize); for (Calendar currCal : calendarList) { boolean hasDate = NotesDateTimeUtils.hasDate(currCal); boolean hasTime = NotesDateTimeUtils.hasTime(currCal); int[] innards = NotesDateTimeUtils.calendarToInnards(currCal, hasDate, hasTime); dateListPtr.setInt(0, innards[0]); dateListPtr = dateListPtr.share(4); dateListPtr.setInt(0, innards[1]); dateListPtr = dateListPtr.share(4); } Pointer rangeListPtr = dateListPtr; for (int i=0; i<calendarArrList.size(); i++) { Calendar[] currRangeVal = calendarArrList.get(i); boolean hasDateStart = NotesDateTimeUtils.hasDate(currRangeVal[0]); boolean hasTimeStart = NotesDateTimeUtils.hasTime(currRangeVal[0]); int[] innardsStart = NotesDateTimeUtils.calendarToInnards(currRangeVal[0], hasDateStart, hasTimeStart); boolean hasDateEnd = NotesDateTimeUtils.hasDate(currRangeVal[1]); boolean hasTimeEnd = NotesDateTimeUtils.hasTime(currRangeVal[1]); int[] innardsEnd = NotesDateTimeUtils.calendarToInnards(currRangeVal[1], hasDateEnd, hasTimeEnd); NotesTimeDateStruct timeDateStart = NotesTimeDateStruct.newInstance(innardsStart); NotesTimeDateStruct timeDateEnd = NotesTimeDateStruct.newInstance(innardsEnd); NotesTimeDatePairStruct timeDatePair = NotesTimeDatePairStruct.newInstance(rangeListPtr); timeDatePair.Lower = timeDateStart; timeDatePair.Upper = timeDateEnd; timeDatePair.write(); rangeListPtr = rangeListPtr.share(NotesCAPI.timeDatePairSize); } NotesItem item = appendItemValue(itemName, flags, NotesItem.TYPE_TIME_RANGE, (int) rethItem.getValue(), valueSize); return item; } finally { notesAPI.b32_OSUnlockObject(rethItem.getValue()); } } } else if (value instanceof double[]) { return appendItemValue(itemName, flags, Arrays.asList(value)); } else if (value instanceof int[]) { return appendItemValue(itemName, flags, Arrays.asList(value)); } else if (value instanceof float[]) { return appendItemValue(itemName, flags, Arrays.asList(value)); } else if (value instanceof long[]) { return appendItemValue(itemName, flags, Arrays.asList(value)); } else if (value instanceof Number[]) { return appendItemValue(itemName, flags, Arrays.asList(value)); } else if (value instanceof Double[]) { return appendItemValue(itemName, flags, Arrays.asList(value)); } else if (value instanceof Integer[]) { return appendItemValue(itemName, flags, Arrays.asList(value)); } else if (value instanceof Float[]) { return appendItemValue(itemName, flags, Arrays.asList(value)); } else if (value instanceof Long[]) { return appendItemValue(itemName, flags, Arrays.asList(value)); } else if (value instanceof NotesUniversalNoteId) { NotesUniversalNoteIdStruct struct = ((NotesUniversalNoteId)value).getAdapter(NotesUniversalNoteIdStruct.class); //date type + LIST structure + UNIVERSALNOTEID int valueSize = 2 + 2 + 2 * NotesCAPI.timeDateSize; if (NotesJNAContext.is64Bit()) { LongByReference rethItem = new LongByReference(); short result = notesAPI.b64_OSMemAlloc((short) 0, valueSize, rethItem); NotesErrorUtils.checkResult(result); Pointer valuePtr = notesAPI.b64_OSLockObject(rethItem.getValue()); try { valuePtr.setShort(0, (short) NotesItem.TYPE_NOTEREF_LIST); valuePtr = valuePtr.share(2); //LIST structure valuePtr.setShort(0, (short) 1); valuePtr = valuePtr.share(2); struct.write(); valuePtr.write(0, struct.getAdapter(Pointer.class).getByteArray(0, 2*NotesCAPI.timeDateSize), 0, 2*NotesCAPI.timeDateSize); NotesItem item = appendItemValue(itemName, flags, NotesItem.TYPE_NOTEREF_LIST, (int) rethItem.getValue(), valueSize); return item; } finally { notesAPI.b64_OSUnlockObject(rethItem.getValue()); } } else { IntByReference rethItem = new IntByReference(); short result = notesAPI.b32_OSMemAlloc((short) 0, valueSize, rethItem); NotesErrorUtils.checkResult(result); Pointer valuePtr = notesAPI.b32_OSLockObject(rethItem.getValue()); try { valuePtr.setShort(0, (short) NotesItem.TYPE_NOTEREF_LIST); valuePtr = valuePtr.share(2); //LIST structure valuePtr.setShort(0, (short) 1); valuePtr = valuePtr.share(2); struct.write(); valuePtr.write(0, struct.getAdapter(Pointer.class).getByteArray(0, 2*NotesCAPI.timeDateSize), 0, 2*NotesCAPI.timeDateSize); NotesItem item = appendItemValue(itemName, flags, NotesItem.TYPE_NOTEREF_LIST, (int) rethItem.getValue(), valueSize); return item; } finally { notesAPI.b32_OSUnlockObject(rethItem.getValue()); } } } else { throw new IllegalArgumentException("Unsupported value type: "+(value==null ? "null" : value.getClass().getName())); } } private List<?> toNumberOrNumberArrayList(List<?> list) { boolean allNumbers = true; for (int i=0; i<list.size(); i++) { if (!(list.get(i) instanceof double[]) && !(list.get(i) instanceof Double)) { allNumbers = false; break; } } if (allNumbers) return (List<?>) list; List convertedList = new ArrayList(); for (int i=0; i<list.size(); i++) { if (list.get(i) instanceof Number) { convertedList.add(((Number)list.get(i)).doubleValue()); } else if (list.get(i) instanceof double[]) { if (((double[])list.get(i)).length!=2) { throw new IllegalArgumentException("Length of double array entry must be 2 for number ranges"); } convertedList.add((double[]) list.get(i)); } else if (list.get(i) instanceof Number[]) { Number[] numberArr = (Number[]) list.get(i); if (numberArr.length!=2) { throw new IllegalArgumentException("Length of Number array entry must be 2 for number ranges"); } convertedList.add(new double[] { numberArr[0].doubleValue(), numberArr[1].doubleValue() }); } else if (list.get(i) instanceof Double[]) { Double[] doubleArr = (Double[]) list.get(i); if (doubleArr.length!=2) { throw new IllegalArgumentException("Length of Number array entry must be 2 for number ranges"); } convertedList.add(new double[] { doubleArr[0], doubleArr[1] }); } else if (list.get(i) instanceof Integer[]) { Integer[] integerArr = (Integer[]) list.get(i); if (integerArr.length!=2) { throw new IllegalArgumentException("Length of Integer array entry must be 2 for number ranges"); } convertedList.add(new double[] { integerArr[0].doubleValue(), integerArr[1].doubleValue() }); } else if (list.get(i) instanceof Long[]) { Long[] longArr = (Long[]) list.get(i); if (longArr.length!=2) { throw new IllegalArgumentException("Length of Long array entry must be 2 for number ranges"); } convertedList.add(new double[] { longArr[0].doubleValue(), longArr[1].doubleValue() }); } else if (list.get(i) instanceof Float[]) { Float[] floatArr = (Float[]) list.get(i); if (floatArr.length!=2) { throw new IllegalArgumentException("Length of Float array entry must be 2 for number ranges"); } convertedList.add(new double[] { floatArr[0].doubleValue(), floatArr[1].doubleValue() }); } else if (list.get(i) instanceof int[]) { int[] intArr = (int[]) list.get(i); if (intArr.length!=2) { throw new IllegalArgumentException("Length of int array entry must be 2 for number ranges"); } convertedList.add(new double[] { intArr[0], intArr[1] }); } else if (list.get(i) instanceof long[]) { long[] longArr = (long[]) list.get(i); if (longArr.length!=2) { throw new IllegalArgumentException("Length of long array entry must be 2 for number ranges"); } convertedList.add(new double[] { longArr[0], longArr[1] }); } else if (list.get(i) instanceof float[]) { float[] floatArr = (float[]) list.get(i); if (floatArr.length!=2) { throw new IllegalArgumentException("Length of float array entry must be 2 for number ranges"); } convertedList.add(new double[] { floatArr[0], floatArr[1] }); } else { throw new IllegalArgumentException("Unsupported date format found in list: "+(list.get(i)==null ? "null" : list.get(i).getClass().getName())); } } return convertedList; } private List<?> toCalendarOrCalendarArrayList(List<?> list) { boolean allCalendar = true; for (int i=0; i<list.size(); i++) { if (!(list.get(i) instanceof Calendar[]) && !(list.get(i) instanceof Calendar)) { allCalendar = false; break; } } if (allCalendar) return (List<?>) list; List convertedList = new ArrayList(); for (int i=0; i<list.size(); i++) { if (list.get(i) instanceof Calendar) { convertedList.add(list.get(i)); } else if (list.get(i) instanceof Calendar[]) { convertedList.add((Calendar[]) list.get(i)); } else if (list.get(i) instanceof Date) { Calendar cal = Calendar.getInstance(); cal.setTime((Date) list.get(i)); convertedList.add(cal); } else if (list.get(i) instanceof NotesTimeDate) { Calendar cal = ((NotesTimeDate)list.get(i)).toCalendar(); convertedList.add(cal); } else if (list.get(i) instanceof Date[]) { Date[] dateArr = (Date[]) list.get(i); if (dateArr.length!=2) { throw new IllegalArgumentException("Length of Date array entry must be 2 for date ranges"); } Calendar val1 = Calendar.getInstance(); val1.setTime(dateArr[0]); Calendar val2 = Calendar.getInstance(); val2.setTime(dateArr[1]); convertedList.add(new Calendar[] {val1, val2}); } else if (list.get(i) instanceof NotesTimeDate[]) { NotesTimeDate[] ntdArr = (NotesTimeDate[]) list.get(i); if (ntdArr.length!=2) { throw new IllegalArgumentException("Length of NotesTimeDate array entry must be 2 for date ranges"); } Calendar val1 = ntdArr[0].toCalendar(); Calendar val2 = ntdArr[1].toCalendar(); convertedList.add(new Calendar[] {val1, val2}); } else { throw new IllegalArgumentException("Unsupported date format found in list: "+(list.get(i)==null ? "null" : list.get(i).getClass().getName())); } } return convertedList; } private boolean isStringList(List<?> list) { if (list==null || list.isEmpty()) { return false; } for (int i=0; i<list.size(); i++) { if (!(list.get(i) instanceof String)) { return false; } } return true; } private boolean isCalendarOrCalendarArrayList(List<?> list) { if (list==null || list.isEmpty()) { return false; } for (int i=0; i<list.size(); i++) { boolean isAccepted=false; Object currObj = list.get(i); if (currObj instanceof Calendar[]) { Calendar[] calArr = (Calendar[]) currObj; if (calArr.length==2) { isAccepted = true; } } else if (currObj instanceof Date[]) { Date[] dateArr = (Date[]) currObj; if (dateArr.length==2) { isAccepted = true; } } else if (currObj instanceof NotesTimeDate[]) { NotesTimeDate[] ndtArr = (NotesTimeDate[]) currObj; if (ndtArr.length==2) { isAccepted = true; } } else if (currObj instanceof Calendar) { isAccepted = true; } else if (currObj instanceof Date) { isAccepted = true; } else if (currObj instanceof NotesTimeDate) { isAccepted = true; } if (!isAccepted) { return false; } } return true; } private boolean isNumberOrNumberArrayList(List<?> list) { if (list==null || list.isEmpty()) { return false; } for (int i=0; i<list.size(); i++) { boolean isAccepted=false; Object currObj = list.get(i); if (currObj instanceof double[]) { double[] valArr = (double[]) currObj; if (valArr.length==2) { isAccepted = true; } } if (currObj instanceof int[]) { int[] valArr = (int[]) currObj; if (valArr.length==2) { isAccepted = true; } } if (currObj instanceof long[]) { long[] valArr = (long[]) currObj; if (valArr.length==2) { isAccepted = true; } } if (currObj instanceof float[]) { float[] valArr = (float[]) currObj; if (valArr.length==2) { isAccepted = true; } } else if (currObj instanceof Number[]) { Number[] valArr = (Number[]) currObj; if (valArr.length==2) { isAccepted = true; } } else if (currObj instanceof Integer[]) { Integer[] valArr = (Integer[]) currObj; if (valArr.length==2) { isAccepted = true; } } else if (currObj instanceof Long[]) { Long[] valArr = (Long[]) currObj; if (valArr.length==2) { isAccepted = true; } } else if (currObj instanceof Double[]) { Double[] valArr = (Double[]) currObj; if (valArr.length==2) { isAccepted = true; } } else if (currObj instanceof Float[]) { Float[] valArr = (Float[]) currObj; if (valArr.length==2) { isAccepted = true; } } else if (currObj instanceof Number) { isAccepted = true; } if (!isAccepted) { return false; } } return true; } /** * Internal method that calls the C API method to write the item * * @param itemName item name * @param flags item flags * @param itemType item type * @param hItemValue handle to memory block with item value * @param valueLength length of binary item value (without data type short) */ private NotesItem appendItemValue(String itemName, EnumSet<ItemType> flags, int itemType, int hItemValue, int valueLength) { checkHandle(); Memory itemNameMem = NotesStringUtils.toLMBCS(itemName, false); NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); short flagsShort = ItemType.toBitMask(flags); NotesBlockIdStruct.ByValue valueBlockIdByVal = NotesBlockIdStruct.ByValue.newInstance(); valueBlockIdByVal.pool = hItemValue; valueBlockIdByVal.block = 0; valueBlockIdByVal.write(); NotesBlockIdStruct retItemBlockId = NotesBlockIdStruct.newInstance(); retItemBlockId.pool = 0; retItemBlockId.block = 0; retItemBlockId.write(); short result; if (NotesJNAContext.is64Bit()) { result = notesAPI.b64_NSFItemAppendByBLOCKID(m_hNote64, flagsShort, itemNameMem, (short) (itemNameMem==null ? 0 : itemNameMem.size()), valueBlockIdByVal, valueLength, retItemBlockId); } else { result = notesAPI.b32_NSFItemAppendByBLOCKID(m_hNote32, flagsShort, itemNameMem, (short) (itemNameMem==null ? 0 : itemNameMem.size()), valueBlockIdByVal, valueLength, retItemBlockId); } NotesErrorUtils.checkResult(result); NotesItem item = new NotesItem(this, retItemBlockId, itemType, valueBlockIdByVal); return item; } /** * Internal method that calls the C API method to write the item * * @param itemName item name * @param flags item flags * @param itemType item type * @param itemValue binary item value * @param valueLength length of binary item value (without data type short) */ // private void appendItemx(String itemName, EnumSet<ItemType> flags, int itemType, Pointer itemValue, int valueLength) { // checkHandle(); // Memory itemNameMem = NotesStringUtils.toLMBCS(itemName, false); // NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); // short flagsShort = ItemType.toBitMask(flags); // short result; // if (NotesJNAContext.is64Bit()) { // result = notesAPI.b64_NSFItemAppend(m_hNote64, flagsShort, itemNameMem, (short) // (itemNameMem==null ? 0 : itemNameMem.size()), (short) (itemType & 0xffff), itemValue, valueLength); // else { // result = notesAPI.b32_NSFItemAppend(m_hNote32, flagsShort, itemNameMem, (short) // (itemNameMem==null ? 0 : itemNameMem.size()), (short) (itemType & 0xffff), itemValue, valueLength); // NotesErrorUtils.checkResult(result); /** * This function signs a document by creating a unique electronic signature and appending this * signature to the note.<br> * <br> * A signature constitutes proof of the user's identity and serves to assure the reader that * the user was the real author of the document.<br> * <br> * The signature is derived from the User ID. A signature item has data type {@link NotesItem#TYPE_SIGNATURE} * and item flags {@link NotesCAPI#ITEM_SEAL}. The data value of the signature item is a digest * of the data stored in items in the note, signed with the user's private key.<br> * <br> * This method signs entire document. It creates a digest of all the items in the note, and * appends a signature item with field name $Signature (ITEM_NAME_NOTE_SIGNATURE).<br> * <br> * If the document to be signed is encrypted, this function will attempt to decrypt the * document in order to generate a valid signature.<br> * If you want the document to be signed and encrypted, you must sign the document * {@link #copyAndEncrypt(NotesUserId, EnumSet)}.<br> * <br> * Note: When the Notes user interface opens a note, it always uses the {@link OpenNote#EXPAND} * option to promote items of type number to number list, and items of type text to text list.<br> */ public void sign() { checkHandle(); NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); short result; if (NotesJNAContext.is64Bit()) { result = notesAPI.b64_NSFNoteExpand(m_hNote64); NotesErrorUtils.checkResult(result); result = notesAPI.b64_NSFNoteSign(m_hNote64); NotesErrorUtils.checkResult(result); result = notesAPI.b64_NSFNoteContract(m_hNote64); NotesErrorUtils.checkResult(result); } else { result = notesAPI.b32_NSFNoteExpand(m_hNote32); NotesErrorUtils.checkResult(result); result = notesAPI.b32_NSFNoteSign(m_hNote32); NotesErrorUtils.checkResult(result); result = notesAPI.b32_NSFNoteContract(m_hNote32); NotesErrorUtils.checkResult(result); } } public void sign(NotesUserId id, boolean signNotesIfMimePresent) { checkHandle(); NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); short result; if (NotesJNAContext.is64Bit()) { result = notesAPI.b64_NSFNoteExpand(m_hNote64); NotesErrorUtils.checkResult(result); result = notesAPI.b64_NSFNoteSignExt3(m_hNote64, id==null ? 0 : id.getHandle64(), null, NotesCAPI.MAXWORD, 0, signNotesIfMimePresent ? NotesCAPI.SIGN_NOTES_IF_MIME_PRESENT : 0, 0, null); NotesErrorUtils.checkResult(result); result = notesAPI.b64_NSFNoteContract(m_hNote64); NotesErrorUtils.checkResult(result); //verify signature NotesTimeDateStruct retWhenSigned = NotesTimeDateStruct.newInstance(); Memory retSigner = new Memory(NotesCAPI.MAXUSERNAME); Memory retCertifier = new Memory(NotesCAPI.MAXUSERNAME); result = notesAPI.b64_NSFNoteVerifySignature (m_hNote64, null, retWhenSigned, retSigner, retCertifier); NotesErrorUtils.checkResult(result); } else { result = notesAPI.b32_NSFNoteExpand(m_hNote32); NotesErrorUtils.checkResult(result); result = notesAPI.b32_NSFNoteSignExt3(m_hNote32, id==null ? 0 : id.getHandle32(), null, NotesCAPI.MAXWORD, 0, signNotesIfMimePresent ? NotesCAPI.SIGN_NOTES_IF_MIME_PRESENT : 0, 0, null); NotesErrorUtils.checkResult(result); result = notesAPI.b32_NSFNoteContract(m_hNote32); NotesErrorUtils.checkResult(result); //verify signature NotesTimeDateStruct retWhenSigned = NotesTimeDateStruct.newInstance(); Memory retSigner = new Memory(NotesCAPI.MAXUSERNAME); Memory retCertifier = new Memory(NotesCAPI.MAXUSERNAME); result = notesAPI.b32_NSFNoteVerifySignature (m_hNote32, null, retWhenSigned, retSigner, retCertifier); NotesErrorUtils.checkResult(result); } } /** * Container for note signature data * * @author Karsten Lehmann */ public static class SignatureData { private NotesTimeDate m_whenSigned; private String m_signer; private String m_certifier; private SignatureData(NotesTimeDate whenSigned, String signer, String certifier) { m_whenSigned = whenSigned; m_signer = signer; m_certifier = certifier; } public NotesTimeDate getWhenSigned() { return m_whenSigned; } public String getSigner() { return m_signer; } public String getCertifier() { return m_certifier; } } /** * Returns the signer of a note * * @return signer or empty string if not signed */ public String getSigner() { try { SignatureData signatureData = verifySignature(); return signatureData.getSigner(); } catch (NotesError e) { if (e.getId()==INotesErrorConstants.ERR_NOTE_NOT_SIGNED) { return ""; } else { throw e; } } } /** * This function verifies a signature on a note or section(s) within a note.<br> * It returns an error if a signature did not verify.<br> * <br> * @return signer data */ public SignatureData verifySignature() { checkHandle(); NotesTimeDateStruct retWhenSigned = NotesTimeDateStruct.newInstance(); Memory retSigner = new Memory(NotesCAPI.MAXUSERNAME); Memory retCertifier = new Memory(NotesCAPI.MAXUSERNAME); NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); short result; if (NotesJNAContext.is64Bit()) { result = notesAPI.b64_NSFNoteExpand(m_hNote64); NotesErrorUtils.checkResult(result); result = notesAPI.b64_NSFNoteVerifySignature (m_hNote64, null, retWhenSigned, retSigner, retCertifier); NotesErrorUtils.checkResult(result); result = notesAPI.b64_NSFNoteContract(m_hNote64); NotesErrorUtils.checkResult(result); } else { result = notesAPI.b32_NSFNoteExpand(m_hNote32); NotesErrorUtils.checkResult(result); result = notesAPI.b32_NSFNoteVerifySignature (m_hNote32, null, retWhenSigned, retSigner, retCertifier); NotesErrorUtils.checkResult(result); result = notesAPI.b32_NSFNoteContract(m_hNote32); NotesErrorUtils.checkResult(result); } String signer = NotesStringUtils.fromLMBCS(retSigner, NotesStringUtils.getNullTerminatedLength(retSigner)); String certifier = NotesStringUtils.fromLMBCS(retCertifier, NotesStringUtils.getNullTerminatedLength(retCertifier)); SignatureData data = new SignatureData(new NotesTimeDate(retWhenSigned), signer, certifier); return data; } /** * Creates/overwrites a $REF item pointing to another {@link NotesNote} * * @param note $REF target note */ public void makeResponse(NotesNote note) { makeResponse(note.getUNID()); } /** * Creates/overwrites a $REF item pointing to a UNID * * @param targetUnid $REF target UNID */ public void makeResponse(String targetUnid) { replaceItemValue("$REF", EnumSet.of(ItemType.SUMMARY), new NotesUniversalNoteId(targetUnid)); } /** * Callback interface that receives data of images embedded in a HTML conversion result * * @author Karsten Lehmann */ public static interface IHtmlItemImageConversionCallback { public static enum Action {Continue, Stop}; /** * Reports the size of the image * * @param size size * @return return how many bytes to skip before reading */ public int setSize(int size); /** * Implement this method to receive element data * * @param data data * @return action, either Continue or Stop */ public Action read(byte[] data); } public enum HtmlConvertOption { ForceSectionExpand, RowAtATimeTableAlt, ForceOutlineExpand; public static String[] toStringArray(EnumSet<HtmlConvertOption> options) { List<String> optionsAsStrList = new ArrayList<String>(options.size()); for (HtmlConvertOption currOption : options) { optionsAsStrList.add(currOption.toString()+"=1"); } return optionsAsStrList.toArray(new String[optionsAsStrList.size()]); } } /** * Convenience method to read the binary data of a {@link IHtmlImageRef} * * @param image image reference * @param callback callback to receive the data */ public void convertHtmlElement(IHtmlImageRef image, IHtmlItemImageConversionCallback callback) { String itemName = image.getItemName(); int itemIndex = image.getItemIndex(); int itemOffset = image.getItemOffset(); EnumSet<HtmlConvertOption> options = image.getOptions(); convertHtmlElement(itemName, options, itemIndex, itemOffset, callback); } /** * Method to access images embedded in HTML conversion result. Compute index and offset parameters * from the img tag path like this: 1.3E =&gt; index=1, offset=63 * * @param itemName rich text field which is being converted * @param options conversion options * @param itemIndex the relative item index -- if there is more than one, Item with the same pszItemName, then this indicates which one (zero relative) * @param itemOffset byte offset in the Item where the element starts * @param callback callback to receive the data */ public void convertHtmlElement(String itemName, EnumSet<HtmlConvertOption> options, int itemIndex, int itemOffset, IHtmlItemImageConversionCallback callback) { checkHandle(); NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); IntByReference phHTML = new IntByReference(); short result = notesAPI.HTMLCreateConverter(phHTML); NotesErrorUtils.checkResult(result); int hHTML = phHTML.getValue(); try { if (!options.isEmpty()) { result = notesAPI.HTMLSetHTMLOptions(hHTML, new StringArray(HtmlConvertOption.toStringArray(options))); NotesErrorUtils.checkResult(result); } Memory itemNameMem = NotesStringUtils.toLMBCS(itemName, true); int totalLen; int skip; if (NotesJNAContext.is64Bit()) { result = notesAPI.b64_HTMLConvertElement(hHTML, getParent().getHandle64(), m_hNote64, itemNameMem, itemIndex, itemOffset); NotesErrorUtils.checkResult(result); Memory tLenMem = new Memory(4); result = notesAPI.b64_HTMLGetProperty(hHTML, (long) NotesCAPI.HTMLAPI_PROP_TEXTLENGTH, tLenMem); NotesErrorUtils.checkResult(result); totalLen = tLenMem.getInt(0); skip = callback.setSize(totalLen); } else { result = notesAPI.b32_HTMLConvertElement(hHTML, getParent().getHandle32(), m_hNote32, itemNameMem, itemIndex, itemOffset); NotesErrorUtils.checkResult(result); Memory tLenMem = new Memory(4); result = notesAPI.b32_HTMLGetProperty(hHTML, (int) NotesCAPI.HTMLAPI_PROP_TEXTLENGTH, tLenMem); NotesErrorUtils.checkResult(result); totalLen = tLenMem.getInt(0); skip = callback.setSize(totalLen); } if (skip > totalLen) throw new IllegalArgumentException("Skip value cannot be greater than size: "+skip+" > "+totalLen); IntByReference len = new IntByReference(); len.setValue(NotesCAPI.MAXPATH); int startOffset=skip; Memory bufMem = new Memory(NotesCAPI.MAXPATH+1); while (result==0 && len.getValue()>0 && startOffset<totalLen) { len.setValue(NotesCAPI.MAXPATH); result = notesAPI.HTMLGetText(hHTML, startOffset, len, bufMem); NotesErrorUtils.checkResult(result); byte[] data = bufMem.getByteArray(0, len.getValue()); IHtmlItemImageConversionCallback.Action action = callback.read(data); if (action == IHtmlItemImageConversionCallback.Action.Stop) break; startOffset += len.getValue(); } } finally { result = notesAPI.HTMLDestroyConverter(hHTML); NotesErrorUtils.checkResult(result); } } /** * Method to convert the whole note to HTML * * @param options conversion options * @return conversion result */ public IHtmlConversionResult convertNoteToHtml(EnumSet<HtmlConvertOption> options) { return convertNoteToHtml(options, (EnumSet<ReferenceType>) null, (Map<ReferenceType,EnumSet<TargetType>>) null); } /** * Method to convert the whole note to HTML with additional filters for the * data returned in the conversion result * * @param options conversion options * @param refTypeFilter optional filter for ref types to be returned or null for no filter * @param targetTypeFilter optional filter for target types to be returned or null for no filter * @return conversion result */ public IHtmlConversionResult convertNoteToHtml(EnumSet<HtmlConvertOption> options, EnumSet<ReferenceType> refTypeFilter, Map<ReferenceType,EnumSet<TargetType>> targetTypeFilter) { return internalConvertItemToHtml(null, options, refTypeFilter, targetTypeFilter); } /** * Method to convert a single item of this note to HTML * * @param itemName item name * @param options conversion options * @return conversion result */ public IHtmlConversionResult convertItemToHtml(String itemName, EnumSet<HtmlConvertOption> options) { return convertItemToHtml(itemName, options, (EnumSet<ReferenceType>) null, (Map<ReferenceType,EnumSet<TargetType>>) null); } /** * Method to convert a single item of this note to HTML with additional filters for the * data returned in the conversion result * * @param itemName item name * @param options conversion options * @param refTypeFilter optional filter for ref types to be returned or null for no filter * @param targetTypeFilter optional filter for target types to be returned or null for no filter * @return conversion result */ public IHtmlConversionResult convertItemToHtml(String itemName, EnumSet<HtmlConvertOption> options, EnumSet<ReferenceType> refTypeFilter, Map<ReferenceType,EnumSet<TargetType>> targetTypeFilter) { if (StringUtil.isEmpty(itemName)) throw new NullPointerException("Item name cannot be null"); return internalConvertItemToHtml(itemName, options, refTypeFilter, targetTypeFilter); } /** * Implementation of {@link IHtmlConversionResult} that contains the HTML conversion result * * @author Karsten Lehmann */ private class HtmlConversionResult implements IHtmlConversionResult { private String m_html; private List<IHtmlApiReference> m_references; private EnumSet<HtmlConvertOption> m_options; private HtmlConversionResult(String html, List<IHtmlApiReference> references, EnumSet<HtmlConvertOption> options) { m_html = html; m_references = references; m_options = options; } @Override public String getText() { return m_html; } @Override public List<IHtmlApiReference> getReferences() { return m_references; } private IHtmlImageRef createImageRef(final String refText, final String fieldName, final int itemIndex, final int itemOffset, final String format) { return new IHtmlImageRef() { @Override public void readImage(IHtmlItemImageConversionCallback callback) { NotesNote.this.convertHtmlElement(this, callback); } @Override public void writeImage(File f) throws IOException { if (f.exists() && !f.delete()) throw new IOException("Cannot delete existing file "+f.getAbsolutePath()); final FileOutputStream fOut = new FileOutputStream(f); final IOException[] ex = new IOException[1]; try { NotesNote.this.convertHtmlElement(this, new IHtmlItemImageConversionCallback() { @Override public int setSize(int size) { return 0; } @Override public Action read(byte[] data) { try { fOut.write(data); return Action.Continue; } catch (IOException e) { ex[0] = e; return Action.Stop; } } }); if (ex[0]!=null) throw ex[0]; } finally { fOut.close(); } } @Override public void writeImage(final OutputStream out) throws IOException { final IOException[] ex = new IOException[1]; NotesNote.this.convertHtmlElement(this, new IHtmlItemImageConversionCallback() { @Override public int setSize(int size) { return 0; } @Override public Action read(byte[] data) { try { out.write(data); return Action.Continue; } catch (IOException e) { ex[0] = e; return Action.Stop; } } }); if (ex[0]!=null) throw ex[0]; out.flush(); } @Override public String getReferenceText() { return refText; } @Override public EnumSet<HtmlConvertOption> getOptions() { return m_options; } @Override public int getItemOffset() { return itemOffset; } @Override public String getItemName() { return fieldName; } @Override public int getItemIndex() { return itemIndex; } @Override public String getFormat() { return format; } }; } public java.util.List<com.mindoo.domino.jna.html.IHtmlImageRef> getImages() { List<IHtmlImageRef> imageRefs = new ArrayList<IHtmlImageRef>(); for (IHtmlApiReference currRef : m_references) { if (currRef.getType() == ReferenceType.IMG) { String refText = currRef.getReferenceText(); String format = "gif"; int iFormatPos = refText.indexOf("FieldElemFormat="); if (iFormatPos!=-1) { String remainder = refText.substring(iFormatPos + "FieldElemFormat=".length()); int iNextDelim = remainder.indexOf('&'); if (iNextDelim==-1) { format = remainder; } else { format = remainder.substring(0, iNextDelim); } } IHtmlApiUrlTargetComponent<?> fieldOffsetTarget = currRef.getTargetByType(TargetType.FIELDOFFSET); if (fieldOffsetTarget!=null) { Object fieldOffsetObj = fieldOffsetTarget.getValue(); if (fieldOffsetObj instanceof String) { String fieldOffset = (String) fieldOffsetObj; // 1.3E -> index=1, offset=63 int iPos = fieldOffset.indexOf('.'); if (iPos!=-1) { String indexStr = fieldOffset.substring(0, iPos); String offsetStr = fieldOffset.substring(iPos+1); int itemIndex = Integer.parseInt(indexStr, 16); int itemOffset = Integer.parseInt(offsetStr, 16); IHtmlApiUrlTargetComponent<?> fieldTarget = currRef.getTargetByType(TargetType.FIELD); if (fieldTarget!=null) { Object fieldNameObj = fieldTarget.getValue(); String fieldName = (fieldNameObj instanceof String) ? (String) fieldNameObj : null; IHtmlImageRef newImgRef = createImageRef(refText, fieldName, itemIndex, itemOffset, format); imageRefs.add(newImgRef); } } } } } } return imageRefs; }; } private static class HTMLApiReference implements IHtmlApiReference { private ReferenceType m_type; private String m_refText; private String m_fragment; private CommandId m_commandId; private List<IHtmlApiUrlTargetComponent<?>> m_targets; private Map<TargetType, IHtmlApiUrlTargetComponent<?>> m_targetByType; private HTMLApiReference(ReferenceType type, String refText, String fragment, CommandId commandId, List<IHtmlApiUrlTargetComponent<?>> targets) { m_type = type; m_refText = refText; m_fragment = fragment; m_commandId = commandId; m_targets = targets; } @Override public ReferenceType getType() { return m_type; } @Override public String getReferenceText() { return m_refText; } @Override public String getFragment() { return m_fragment; } @Override public CommandId getCommandId() { return m_commandId; } @Override public List<IHtmlApiUrlTargetComponent<?>> getTargets() { return m_targets; } @Override public IHtmlApiUrlTargetComponent<?> getTargetByType(TargetType type) { if (m_targetByType==null) { m_targetByType = new HashMap<TargetType, IHtmlApiUrlTargetComponent<?>>(); if (m_targets!=null && !m_targets.isEmpty()) { for (IHtmlApiUrlTargetComponent<?> currTarget : m_targets) { m_targetByType.put(currTarget.getType(), currTarget); } } } return m_targetByType.get(type); } } private static class HtmlApiUrlTargetComponent<T> implements IHtmlApiUrlTargetComponent<T> { private TargetType m_type; private Class<T> m_valueClazz; private T m_value; private HtmlApiUrlTargetComponent(TargetType type, Class<T> valueClazz, T value) { m_type = type; m_valueClazz = valueClazz; m_value = value; } @Override public TargetType getType() { return m_type; } @Override public Class<T> getValueClass() { return m_valueClazz; } @Override public T getValue() { return m_value; } } /** * Internal method doing the HTML conversion work * * @param itemName item name to be converted or null for whole note * @param options conversion options * @param refTypeFilter optional filter for ref types to be returned or null for no filter * @param targetTypeFilter optional filter for target types to be returned or null for no filter * @return conversion result */ private IHtmlConversionResult internalConvertItemToHtml(String itemName, EnumSet<HtmlConvertOption> options, EnumSet<ReferenceType> refTypeFilter, Map<ReferenceType,EnumSet<TargetType>> targetTypeFilter) { checkHandle(); NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); IntByReference phHTML = new IntByReference(); short result = notesAPI.HTMLCreateConverter(phHTML); NotesErrorUtils.checkResult(result); int hHTML = phHTML.getValue(); try { if (!options.isEmpty()) { result = notesAPI.HTMLSetHTMLOptions(hHTML, new StringArray(HtmlConvertOption.toStringArray(options))); NotesErrorUtils.checkResult(result); } Memory itemNameMem = NotesStringUtils.toLMBCS(itemName, true); int totalLen; if (NotesJNAContext.is64Bit()) { if (itemName==null) { result = notesAPI.b64_HTMLConvertNote(hHTML, getParent().getHandle64(), m_hNote64, 0, null); NotesErrorUtils.checkResult(result); } else { result = notesAPI.b64_HTMLConvertItem(hHTML, getParent().getHandle64(), m_hNote64, itemNameMem); NotesErrorUtils.checkResult(result); } Memory tLenMem = new Memory(4); result = notesAPI.b64_HTMLGetProperty(hHTML, (long) NotesCAPI.HTMLAPI_PROP_TEXTLENGTH, tLenMem); NotesErrorUtils.checkResult(result); totalLen = tLenMem.getInt(0); } else { if (itemName==null) { result = notesAPI.b32_HTMLConvertNote(hHTML, getParent().getHandle32(), m_hNote32, 0, null); NotesErrorUtils.checkResult(result); } else { result = notesAPI.b32_HTMLConvertItem(hHTML, getParent().getHandle32(), m_hNote32, itemNameMem); NotesErrorUtils.checkResult(result); } Memory tLenMem = new Memory(4); result = notesAPI.b32_HTMLGetProperty(hHTML, NotesCAPI.HTMLAPI_PROP_TEXTLENGTH, tLenMem); NotesErrorUtils.checkResult(result); totalLen = tLenMem.getInt(0); } IntByReference len = new IntByReference(); len.setValue(NotesCAPI.MAXPATH); int startOffset=0; Memory textMem = new Memory(NotesCAPI.MAXPATH+1); StringBuilder htmlText = new StringBuilder(); while (result==0 && len.getValue()>0 && startOffset<totalLen) { len.setValue(NotesCAPI.MAXPATH); textMem.setByte(0, (byte) 0); result = notesAPI.HTMLGetText(hHTML, startOffset, len, textMem); NotesErrorUtils.checkResult(result); if (result == 0) { textMem.setByte(len.getValue(), (byte) 0); String currText = NotesStringUtils.fromLMBCS(textMem, -1); htmlText.append(currText); startOffset += len.getValue(); } } Memory refCount = new Memory(4); if (NotesJNAContext.is64Bit()) { result=notesAPI.b64_HTMLGetProperty(hHTML, NotesCAPI.HTMLAPI_PROP_NUMREFS, refCount); } else { result=notesAPI.b32_HTMLGetProperty(hHTML, NotesCAPI.HTMLAPI_PROP_NUMREFS, refCount); } NotesErrorUtils.checkResult(result); int iRefCount = refCount.getInt(0); List<IHtmlApiReference> references = new ArrayList<IHtmlApiReference>(); for (int i=0; i<iRefCount; i++) { IntByReference phRef = new IntByReference(); result = notesAPI.HTMLGetReference(hHTML, i, phRef); NotesErrorUtils.checkResult(result); Memory ppRef = new Memory(Pointer.SIZE); int hRef = phRef.getValue(); result = notesAPI.HTMLLockAndFixupReference(hRef, ppRef); NotesErrorUtils.checkResult(result); try { int iRefType; Pointer pRefText; Pointer pFragment; int iCmdId; int nTargets; Pointer pTargets; //use separate structs for 64/32, because RefType uses 8 bytes on 64 and 4 bytes on 32 bit if (NotesJNAContext.is64Bit()) { HTMLAPIReference64Struct htmlApiRef = HTMLAPIReference64Struct.newInstance(ppRef.getPointer(0)); htmlApiRef.read(); iRefType = (int) htmlApiRef.RefType; pRefText = htmlApiRef.pRefText; pFragment = htmlApiRef.pFragment; iCmdId = (int) htmlApiRef.CommandId; nTargets = htmlApiRef.NumTargets; pTargets = htmlApiRef.pTargets; } else { HTMLAPIReference32Struct htmlApiRef = HTMLAPIReference32Struct.newInstance(ppRef.getPointer(0)); htmlApiRef.read(); iRefType = htmlApiRef.RefType; pRefText = htmlApiRef.pRefText; pFragment = htmlApiRef.pFragment; iCmdId = htmlApiRef.CommandId; nTargets = htmlApiRef.NumTargets; pTargets = htmlApiRef.pTargets; } ReferenceType refType = ReferenceType.getType((int) iRefType); if (refTypeFilter==null || refTypeFilter.contains(refType)) { String refText = NotesStringUtils.fromLMBCS(pRefText, -1); String fragment = NotesStringUtils.fromLMBCS(pFragment, -1); CommandId cmdId = CommandId.getCommandId(iCmdId); List<IHtmlApiUrlTargetComponent<?>> targets = new ArrayList<IHtmlApiUrlTargetComponent<?>>(nTargets); for (int t=0; t<nTargets; t++) { Pointer pCurrTarget = pTargets.share(t * NotesCAPI.htmlApiUrlComponentSize); HtmlApi_UrlTargetComponentStruct currTarget = HtmlApi_UrlTargetComponentStruct.newInstance(pCurrTarget); currTarget.read(); int iTargetType = currTarget.AddressableType; TargetType targetType = TargetType.getType(iTargetType); EnumSet<TargetType> targetTypeFilterForRefType = targetTypeFilter==null ? null : targetTypeFilter.get(refType); if (targetTypeFilterForRefType==null || targetTypeFilterForRefType.contains(targetType)) { switch (currTarget.ReferenceType) { case NotesCAPI.URT_Name: currTarget.Value.setType(Pointer.class); currTarget.Value.read(); String name = NotesStringUtils.fromLMBCS(currTarget.Value.name, -1); targets.add(new HtmlApiUrlTargetComponent(targetType, String.class, name)); break; case NotesCAPI.URT_NoteId: currTarget.Value.setType(NoteIdStruct.class); currTarget.Value.read(); NoteIdStruct noteIdStruct = currTarget.Value.nid; int iNoteId = noteIdStruct.nid; targets.add(new HtmlApiUrlTargetComponent(targetType, Integer.class, iNoteId)); break; case NotesCAPI.URT_Unid: currTarget.Value.setType(NotesUniversalNoteIdStruct.class); currTarget.Value.read(); NotesUniversalNoteIdStruct unidStruct = currTarget.Value.unid; unidStruct.read(); String unid = unidStruct.toString(); targets.add(new HtmlApiUrlTargetComponent(targetType, String.class, unid)); break; case NotesCAPI.URT_None: targets.add(new HtmlApiUrlTargetComponent(targetType, Object.class, null)); break; case NotesCAPI.URT_RepId: //TODO find out how to decode this one break; case NotesCAPI.URT_Special: //TODO find out how to decode this one break; } } } IHtmlApiReference newRef = new HTMLApiReference(refType, refText, fragment, cmdId, targets); references.add(newRef); } } finally { if (hRef!=0) { notesAPI.OSMemoryUnlock(hRef); notesAPI.OSMemoryFree(hRef); } } } return new HtmlConversionResult(htmlText.toString(), references, options); } finally { result = notesAPI.HTMLDestroyConverter(hHTML); NotesErrorUtils.checkResult(result); } } /** * This function can be used to create basic richtext content. It uses C API methods to create * "CompoundText", which provide some high-level methods for richtext creation, e.g. * to add text, doclinks, render notes as richtext or append other richtext items.<br> * <br> * <b>After calling the available methods in the returned {@link RichTextBuilder}, you must * call {@link RichTextBuilder#close()} to write your changes into the note. Otherwise * it is discarded.</b> * * @param itemName item name * @return richtext builder */ public RichTextBuilder createRichTextItem(String itemName) { checkHandle(); NotesCAPI notesAPI = NotesJNAContext.getNotesAPI(); Memory itemNameMem = NotesStringUtils.toLMBCS(itemName, true); short result; if (NotesJNAContext.is64Bit()) { LongByReference rethCompound = new LongByReference(); result = notesAPI.b64_CompoundTextCreate(m_hNote64, itemNameMem, rethCompound); NotesErrorUtils.checkResult(result); long hCompound = rethCompound.getValue(); RichTextBuilder ct = new RichTextBuilder(this, hCompound); NotesGC.__objectCreated(RichTextBuilder.class, ct); return ct; } else { IntByReference rethCompound = new IntByReference(); result = notesAPI.b32_CompoundTextCreate(m_hNote32, itemNameMem, rethCompound); NotesErrorUtils.checkResult(result); int hCompound = rethCompound.getValue(); RichTextBuilder ct = new RichTextBuilder(this, hCompound); NotesGC.__objectCreated(RichTextBuilder.class, ct); return ct; } } /** * Callback interface to read CD record data * * @author Karsten Lehmann */ public static interface ICDRecordCallback { public enum Action {Continue, Stop} /** * Method is called for all CD records in this item * * @param data read-only bytebuffer to access data * @param parsedSignature enum with converted signature WORD * @param signature signature WORD for the record type * @param dataLength length of data to read * @param cdRecordLength total length of CD record (BSIG/WSIG/LSIG header plus <code>dataLength</code> * @return action value to continue or stop */ public Action recordVisited(ByteBuffer data, CDRecord parsedSignature, short signature, int dataLength, int cdRecordLength); } }
package battle; import java.time.Duration; import java.util.function.Predicate; public class SkillBuilder { private String name; private String description = ""; private Target target = Target.SELF; private Duration maxCooldown = Duration.ofSeconds(5); /** * This default Predicate returns {@code true} if the fighter is not stunned * or defeated. */ private Predicate<Skill> usablity = a -> true; public SkillBuilder(String name) { this.name = name; } public SkillBuilder setName(String name) { this.name = name; return this; } public SkillBuilder setDescription(String description) { this.description = description; return this; } public SkillBuilder setTarget(Target target) { this.target = target; return this; } public SkillBuilder setMaxCooldown(Duration maxCooldown) { this.maxCooldown = maxCooldown; return this; } public SkillBuilder setUsablity(Predicate<Skill> usablity) { this.usablity = usablity; return this; } public Skill build() { return new Skill(name, description, target, maxCooldown, usablity, null, null, null, null); } }
package org.slf4j; import java.util.logging.Level; import junit.framework.TestCase; /** * Test whether invoking the SLF4J API causes problems or not. * * @author Ceki Gulcu * */ public class InvocationTest extends TestCase { Level oldLevel; java.util.logging.Logger root = java.util.logging.Logger.getLogger(""); public InvocationTest (String arg0) { super(arg0); } protected void setUp() throws Exception { super.setUp(); oldLevel = root.getLevel(); root.setLevel(Level.OFF); } protected void tearDown() throws Exception { super.tearDown(); root.setLevel(oldLevel); } public void test1() { Logger logger = LoggerFactory.getLogger("test1"); logger.debug("Hello world."); } public void test2() { Integer i1 = new Integer(1); Integer i2 = new Integer(2); Integer i3 = new Integer(3); Exception e = new Exception("This is a test exception."); Logger logger = LoggerFactory.getLogger("test2"); logger.debug("Hello world 1."); logger.debug("Hello world {}", i1); logger.debug("val={} val={}", i1, i2); logger.debug("val={} val={} val={}", new Object[]{i1, i2, i3}); logger.debug("Hello world 2", e); logger.info("Hello world 2."); logger.warn("Hello world 3."); logger.warn("Hello world 3", e); logger.error("Hello world 4."); logger.error("Hello world {}", new Integer(3)); logger.error("Hello world 4.", e); } public void testNull() { Logger logger = LoggerFactory.getLogger("testNull"); logger.debug(null); logger.info(null); logger.warn(null); logger.error(null); Exception e = new Exception("This is a test exception."); logger.debug(null, e); logger.info(null, e); logger.warn(null, e); logger.error(null, e); } public void testMarker() { Logger logger = LoggerFactory.getLogger("testMarker"); Marker blue = MarkerFactory.getMarker("BLUE"); logger.debug(blue, "hello"); logger.info(blue, "hello"); logger.warn(blue, "hello"); logger.error(blue, "hello"); logger.debug(blue, "hello {}", "world"); logger.info(blue, "hello {}", "world"); logger.warn(blue, "hello {}", "world"); logger.error(blue, "hello {}", "world"); logger.debug(blue, "hello {} and {} ", "world", "universe"); logger.info(blue, "hello {} and {} ", "world", "universe"); logger.warn(blue, "hello {} and {} ", "world", "universe"); logger.error(blue, "hello {} and {} ", "world", "universe"); } public void testMDC() { MDC.put("k", "v"); assertNull(MDC.get("k")); MDC.remove("k"); assertNull(MDC.get("k")); MDC.clear(); } }
package com.smartnsoft.droid4me.ws; import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.StringWriter; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.net.UnknownHostException; import java.util.Map; import java.util.Map.Entry; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.FactoryConfigurationError; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpDelete; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.client.methods.HttpPut; import org.apache.http.client.methods.HttpRequestBase; import org.apache.http.client.protocol.ClientContext; import org.apache.http.conn.ClientConnectionManager; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HttpContext; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.xml.sax.ContentHandler; import org.xml.sax.InputSource; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import com.smartnsoft.droid4me.log.Logger; import com.smartnsoft.droid4me.log.LoggerFactory; public abstract class WebServiceCaller implements WebServiceClient { /** * An empty interface which states that the underlying {@link HttpClient} instance should be reused for all HTTP requests, instead of creating a new * one each time. */ public static interface ReuseHttpClient { } protected static class SensibleHttpClient extends DefaultHttpClient { public SensibleHttpClient() { this(null, null); } public SensibleHttpClient(HttpParams params) { this(null, params); } public SensibleHttpClient(ClientConnectionManager connectionManager, HttpParams params) { super(connectionManager, params); } @Override protected HttpContext createHttpContext() { // Same as DefaultHttpClient.createHttpContext() minus the cookie store final HttpContext context = new BasicHttpContext(); context.setAttribute(ClientContext.AUTHSCHEME_REGISTRY, getAuthSchemes()); context.setAttribute(ClientContext.COOKIESPEC_REGISTRY, getCookieSpecs()); context.setAttribute(ClientContext.CREDS_PROVIDER, getCredentialsProvider()); return context; } } protected final static Logger log = LoggerFactory.getInstance(WebServiceCaller.class); private static DocumentBuilder builder; private boolean isConnected = true; private HttpClient httpClient; /** * A helper method for generating an input stream from a {@link JSONObject} object. * * @param jsonObject * the JSON object to turn into an input stream * @return the input stream resulting from the JSON marshalling */ public static InputStream createInputStreamFromJson(JSONObject jsonObject) { return new ByteArrayInputStream(jsonObject.toString().getBytes()); } /** * A helper method for generating an input stream from a {@link JSONArray} object. * * @param jsonArray * the JSON array to turn into an input stream * @return the input stream resulting from the JSON marshalling */ public static InputStream createInputStreamFromJson(JSONArray jsonArray) { return new ByteArrayInputStream(jsonArray.toString().getBytes()); } private static XMLReader getNewXmlReader() throws FactoryConfigurationError { final SAXParserFactory saxParserFactory = SAXParserFactory.newInstance(); XMLReader theReader = null; try { final SAXParser saxParser = saxParserFactory.newSAXParser(); try { theReader = saxParser.getXMLReader(); } catch (SAXException exception) { if (log.isFatalEnabled()) { log.fatal("Cannot create the SAX XML reader", exception); } } } catch (Exception exception) { if (log.isFatalEnabled()) { log.fatal("Cannot create the SAX parser", exception); } } return theReader; } /** * @return the value previously set by the {@link #setConnected(boolean)} method */ public boolean isConnected() { return isConnected; } /** * Enables to indicate that no Internet connectivity is available, or that the connectivity has been restored. The initial value is {@code true}. */ public void setConnected(boolean isConnected) { if (log.isDebugEnabled()) { log.debug("Setting the connectivity to " + isConnected); } this.isConnected = isConnected; } public final InputStream getInputStream(String uri) throws WebServiceCaller.CallException { return getInputStream(uri, WebServiceCaller.CallType.Get, null); } /** * Performs an HTTP request corresponding to the provided parameters. * * @param uri * the URI being requested * @param callType * the HTTP method * @param body * if the HTTP method is set to {@link WebServiceCaller.CallType#Post} or {@link WebServiceCaller.CallType#Put}, this is the body of the * request * @return the input stream of the HTTP method call; cannot be {@code null} * @throws WebServiceCaller.CallException * if the status code of the HTTP response does not belong to the [{@link HttpStatus.SC_OK}, {@link HttpStatus.SC_MULTI_STATUS}] range. * Also if a connection issue occurred: the exception will {@link Throwable#getCause() embed} the cause of the exception. If the * {@link #isConnected()} method returns {@code false}, no request will be attempted and a {@link WebServiceCaller.CallException} * exception will be thrown (embedding a {@link UnknownHostException} exception). */ public final InputStream getInputStream(String uri, WebServiceCaller.CallType callType, HttpEntity body) throws WebServiceCaller.CallException { if (isConnected == false) { throw new WebServiceCaller.CallException(new UnknownHostException("No connectivity")); } try { final HttpResponse response = performHttpRequest(uri, callType, body, 0); return getContent(uri, callType, response); } catch (WebServiceCaller.CallException exception) { throw exception; } catch (Exception exception) { throw new WebServiceCaller.CallException(exception); } } protected abstract String getUrlEncoding(); /** * @return the top XML element of the DOM */ protected final Element performHttpGetDom(String methodUriPrefix, String methodUriSuffix, Map<String, String> uriParameters) throws UnsupportedEncodingException, ClientProtocolException, IOException, CallException, IllegalStateException, SAXException { return performHttpGetDom(computeUri(methodUriPrefix, methodUriSuffix, uriParameters)); } /** * @see #performHttpGetDom(String, String, Map) */ protected final Element performHttpGetDom(String uri) throws UnsupportedEncodingException, ClientProtocolException, IOException, CallException, SAXException { final HttpResponse response = performHttpRequest(uri, WebServiceCaller.CallType.Get, null, 0); return WebServiceCaller.getDom(getContent(uri, WebServiceCaller.CallType.Get, response)); } protected final void performHttpGetSAX(String methodUriPrefix, String methodUriSuffix, Map<String, String> uriParameters, ContentHandler contentHandler) throws UnsupportedEncodingException, ClientProtocolException, IOException, IllegalStateException, SAXException, ParserConfigurationException, WebServiceCaller.CallException { parseSax(contentHandler, getInputStream(computeUri(methodUriPrefix, methodUriSuffix, uriParameters))); } protected final String performHttpGetJson(String methodUriPrefix, String methodUriSuffix, Map<String, String> uriParameters) throws UnsupportedEncodingException, ClientProtocolException, IOException, CallException, JSONException { return performHttpGetJson(computeUri(methodUriPrefix, methodUriSuffix, uriParameters)); } protected final String performHttpPostJson(String methodUriPrefix, String methodUriSuffix, HttpEntity postContents) throws UnsupportedEncodingException, ClientProtocolException, IllegalStateException, IOException, CallException, JSONException { return performHttpPostJson(computeUri(methodUriPrefix, methodUriSuffix, null), postContents); } protected final String performHttpPutJson(String methodUriPrefix, String methodUriSuffix, HttpEntity postContents) throws UnsupportedEncodingException, ClientProtocolException, IllegalStateException, IOException, CallException, JSONException { return performHttpPutJson(computeUri(methodUriPrefix, methodUriSuffix, null), postContents); } protected final String performHttpDeleteJson(String methodUriPrefix, String methodUriSuffix) throws UnsupportedEncodingException, ClientProtocolException, IllegalStateException, IOException, CallException, JSONException { return performHttpDeleteJson(computeUri(methodUriPrefix, methodUriSuffix, null)); } protected final String performHttpGetJson(String uri) throws UnsupportedEncodingException, ClientProtocolException, IOException, CallException, JSONException { final HttpResponse response = performHttpRequest(uri, WebServiceCaller.CallType.Get, null, 0); return getJson(getContent(uri, WebServiceCaller.CallType.Get, response)); } protected final String performHttpPostJson(String uri, HttpEntity body) throws UnsupportedEncodingException, ClientProtocolException, IOException, CallException, JSONException { final HttpResponse response = performHttpRequest(uri, WebServiceCaller.CallType.Post, body, 0); return getJson(getContent(uri, WebServiceCaller.CallType.Post, response)); } protected final String performHttpPutJson(String uri, HttpEntity body) throws UnsupportedEncodingException, ClientProtocolException, IOException, CallException, JSONException { final HttpResponse response = performHttpRequest(uri, WebServiceCaller.CallType.Put, body, 0); return getJson(getContent(uri, WebServiceCaller.CallType.Put, response)); } protected final String performHttpDeleteJson(String uri) throws UnsupportedEncodingException, ClientProtocolException, IOException, CallException, JSONException { final HttpResponse response = performHttpRequest(uri, WebServiceCaller.CallType.Delete, null, 0); return getJson(getContent(uri, WebServiceCaller.CallType.Delete, response)); } public static final String getString(InputStream inputStream) throws IOException { final StringWriter writer = new StringWriter(); final InputStreamReader streamReader = new InputStreamReader(inputStream); // The 8192 parameter is there to please Android at runtime and discard the // "INFO/global(16464): INFO: Default buffer size used in BufferedReader constructor. It would be better to be explicit if a 8k-char buffer is required." // log final BufferedReader buffer = new BufferedReader(streamReader, 8192); String line = ""; while (null != (line = buffer.readLine())) { writer.write(line); } return writer.toString(); } public static final String getJson(InputStream inputStream) throws JSONException { try { return WebServiceCaller.getString(inputStream); } catch (IOException exception) { throw new JSONException(exception.getMessage()); } } public static final Element getDom(InputStream inputStream) throws SAXException, IOException { return WebServiceCaller.parseDom(inputStream).getDocumentElement(); } public static Document parseDom(InputStream inputStream) throws SAXException, IOException { // TODO: make this thread-safe one day, even if it is very likely that it is not necessary at all if (WebServiceCaller.builder == null) { final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setNamespaceAware(false); factory.setValidating(false); try { WebServiceCaller.builder = factory.newDocumentBuilder(); } catch (ParserConfigurationException exception) { if (log.isFatalEnabled()) { log.fatal("Cannot create the DOM XML parser factories", exception); } } } return builder.parse(inputStream); } protected final Document parseDom(String uri, WebServiceCaller.CallType callType, HttpResponse response) throws CallException { try { return WebServiceCaller.parseDom(getContent(uri, callType, response)); } catch (IOException exception) { throw new WebServiceCaller.CallException("A I/O problem occurred while attempting to parse in DOM the HTTP response!", exception); } catch (SAXException exception) { throw new WebServiceCaller.CallException("Cannot parse properly in DOM the input stream!", exception); } } /** * Runs the input stream SAX parsing. * * @param contentHandler * the SAX parser * @param inputStream * the input stream which contains the XML to be parsed */ public final void parseSax(ContentHandler contentHandler, InputStream inputStream) throws FactoryConfigurationError, IOException, SAXException { // Now that multiple SAX parsings can be done in parallel, we create a new XML reader each time try { final InputSource inputSource = new InputSource(inputStream); parseSax(contentHandler, inputSource); } finally { try { inputStream.close(); } catch (IOException exception) { if (log.isWarnEnabled()) { log.warn("Could not properly close the input stream used for parsing the XML in SAX", exception); } } } } /** * Runs the input source SAX parsing. * * @param contentHandler * the SAX parser * @param inputSource * the XML to be parsed */ public final void parseSax(ContentHandler contentHandler, InputSource inputSource) throws FactoryConfigurationError, IOException, SAXException { final XMLReader xmlReader = getNewXmlReader(); xmlReader.setContentHandler(contentHandler); inputSource.setEncoding(getUrlEncoding()); xmlReader.parse(inputSource); } protected final HttpResponse performHttpGet(String methodUriPrefix, String methodUriSuffix, Map<String, String> uriParameters) throws UnsupportedEncodingException, IOException, ClientProtocolException, WebServiceCaller.CallException { return performHttpRequest(computeUri(methodUriPrefix, methodUriSuffix, uriParameters), WebServiceCaller.CallType.Get, null, 0); } protected final HttpResponse performHttpPost(String uri, HttpEntity body) throws UnsupportedEncodingException, IOException, ClientProtocolException, WebServiceCaller.CallException { return performHttpRequest(uri, WebServiceCaller.CallType.Post, body, 0); } protected final HttpResponse performHttpPut(String uri, HttpEntity body) throws UnsupportedEncodingException, IOException, ClientProtocolException, WebServiceCaller.CallException { return performHttpRequest(uri, WebServiceCaller.CallType.Put, body, 0); } private HttpResponse performHttpRequest(String uri, WebServiceCaller.CallType callType, HttpEntity body, int attemptsCount) throws UnsupportedEncodingException, IOException, ClientProtocolException, WebServiceCaller.CallException { if (uri == null) { throw new WebServiceCaller.CallException("Cannot perform an HTTP request with a null URI!"); } final long start = System.currentTimeMillis(); final HttpRequestBase request; switch (callType.verb) { default: case Get: request = new HttpGet(uri); break; case Post: final HttpPost httpPost = new HttpPost(uri); // final List<NameValuePair> values = new ArrayList<NameValuePair>(); // for (Entry<String, String> entry : postContents.entrySet()) // values.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); // httpPost.setEntity(new UrlEncodedFormEntity(values, getUrlEncoding())); httpPost.setEntity(body); request = httpPost; break; case Put: final HttpPut httpPut = new HttpPut(uri); httpPut.setEntity(body); request = httpPut; break; case Delete: final HttpDelete httpDelete = new HttpDelete(uri); request = httpDelete; break; } final HttpClient httpClient = getHttpClient(); onBeforeHttpRequestExecution(httpClient, request); if (log.isDebugEnabled()) { log.debug("Running the HTTP " + callType + " request '" + uri + "'"); } final HttpResponse response = httpClient.execute(request); if (log.isDebugEnabled()) { log.debug("The call to the HTTP " + callType + " request '" + uri + "' took " + (System.currentTimeMillis() - start) + " ms"); } final int statusCode = response.getStatusLine().getStatusCode(); if (log.isInfoEnabled()) { log.info("The call to the HTTP " + callType + " request '" + uri + "' returned the status code " + statusCode); } if (!(statusCode >= HttpStatus.SC_OK && statusCode <= HttpStatus.SC_MULTI_STATUS)) { if (onStatusCodeNotOk(uri, callType, body, response, statusCode, attemptsCount + 1) == true) { return performHttpRequest(uri, callType, body, attemptsCount + 1); } } return response; } /** * Invoked when the result of the HTTP request is not <code>20X</code>. The default implementation logs the problem and throws an exception. * * @param uri * the URI of the HTTP call * @param callType * the type of the HTTP method * @param body * the body of the HTTP method when its a {@link WebServiceCaller.CallType#Post} or a {@link WebServiceCaller.CallType#Put} ; {@code null} * otherwise * @param response * the HTTP response * @param statusCode * the status code of the response, which is not <code>20X</code> * @param attemptsCount * the number of attempts that have been run for this HTTP method. Starts at <code>1</code> * @return {@code true} if you want the request to be re-run if it has failed * @throws WebServiceCaller.CallException * if you want the call to be considered as not OK */ protected boolean onStatusCodeNotOk(String uri, WebServiceCaller.CallType callType, HttpEntity body, HttpResponse response, int statusCode, int attemptsCount) throws WebServiceCaller.CallException { final String message = "The result code of the call to the web method '" + uri + "' is not OK (not 20X). Status: " + response.getStatusLine(); if (log.isErrorEnabled()) { log.error(message); } throw new WebServiceCaller.CallException(message, statusCode); } /** * This is the perfect place for customizing the HTTP request that is bound to be run. * * @param httpClient * the Apache HTTP client that will run the HTTP request * @param request * the HTTP request * @throws WebServiceCaller.CallException * in case the HTTP request cannot be eventually invoked properly */ protected void onBeforeHttpRequestExecution(HttpClient httpClient, HttpRequestBase request) throws WebServiceCaller.CallException { } /** * Invoked on every call, in order to extract the input stream from the response. * * <p> * If the content type is gzipped, this is the ideal place for unzipping it. * </p> * * @param uri * the web call initial URI * @param callType * the kind of request * @param response * the HTTP response * @return the (decoded) input stream of the response * @throws IOException * if some exception occurred while extracting the content of the response */ protected InputStream getContent(String uri, WebServiceCaller.CallType callType, HttpResponse response) throws IOException { return response.getEntity().getContent(); } /** * Just invokes {@code #computeUri(String, String, Map, boolean)}, with {@code false} as last parameter. */ public final String computeUri(String methodUriPrefix, String methodUriSuffix, Map<String, String> uriParameters) { return WebServiceCaller.encodeUri(methodUriPrefix, methodUriSuffix, uriParameters, false, getUrlEncoding()); } /** * Just invokes {@code #encodeUri(String, String, Map, boolean, String)}, with {@code #getUrlEncoding()} as last parameter. */ public final String computeUri(String methodUriPrefix, String methodUriSuffix, Map<String, String> uriParameters, boolean alreadyContainsQuestionMark) { return WebServiceCaller.encodeUri(methodUriPrefix, methodUriSuffix, uriParameters, alreadyContainsQuestionMark, getUrlEncoding()); } /** * Computes a URI from its path elements. * * @param methodUriPrefix * the URI prefix * @param methodUriSuffix * the URI suffix ; a {@code /} separator will be appended after the {@code methodUriPrefix} parameter, if not {@code null}. May be * {@code null} * @param uriParameters * a dictionary with {@link String} keys and {@link String} values, which holds the URI query parameters ; may be {@code null}. If a value * is {@code null}, an error log will be issued. If a value is the empty string ({@code ""}), the dictionary key will be used as the * name+value URI parameter ; this is especially useful when the parameter value should not be encoded * @param indicates * whether the provided {@code methodUriPrefix} or the {@code methodUriSuffix} parameters already contain a question mark {@code ?}, so * that, when computing the URI with the additional {@code uriParameters}, it is not appended again. This is especially useful when * building an URI from a basis URI, which already contains a {@code ?} for declaring URI parameters * @param urlEnconding * the encoding used for writing the URI query parameters values * @return a valid URI that may be used for running an HTTP request, for instance */ public static String encodeUri(String methodUriPrefix, String methodUriSuffix, Map<String, String> uriParameters, boolean alreadyContainsQuestionMark, String urlEnconding) { final StringBuffer buffer = new StringBuffer(methodUriPrefix); if (methodUriSuffix != null && methodUriSuffix.length() > 0) { buffer.append("/").append(methodUriSuffix); } boolean first = true; if (uriParameters != null) { for (Entry<String, String> entry : uriParameters.entrySet()) { final String rawParameterName = entry.getKey(); final String rawParameterValue = entry.getValue(); if (rawParameterValue == null) { if (log.isErrorEnabled()) { log.error("Could not encoce the URI parameter with key '" + rawParameterName + "' because its value is null"); } } if (first == true) { buffer.append(alreadyContainsQuestionMark == false ? "?" : "&"); first = false; } else { buffer.append("&"); } try { if (rawParameterValue.length() <= 0) { // The value is empty, and in that case we use the key as a pair URI parameter name+value buffer.append(rawParameterName); } else { buffer.append(rawParameterName).append("=").append(URLEncoder.encode(rawParameterValue, urlEnconding)); } } catch (UnsupportedEncodingException exception) { if (log.isErrorEnabled()) { log.error("Cannot encode properly the URI", exception); } return null; } } } final String uri = buffer.toString(); return uri; } /** * Is responsible for returning an HTTP client instance, used for actually running the HTTP request. * * <p> * The current implementation returns a {@link SensibleHttpClient} instance, which is thread-safe, in case the extending class implements the * {@link WebServiceCaller.ReuseHttpClient} interface. * </p> * * @return a valid HTTP client * @see #computeHttpClient() */ protected final HttpClient getHttpClient() { if (this instanceof WebServiceCaller.ReuseHttpClient) { if (httpClient == null) { httpClient = computeHttpClient(); } return httpClient; } else { return new SensibleHttpClient(); } } /** * This method will be invoked by the {@link #getHttpClient()} method, when it needs to use a new {@link HttpClient}. The method should be * overridden, when the {@link HttpClient} to use should be customized; a typical case is when the connection time-outs, the HTTP {@code User-Agent} * parameters need to fine-tuned. * * <p> * In the case the class implements {@link WebServiceCaller.ReuseHttpClient} interface, this method will be invoked only once. * </p> * * @return an HTTP client that will be used for running HTTP requests */ protected HttpClient computeHttpClient() { if (this instanceof WebServiceCaller.ReuseHttpClient) { final DefaultHttpClient initialHttpClient = new DefaultHttpClient(); final ClientConnectionManager clientConnectionManager = initialHttpClient.getConnectionManager(); final HttpParams params = initialHttpClient.getParams(); // This turns off stale checking. Our connections breaks all the time anyway, and it's not worth it to pay the penalty of checking every time HttpConnectionParams.setStaleCheckingEnabled(params, false); @SuppressWarnings("deprecation") final ThreadSafeClientConnManager threadSafeClientConnectionManager = new ThreadSafeClientConnManager(params, clientConnectionManager.getSchemeRegistry()); return new SensibleHttpClient(threadSafeClientConnectionManager, params); } else { return new SensibleHttpClient(); } } }
package com.malhartech.stream;
package org.mihalis.opal.itemSelector; import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.SWTException; import org.eclipse.swt.events.MouseAdapter; import org.eclipse.swt.events.MouseEvent; import org.eclipse.swt.events.SelectionEvent; import org.eclipse.swt.events.SelectionListener; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.layout.GridData; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Table; import org.eclipse.swt.widgets.TableColumn; import org.eclipse.swt.widgets.TableItem; import org.mihalis.opal.utils.SWTGraphicUtil; import org.mihalis.opal.utils.SimpleSelectionAdapter; /** * Instances of this class are controls that allow the user to select multiple * elements. * <dl> * <dt><b>Styles:</b></dt> * <dd>(none)</dd> * <dt><b>Events:</b></dt> * <dd>Selection</dd> * </dl> */ public class DualList extends Composite { private static final String DOUBLE_DOWN_IMAGE = "double_down.png"; private static final String DOUBLE_UP_IMAGE = "double_up.png"; private static final String DOUBLE_LEFT_IMAGE = "double_left.png"; private static final String DOUBLE_RIGHT_IMAGE = "double_right.png"; private static final String ARROW_DOWN_IMAGE = "arrow_down.png"; private static final String ARROW_LEFT_IMAGE = "arrow_left.png"; private static final String ARROW_UP_IMAGE = "arrow_up.png"; private static final String ARROW_RIGHT_IMAGE = "arrow_right.png"; private final List<DLItem> items; private final List<DLItem> selection; private Table itemsTable; private Table selectionTable; private List<SelectionListener> eventTable; private List<DualListSelectionChangedListener> dualListSelectionChangedListener = new ArrayList<DualListSelectionChangedListener>(); public DualList(final Composite parent, final int style) { super(parent, style); this.items = new ArrayList<DLItem>(); this.selection = new ArrayList<DLItem>(); this.setLayout(new GridLayout(4, false)); createItemsTable(); createButtonSelectAll(); createSelectionTable(); createButtonMoveFirst(); createButtonSelect(); createButtonMoveUp(); createButtonDeselect(); createButtonMoveDown(); createButtonDeselectAll(); createButtonMoveLast(); } private void createItemsTable() { this.itemsTable = this.createTable(); this.itemsTable.addMouseListener(new MouseAdapter() { /** * @see org.eclipse.swt.events.MouseAdapter#mouseDoubleClick(org.eclipse.swt.events.MouseEvent) */ @Override public void mouseDoubleClick(final MouseEvent event) { DualList.this.selectItem(); } }); } private void createButtonSelectAll() { final Button buttonSelectAll = this.createButton(DOUBLE_RIGHT_IMAGE, true, GridData.END); buttonSelectAll.addSelectionListener(new SimpleSelectionAdapter() { /** * @see org.mihalis.opal.utils.SimpleSelectionAdapter#handle(org.eclipse.swt.events.SelectionEvent) */ @Override public void handle(final SelectionEvent e) { DualList.this.selectAll(); } }); } private void createSelectionTable() { this.selectionTable = this.createTable(); this.selectionTable.addMouseListener(new MouseAdapter() { /** * @see org.eclipse.swt.events.MouseAdapter#mouseDoubleClick(org.eclipse.swt.events.MouseEvent) */ @Override public void mouseDoubleClick(final MouseEvent event) { DualList.this.deselectItem(); } }); } private void createButtonMoveFirst() { final Button buttonMoveFirst = this.createButton(DOUBLE_UP_IMAGE, true, GridData.END); buttonMoveFirst.addSelectionListener(new SimpleSelectionAdapter() { /** * @see org.mihalis.opal.utils.SimpleSelectionAdapter#handle(org.eclipse.swt.events.SelectionEvent) */ @Override public void handle(final SelectionEvent e) { DualList.this.moveSelectionToFirstPosition(); } }); } private void createButtonSelect() { final Button buttonSelect = this.createButton(ARROW_RIGHT_IMAGE, false, GridData.CENTER); buttonSelect.addSelectionListener(new SimpleSelectionAdapter() { /** * @see org.mihalis.opal.utils.SimpleSelectionAdapter#handle(org.eclipse.swt.events.SelectionEvent) */ @Override public void handle(final SelectionEvent e) { DualList.this.selectItem(); } }); } private void createButtonMoveUp() { final Button buttonMoveUp = this.createButton(ARROW_UP_IMAGE, false, GridData.CENTER); buttonMoveUp.addSelectionListener(new SimpleSelectionAdapter() { /** * @see org.mihalis.opal.utils.SimpleSelectionAdapter#handle(org.eclipse.swt.events.SelectionEvent) */ @Override public void handle(final SelectionEvent e) { DualList.this.moveUpItem(); } }); } private void createButtonDeselect() { final Button buttonDeselect = this.createButton(ARROW_LEFT_IMAGE, false, GridData.CENTER); buttonDeselect.addSelectionListener(new SimpleSelectionAdapter() { /** * @see org.mihalis.opal.utils.SimpleSelectionAdapter#handle(org.eclipse.swt.events.SelectionEvent) */ @Override public void handle(final SelectionEvent e) { DualList.this.deselectItem(); } }); } private void createButtonMoveDown() { final Button buttonMoveDown = this.createButton(ARROW_DOWN_IMAGE, false, GridData.CENTER); buttonMoveDown.addSelectionListener(new SimpleSelectionAdapter() { /** * @see org.mihalis.opal.utils.SimpleSelectionAdapter#handle(org.eclipse.swt.events.SelectionEvent) */ @Override public void handle(final SelectionEvent e) { DualList.this.moveDownItem(); } }); } private void createButtonDeselectAll() { final Button buttonDeselectAll = this.createButton(DOUBLE_LEFT_IMAGE, false, GridData.BEGINNING); buttonDeselectAll.addSelectionListener(new SimpleSelectionAdapter() { /** * @see org.mihalis.opal.utils.SimpleSelectionAdapter#handle(org.eclipse.swt.events.SelectionEvent) */ @Override public void handle(final SelectionEvent e) { DualList.this.deselectAll(); } }); } private void createButtonMoveLast() { final Button buttonMoveLast = this.createButton(DOUBLE_DOWN_IMAGE, true, GridData.BEGINNING); buttonMoveLast.addSelectionListener(new SimpleSelectionAdapter() { /** * @see org.mihalis.opal.utils.SimpleSelectionAdapter#handle(org.eclipse.swt.events.SelectionEvent) */ @Override public void handle(final SelectionEvent e) { DualList.this.moveSelectionToLastPosition(); } }); } /** * @return a table that will contain data */ private Table createTable() { final Table table = new Table(this, SWT.V_SCROLL | SWT.H_SCROLL | SWT.MULTI | SWT.FULL_SELECTION); table.setLinesVisible(false); table.setHeaderVisible(false); final GridData gd = new GridData(GridData.FILL, GridData.FILL, true, true, 1, 4); gd.widthHint = 200; table.setLayoutData(gd); new TableColumn(table, SWT.CENTER); new TableColumn(table, SWT.LEFT); table.setData(-1); return table; } /** * Create a button * * @param fileName file name of the icon * @param verticalExpand if <code>true</code>, the button will take all the * available space vertically * @param alignment button alignment * @return a new button */ private Button createButton(final String fileName, final boolean verticalExpand, final int alignment) { final Button button = new Button(this, SWT.PUSH); final Image image = new Image(this.getDisplay(), this.getClass().getClassLoader().getResourceAsStream("images/" + fileName)); button.setImage(image); button.setLayoutData(new GridData(GridData.CENTER, alignment, false, verticalExpand)); SWTGraphicUtil.addDisposer(button, image); return button; } public void add(final DLItem item) { this.checkWidget(); if (item == null) { SWT.error(SWT.ERROR_NULL_ARGUMENT); } this.items.add(item); } public void add(final DLItem item, final int index) { this.checkWidget(); if (item == null) { SWT.error(SWT.ERROR_NULL_ARGUMENT); } if (index < 0 || index >= this.items.size()) { SWT.error(SWT.ERROR_INVALID_ARGUMENT); } this.items.add(index, item); } public void addSelectionListener(final SelectionListener listener) { this.checkWidget(); if (listener == null) { SWT.error(SWT.ERROR_NULL_ARGUMENT); } if (this.eventTable == null) { this.eventTable = new ArrayList<SelectionListener>(); } this.eventTable.add(listener); } public void removeSelectionListener(final SelectionListener listener) { this.checkWidget(); if (listener == null) { SWT.error(SWT.ERROR_NULL_ARGUMENT); } if (this.eventTable == null) { return; } this.eventTable.remove(listener); } /** * Deselects the item at the given zero-relative index in the receiver. If * the item at the index was already deselected, it remains deselected. * Indices that are out of range are ignored. * * @param index the index of the item to deselect * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been * disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public void deselect(final int index) { this.checkWidget(); if (index < 0 || index >= this.items.size()) { return; } this.fireEvents(this.selection.remove(index)); this.redrawTables(); } public void deselect(final int[] indices) { this.checkWidget(); if (indices == null) { SWT.error(SWT.ERROR_NULL_ARGUMENT); } final List<DLItem> toBeRemoved = new ArrayList<DLItem>(); for (final int index : indices) { if (index < 0 || index >= this.items.size()) { continue; } toBeRemoved.add(this.selection.get(index)); } for (final DLItem item : toBeRemoved) { this.selection.remove(item); } toBeRemoved.clear(); this.redrawTables(); } public void deselect(final int start, final int end) { this.checkWidget(); if (start > end) { SWT.error(SWT.ERROR_INVALID_RANGE); } final List<DLItem> toBeRemoved = new ArrayList<DLItem>(); for (int index = start; index <= end; index++) { if (index < 0 || index >= this.items.size()) { continue; } toBeRemoved.add(this.selection.get(index)); } for (final DLItem item : toBeRemoved) { this.selection.remove(item); } toBeRemoved.clear(); this.redrawTables(); } /** * Deselects all selected items in the receiver. * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been * disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public void deselectAll() { this.checkWidget(); this.items.addAll(this.selection); this.selection.clear(); this.redrawTables(); } public DLItem getItem(final int index) { this.checkWidget(); if (index < 0 || index >= this.items.size()) { SWT.error(SWT.ERROR_INVALID_ARGUMENT); } return this.items.get(index); } /** * Returns the number of items contained in the receiver. * * @return the number of items * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been * disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public int getItemCount() { this.checkWidget(); return this.items.size(); } /** * Returns a (possibly empty) array of <code>DLItem</code>s which are the * items in the receiver. * <p> * Note: This is not the actual structure used by the receiver to maintain * its list of items, so modifying the array will not affect the receiver. * </p> * * @return the items in the receiver's list * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been * disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public DLItem[] getItems() { this.checkWidget(); return this.items.toArray(new DLItem[this.items.size()]); } /** * Returns a (possibly empty) list of <code>DLItem</code>s which are the * items in the receiver. * <p> * Note: This is not the actual structure used by the receiver to maintain * its list of items, so modifying the array will not affect the receiver. * </p> * * @return the items in the receiver's list * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been * disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public List<DLItem> getItemsAsList() { this.checkWidget(); return new ArrayList<DLItem>(this.items); } /** * Returns an array of <code>DLItem</code>s that are currently selected in * the receiver. An empty array indicates that no items are selected. * <p> * Note: This is not the actual structure used by the receiver to maintain * its selection, so modifying the array will not affect the receiver. * </p> * * @return an array representing the selection * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been * disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public DLItem[] getSelection() { this.checkWidget(); return this.selection.toArray(new DLItem[this.items.size()]); } /** * Returns a list of <code>DLItem</code>s that are currently selected in the * receiver. An empty array indicates that no items are selected. * <p> * Note: This is not the actual structure used by the receiver to maintain * its selection, so modifying the array will not affect the receiver. * </p> * * @return an array representing the selection * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been * disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public List<DLItem> getSelectionAsList() { this.checkWidget(); return new ArrayList<DLItem>(this.selection); } /** * Returns the number of selected items contained in the receiver. * * @return the number of selected items * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been * disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public int getSelectionCount() { this.checkWidget(); return this.selection.size(); } public void remove(final int index) { this.checkWidget(); if (index < 0 || index >= this.items.size()) { SWT.error(SWT.ERROR_INVALID_ARGUMENT); } this.items.remove(index); this.redrawTables(); } public void remove(final int[] indices) { this.checkWidget(); for (final int index : indices) { if (index < 0 || index >= this.items.size()) { SWT.error(SWT.ERROR_INVALID_ARGUMENT); } this.items.remove(index); } this.redrawTables(); } public void remove(final int start, final int end) { this.checkWidget(); if (start > end) { SWT.error(SWT.ERROR_INVALID_ARGUMENT); } for (int index = start; index < end; index++) { if (index < 0 || index >= this.items.size()) { SWT.error(SWT.ERROR_INVALID_ARGUMENT); } this.items.remove(index); } this.redrawTables(); } public void remove(final DLItem item) { this.checkWidget(); if (item == null) { SWT.error(SWT.ERROR_NULL_ARGUMENT); } if (!this.items.contains(item)) { SWT.error(SWT.ERROR_INVALID_ARGUMENT); } this.items.remove(item); this.redrawTables(); } /** * Removes all of the items from the receiver. * <p> * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been * disposed</li> <li>ERROR_THREAD_INVALID_ACCESS - if not * called from the thread that created the receiver</li> * </ul> */ public void removeAll() { this.checkWidget(); this.items.clear(); this.redrawTables(); } /** * Selects the item at the given zero-relative index in the receiver's list. * If the item at the index was already selected, it remains selected. * Indices that are out of range are ignored. * * @param index the index of the item to select * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been * disposed</li> * <li>ERROR_THREAD_INVALID_ACCESS - if not called from the * thread that created the receiver</li> * </ul> */ public void select(final int index) { this.checkWidget(); if (index < 0 || index >= this.items.size()) { return; } this.selection.add(this.items.get(index)); this.fireEvents(this.items.get(index)); this.redrawTables(); } public void select(final int[] indices) { this.checkWidget(); if (indices == null) { SWT.error(SWT.ERROR_NULL_ARGUMENT); } for (final int index : indices) { if (index < 0 || index >= this.items.size()) { continue; } this.selection.add(this.items.get(index)); this.fireEvents(this.items.get(index)); } this.redrawTables(); } /** * Selects the items in the range specified by the given zero-relative * indices in the receiver. The range of indices is inclusive. The current * selection is not cleared before the new items are selected. * <p> * If an item in the given range is not selected, it is selected. If an item * in the given range was already selected, it remains selected. Indices * that are out of range are ignored and no items will be selected if start * is greater than end. If the receiver is single-select and there is more * than one item in the given range, then all indices are ignored. * * @param start the start of the range * @param end the end of the range * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been * disposed</li> <li>ERROR_THREAD_INVALID_ACCESS - if not * called from the thread that created the receiver</li> * </ul> * * @see List#setSelection(int,int) */ public void select(final int start, final int end) { this.checkWidget(); if (start > end) { SWT.error(SWT.ERROR_INVALID_RANGE); } for (int index = start; index <= end; index++) { if (index < 0 || index >= this.items.size()) { continue; } this.selection.add(this.items.get(index)); this.fireEvents(this.items.get(index)); } this.redrawTables(); } /** * Selects all of the items in the receiver. * <p> * If the receiver is single-select, do nothing. * * @exception SWTException <ul> * <li>ERROR_WIDGET_DISPOSED - if the receiver has been * disposed</li> <li>ERROR_THREAD_INVALID_ACCESS - if not * called from the thread that created the receiver</li> * </ul> */ public void selectAll() { this.checkWidget(); this.selection.addAll(this.items); for (final DLItem item : this.items) { this.fireEvents(item); } this.items.clear(); this.redrawTables(); } /** * @see org.eclipse.swt.widgets.Control#setBounds(int, int, int, int) */ @Override public void setBounds(final int x, final int y, final int width, final int height) { super.setBounds(x, y, width, height); final boolean itemsContainImage = this.itemsContainImage(); final Point itemsTableDefaultSize = this.itemsTable.computeSize(SWT.DEFAULT, SWT.DEFAULT); final Point selectionTableDefaultSize = this.selectionTable.computeSize(SWT.DEFAULT, SWT.DEFAULT); int itemsTableSize = this.itemsTable.getSize().x; if (itemsTableDefaultSize.y > this.itemsTable.getSize().y) { itemsTableSize -= this.itemsTable.getVerticalBar().getSize().x; } int selectionTableSize = this.selectionTable.getSize().x; if (selectionTableDefaultSize.y > this.selectionTable.getSize().y) { selectionTableSize -= this.selectionTable.getVerticalBar().getSize().x; } if (itemsContainImage) { this.itemsTable.getColumn(0).pack(); this.itemsTable.getColumn(1).setWidth(itemsTableSize - this.itemsTable.getColumn(0).getWidth()); this.selectionTable.getColumn(0).pack(); this.selectionTable.getColumn(1).setWidth(selectionTableSize - this.selectionTable.getColumn(0).getWidth()); } else { this.itemsTable.getColumn(0).setWidth(itemsTableSize); this.selectionTable.getColumn(0).setWidth(selectionTableSize); } } /** * @return <code>true</code> if any item contains an image */ private boolean itemsContainImage() { for (final DLItem item : this.items) { if (item.getImage() != null) { return true; } } for (final DLItem item : this.selection) { if (item.getImage() != null) { return true; } } return false; } public void setItem(final int index, final DLItem item) { this.checkWidget(); if (item == null) { SWT.error(SWT.ERROR_NULL_ARGUMENT); } if (index < 0 || index >= this.items.size()) { SWT.error(SWT.ERROR_INVALID_RANGE); } this.items.set(index, item); this.redrawTables(); } public void setItems(final DLItem[] items) { this.checkWidget(); if (items == null) { SWT.error(SWT.ERROR_NULL_ARGUMENT); } final List<DLItem> temp = new ArrayList<DLItem>(); for (final DLItem item : items) { if (item == null) { SWT.error(SWT.ERROR_INVALID_ARGUMENT); } temp.add(item); } this.items.clear(); this.items.addAll(temp); this.redrawTables(); } public void setItems(final List<DLItem> items) { this.checkWidget(); this.checkWidget(); if (items == null) { SWT.error(SWT.ERROR_NULL_ARGUMENT); } final List<DLItem> temp = new ArrayList<DLItem>(); for (final DLItem item : items) { if (item == null) { SWT.error(SWT.ERROR_INVALID_ARGUMENT); } temp.add(item); } this.items.clear(); this.items.addAll(temp); this.redrawTables(); } /** * Redraws all tables that compose this widget */ private void redrawTables() { this.setRedraw(false); this.redrawTable(this.itemsTable, false); this.redrawTable(this.selectionTable, true); this.setRedraw(true); this.setBounds(this.getBounds()); } /** * Redraw a given table * * @param table table to be redrawned * @param isSelected if <code>true</code>, fill the table with the * selection. Otherwise, fill the table with the unselected * items. */ private void redrawTable(final Table table, final boolean isSelected) { this.clean(table); this.fillData(table, isSelected ? this.selection : this.items); } /** * Cleans the content of a table * * @param table table to be emptied */ private void clean(final Table table) { if (table == null) { return; } for (final TableItem item : table.getItems()) { item.dispose(); } } /** * Fill a table with data * * @param table table to be filled * @param listOfData list of data */ private void fillData(final Table table, final List<DLItem> listOfData) { // handle image icons when filling the table final boolean itemsContainImage = this.itemsContainImage(); for (final DLItem item : listOfData) { final TableItem tableItem = new TableItem(table, SWT.NONE); tableItem.setData(item); if (item.getBackground() != null) { tableItem.setBackground(item.getBackground()); } if (item.getForeground() != null) { tableItem.setForeground(item.getForeground()); } if (item.getImage() != null) { tableItem.setImage(0, item.getImage()); } if (item.getFont() != null) { tableItem.setFont(item.getFont()); } // decide about the column to place text in int textColumn = itemsContainImage ? 1 : 0; tableItem.setText(textColumn, item.getText()); } } /** * Move the selected item to the first position */ protected void moveSelectionToFirstPosition() { if (this.selectionTable.getSelectionCount() == 0) { return; } int index = 0; for (final TableItem tableItem : this.selectionTable.getSelection()) { final DLItem item = (DLItem) tableItem.getData(); this.selection.remove(item); this.selection.add(index++, item); } this.redrawTables(); this.selectionTable.select(0, index - 1); this.selectionTable.forceFocus(); } /** * Select a given item */ protected void selectItem() { if (this.itemsTable.getSelectionCount() == 0) { return; } LinkedHashSet<DLItem> selectedItems = new LinkedHashSet<DLItem>(); for (final TableItem tableItem : this.itemsTable.getSelection()) { final DLItem item = (DLItem) tableItem.getData(); this.selection.add(item); this.items.remove(item); selectedItems.add(item); } fireItemsSelectedEvent(selectedItems); this.redrawTables(); } /** * Move the selected item up */ protected void moveUpItem() { if (this.selectionTable.getSelectionCount() == 0) { return; } for (final int index : this.selectionTable.getSelectionIndices()) { if (index == 0) { this.selectionTable.forceFocus(); return; } } final int[] newSelection = new int[this.selectionTable.getSelectionCount()]; int newSelectionIndex = 0; for (final TableItem tableItem : this.selectionTable.getSelection()) { final int position = this.selection.indexOf(tableItem.getData()); this.swap(position, position - 1); newSelection[newSelectionIndex++] = position - 1; } this.redrawTables(); this.selectionTable.select(newSelection); this.selectionTable.forceFocus(); } /** * Deselect a given item */ protected void deselectItem() { if (this.selectionTable.getSelectionCount() == 0) { return; } LinkedHashSet<DLItem> deSelectedItems = new LinkedHashSet<DLItem>(); for (final TableItem tableItem : this.selectionTable.getSelection()) { final DLItem item = (DLItem) tableItem.getData(); this.items.add(item); this.selection.remove(item); deSelectedItems.add(item); } fireItemsDeSelectedEvent(deSelectedItems); this.redrawTables(); } /** * Move the selected item down */ protected void moveDownItem() { if (this.selectionTable.getSelectionCount() == 0) { return; } for (final int index : this.selectionTable.getSelectionIndices()) { if (index == this.selectionTable.getItemCount() - 1) { this.selectionTable.forceFocus(); return; } } final int[] newSelection = new int[this.selectionTable.getSelectionCount()]; int newSelectionIndex = 0; for (final TableItem tableItem : this.selectionTable.getSelection()) { final int position = this.selection.indexOf(tableItem.getData()); this.swap(position, position + 1); newSelection[newSelectionIndex++] = position + 1; } this.redrawTables(); this.selectionTable.select(newSelection); this.selectionTable.forceFocus(); } /** * Swap 2 items * * @param first position of the first item to swap * @param second position of the second item to swap */ private void swap(final int first, final int second) { final DLItem temp = this.selection.get(first); this.selection.set(first, this.selection.get(second)); this.selection.set(second, temp); } /** * Move the selected item to the last position */ protected void moveSelectionToLastPosition() { if (this.selectionTable.getSelectionCount() == 0) { return; } final int numberOfSelectedElements = this.selectionTable.getSelectionCount(); for (final TableItem tableItem : this.selectionTable.getSelection()) { final DLItem item = (DLItem) tableItem.getData(); this.selection.remove(item); this.selection.add(item); } this.redrawTables(); final int numberOfElements = this.selectionTable.getItemCount(); this.selectionTable.select(numberOfElements - numberOfSelectedElements, numberOfElements - 1); this.selectionTable.forceFocus(); } /** * Call all selection listeners * * @param item selected item */ private void fireEvents(final DLItem item) { if (this.eventTable == null) { return; } final Event event = new Event(); event.button = 1; event.display = this.getDisplay(); event.item = null; event.widget = this; event.data = item; final SelectionEvent selectionEvent = new SelectionEvent(event); for (final SelectionListener listener : this.eventTable) { listener.widgetSelected(selectionEvent); } } /** * Register a new listener for changed item selections. * * @param listener * The listener to register (only if not null); */ public void addDualListSelectionChangedListener(DualListSelectionChangedListener listener) { if (listener != null) { dualListSelectionChangedListener.add(listener); } } /** * Register a new listener for changed item selections. * * @param listener * The listener to register (only if not null); */ public void removeDualListSelectionChangedListener(DualListSelectionChangedListener listener) { if (listener != null && dualListSelectionChangedListener.contains(listener)) { dualListSelectionChangedListener.remove(listener); } } private void fireItemsSelectedEvent(LinkedHashSet<DLItem> selectedItems) { for (DualListSelectionChangedListener listener : dualListSelectionChangedListener) { listener.itemsSelected(selectedItems); } } private void fireItemsDeSelectedEvent(LinkedHashSet<DLItem> deSelectedItems) { for (DualListSelectionChangedListener listener : dualListSelectionChangedListener) { listener.itemsDeSelected(deSelectedItems); } } /** * Listener notified about newly selected or de-selected items. */ interface DualListSelectionChangedListener { /** * Handle items that were moved to the selected item table. * * @param selectedItems * The items moved. */ public void itemsSelected(LinkedHashSet<DLItem> selectedItems); /** * Handle items that were removed from the selected item table. * * @param deselectedItems * The items de-selected. */ public void itemsDeSelected(LinkedHashSet<DLItem> deselectedItems); } }
package org.openlaszlo.utils; import java.net.*; import java.util.*; import java.util.regex.*; import java.util.zip.*; import java.io.*; import java.text.SimpleDateFormat; import org.openlaszlo.utils.FileUtils.*; import org.openlaszlo.xml.internal.XMLUtils.*; import org.openlaszlo.compiler.*; import org.openlaszlo.server.LPS; import org.w3c.dom.*; import javax.xml.transform.*; import javax.xml.transform.dom.*; import javax.xml.transform.stream.*; import javax.xml.parsers.DocumentBuilderFactory; a subdir named /foo/bar/lps/resources/** */ public class DeploySOLODHTML { public static void main(String args[]) throws IOException { File tmpdir = File.createTempFile("foo", "bar").getParentFile(); deploy(true, null, null, null, "/Users/hqm/openlaszlo/trunk/test/deploy/hello.lzx", new FileOutputStream("/tmp/solo.zip"), tmpdir, null); } /** * Create SOLO deploy archive or wrapper page for app * * @param wrapperonly if true, write only the wrapper html file to the output stream. If false, write entire zipfile archive. * @param canvas If canvas is null, compile the app, and write an entire SOLO zip archive to outstream. Otherwise, use the supplied canvas. * @param lpspath optional, if non-null, use as path to LPS root. * @param url optional, if non-null, use as URL to application in the wrapper html file. * @param sourcepath pathname to application source file * @param outstream stream to write output to * @param tmpdir temporary file to hold compiler output, can be null * @param title optional, if non-null, use as app title in wrapper html file */ public static void deploy(boolean wrapperonly, Canvas canvas, String lpspath, String url, String sourcepath, FileOutputStream outstream, File tmpdir, String title) throws IOException { // Set this to make a limit on the size of zip file that is created int maxZipFileSize = 64000000; // 64MB max int warnZipFileSize = 10000000; // warn at 10MB of content (before compression) boolean warned = false; File sourcefile = new File(sourcepath); // If no canvas is supplied, compile the app to get the canvas and the 'binary' if (canvas == null) { // Create tmp dir if needed if (tmpdir == null) { tmpdir = File.createTempFile("solo_output", "js").getParentFile(); } File tempFile = File.createTempFile(sourcefile.getName(), null, tmpdir); Properties compilationProperties = new Properties(); // Compile a SOLO app with DHTML runtime. compilationProperties.setProperty(CompilationEnvironment.RUNTIME_PROPERTY, "dhtml"); compilationProperties.setProperty(CompilationEnvironment.PROXIED_PROPERTY, "false"); org.openlaszlo.compiler.Compiler compiler = new org.openlaszlo.compiler.Compiler(); canvas = compiler.compile(sourcefile, tempFile, compilationProperties); } if (title == null) { title = sourcefile.getName(); } // Get the HTML wrapper by applying the html-response XSLT template ByteArrayOutputStream wrapperbuf = new ByteArrayOutputStream(); String styleSheetPathname = org.openlaszlo.server.LPS.getTemplateDirectory() + File.separator + "html-response.xslt"; String appname = sourcefile.getName(); String DUMMY_LPS_PATH = "__DUMMY_LPS_ROOT_PATH__"; if (lpspath == null) { lpspath = DUMMY_LPS_PATH; } if (url == null) { url = appname; } String request = "<request " + "lps=\"" + lpspath + "\" " + "url=\"" + url + "\" " + "/>"; String canvasXML = canvas.getXML(request); Properties properties = new Properties(); TransformUtils.applyTransform(styleSheetPathname, properties, canvasXML, wrapperbuf); String wrapper = wrapperbuf.toString(); if (wrapperonly) { // write wrapper to outputstream try { byte wbytes[] = wrapper.getBytes(); outstream.write(wbytes); } finally { if (outstream != null) { outstream.close(); } } return; } /* Create a DOM for the Canvas XML descriptor */ Element canvasElt = parse(canvasXML); // We need to adjust the wrapper, to make the path to lps/includes/dhtml-embed.js // be relative rather than absolute. // remove the servlet prefix and leading slash wrapper = wrapper.replaceAll(lpspath + "/", ""); // Replace object file URL with SOLO filename // Lz.dhtmlEmbedLFC({url: 'animation.lzx?lzt=object&lzproxied=false&lzr=dhtml' // Lz.dhtmlEmbed({url: 'animation.lzx?lzt=object&lzr=dhtml&_canvas_debug=false', // bgcolor: '#eaeaea', width: '800', height: '300', id: 'lzapp'}); //wrapper = wrapper.replaceAll("[.]lzx[?]lzt=object.*'", ".lzx.js'"); wrapper = wrapper.replaceAll("[.]lzx[?]lzt=object.*?'", ".lzx.js'"); // Replace the ServerRoot with a relative path wrapper = wrapper.replaceFirst("ServerRoot:\\s*'_.*?'", "ServerRoot: 'lps/resources'"); // replace title // wrapper = wrapper.replaceFirst("<title>.*</title>", "<title>"+title+"</title>\n"); // extract width and height with regexp String htmlfile = ""; /* System.out.println("wrapper"); System.out.println(wrapper); System.out.println("canvasXML"); System.out.println(canvasXML); */ // add in all the files in the app directory // destination to output the zip file, will be the current jsp directory // The absolute path to the base directory of the server web root //canvas.setFilePath(FileUtils.relativePath(file, LPS.HOME())); File basedir = new File(LPS.HOME()); basedir = basedir.getCanonicalFile(); // The absolute path to the application directory we are packaging // e.g., demos/amazon File appdir = sourcefile.getParentFile(); appdir = appdir.getCanonicalFile(); // Keep track of which files we have output to the zip archive, so we don't // write any duplicate entries. HashSet zippedfiles = new HashSet(); // These are the files to include in the ZIP file ArrayList filenames = new ArrayList();
package com.simolecule.centres; import com.simolecule.centres.config.Configuration; import com.simolecule.centres.config.Octahedral; import com.simolecule.centres.config.Sp2Bond; import com.simolecule.centres.config.SquarePlanar; import com.simolecule.centres.config.Tetrahedral; import com.simolecule.centres.config.TrigonalBipyramidal; import org.openscience.cdk.interfaces.IAtom; import org.openscience.cdk.interfaces.IAtomContainer; import org.openscience.cdk.interfaces.IBond; import org.openscience.cdk.interfaces.IStereoElement; import org.openscience.cdk.stereo.Atropisomeric; import org.openscience.cdk.stereo.DoubleBondStereochemistry; import org.openscience.cdk.stereo.ExtendedTetrahedral; import org.openscience.cdk.stereo.TetrahedralChirality; import java.util.ArrayList; import java.util.List; public final class CdkLabeller extends Labeller<IAtom, IBond> { CdkLabeller() { } static List<Configuration<IAtom, IBond>> createConfigs(IAtomContainer mol) { List<Configuration<IAtom, IBond>> configs = new ArrayList<>(); for (IStereoElement se : mol.stereoElements()) { switch (se.getConfigClass()) { case IStereoElement.TH: { TetrahedralChirality thSe = (TetrahedralChirality) se; configs.add(new Tetrahedral<IAtom, IBond>(thSe.getFocus(), thSe.getCarriers().toArray(new IAtom[4]), thSe.getConfigOrder())); } break; case IStereoElement.CT: { DoubleBondStereochemistry dbSe = (DoubleBondStereochemistry) se; IBond bond = dbSe.getFocus(); IBond[] bonds = dbSe.getBonds(); configs.add(new Sp2Bond<>(bond, new IAtom[]{bond.getBegin(), bond.getEnd()}, new IAtom[]{bonds[0].getOther(bond.getBegin()), bonds[1].getOther(bond.getEnd())}, dbSe.getConfigOrder())); } break; case IStereoElement.AT: { Atropisomeric atSe = (Atropisomeric) se; IBond bond = atSe.getFocus(); configs.add(new com.simolecule.centres.config.Atropisomeric<IAtom, IBond>( bond, new IAtom[]{bond.getBegin(), bond.getEnd()}, atSe.getCarriers().toArray(new IAtom[4]), atSe.getConfigOrder())); } break; case IStereoElement.AL: { ExtendedTetrahedral etSe = (ExtendedTetrahedral) se; IAtom middle = etSe.getFocus(); IAtom[] endAtoms = ExtendedTetrahedral.findTerminalAtoms(mol, middle); IAtom[] focus = new IAtom[]{middle, endAtoms[0], endAtoms[1]}; IAtom[] carriers = etSe.getCarriers().toArray(new IAtom[4]); configs.add(new com.simolecule.centres.config.ExtendedTetrahedral<IAtom, IBond>(focus, carriers, etSe.getConfigOrder())); } break; case IStereoElement.OC: { org.openscience.cdk.stereo.Octahedral ocSe = ((org.openscience.cdk.stereo.Octahedral) se).normalize(); configs.add(new Octahedral<IAtom, IBond>(ocSe.getFocus(), ocSe.getCarriers().toArray(new IAtom[6]))); } break; case IStereoElement.SP: { org.openscience.cdk.stereo.SquarePlanar spSe = ((org.openscience.cdk.stereo.SquarePlanar) se).normalize(); configs.add(new SquarePlanar<IAtom, IBond>(spSe.getFocus(), spSe.getCarriers().toArray(new IAtom[4]))); } break; case IStereoElement.TBPY: { org.openscience.cdk.stereo.TrigonalBipyramidal tbpySe = ((org.openscience.cdk.stereo.TrigonalBipyramidal) se).normalize(); configs.add(new TrigonalBipyramidal<IAtom, IBond>(tbpySe.getFocus(), tbpySe.getCarriers().toArray(new IAtom[4]))); } break; } } return configs; } public static void label(IAtomContainer mol) { new CdkLabeller().label(new CdkMol(mol), createConfigs(mol)); } }
package com.angcyo.uiview.widget; import android.content.Context; import android.content.res.TypedArray; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.drawable.ColorDrawable; import android.graphics.drawable.Drawable; import android.support.annotation.DrawableRes; import android.support.annotation.Px; import android.support.v4.content.ContextCompat; import android.text.Layout; import android.text.Selection; import android.text.Spannable; import android.text.SpannableStringBuilder; import android.text.Spanned; import android.text.TextPaint; import android.text.TextUtils; import android.text.method.LinkMovementMethod; import android.text.method.MovementMethod; import android.text.style.CharacterStyle; import android.text.style.ClickableSpan; import android.text.style.ImageSpan; import android.util.AttributeSet; import android.util.Patterns; import android.view.MotionEvent; import android.view.View; import android.widget.TextView; import com.angcyo.library.utils.L; import com.angcyo.uiview.R; import com.angcyo.uiview.kotlin.ExKt; import com.angcyo.uiview.skin.SkinHelper; import com.angcyo.uiview.utils.RTextPaint; import java.util.regex.Matcher; import java.util.regex.Pattern; public class RExTextView extends RTextView { /** * url */ //public final static Pattern patternUrl = Pattern.compile("(http|ftp|https):\\/\\/[\\w\\-_]+(\\.[\\w\\-_]+)+([\\w\\-\\.:+#]*[\\w\\-+#])?");//Patterns.WEB_URL;// public final static Pattern patternUrlSys = Patterns.WEB_URL; public final static Pattern patternUrl = Pattern.compile("^(http|https|ftp)\\://([a-zA-Z0-9\\.\\-]+(\\:[a-zA-Z0-9\\.&%\\$\\-]+)*@)?((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|([a-zA-Z0-9\\-]+\\.)*[a-zA-Z0-9\\-]+\\.[a-zA-Z]{2,4})(\\:[0-9]+)?(/[^/][a-zA-Z0-9\\.\\,\\?\\'\\\\/\\+&%\\$#\\=~_\\-@]*)*$");//Patterns.WEB_URL;// public final static Pattern patternMention = Pattern.compile("<m id='(\\d+)'>([^<>]+)</m>"); public final static Pattern patternNumber = Pattern.compile("^\\d+$"); public final static Pattern patternPhone = Pattern.compile("\\d{3}-\\d{8}|\\d{3}-\\d{7}|\\d{4}-\\d{8}|\\d{3}-\\d{4}-\\d{4}|\\d{4}-\\d{7}|1+[34578]+\\d{9}|\\d{8}|\\d{7}"); public final static Pattern patternNumberAccount = Pattern.compile("\\d{5,}"); public final static Pattern patternTel = Pattern.compile("^([0-9]{3,4}-)?[0-9]{7,8}$"); protected ImageTextSpan.OnImageSpanClick mOnImageSpanClick; private int maxShowLine = -1; private String more = "..."; private String foldString = ""; private int mImageSpanTextColor = ImageTextSpan.getDefaultColor(); private boolean needPatternUrl = true; /** * Url, Http */ private boolean needPatternUrlCheckHttp = true; /** * URL, Link Ico */ private boolean showPatternUrlIco = true; /** * url, '' */ private boolean showUrlRawText = false; private boolean needPatternMention = true; private boolean needPatternPhone = true; private boolean needPatternNumberAccount = true; public RExTextView(Context context) { this(context, null); } public RExTextView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public RExTextView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); initExTextView(context, attrs); } /** * str */ // public static boolean isNumber(String str) { // Pattern compile = Pattern.compile("^\\d+$"); // Matcher matcher = compile.matcher(str); // //matcher.group(matcher.groupCount()) // return matcher.find(); public static boolean isWebUrl(String url) { // if (TextUtils.isEmpty(url)) { // return false; // return patternUrl.matcher(url).matches(); return isWebUrlSys(url, true); } public static boolean isWebUrlSys(String url, boolean checkHttp) { if (TextUtils.isEmpty(url)) { return false; } if (checkHttp) { if (isStartWidthUrl(url)) { } else { return false; } } return patternUrlSys.matcher(url).matches(); } /** * url http */ public static boolean isStartWidthUrl(String url) { if (TextUtils.isEmpty(url)) { return false; } if (url.startsWith("http") || url.startsWith("HTTP")) { return true; } else { return false; } } /** * str */ public static boolean isNumber(String str) { if (TextUtils.isEmpty(str)) { return false; } return patternNumber.matcher(str).matches(); } public static boolean isPhone(String str) { if (TextUtils.isEmpty(str)) { return false; } return patternPhone.matcher(str).matches(); } public static boolean isTel(String str) { if (TextUtils.isEmpty(str)) { return false; } return patternTel.matcher(str).matches(); } private void initExTextView(Context context, AttributeSet attrs) { //foldString = getResources().getString(R.string.see_all); TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RExTextView); maxShowLine = typedArray.getInt(R.styleable.RExTextView_r_max_show_line, maxShowLine); foldString = typedArray.getString(R.styleable.RExTextView_r_show_fold_text); more = typedArray.getString(R.styleable.RExTextView_r_show_more_text); if (more == null) { more = "..."; } if (foldString == null) { foldString = ""; } if (maxShowLine > 0) { setMaxShowLine(maxShowLine); } typedArray.recycle(); setMovementMethod(getDefaultMovementMethod()); } public RExTextView setImageSpanTextColor(int imageSpanTextColor) { mImageSpanTextColor = imageSpanTextColor; return this; } @Override protected void onAttachedToWindow() { super.onAttachedToWindow(); //setMovementMethod(ImageClickMethod.getInstance()); } @Override protected MovementMethod getDefaultMovementMethod() { if (isNeedPattern()) { return ImageClickMethod.getInstance(); } return super.getDefaultMovementMethod(); } @Override public boolean onTouchEvent(MotionEvent event) { boolean touchEvent = super.onTouchEvent(event); if (isNeedPattern()) { if (hasOnClickListeners()) { return touchEvent || ImageClickMethod.isTouchInSpan; } else { return ImageClickMethod.isTouchInSpan; } } else { return touchEvent; } } public void setMaxShowLine(int maxShowLine) { this.maxShowLine = maxShowLine; if (maxShowLine < 0) { setMaxLines(Integer.MAX_VALUE); } else { setEllipsize(TextUtils.TruncateAt.END); setMaxLines(maxShowLine); } } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); // Layout layout = getLayout(); // if (layout != null) { // int lines = layout.getLineCount(); // L.e("call: onDraw([canvas])-> line Count:" + lines); // if (lines > 0) { // if (layout.getEllipsisCount(lines - 1) > 0) { // L.e("call: onDraw([canvas])-> getEllipsisCount:"); } public void setOnImageSpanClick(ImageTextSpan.OnImageSpanClick onImageSpanClick) { mOnImageSpanClick = onImageSpanClick; } @Override public void setText(CharSequence text, BufferType type) { if (isInEditMode()) { super.setText(text, type); return; } if (TextUtils.isEmpty(text)) { super.setText(text, type); } else { SpannableStringBuilder spanBuilder = new SpannableStringBuilder(text); if (needPatternUrl) { patternUrl(spanBuilder, text); } if (needPatternMention) { patternMention(spanBuilder, text); } if (needPatternNumberAccount) { patternNumberAccount(spanBuilder, text); } if (needPatternPhone) { patternPhone(spanBuilder, text); } afterPattern(spanBuilder, text); super.setText(spanBuilder, type); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); //int lastLineHeight = getLastLineHeight(); //float descent = getPaint().descent(); //setMeasuredDimension(getMeasuredWidth(), (int) (getMeasuredHeight() + density() * 40)); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { super.onLayout(changed, left, top, right, bottom); checkMaxShowLine(); } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); checkMaxShowLine(); } private void checkMaxShowLine() { Layout layout = getLayout(); if (maxShowLine > 0 && layout != null) { int lines = layout.getLineCount(); if (lines > 0) { if (lines > maxShowLine) { CharSequence sequence = getText(); if (sequence instanceof Spannable) { Spannable spannable = (Spannable) sequence; int textLength = spannable.length(); String foldString = getFoldString(); if (textLength <= more.length() + foldString.length()) { setMaxShowLine(-1); return; } int lineStart = layout.getLineStart(maxShowLine);//, index float needWidth = getPaint().measureText(more + foldString) /*+ 20 * ImageTextSpan.getSpace(getContext())*/;// int startPosition = -1; for (int i = 0; i < textLength && lineStart > 0; i++) { int start = lineStart - i; if (start >= 0 && start < lineStart) { CharSequence charSequence = sequence.subSequence(start, lineStart); float textWidth = getPaint().measureText(String.valueOf(charSequence)); if (textWidth > needWidth) { startPosition = lineStart - i - 1; break; } } } //int startPosition = lineStart - more.length() - foldString.length(); if (startPosition < 0) { //L.e("call: onMeasure([widthMeasureSpec, heightMeasureSpec])-> Set Span 1"); spannable.setSpan(new ImageTextSpan(getContext(), getTextSize(), getCurrentTextColor(), more), lineStart - 1, lineStart, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); return; } int start = findStartPosition(spannable, startPosition); int offset = more.length();//(sequence.length() % 2 == 0) ? 4 : 3; if (TextUtils.isEmpty(foldString)) { if (!TextUtils.isEmpty(more)) { //L.e("call: onMeasure([widthMeasureSpec, heightMeasureSpec])-> Set Span 2:" + start); spannable.setSpan(new ImageTextSpan(getContext(), getTextSize(), getCurrentTextColor(), more), start, textLength, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } } else { if (!TextUtils.isEmpty(more)) { //L.e("call: onMeasure([widthMeasureSpec, heightMeasureSpec])-> Set Span 3:" + start); spannable.setSpan(new ImageTextSpan(getContext(), getTextSize(), getCurrentTextColor(), more), start, start + offset, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } //L.e("call: onMeasure([widthMeasureSpec, heightMeasureSpec])-> Set Span 4:" + start); spannable.setSpan(new ImageTextSpan(getContext(), getTextSize(), foldString), start + offset, textLength, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } //setMeasuredDimension(getMeasuredWidth(), (int) (getMeasuredHeight() + density() * 140)); } } } } } private int getLastLineHeight() { Layout layout = getLayout(); if (layout != null) { int lineCount = layout.getLineCount(); if (lineCount > 0) { //view, LineTopViewheight return layout.getLineTop(lineCount) - layout.getLineTop(lineCount - 1); } } return 0; } @Override public boolean canScrollVertically(int direction) { if (maxShowLine > 0) { return false; } return super.canScrollVertically(direction); } @Override public void scrollTo(@Px int x, @Px int y) { if (maxShowLine > 0) { return; } super.scrollTo(x, y); } /** * spannable, , spannablestart position */ private int findStartPosition(Spannable spannable, int startWidthPosition) { CharacterStyle[] oldSpans = spannable.getSpans(startWidthPosition, spannable.length(), CharacterStyle.class); int position = startWidthPosition; for (CharacterStyle oldSpan : oldSpans) { int spanStart = spannable.getSpanStart(oldSpan); int spanEnd = spannable.getSpanEnd(oldSpan); if (spanStart <= startWidthPosition && spanEnd > startWidthPosition) { position = spanStart; } if (spanStart >= startWidthPosition) { spannable.removeSpan(oldSpan); } } //L.e("call: findStartPosition([spannable, startWidthPosition]) " + startWidthPosition + " -> " + position); return position; } private String getFoldString() { if (TextUtils.isEmpty(foldString)) { return ""; } return foldString; } public void setFoldString(String foldString) { this.foldString = foldString; } protected void afterPattern(SpannableStringBuilder spanBuilder, CharSequence text) { } /** * Url */ protected void patternUrl(SpannableStringBuilder builder, CharSequence input) { Matcher matcher = patternUrlSys.matcher(input); while (matcher.find()) { int start = matcher.start(); int end = matcher.end(); String text = matcher.group();//input.subSequence(start, end); if (needPatternUrlCheckHttp && !isStartWidthUrl(text)) { continue; } if (showUrlRawText) { builder.setSpan(new ImageTextSpan(getContext(), ImageTextSpan.initDrawable(getTextSize()), text, text) .setOnImageSpanClick(mOnImageSpanClick) .setTextColor(mImageSpanTextColor), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } else if (showPatternUrlIco) { builder.setSpan(new ImageTextSpan(getContext(), ImageTextSpan.initDrawable(getContext(), R.drawable.base_link_ico, getTextSize()), getContext().getString(R.string.url_link_tip), text) .setOnImageSpanClick(mOnImageSpanClick) .setTextColor(mImageSpanTextColor), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } else { builder.setSpan(new ImageTextSpan(getContext(), ImageTextSpan.initDrawable(getTextSize()), getContext().getString(R.string.url_link_tip), text) .setOnImageSpanClick(mOnImageSpanClick) .setTextColor(mImageSpanTextColor), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } } } protected void patternMention(SpannableStringBuilder builder, CharSequence input) { //<m id='60763'>@i<\/m> <m id='61145'>@<\/m> <m id='61536'>@<\/m> //String p ;//"<m id='\\d+'>\\w+</m>"; Matcher matcher = patternMention.matcher(input); while (matcher.find()) { int start = matcher.start(); int end = matcher.end(); if (!isInOtherSpan(builder, input.length(), start, end)) { builder.setSpan(new ImageTextSpan(getContext(), ImageTextSpan.initDrawable(getTextSize()), matcher.group(2), matcher.group(1)) .setOnImageSpanClick(mOnImageSpanClick) .setTextColor(mImageSpanTextColor), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } } } protected void patternPhone(SpannableStringBuilder builder, CharSequence input) { Matcher matcher = patternPhone.matcher(input); while (matcher.find()) { int start = matcher.start(); int end = matcher.end(); String group = matcher.group(); if (!isInOtherSpan(builder, input.length(), start, end)) { builder.setSpan(new ImageTextSpan(getContext(), ImageTextSpan.initDrawable(getTextSize()), group, group) .setOnImageSpanClick(mOnImageSpanClick) .setTextColor(mImageSpanTextColor), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } } } protected void patternNumberAccount(SpannableStringBuilder builder, CharSequence input) { Matcher matcher = patternNumberAccount.matcher(input); while (matcher.find()) { int start = matcher.start(); int end = matcher.end(); String group = matcher.group(); if (!isInOtherSpan(builder, input.length(), start, end)) { builder.setSpan(new ImageTextSpan(getContext(), ImageTextSpan.initDrawable(getTextSize()), group, group) .setOnImageSpanClick(mOnImageSpanClick) .setTextColor(mImageSpanTextColor), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); } } } /** * ,, span */ @Override protected boolean isInOtherSpan(SpannableStringBuilder builder, int length, int startPosition, int endPosition) { return isInOtherSpan(builder, ImageTextSpan.class, length, startPosition, endPosition); } public void resetPatternState() { needPatternMention = true; needPatternPhone = true; needPatternNumberAccount = true; needPatternUrl = true; needPatternUrlCheckHttp = true; showPatternUrlIco = true; showUrlRawText = false; } public boolean isNeedPattern() { return needPatternPhone || needPatternMention || needPatternUrl || needPatternNumberAccount; } public RExTextView setNeedPattern(boolean needPattern) { this.needPatternUrl = needPattern; this.needPatternMention = needPattern; this.needPatternPhone = needPattern; this.needPatternNumberAccount = needPattern; setMovementMethod(getDefaultMovementMethod()); return this; } public RExTextView setNeedPatternUrl(boolean needPatternUrl) { this.needPatternUrl = needPatternUrl; setMovementMethod(getDefaultMovementMethod()); return this; } public RExTextView setNeedPatternUrlCheckHttp(boolean needPatternUrlCheckHttp) { this.needPatternUrlCheckHttp = needPatternUrlCheckHttp; return this; } public RExTextView setNeedPatternNumberAccount(boolean needPatternNumberAccount) { this.needPatternNumberAccount = needPatternNumberAccount; return this; } public RExTextView setShowPatternUrlIco(boolean showPatternUrlIco) { this.showPatternUrlIco = showPatternUrlIco; return this; } public RExTextView setShowUrlRawText(boolean showUrlRawText) { this.showUrlRawText = showUrlRawText; return this; } public RExTextView setNeedPatternMention(boolean needPatternMention) { this.needPatternMention = needPatternMention; setMovementMethod(getDefaultMovementMethod()); return this; } public RExTextView setNeedPatternPhone(boolean needPatternPhone) { this.needPatternPhone = needPatternPhone; setMovementMethod(getDefaultMovementMethod()); return this; } /** * span, */ public RExTextView setShowSelectionSpanBgColor(boolean showSelectionSpanBgColor) { ImageClickMethod.getInstance().showSelectionSpanBgColor = showSelectionSpanBgColor; return this; } /** * , , , . * {@link ImageClickMethod} */ public static class ImageTextSpan extends ImageSpan { static float downX = -1, downY = -1; static boolean isTouchDown = false; OnImageSpanClick mOnImageSpanClick; private String mShowContent = ""; private Context mContext; private int mImageSize; private int space; private int textColor; private Rect tempRect = new Rect(); private String url; private Rect mTextBounds; private int mSpanWidth; private boolean canClick = true; private boolean enableTouchEffect = false; /** * ImageSpan */ public ImageTextSpan(Context context, float textSize, String showContent) { this(context, textSize, getDefaultColor(), showContent); } public ImageTextSpan(Context context, float textSize, int textColor, String showContent) { super(initDrawable(textSize), ALIGN_BASELINE); this.mShowContent = showContent; init(context); setCanClick(false); setTextColor(textColor); } public ImageTextSpan(Context context, Drawable d, String showContent, String url) { super(d, ALIGN_BASELINE); this.url = url; mShowContent = showContent; init(context); } public ImageTextSpan(Context context, @DrawableRes int resourceId, String show, String url) { super(context, resourceId, ALIGN_BASELINE); this.mShowContent = show; this.url = url; init(context); } public static Drawable initDrawable(Context context, @DrawableRes int resourceId, float textSize) { Drawable drawable = ContextCompat.getDrawable(context, resourceId); int height = drawable.getIntrinsicHeight(); int width = drawable.getIntrinsicWidth(); TextPaint textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG); textPaint.setTextSize(textSize); float textHeight = textPaint.descent() - textPaint.ascent(); //(int) RTextPaint.getTextHeight(textPaint); // if (textHeight > height) { // int offset = textHeight - height + textPaint.getFontMetricsInt().descent / 2; // InsetDrawable insetDrawable = new InsetDrawable(drawable, 0, offset, 0, 0); // insetDrawable.setBounds(0, 0, width, textHeight); // return insetDrawable; // } else { // drawable.setBounds(0, 0, width, height); // return drawable; //drawable.setBounds(0, 0, width, (int) Math.max(height, textHeight)); drawable.setBounds(0, 0, width, (int) -textPaint.ascent()/*(int) Math.max(height, textHeight)*/); return drawable; } /** * ImageSpan */ public static Drawable initDrawable(float textSize) { Drawable drawable = new ColorDrawable(Color.WHITE); TextPaint textPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG); textPaint.setTextSize(textSize); //int textHeight = (int) (textPaint.descent());// - textPaint.ascent());//(int) RTextPaint.getTextHeight(textPaint); //drawable.setBounds(0, 0, 1, textHeight); drawable.setBounds(0, 0, 0, (int) -textPaint.ascent() /*(int) ExKt.textHeight(textPaint)*/); return drawable; } public static int getDefaultColor() { return Color.parseColor("#507daf"); } private static int getSpace(Context context) { return (int) (2 * context.getResources().getDisplayMetrics().density); } public ImageTextSpan setOnImageSpanClick(OnImageSpanClick onImageSpanClick) { mOnImageSpanClick = onImageSpanClick; if (mOnImageSpanClick == null) { canClick = false; } else { canClick = true; } return this; } private void init(Context context) { mContext = context; space = getSpace(context); setDefaultTextColor(); } @Override public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) { if (TextUtils.isEmpty(mShowContent)) { mImageSize = super.getSize(paint, text, start, end, fm); mSpanWidth = mImageSize; return mSpanWidth; } else { String string = mShowContent; mTextBounds = getTextBounds(paint, string); mImageSize = super.getSize(paint, text, start, end, fm); mSpanWidth = mImageSize + mTextBounds.width(); if (haveIco()) { mSpanWidth += space; } return mSpanWidth; } } @Override public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) { if (TextUtils.isEmpty(mShowContent)) { super.draw(canvas, text, start, end, x, top, y, bottom, paint); } else { tempRect.set((int) x, top, ((int) (x + mSpanWidth)), bottom); canvas.save(); if (enableTouchEffect) { if (isTouchDown && tempRect.contains(((int) downX), (int) downY)) { paint.setColor(SkinHelper.getTranColor(textColor, 0x80)); canvas.drawRect(tempRect, paint); } else { paint.setColor(Color.TRANSPARENT); canvas.drawRect(tempRect, paint); } } else { paint.setColor(Color.TRANSPARENT); canvas.drawRect(tempRect, paint); } // paint.setColor(Color.WHITE); // canvas.drawRect(tempRect, paint); // canvas.drawColor(Color.TRANSPARENT); canvas.restore(); super.draw(canvas, text, start, end, x, top, y, bottom, paint); paint.setColor(textColor); int height = bottom - top; String string = mShowContent; int textHeight = (int) RTextPaint.getTextHeight(paint); float textY; textY = y /*+ textHeight / 2 + height / 2 */ /*- paint.getFontMetricsInt().descent*/; if (y == bottom) { textY = y - paint.descent(); } // if (paint.getFontMetricsInt().descent > 0) { // textY = top + textHeight / 2 + height / 2 - paint.getFontMetricsInt().descent / 2; // } else { // textY = top + textHeight / 2 + height / 2 - paint.getFontMetricsInt().descent; if (top != y) { canvas.save(); // canvas.saveLayer(x, top, x + x, bottom, null, Canvas.ALL_SAVE_FLAG); // paint.setStyle(Paint.Style.FILL_AND_STROKE); // paint.setColor(Color.RED); // canvas.drawRect(x, top, x + x, bottom, paint); // paint.setColor(textColor); int sp = 0; if (haveIco()) { sp = space; } canvas.drawText(string, x + mImageSize + sp, textY, paint); canvas.restore(); } // paint.setColor(Color.RED); } } public ImageTextSpan setDefaultTextColor() { setTextColor(getDefaultColor()); return this; } private boolean haveIco() { Drawable drawable = getDrawable(); if (drawable == null) { return false; } if (drawable instanceof ColorDrawable) { return false; } return true; } public ImageTextSpan setTextColor(int textColor) { this.textColor = textColor; return this; } public int getShowTextLength() { return mShowContent.length(); } public String getShowContent() { return mShowContent; } public boolean isCanClick() { return canClick; } public ImageTextSpan setCanClick(boolean canClick) { this.canClick = canClick; return this; } public void onClick(TextView view) { L.e("call: onClick([view])-> " + mShowContent + " : " + url); if (mOnImageSpanClick != null) { if (!mOnImageSpanClick.onClick(view, mShowContent, url)) { if (isWebUrl(url)) { mOnImageSpanClick.onUrlClick(view, url); } else if (isPhone(url)) { mOnImageSpanClick.onPhoneClick(view, url); } else if (isNumber(url)) { mOnImageSpanClick.onMentionClick(view, url); } } } } public void onTouchUp(final TextView view) { isTouchDown = false; downX = -1; downY = -1; if (enableTouchEffect) { view.postInvalidate();//RecyclerView, BUG } } public void onTouchDown(final TextView view, float x, float y) { isTouchDown = true; downX = x; downY = y; if (enableTouchEffect) { view.postInvalidate(); } // view.postDelayed(new Runnable() { // @Override // public void run() { // onTouchUp(view); // }, 300);//300, } public void onTouchCancel(TextView view, float x, float y) { onTouchUp(view); } public Rect getTextBounds(Paint paint, String text) { tempRect.set(0, 0, 0, 0); if (TextUtils.isEmpty(text)) { return tempRect; } //paint.getTextBounds(text, 0, text.length(), tempRect); tempRect.set(0, 0, (int) paint.measureText(text), (int) ExKt.textHeight(paint)); return tempRect; } @Override public String getSource() { return mShowContent; } public static abstract class OnImageSpanClick { public void onUrlClick(TextView view, String url) { } public void onMentionClick(TextView view, String mention) { } public void onPhoneClick(TextView view, String phone) { } /** * @return false , {@link OnImageSpanClick#onUrlClick(TextView, String)} * {@link OnImageSpanClick#onMentionClick(TextView, String)} */ public boolean onClick(TextView view, String showContent, String url) { return false; } } } public static class ImageClickMethod extends LinkMovementMethod { /** * Span */ public static boolean isTouchInSpan = false; private static ImageClickMethod sInstance; /** * span, */ private boolean showSelectionSpanBgColor = false; public static ImageClickMethod getInstance() { if (sInstance == null) sInstance = new ImageClickMethod(); return sInstance; } @Override public boolean onTouchEvent(TextView widget, Spannable buffer, MotionEvent event) { int action = event.getAction(); if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_MOVE || action == MotionEvent.ACTION_CANCEL) { int x = (int) event.getX(); int y = (int) event.getY(); x -= widget.getTotalPaddingLeft(); y -= widget.getTotalPaddingTop(); x += widget.getScrollX(); y += widget.getScrollY(); Layout layout = widget.getLayout(); int line = layout.getLineForVertical(y); int off = layout.getOffsetForHorizontal(line, x); ImageTextSpan[] link = buffer.getSpans(off, off, ImageTextSpan.class); if (link.length > 0) { ImageTextSpan imageTextSpan = link[0]; int spanStart = buffer.getSpanStart(imageTextSpan); int spanEnd = buffer.getSpanEnd(imageTextSpan); int showTextLength = imageTextSpan.getShowTextLength(); int top = layout.getLineTop(line); int bottom = layout.getLineTop(line + 1); float left = layout.getPrimaryHorizontal(spanStart); float right = layout.getPrimaryHorizontal(spanStart + showTextLength); if (imageTextSpan.isCanClick() && (x >= left && x <= right) /*(off >= spanStart && off <= spanStart + showTextLength)*/) { if (action == MotionEvent.ACTION_UP) { imageTextSpan.onTouchUp(widget); imageTextSpan.onClick(widget); isTouchInSpan = false; } else if (action == MotionEvent.ACTION_DOWN) { isTouchInSpan = true; imageTextSpan.onTouchDown(widget, event.getX(), event.getY()); if (showSelectionSpanBgColor) { Selection.setSelection(buffer, spanStart, spanEnd); } } else if (action == MotionEvent.ACTION_MOVE) { //link[0].onTouchMove(widget, event.getX(), event.getY()); //return super.onTouchEvent(widget, buffer, event); } else { isTouchInSpan = false; imageTextSpan.onTouchCancel(widget, event.getX(), event.getY()); //return super.onTouchEvent(widget, buffer, event); } } else { L.e("onTouchEvent-> " + imageTextSpan.getShowContent()); Selection.removeSelection(buffer); } return isTouchInSpan; } else { Selection.removeSelection(buffer); } } return super.onTouchEvent(widget, buffer, event); } } /** * span */ @Deprecated public static class ClickableTextSpan extends ClickableSpan { String show, content; private int textColor; public ClickableTextSpan(String show, String content) { this.show = show; textColor = Color.parseColor("#507daf");// } @Override public void onClick(View widget) { L.i("onClick @: " + content); } @Override public void updateDrawState(TextPaint ds) { ds.bgColor = SkinHelper.getTranColor(textColor, 0x80); //ds.setColor(getResources().getColor(R.color.theme_color_accent)); ds.setColor(textColor); } } }
package com.psddev.dari.util; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.UncheckedIOException; import java.util.ArrayList; import java.util.List; import java.util.Map; import javax.servlet.FilterChain; import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import com.google.common.base.Preconditions; /** * For creating {@link StorageItem}(s) from a {@link MultipartRequest} */ public class StorageItemFilter extends AbstractFilter { private static final String DEFAULT_UPLOAD_PATH = "/_dari/upload"; private static final String FILE_PARAM = "fileParameter"; private static final String STORAGE_PARAM = "storageName"; private static final String SETTING_PREFIX = "dari/upload"; /** * Intercepts requests to {@code UPLOAD_PATH}, * creates a {@link StorageItem} and returns the StorageItem as json. * * @param request Can't be {@code null}. * @param response Can't be {@code null}. * @param chain Can't be {@code null}. * @throws Exception */ @Override protected void doRequest(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws Exception { if (request.getServletPath().equals(Settings.getOrDefault(String.class, SETTING_PREFIX + "/path", DEFAULT_UPLOAD_PATH))) { WebPageContext page = new WebPageContext((ServletContext) null, request, response); String fileParam = page.param(String.class, FILE_PARAM); String storageName = page.param(String.class, STORAGE_PARAM); Object responseObject = StorageItemFilter.getParameters(request, fileParam, storageName); if (responseObject != null && ((List) responseObject).size() == 1) { responseObject = ((List) responseObject).get(0); } response.setContentType("application/json"); page.write(ObjectUtils.toJson(responseObject)); return; } chain.doFilter(request, response); } /** * Creates {@link StorageItem} from a request and request parameter. * * @param request Can't be {@code null}. May be multipart or otherwise. * @param parameterName The parameter name for the file input. Can't be {@code null} or blank. * @param storageName Optionally accepts a storageName, will default to using {@code StorageItem.DEFAULT_STORAGE_SETTING} * @return the created {@link StorageItem} * @throws IOException */ public static StorageItem getParameter(HttpServletRequest request, String parameterName, String storageName) throws IOException { List<StorageItem> storageItems = getParameters(request, parameterName, storageName); return !ObjectUtils.isBlank(storageItems) ? storageItems.get(0) : null; } /** * Creates a {@link List} of {@link StorageItem} from a request and request parameter. * * @param request Can't be {@code null}. May be multipart or otherwise. * @param parameterName The parameter name for the file inputs. Can't be {@code null} or blank. * @param storageName Optional storageName, will default to using {@code StorageItem.DEFAULT_STORAGE_SETTING}. * @return the {@link List} of created {@link StorageItem}(s). * @throws IOException */ public static List<StorageItem> getParameters(HttpServletRequest request, String parameterName, String storageName) throws IOException { Preconditions.checkNotNull(request); Preconditions.checkArgument(!StringUtils.isBlank(parameterName)); List<StorageItem> storageItems = new ArrayList<>(); MultipartRequest mpRequest = MultipartRequestFilter.Static.getInstance(request); if (mpRequest != null) { FileItem[] items = mpRequest.getFileItems(parameterName); if (!ObjectUtils.isBlank(items)) { for (int i = 0; i < items.length; i++) { FileItem item = items[i]; if (item == null) { continue; } // handles input non-file input types in case of mixed input scenario if (item.isFormField()) { storageItems.add(createStorageItem(request.getParameterValues(parameterName)[i])); continue; } // No file value found attached to input if (StringUtils.isBlank(item.getName())) { continue; } storageItems.add(createStorageItem(item, storageName)); } } } else { for (String json : request.getParameterValues(parameterName)) { storageItems.add(createStorageItem(json)); } } return storageItems; } private static StorageItem createStorageItem(String jsonString) { Preconditions.checkNotNull(jsonString); Map<String, Object> json = Preconditions.checkNotNull( ObjectUtils.to( new TypeReference<Map<String, Object>>() { }, ObjectUtils.fromJson(jsonString))); Object storage = json.get("storage"); StorageItem storageItem = StorageItem.Static.createIn(storage != null ? storage.toString() : null); new ObjectMap(storageItem).putAll(json); return storageItem; } private static StorageItem createStorageItem(FileItem fileItem, String storageName) throws IOException { File file = null; try { try { file = File.createTempFile("cms.", ".tmp"); fileItem.write(file); } catch (Exception e) { throw new IOException("Unable to write [" + (StringUtils.isBlank(fileItem.getName()) ? fileItem.getName() : "fileItem") + "] to temporary file.", e); } StorageItemUploadPart part = new StorageItemUploadPart(); part.setContentType(fileItem.getContentType()); part.setName(fileItem.getName()); part.setFile(file); part.setStorageName(storageName); StorageItem storageItem = StorageItem.Static.createIn(part.getStorageName()); storageItem.setContentType(part.getContentType()); storageItem.setPath(createPath(part)); storageItem.setData(new FileInputStream(file)); // Add additional beforeSave functionality through StorageItemBeforeSave implementations ClassFinder.findConcreteClasses(StorageItemBeforeSave.class) .forEach(c -> { try { TypeDefinition.getInstance(c).newInstance().beforeSave(storageItem, part); } catch (IOException e) { throw new UncheckedIOException(e); } }); storageItem.save(); // Add additional afterSave functionality through StorageItemAfterSave implementations ClassFinder.findConcreteClasses(StorageItemAfterSave.class) .forEach(c -> { try { TypeDefinition.getInstance(c).newInstance().afterSave(storageItem); } catch (IOException e) { throw new UncheckedIOException(e); } }); return storageItem; } finally { if (file != null && file.exists()) { file.delete(); } } } private static String createPath(StorageItemUploadPart part) { String pathGeneratorClassName = Settings.get(String.class, SETTING_PREFIX + "/" + part.getStorageName() + "/pathGenerator"); Class<?> pathGeneratorClass = null; if (!StringUtils.isBlank(pathGeneratorClassName)) { pathGeneratorClass = ObjectUtils.getClassByName(pathGeneratorClassName); } StorageItemPathGenerator pathGenerator; if (pathGeneratorClass != null) { Object instance = TypeDefinition.getInstance(pathGeneratorClass).newInstance(); Preconditions.checkState( instance instanceof StorageItemPathGenerator, "Class [" + pathGeneratorClass.getName() + "] does not implement StorageItemPathGenerator."); pathGenerator = (StorageItemPathGenerator) instance; } else { pathGenerator = TypeDefinition.getInstance(RandomUuidStorageItemPathGenerator.class).newInstance(); } return pathGenerator.createPath(part.getName()); } }
package ru.job4j; /** * Removes duplicates from the array. * * @author Ruzhev Alexander * @since 21.02.2017 */ public class DuplicatesDeleter { /** * Removes duplicates from the String[] array. * * @param array massive is String[] * @return String[] array - array without duplicates */ public String[] removeDuplicates(String[] array) { int temp = 0; for (int i = 0; i < array.length - temp; i++) { for (int j = i + 1; j < array.length - temp; j++) { if (array[i].equals(array[j])) { System.arraycopy(array, j + 1, array, j, array.length - j - 1); temp++; } } } return Arrays.copyOf(array, array.length - temp); } }
package net.java.sip.communicator.impl.gui.main.message; import java.io.*; import java.util.*; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.text.*; import javax.swing.text.html.*; import net.java.sip.communicator.impl.gui.*; import net.java.sip.communicator.impl.gui.customcontrols.*; import net.java.sip.communicator.impl.gui.i18n.*; import net.java.sip.communicator.impl.gui.lookandfeel.*; import net.java.sip.communicator.impl.gui.utils.*; import net.java.sip.communicator.service.contactlist.*; import net.java.sip.communicator.service.gui.*; import net.java.sip.communicator.service.msghistory.*; import net.java.sip.communicator.service.protocol.*; import net.java.sip.communicator.service.protocol.event.*; import net.java.sip.communicator.util.*; /** * The <tt>ChatPanel</tt> is the panel, where users can write and send messages, * view received messages. A ChatPanel is created for a contact or for a group * of contacts in case of a chat conference. There is always one default contact * for the chat, which is the first contact which was added to the chat. * When chat is in mode "open all messages in new window", each ChatPanel * corresponds to a ChatWindow. When chat is in mode "group all messages in * one chat window", each ChatPanel corresponds to a tab in the ChatWindow. * * @author Yana Stamcheva */ public class ChatPanel extends JPanel implements ExportedDialog, ChatConversationContainer { private static final Logger logger = Logger .getLogger(ChatPanel.class.getName()); private JSplitPane topSplitPane = new JSplitPane( JSplitPane.HORIZONTAL_SPLIT); private JSplitPane messagePane = new JSplitPane(JSplitPane.VERTICAL_SPLIT); private ChatConversationPanel conversationPanel; private ChatWritePanel writeMessagePanel; private ChatConferencePanel chatConferencePanel = new ChatConferencePanel(); private ChatSendPanel sendPanel; private ChatWindow chatWindow; private OperationSetBasicInstantMessaging imOperationSet; private OperationSetTypingNotifications tnOperationSet; private Contact protocolContact; private MetaContact metaContact; private boolean isVisible = false; private Date lastMsgTimestamp; MessageHistoryService msgHistory = GuiActivator.getMsgHistoryService(); /** * Creates a <tt>ChatPanel</tt> which is added to the given chat window. * * @param chatWindow The parent window of this chat panel. * @param protocolContact The subContact which is selected ins * the chat. */ public ChatPanel( ChatWindow chatWindow, MetaContact metaContact, Contact protocolContact) { super(new BorderLayout()); this.chatWindow = chatWindow; this.metaContact = metaContact; this.protocolContact = protocolContact; this.imOperationSet = this.chatWindow.getMainFrame().getProtocolIM( protocolContact.getProtocolProvider()); this.tnOperationSet = this.chatWindow.getMainFrame() .getTypingNotifications(protocolContact.getProtocolProvider()); this.conversationPanel = new ChatConversationPanel(this); this.sendPanel = new ChatSendPanel(this); this.writeMessagePanel = new ChatWritePanel(this); this.topSplitPane.setResizeWeight(1.0D); this.messagePane.setResizeWeight(1.0D); this.chatConferencePanel.setPreferredSize(new Dimension(120, 100)); this.chatConferencePanel.setMinimumSize(new Dimension(120, 100)); this.writeMessagePanel.setPreferredSize(new Dimension(400, 100)); this.writeMessagePanel.setMinimumSize(new Dimension(400, 100)); this.init(); this.setChatMetaContact(metaContact, protocolContact.getPresenceStatus()); addComponentListener(new TabSelectionFocusGainListener()); } /** * Initializes this panel. */ private void init() { this.topSplitPane.setOneTouchExpandable(true); topSplitPane.setLeftComponent(conversationPanel); topSplitPane.setRightComponent(chatConferencePanel); this.messagePane.setTopComponent(topSplitPane); this.messagePane.setBottomComponent(writeMessagePanel); this.add(messagePane, BorderLayout.CENTER); this.add(sendPanel, BorderLayout.SOUTH); } public void loadHistory() { this.loadHistory(new Date(0)); } /** * * @param lastMsgTimestamp */ public void loadHistory(Date timestamp) { this.lastMsgTimestamp = timestamp; Collection historyList = msgHistory.findLast( metaContact, Constants.CHAT_HISTORY_SIZE); if(historyList.size() > 0) { Iterator i = historyList.iterator(); while (i.hasNext()) { Object o = i.next(); if(o instanceof MessageDeliveredEvent) { MessageDeliveredEvent evt = (MessageDeliveredEvent)o; ProtocolProviderService protocolProvider = evt .getDestinationContact().getProtocolProvider(); conversationPanel.processMessage( chatWindow.getMainFrame() .getAccount(protocolProvider), evt.getTimestamp(), Constants.HISTORY_OUTGOING_MESSAGE, evt.getSourceMessage().getContent()); } else if(o instanceof MessageReceivedEvent) { MessageReceivedEvent evt = (MessageReceivedEvent)o; if(evt.getTimestamp().compareTo(lastMsgTimestamp) != 0) { conversationPanel.processMessage( evt.getSourceContact().getDisplayName(), evt.getTimestamp(), Constants.HISTORY_INCOMING_MESSAGE, evt.getSourceMessage().getContent()); } } } } } /** * Adds a new <tt>MetaContact</tt> to this chat panel. * * @param contactItem The MetaContact to add. * @param status The current presence status of the contact. */ private void setChatMetaContact(MetaContact metaContact, PresenceStatus status) { this.metaContact = metaContact; this.chatConferencePanel.setChatMetaContact(metaContact, status); this.sendPanel.addProtocolContacts(metaContact); this.sendPanel.setSelectedProtocolContact(this.protocolContact); } /** * Adds a new <tt>MetaContact</tt> to this chat panel. * * @param contactItem The <tt>MetaContact</tt> to add. */ private void setChatMetaContact(MetaContact metaContact) { this.metaContact = metaContact; this.chatConferencePanel.setChatMetaContact(metaContact); this.sendPanel.addProtocolContacts(metaContact); } /** * Updates the contact status in the contact info panel. * * @param status The presence status of the contact. */ public void updateContactStatus(PresenceStatus status) { this.chatConferencePanel.updateContactStatus(status); this.conversationPanel.processMessage( this.metaContact.getDisplayName(), new Date(System.currentTimeMillis()), Constants.SYSTEM_MESSAGE, Messages.getString("statusChangedChatMessage", status.getStatusName())); } /** * Returns the default contact for the chat. The case of conference * is not yet implemented and for now it returns the first contact. * * @return The default contact for the chat. */ public MetaContact getMetaContact() { return this.metaContact; } /** * Returns the chat window, where this chat panel * is located. * * @return ChatWindow The chat window, where this * chat panel is located. */ public ChatWindow getChatWindow() { return chatWindow; } /** * Returns the chat window, where this chat panel * is located. * * @return ChatWindow The chat window, where this * chat panel is located. */ public Window getWindow() { return chatWindow; } /** * Returns the instant messaging operation set for * this chat panel. * * @return OperationSetBasicInstantMessaging The instant * messaging operation set for this chat panel. */ public OperationSetBasicInstantMessaging getImOperationSet() { return imOperationSet; } /** * Sets the instant messaging operation set for * this chat panel. * @param imOperationSet The operation set to be set. */ public void setImOperationSet( OperationSetBasicInstantMessaging imOperationSet) { this.imOperationSet = imOperationSet; } /** * Returns the typing notifications operation set for * this chat panel. * * @return OperationSetTypingNotifications The typing * notifications operation set for this chat panel. */ public OperationSetTypingNotifications getTnOperationSet() { return tnOperationSet; } /** * Sets the typing notifications operation set for * this chat panel. * @param tnOperationSet The operation set to be set. */ public void setTnOperationSet( OperationSetTypingNotifications tnOperationSet) { this.tnOperationSet = tnOperationSet; } /** * Returns the chat send panel. * @return ChatSendPanel The chat send panel. */ /* public ChatSendPanel getSendPanel() { return sendPanel; } */ private class TabSelectionFocusGainListener implements ComponentListener { public TabSelectionFocusGainListener() { super(); } public void componentResized(ComponentEvent e) { } public void componentMoved(ComponentEvent e) { } public void componentShown(ComponentEvent e) { Component component = e.getComponent(); Container parent = component.getParent(); if (parent instanceof JTabbedPane) { JTabbedPane tabbedPane = (JTabbedPane) parent; if (tabbedPane.getSelectedComponent() == component) { SwingUtilities.invokeLater(new Runnable() { public void run() { getChatWindow().setTitle( getMetaContact().getDisplayName()); chatWindow.setCurrentChatPanel(ChatPanel.this); writeMessagePanel.getEditorPane() .requestFocus(); } }); } } } public void componentHidden(ComponentEvent e) { } } /** * Returns the protocol contact for this chat. * @return The protocol contact for this chat. */ public Contact getProtocolContact() { return protocolContact; } /** * Sets the protocol contact for this chat. * @param protocolContact The subcontact for the protocol. */ public void setProtocolContact(Contact protocolContact) { this.protocolContact = protocolContact; } /** * Passes the message to the contained <code>ChatConversationPanel</code> * for processing. * * @param contactName The name of the contact sending the message. * @param date The time at which the message is sent or received. * @param messageType The type of the message. One of OUTGOING_MESSAGE * or INCOMING_MESSAGE. * @param message The message text. */ public void processMessage(String contactName, Date date, String messageType, String message){ this.conversationPanel.processMessage(contactName, date, messageType, message); } /** * Refreshes write area editor pane. Deletes all existing text * content. */ public void refreshWriteArea(){ JEditorPane writeMsgPane = this.writeMessagePanel.getEditorPane(); writeMsgPane.setText(""); } /** * Requests the focus in the write message area. */ public void requestFocusInWriteArea(){ JEditorPane writeMsgPane = this.writeMessagePanel.getEditorPane(); writeMsgPane.requestFocus(); } /** * Sets the message text to the status panel in the bottom of the chat * window. Used to show typing notification messages, links' hrefs, etc. * @param statusMessage The message text to be displayed. */ public void setStatusMessage(String statusMessage){ this.sendPanel.setStatusMessage(statusMessage); } /** * Returns the time of the last received message. * * @return The time of the last received message. */ public Date getLastIncomingMsgTimestamp() { return this.conversationPanel.getLastIncomingMsgTimestamp(); } /** * Checks if the editor contains text. * * @return TRUE if editor contains text, FALSE otherwise. */ public boolean isWriteAreaEmpty(){ JEditorPane editorPane = this.writeMessagePanel.getEditorPane(); if (editorPane.getText() == null || editorPane.getText().equals("")) return true; else return false; } /** * Adds text to the write area editor. * * @param text The text to add. */ public void addTextInWriteArea(String text){ JEditorPane editorPane = this.writeMessagePanel.getEditorPane(); editorPane.setText(editorPane.getText() + text); } /** * Returns the text contained in the write area editor. * @return The text contained in the write area editor. */ public String getTextFromWriteArea(){ JEditorPane editorPane = this.writeMessagePanel.getEditorPane(); return editorPane.getText(); } /** * Stops typing notifications sending. */ public void stopTypingNotifications(){ this.writeMessagePanel.stopTypingTimer(); } /** * Cuts the write area selected content to the clipboard. */ public void cut(){ this.writeMessagePanel.getEditorPane().cut(); } /** * Copies either the selected write area content or the selected * conversation panel content to the clipboard. */ public void copy(){ JEditorPane editorPane = this.conversationPanel.getChatEditorPane(); if (editorPane.getSelectedText() == null) { editorPane = this.writeMessagePanel.getEditorPane(); } editorPane.copy(); } /** * Copies the selected write panel content to the clipboard. */ public void copyWriteArea(){ JEditorPane editorPane = this.writeMessagePanel.getEditorPane(); editorPane.copy(); } /** * Pastes the content of the clipboard to the write area. */ public void paste(){ JEditorPane editorPane = this.writeMessagePanel.getEditorPane(); editorPane.paste(); editorPane.requestFocus(); } /** * Sends current write area content. */ public void sendMessage(){ JButton sendButton = this.sendPanel.getSendButton(); sendButton.requestFocus(); sendButton.doClick(); } /** * Moves the caret to the end of the conversation panel. * * Workaround for the following problem: * The scrollbar in the conversation area moves up when the * scrollpane is resized. This happens when ChatWindow is in * mode "Group messages in one window" and the first chat panel * is added to the tabbed pane. Then the scrollpane in the * conversation area is slightly resized and is made smaller, * which moves the scrollbar up. */ public void setCaretToEnd(){ HTMLDocument doc = (HTMLDocument)this.conversationPanel .getChatEditorPane().getDocument(); Element root = doc.getDefaultRootElement(); try { doc.insertAfterEnd(root .getElement(root.getElementCount() - 1), "<br>"); } catch (BadLocationException e) { logger.error("Insert in the HTMLDocument failed.", e); } catch (IOException e) { logger.error("Insert in the HTMLDocument failed.", e); } //Scroll to the last inserted text in the document. this.conversationPanel.setCarretToEnd(); } /** * Opens the selector box containing the protocol contact icons. This is the * menu, where user could select the protocol specific contact to * communicate through. */ public void openProtocolSelectorBox() { SIPCommSelectorBox contactSelector = this.sendPanel.getContactSelectorBox(); JPopupMenu popup = contactSelector.getPopup(); if (!popup.isVisible()) { popup.setLocation(contactSelector.calculatePopupLocation()); popup.setVisible(true); } } /** * Returns the <tt>PresenceStatus</tt> of the default contact for this chat * panel. * @return the <tt>PresenceStatus</tt> of the default contact for this chat * panel. */ public PresenceStatus getPresenceStatus() { return getMetaContact().getDefaultContact().getPresenceStatus(); } /** * Implements the <code>ExportedDialog.isDialogVisible</code> method, to * check whether this chat panel is currently visible. * @return <code>true</code> if this chat panel is currently visible, * <code>false</code> otherwise. */ public boolean isDialogVisible() { return this.isVisible; } /** * Implements the <code>ExportedDialog.showDialog</code> method, to * make a chat panel visible. */ public void showDialog() { Hashtable contactChats = chatWindow.getContactChatsTable(); if(Constants.TABBED_CHAT_WINDOW) { if(!contactChats.containsValue(this)) this.chatWindow.addChatTab(this); else this.chatWindow.setSelectedContactTab(getMetaContact()); } else { if(!contactChats.containsValue(this)) this.chatWindow.addChat(this); } this.chatWindow.setVisible(true); } /** * Implements the <code>ExportedDialog.hideDialog</code> method, to * hide a chat panel. */ public void hideDialog() { this.isVisible = false; if(Constants.TABBED_CHAT_WINDOW) { this.chatWindow.removeChatTab(this); } else { this.chatWindow.removeChat(this); } } /** * Implements the <code>ExportedDialog.resizeDialog</code> method, to * resize the chat window to the given width and height. * @param width The new width to set. * @param height The new height to set. */ public void resizeDialog(int width, int height) { this.chatWindow.setSize(width, height); } /** * Implements the <code>ExportedDialog.moveDialog</code> method, to * move the chat window to the given x and y coordinates. * @param x The <code>x</code> coordinate. * @param y The <code>y</code> coordinate. */ public void moveDialog(int x, int y) { this.chatWindow.setLocation(x, y); } /** * Sets the chat <code>isVisible</code> variable to <code>true</code> or * <code>false</code> to indicate that this chat panel is visible or * invisible. */ public void setChatVisible(boolean isVisible) { this.isVisible = isVisible; } }
package us.myles.ViaVersion.util; import org.yaml.snakeyaml.DumperOptions; import org.yaml.snakeyaml.Yaml; import org.yaml.snakeyaml.representer.Representer; import us.myles.ViaVersion.api.configuration.ConfigurationProvider; import java.io.*; import java.net.URL; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentSkipListMap; public abstract class Config implements ConfigurationProvider { private static ThreadLocal<Yaml> yaml = new ThreadLocal<Yaml>() { @Override protected Yaml initialValue() { DumperOptions options = new DumperOptions(); options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK); options.setPrettyFlow(false); options.setIndent(2); return new Yaml(new YamlConstructor(), new Representer(), options); } }; private CommentStore commentStore = new CommentStore('.', 2); private final File configFile; private ConcurrentSkipListMap<String, Object> config; public Config(File configFile) { this.configFile = configFile; reloadConfig(); } public Map<String, Object> loadConfig(File location) { List<String> unsupported = getUnsupportedOptions(); URL jarConfigFile = Config.class.getClassLoader().getResource("config.yml"); try { commentStore.storeComments(jarConfigFile.openStream()); for (String option : unsupported) { List<String> comments = commentStore.header(option); if (comments != null) { comments.clear(); } } } catch (IOException e) { e.printStackTrace(); } Map<String, Object> config = null; if (location.exists()) { try (FileInputStream input = new FileInputStream(location)) { config = (Map<String, Object>) yaml.get().load(input); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } if (config == null) { config = new HashMap<>(); } Map<String, Object> defaults = config; try (InputStream stream = jarConfigFile.openStream()) { defaults = (Map<String, Object>) yaml.get().load(stream); for (String option : unsupported) { defaults.remove(option); } // Merge with defaultLoader for (Object key : config.keySet()) { // Set option in new conf if exists if (defaults.containsKey(key) && !unsupported.contains(key.toString())) { defaults.put((String) key, config.get(key)); } } } catch (IOException e) { e.printStackTrace(); } // Call Handler handleConfig(defaults); // Save saveConfig(location, defaults); return defaults; } protected abstract void handleConfig(Map<String, Object> config); public void saveConfig(File location, Map<String, Object> config) { try { commentStore.writeComments(yaml.get().dump(config), location); } catch (IOException e) { e.printStackTrace(); } } public abstract List<String> getUnsupportedOptions(); @Override public void set(String path, Object value) { config.put(path, value); } @Override public void saveConfig() { this.configFile.getParentFile().mkdirs(); saveConfig(this.configFile, this.config); } @Override public void reloadConfig() { this.configFile.getParentFile().mkdirs(); this.config = new ConcurrentSkipListMap<>(loadConfig(this.configFile)); } @Override public Map<String, Object> getValues() { return this.config; } public <T> T get(String key, Class<T> clazz, T def) { if (this.config.containsKey(key)) { return (T) this.config.get(key); } else { return def; } } public boolean getBoolean(String key, boolean def) { if (this.config.containsKey(key)) { return (boolean) this.config.get(key); } else { return def; } } public String getString(String key, String def) { if (this.config.containsKey(key)) { return (String) this.config.get(key); } else { return def; } } public int getInt(String key, int def) { if (this.config.containsKey(key)) { if (this.config.get(key) instanceof Number) { return ((Number) this.config.get(key)).intValue(); } else { return def; } } else { return def; } } public double getDouble(String key, double def) { if (this.config.containsKey(key)) { if (this.config.get(key) instanceof Number) { return ((Number) this.config.get(key)).doubleValue(); } else { return def; } } else { return def; } } public List<Integer> getIntegerList(String key) { if (this.config.containsKey(key)) { return (List<Integer>) this.config.get(key); } else { return new ArrayList<>(); } } }
package de.gurkenlabs.utiliti.components; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics2D; import java.awt.event.FocusAdapter; import java.awt.event.FocusEvent; import java.awt.event.KeyEvent; import java.awt.event.MouseEvent; import java.awt.geom.Point2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.File; import java.nio.file.Paths; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.function.Consumer; import java.util.function.IntConsumer; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; import de.gurkenlabs.litiengine.Game; import de.gurkenlabs.litiengine.environment.Environment; import de.gurkenlabs.litiengine.environment.tilemap.IImageLayer; import de.gurkenlabs.litiengine.environment.tilemap.IMapObject; import de.gurkenlabs.litiengine.environment.tilemap.IMapObjectLayer; import de.gurkenlabs.litiengine.environment.tilemap.ITileset; import de.gurkenlabs.litiengine.environment.tilemap.MapObjectProperty; import de.gurkenlabs.litiengine.environment.tilemap.MapObjectType; import de.gurkenlabs.litiengine.environment.tilemap.MapRenderer; import de.gurkenlabs.litiengine.environment.tilemap.xml.Blueprint; import de.gurkenlabs.litiengine.environment.tilemap.xml.MapObject; import de.gurkenlabs.litiengine.environment.tilemap.xml.MapObjectLayer; import de.gurkenlabs.litiengine.environment.tilemap.xml.Tileset; import de.gurkenlabs.litiengine.environment.tilemap.xml.TmxMap; import de.gurkenlabs.litiengine.graphics.Spritesheet; import de.gurkenlabs.litiengine.gui.ComponentMouseEvent; import de.gurkenlabs.litiengine.gui.ComponentMouseWheelEvent; import de.gurkenlabs.litiengine.gui.GuiComponent; import de.gurkenlabs.litiengine.input.Input; import de.gurkenlabs.litiengine.physics.Collision; import de.gurkenlabs.litiengine.resources.ImageFormat; import de.gurkenlabs.litiengine.resources.Resources; import de.gurkenlabs.litiengine.resources.SpritesheetResource; import de.gurkenlabs.litiengine.util.MathUtilities; import de.gurkenlabs.litiengine.util.geom.GeometricUtilities; import de.gurkenlabs.litiengine.util.io.FileUtilities; import de.gurkenlabs.litiengine.util.io.ImageSerializer; import de.gurkenlabs.utiliti.Cursors; import de.gurkenlabs.utiliti.UndoManager; import de.gurkenlabs.utiliti.handlers.Snap; import de.gurkenlabs.utiliti.handlers.Transform; import de.gurkenlabs.utiliti.handlers.Transform.TransformType; import de.gurkenlabs.utiliti.handlers.Zoom; import de.gurkenlabs.utiliti.renderers.Renderers; import de.gurkenlabs.utiliti.swing.UI; import de.gurkenlabs.utiliti.swing.dialogs.ConfirmDialog; import de.gurkenlabs.utiliti.swing.dialogs.XmlExportDialog; import de.gurkenlabs.utiliti.swing.dialogs.XmlImportDialog; public class MapComponent extends GuiComponent { public static final int EDITMODE_CREATE = 0; public static final int EDITMODE_EDIT = 1; /** * @deprecated Will be replaced by {@link TransformType#MOVE} */ @Deprecated() public static final int EDITMODE_MOVE = 2; private static final Logger log = Logger.getLogger(MapComponent.class.getName()); private static final int BASE_SCROLL_SPEED = 50; private final List<IntConsumer> editModeChangedConsumer; private final List<Consumer<IMapObject>> focusChangedConsumer; private final List<Consumer<List<IMapObject>>> selectionChangedConsumer; private final List<Consumer<TmxMap>> loadingConsumer; private final List<Consumer<TmxMap>> loadedConsumer; private final List<Consumer<Blueprint>> copyTargetChangedConsumer; private final Map<String, Point2D> cameraFocus; private final Map<String, IMapObject> focusedObjects; private final Map<String, List<IMapObject>> selectedObjects; private final Map<String, Environment> environments; private int editMode = EDITMODE_EDIT; private final List<TmxMap> maps; private double scrollSpeed = BASE_SCROLL_SPEED; private Point2D startPoint; private Blueprint copiedBlueprint; /** * This flag is used to control the undo behavior of a <b>move * transformation</b>. It ensures that the UndoManager tracks the "changing" * event in the beginning of the operation (when the key event is recorded for * the first time) and also triggers the "changed" event upon key release. */ private boolean isMoving; /** * This flag is used to control the undo behavior of a <b>resize * transformation</b>. It ensures that the UndoManager tracks the "changing" * event in the beginning of the operation (when the key event is recorded for * the first time) and also triggers the "changed" event upon key release. */ private boolean isResizing; /** * This flag is used to bundle a move operation over several key events until * the arrow keys are released. This allows for the UndoManager to revert the * keyboard move operation once instead of having to revert for each * individual key stroke. */ private boolean isMovingWithKeyboard; /** * This flag prevents circular focusing approaches while this instance is * already performing a focus process. */ private boolean isFocussing; /** * This flag prevents certain UI operations from executing while the editor is * loading an environment. */ private boolean loading; /** * Ensures that various initialization processes are only carried out once. */ private boolean initialized; public MapComponent() { super(0, 0); this.editModeChangedConsumer = new CopyOnWriteArrayList<>(); this.focusChangedConsumer = new CopyOnWriteArrayList<>(); this.selectionChangedConsumer = new CopyOnWriteArrayList<>(); this.loadingConsumer = new CopyOnWriteArrayList<>(); this.loadedConsumer = new CopyOnWriteArrayList<>(); this.copyTargetChangedConsumer = new CopyOnWriteArrayList<>(); this.focusedObjects = new ConcurrentHashMap<>(); this.selectedObjects = new ConcurrentHashMap<>(); this.environments = new ConcurrentHashMap<>(); this.maps = new CopyOnWriteArrayList<>(); this.cameraFocus = new ConcurrentHashMap<>(); this.onMouseEnter(e -> Game.window().cursor().setVisible(true)); this.onMouseLeave(e -> Game.window().cursor().setVisible(false)); UndoManager.onUndoStackChanged(e -> Transform.updateAnchors()); } public static boolean mapIsNull() { return Game.world().environment() == null || Game.world().environment().getMap() == null; } public void onEditModeChanged(IntConsumer cons) { this.editModeChangedConsumer.add(cons); } public void onFocusChanged(Consumer<IMapObject> cons) { this.focusChangedConsumer.add(cons); } public void onSelectionChanged(Consumer<List<IMapObject>> cons) { this.selectionChangedConsumer.add(cons); } public void onMapLoading(Consumer<TmxMap> cons) { this.loadingConsumer.add(cons); } public void onMapLoaded(Consumer<TmxMap> cons) { this.loadedConsumer.add(cons); } public void onCopyTargetChanged(Consumer<Blueprint> cons) { this.copyTargetChangedConsumer.add(cons); } @Override public void render(Graphics2D g) { if (Game.world().environment() == null) { return; } Renderers.render(g); super.render(g); } public void loadMaps(String projectPath) { final List<String> files = FileUtilities.findFilesByExtension(new ArrayList<>(), Paths.get(projectPath), "tmx"); log.log(Level.INFO, "{0} maps found in folder {1}", new Object[] { files.size(), projectPath }); final List<TmxMap> loadedMaps = new ArrayList<>(); for (final String mapFile : files) { TmxMap map = (TmxMap) Resources.maps().get(mapFile); if (map != null) { // if an error occurred or it's not in the expected // format loadedMaps.add(map); log.log(Level.INFO, "map found: {0}", new Object[] { map.getName() }); } } this.loadMaps(loadedMaps, true); } public void loadMaps(List<TmxMap> maps, boolean clearSelection) { if (maps == null) { return; } UI.getInspector().bind(null); this.setFocus(null, true); this.getMaps().clear(); Collections.sort(maps); this.getMaps().addAll(maps); UI.getMapController().bind(this.getMaps(), clearSelection); } public List<TmxMap> getMaps() { return this.maps; } public IMapObject getFocusedMapObject() { if (Game.world().environment() != null && Game.world().environment().getMap() != null) { return this.focusedObjects.get(Game.world().environment().getMap().getName()); } return null; } public Rectangle2D getFocusBounds() { final IMapObject focusedObject = this.getFocusedMapObject(); if (focusedObject == null) { return null; } return focusedObject.getBoundingBox(); } public List<IMapObject> getSelectedMapObjects() { if (Game.world().environment() != null && Game.world().environment().getMap() != null) { final String map = Game.world().environment().getMap().getName(); if (this.selectedObjects.containsKey(map)) { return this.selectedObjects.get(map); } } return new ArrayList<>(); } public Blueprint getCopiedBlueprint() { return this.copiedBlueprint; } public boolean isLoading() { return this.loading; } @Override public void prepare() { Game.world().camera().onZoom(event -> { Transform.updateAnchors(); this.scrollSpeed = BASE_SCROLL_SPEED / event.getZoom(); }); Zoom.applyPreference(); if (!this.initialized) { Game.window().getRenderComponent().addFocusListener(new FocusAdapter() { @Override public void focusLost(FocusEvent e) { startPoint = null; } }); this.setupKeyboardControls(); this.setupMouseControls(); this.initialized = true; } super.prepare(); } public void loadEnvironment(TmxMap map) { if (map == null) { return; } this.loading = true; try { if (Game.world().environment() != null && Game.world().environment().getMap() != null) { final String mapName = Game.world().environment().getMap().getName(); double x = Game.world().camera().getFocus().getX(); double y = Game.world().camera().getFocus().getY(); Point2D newPoint = new Point2D.Double(x, y); this.cameraFocus.put(mapName, newPoint); } for (Consumer<TmxMap> cons : this.loadingConsumer) { cons.accept(Game.world().environment() != null ? ((TmxMap) Game.world().environment().getMap()) : null); } Point2D newFocus = null; if (this.cameraFocus.containsKey(map.getName())) { newFocus = this.cameraFocus.get(map.getName()); } else { newFocus = new Point2D.Double(map.getSizeInPixels().getWidth() / 2, map.getSizeInPixels().getHeight() / 2); this.cameraFocus.put(map.getName(), newFocus); } Game.world().camera().setFocus(new Point2D.Double(newFocus.getX(), newFocus.getY())); if (!this.environments.containsKey(map.getName())) { Environment env = new Environment(map); env.init(); this.environments.put(map.getName(), env); } Game.world().loadEnvironment(this.environments.get(map.getName())); UI.getMapController().setSelection(map); UI.getInspector().bind(this.getFocusedMapObject()); for (Consumer<TmxMap> cons : this.loadedConsumer) { cons.accept(map); } } finally { this.loading = false; } } public void reloadEnvironment() { if (mapIsNull()) { return; } this.loadEnvironment((TmxMap) Game.world().environment().getMap()); } public void add(IMapObject mapObject) { this.add(mapObject, UI.getLayerController().getCurrentLayer()); UndoManager.instance().mapObjectAdded(mapObject); } public void add(IMapObjectLayer layer) { if (layer == null) { return; } this.getSelectedMapObjects().clear(); this.setFocus(null, true); for (IMapObject mapObject : layer.getMapObjects()) { Game.world().environment().loadFromMap(mapObject.getId()); this.setSelection(mapObject, false); this.setFocus(mapObject, false); } Transform.updateAnchors(); this.setEditMode(EDITMODE_MOVE); } public void add(IMapObject mapObject, IMapObjectLayer layer) { if (layer == null || mapObject == null) { return; } layer.addMapObject(mapObject); Game.world().environment().loadFromMap(mapObject.getId()); Game.window().getRenderComponent().requestFocus(); this.setFocus(mapObject, false); this.setEditMode(EDITMODE_EDIT); } public void delete(IMapObjectLayer layer) { if (layer == null) { return; } boolean shadow = layer.getMapObjects().stream().anyMatch(x -> MapObjectType.get(x.getType()) == MapObjectType.STATICSHADOW); for (IMapObject mapObject : layer.getMapObjects()) { if (!shadow && MapObjectType.get(mapObject.getType()) == MapObjectType.LIGHTSOURCE) { Game.world().environment().updateLighting(mapObject.getBoundingBox()); } Game.world().environment().remove(mapObject.getId()); if (mapObject.equals(this.getFocusedMapObject())) { this.setFocus(null, true); } this.getSelectedMapObjects().remove(mapObject); } if (shadow) { Game.world().environment().updateLighting(); } } public void copy() { this.setCopyBlueprint(new Blueprint("", this.getSelectedMapObjects().toArray(new MapObject[this.getSelectedMapObjects().size()]))); } public void paste() { if (this.copiedBlueprint == null) { return; } int x = (int) Input.mouse().getMapLocation().getX(); int y = (int) Input.mouse().getMapLocation().getY(); this.paste(x, y); } public void paste(int x, int y) { if (this.copiedBlueprint == null) { return; } UndoManager.instance().beginOperation(); try { this.setFocus(null, true); for (IMapObject mapObject : this.copiedBlueprint.build(x, y)) { this.add(mapObject); this.setSelection(mapObject, false); } // clean up copied blueprints in case, we cut the objects and kept the IDs if (this.copiedBlueprint.keepIds()) { this.setCopyBlueprint(null); } } finally { UndoManager.instance().endOperation(); } } public void cut() { this.setCopyBlueprint(new Blueprint("", true, this.getSelectedMapObjects().toArray(new MapObject[this.getSelectedMapObjects().size()]))); UndoManager.instance().beginOperation(); try { for (IMapObject mapObject : this.getSelectedMapObjects()) { // call the undomanager first because otherwise the information about // the object's layer will be lost UndoManager.instance().mapObjectDeleted(mapObject); this.delete(mapObject); } } finally { UndoManager.instance().endOperation(); } } public void clearAll() { this.focusedObjects.clear(); UI.getLayerController().clear(); this.selectedObjects.clear(); this.cameraFocus.clear(); this.environments.clear(); } public void delete() { if (this.isSuspended() || !this.isVisible() || this.getFocusedMapObject() == null) { return; } UndoManager.instance().beginOperation(); try { for (IMapObject deleteObject : this.getSelectedMapObjects()) { if (deleteObject == null) { continue; } // call the undomanager first because otherwise the information about // the object's layer will be lost UndoManager.instance().mapObjectDeleted(deleteObject); this.delete(deleteObject); } } finally { UndoManager.instance().endOperation(); UI.getEntityController().refresh(); } } public void selectAll() { final List<IMapObjectLayer> layers = Game.world().environment().getMap().getMapObjectLayers(); ArrayList<IMapObject> selection = new ArrayList<>(); for (final IMapObjectLayer layer : layers) { if (layer == null || !layer.isVisible()) { continue; } selection.addAll(layer.getMapObjects()); this.setSelection(selection, true); } } public void deselect() { this.setSelection(Collections.emptyList(), true); } public void delete(final IMapObject mapObject) { if (mapObject == null) { return; } Game.world().environment().getMap().removeMapObject(mapObject.getId()); Game.world().environment().remove(mapObject.getId()); if (mapObject.equals(this.getFocusedMapObject())) { this.setFocus(null, true); } } public void defineBlueprint() { if (this.getFocusedMapObject() == null) { return; } Object name = JOptionPane.showInputDialog(Game.window().getRenderComponent(), Resources.strings().get("input_prompt_name"), Resources.strings().get("input_prompt_name_title"), JOptionPane.PLAIN_MESSAGE, null, null, this.getFocusedMapObject().getName()); if (name == null) { return; } Blueprint blueprint = new Blueprint(name.toString(), this.getSelectedMapObjects().toArray(new MapObject[this.getSelectedMapObjects().size()])); Editor.instance().getGameFile().getBluePrints().add(blueprint); } public void centerCameraOnFocus() { if (this.hasFocus() && this.getFocusedMapObject() != null) { final Rectangle2D focus = this.getFocusBounds(); if (focus == null) { return; } Game.world().camera().setFocus(new Point2D.Double(focus.getCenterX(), focus.getCenterY())); } } public void centerCameraOnMap() { final Environment env = Game.world().environment(); if (env == null) { return; } Game.world().camera().setFocus(env.getCenter()); } public int getEditMode() { return this.editMode; } public void setEditMode(int editMode) { if (editMode == this.editMode) { return; } switch (editMode) { case EDITMODE_CREATE: this.setFocus(null, true); UI.getInspector().bind(null); Game.window().cursor().set(Cursors.ADD, 0, 0); break; case EDITMODE_EDIT: Game.window().cursor().set(Cursors.DEFAULT, 0, 0); break; case EDITMODE_MOVE: Game.window().cursor().set(Cursors.MOVE, 0, 0); break; default: break; } this.editMode = editMode; for (IntConsumer cons : this.editModeChangedConsumer) { cons.accept(this.editMode); } } public void setFocus(IMapObject mapObject, boolean clearSelection) { if (this.isFocussing) { return; } this.isFocussing = true; try { final IMapObject currentFocus = this.getFocusedMapObject(); if (mapObject != null && currentFocus != null && mapObject.equals(currentFocus) || mapObject == null && currentFocus == null) { return; } if (mapIsNull()) { return; } if (this.isMoving || this.isResizing) { return; } UI.getInspector().bind(mapObject); UI.getEntityController().select(mapObject); if (mapObject == null) { this.focusedObjects.remove(Game.world().environment().getMap().getName()); } else { this.focusedObjects.put(Game.world().environment().getMap().getName(), mapObject); } for (Consumer<IMapObject> cons : this.focusChangedConsumer) { cons.accept(mapObject); } Transform.updateAnchors(); this.setSelection(mapObject, clearSelection); } finally { this.isFocussing = false; } } public void setSelection(IMapObject mapObject, boolean clearSelection) { this.setSelection(mapObject == null ? null : Collections.singletonList(mapObject), clearSelection); } public void setSelection(List<IMapObject> mapObjects, boolean clearSelection) { if (mapObjects == null || mapObjects.isEmpty()) { this.getSelectedMapObjects().clear(); for (Consumer<List<IMapObject>> cons : this.selectionChangedConsumer) { cons.accept(this.getSelectedMapObjects()); } return; } final String map = Game.world().environment().getMap().getName(); if (!this.selectedObjects.containsKey(map)) { this.selectedObjects.put(map, new CopyOnWriteArrayList<>()); } if (clearSelection) { this.getSelectedMapObjects().clear(); } for (IMapObject mapObject : mapObjects) { if (!this.getSelectedMapObjects().contains(mapObject)) { this.getSelectedMapObjects().add(mapObject); } } for (Consumer<List<IMapObject>> cons : this.selectionChangedConsumer) { cons.accept(this.getSelectedMapObjects()); } } public void deleteMap() { if (this.getMaps() == null || this.getMaps().isEmpty()) { return; } if (mapIsNull()) { return; } if (!ConfirmDialog.show(Resources.strings().get("hud_deleteMap"), Resources.strings().get("hud_deleteMapMessage") + "\n" + Game.world().environment().getMap().getName())) { return; } this.getMaps().removeIf(x -> x.getName().equals(Game.world().environment().getMap().getName())); // TODO: remove all tile sets from the game file that are no longer needed // by any other map. UI.getMapController().bind(this.getMaps()); if (!this.maps.isEmpty()) { this.loadEnvironment(this.maps.get(0)); } else { this.loadEnvironment(null); } Editor.instance().updateGameFileMaps(); } public void importMap() { if (this.getMaps() == null) { return; } XmlImportDialog.importXml("Tilemap", file -> { String mapPath = file.toURI().toString(); Resources.maps().clear(); TmxMap map = (TmxMap) Resources.maps().get(mapPath); if (map == null) { log.log(Level.WARNING, "could not load map from file {0}", new Object[] { mapPath }); return; } if (map.getMapObjectLayers().isEmpty()) { // make sure there's a map object layer on the map because we need one // to add any kind of entities MapObjectLayer layer = new MapObjectLayer(); layer.setName(MapObjectLayer.DEFAULT_MAPOBJECTLAYER_NAME); map.addLayer(layer); } Optional<TmxMap> current = this.maps.stream().filter(x -> x.getName().equals(map.getName())).findFirst(); if (current.isPresent()) { if (ConfirmDialog.show(Resources.strings().get("input_replace_map_title"), Resources.strings().get("input_replace_map", map.getName()))) { this.getMaps().remove(current.get()); } else { return; } } this.getMaps().add(map); Collections.sort(this.getMaps()); for (IImageLayer imageLayer : map.getImageLayers()) { BufferedImage img = Resources.images().get(imageLayer.getImage().getAbsoluteSourcePath(), true); if (img == null) { continue; } Spritesheet sprite = Resources.spritesheets().load(img, imageLayer.getImage().getSource(), img.getWidth(), img.getHeight()); Editor.instance().getGameFile().getSpriteSheets().add(new SpritesheetResource(sprite)); } // remove old spritesheets for (ITileset tileSet : map.getTilesets()) { Editor.instance().loadTileset(tileSet, true); } // remove old tilesets for (ITileset tileset : map.getExternalTilesets()) { Editor.instance().loadTileset(tileset, false); } Editor.instance().updateGameFileMaps(); Resources.images().clear(); if (this.environments.containsKey(map.getName())) { this.environments.remove(map.getName()); } UI.getMapController().bind(this.getMaps(), true); this.loadEnvironment(map); log.log(Level.INFO, "imported map {0}", new Object[] { map.getName() }); }, TmxMap.FILE_EXTENSION); } public void exportMap() { if (this.getMaps() == null || this.getMaps().isEmpty()) { return; } TmxMap map = (TmxMap) Game.world().environment().getMap(); if (map == null) { return; } XmlExportDialog.export(map, "Map", map.getName(), TmxMap.FILE_EXTENSION, dir -> { for (ITileset tileSet : map.getTilesets()) { ImageFormat format = ImageFormat.get(FileUtilities.getExtension(tileSet.getImage().getSource())); ImageSerializer.saveImage(Paths.get(dir, tileSet.getImage().getSource()).toString(), Resources.spritesheets().get(tileSet.getImage().getSource()).getImage(), format); Tileset tile = (Tileset) tileSet; if (tile.isExternal()) { tile.saveSource(dir); } } }); } public void reassignIds(TmxMap map, int startID) { int maxMapId = startID; UndoManager.instance().beginOperation(); for (IMapObject obj : map.getMapObjects()) { final int previousId = obj.getId(); UndoManager.instance().mapObjectChanging(obj); obj.setId(maxMapId); UndoManager.instance().mapObjectChanged(obj, previousId); maxMapId++; } UndoManager.instance().endOperation(); Game.world().environment().clear(); Game.world().environment().load(); UI.getMapController().refresh(); log.log(Level.INFO, "Reassigned IDs for Map {0}.", new Object[] { map.getName() }); } @Override protected boolean mouseEventShouldBeForwarded(final MouseEvent e) { return this.isForwardMouseEvents() && this.isVisible() && this.isEnabled() && !this.isSuspended() && e != null; } public void saveMapSnapshot() { if (mapIsNull()) { return; } final TmxMap currentMap = (TmxMap) Game.world().environment().getMap(); Dimension size = currentMap.getOrientation().getSize(currentMap); BufferedImage img = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_ARGB); MapRenderer.render(img.createGraphics(), currentMap, currentMap.getBounds()); try { final String timeStamp = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date()); final File folder = new File("./screenshots/"); if (!folder.exists()) { folder.mkdirs(); } File snapshot = new File("./screenshots/" + timeStamp + ImageFormat.PNG.toFileExtension()); ImageSerializer.saveImage(snapshot.toString(), img); log.log(Level.INFO, "Saved map snapshot to {0}", new Object[] { snapshot.getCanonicalPath() }); } catch (Exception e) { log.log(Level.SEVERE, e.getLocalizedMessage(), e); } } public Rectangle2D getMouseSelectArea(boolean snap) { final Point2D start = this.startPoint; if (start == null) { return null; } final Point2D endPoint = Input.mouse().getMapLocation(); double minX = Math.min(start.getX(), endPoint.getX()); double maxX = Math.max(start.getX(), endPoint.getX()); double minY = Math.min(start.getY(), endPoint.getY()); double maxY = Math.max(start.getY(), endPoint.getY()); if (snap) { minX = Snap.x(minX); maxX = Snap.x(maxX); minY = Snap.y(minY); maxY = Snap.y(maxY); } final TmxMap map = (TmxMap) Game.world().environment().getMap(); if (map != null && Editor.preferences().clampToMap()) { minX = MathUtilities.clamp(minX, 0, map.getSizeInPixels().width); maxX = MathUtilities.clamp(maxX, 0, map.getSizeInPixels().width); minY = MathUtilities.clamp(minY, 0, map.getSizeInPixels().height); maxY = MathUtilities.clamp(maxY, 0, map.getSizeInPixels().height); } double width = Math.abs(minX - maxX); double height = Math.abs(minY - maxY); return new Rectangle2D.Double(minX, minY, width, height); } private IMapObject createNewMapObject(MapObjectType type) { final Rectangle2D newObjectArea = this.getMouseSelectArea(true); IMapObject mo = new MapObject(); mo.setType(type.toString()); mo.setX((float) newObjectArea.getX()); mo.setY((float) newObjectArea.getY()); // ensure a minimum size for the new object float width = (float) newObjectArea.getWidth(); float height = (float) newObjectArea.getHeight(); mo.setWidth(width == 0 ? 16 : width); mo.setHeight(height == 0 ? 16 : height); mo.setId(Game.world().environment().getNextMapId()); mo.setName(""); switch (type) { case PROP: mo.setValue(MapObjectProperty.COLLISIONBOX_WIDTH, (newObjectArea.getWidth() * 0.4)); mo.setValue(MapObjectProperty.COLLISIONBOX_HEIGHT, (newObjectArea.getHeight() * 0.4)); mo.setValue(MapObjectProperty.COLLISION, true); mo.setValue(MapObjectProperty.COMBAT_INDESTRUCTIBLE, false); mo.setValue(MapObjectProperty.PROP_ADDSHADOW, true); break; case LIGHTSOURCE: mo.setValue(MapObjectProperty.LIGHT_COLOR, Color.WHITE); mo.setValue(MapObjectProperty.LIGHT_SHAPE, "ellipse"); mo.setValue(MapObjectProperty.LIGHT_ACTIVE, true); break; case COLLISIONBOX: mo.setValue(MapObjectProperty.COLLISION_TYPE, Collision.STATIC); break; case SPAWNPOINT: default: break; } this.add(mo); return mo; } private void setCopyBlueprint(Blueprint copyTarget) { this.copiedBlueprint = copyTarget; for (Consumer<Blueprint> consumer : this.copyTargetChangedConsumer) { consumer.accept(this.copiedBlueprint); } } private void setupKeyboardControls() { Input.keyboard().onKeyPressed(KeyEvent.VK_CONTROL, e -> { if (this.editMode == EDITMODE_EDIT && this.getFocusBounds() != null) { this.setEditMode(EDITMODE_MOVE); } }); Input.keyboard().onKeyReleased(KeyEvent.VK_CONTROL, e -> { if (this.editMode == EDITMODE_MOVE) { this.setEditMode(EDITMODE_EDIT); } }); Input.keyboard().onKeyPressed(KeyEvent.VK_ESCAPE, e -> { if (this.editMode == EDITMODE_CREATE) { this.setEditMode(EDITMODE_EDIT); } }); Input.keyboard().onKeyReleased(e -> { if (e.getKeyCode() != KeyEvent.VK_RIGHT && e.getKeyCode() != KeyEvent.VK_LEFT && e.getKeyCode() != KeyEvent.VK_UP && e.getKeyCode() != KeyEvent.VK_DOWN) { return; } // if one of the move buttons is still pressed, don't end the operation if (Input.keyboard().isPressed(KeyEvent.VK_RIGHT) || Input.keyboard().isPressed(KeyEvent.VK_LEFT) || Input.keyboard().isPressed(KeyEvent.VK_UP) || Input.keyboard().isPressed(KeyEvent.VK_DOWN)) { return; } this.afterArrowKeysReleased(); }); Input.keyboard().onKeyPressed(KeyEvent.VK_RIGHT, e -> this.handleKeyboardTransform(1, 0)); Input.keyboard().onKeyPressed(KeyEvent.VK_LEFT, e -> this.handleKeyboardTransform(-1, 0)); Input.keyboard().onKeyPressed(KeyEvent.VK_UP, e -> this.handleKeyboardTransform(0, -1)); Input.keyboard().onKeyPressed(KeyEvent.VK_DOWN, e -> this.handleKeyboardTransform(0, 1)); } private void handleKeyboardTransform(int x, int y) { if (!Game.window().getRenderComponent().hasFocus()) { return; } this.beforeArrowKeyPressed(); Transform.moveEntities(this.getSelectedMapObjects(), x, y); } private void beforeArrowKeyPressed() { if (!this.isMovingWithKeyboard) { UndoManager.instance().beginOperation(); for (IMapObject selected : this.getSelectedMapObjects()) { UndoManager.instance().mapObjectChanging(selected); } this.isMovingWithKeyboard = true; } Transform.startDragging(this.getSelectedMapObjects()); } private void afterArrowKeysReleased() { if (this.isMovingWithKeyboard) { for (IMapObject selected : this.getSelectedMapObjects()) { UndoManager.instance().mapObjectChanged(selected); } UndoManager.instance().endOperation(); this.isMovingWithKeyboard = false; Transform.resetDragging(); } } private void setupMouseControls() { this.onMouseWheelScrolled(this::handleMouseWheelScrolled); this.onMouseMoved(this::handleMouseMoved); this.onMousePressed(this::handleMousePressed); this.onMouseDragged(this::handleMouseDragged); this.onMouseReleased(this::handleMouseReleased); } private void handleMouseWheelScrolled(ComponentMouseWheelEvent e) { if (!this.hasFocus() || mapIsNull()) { return; } final Point2D currentFocus = Game.world().camera().getFocus(); // horizontal scrolling if (Input.keyboard().isPressed(KeyEvent.VK_CONTROL)) { if (e.getEvent().getWheelRotation() < 0) { Point2D newFocus = new Point2D.Double(currentFocus.getX() - this.scrollSpeed, currentFocus.getY()); Game.world().camera().setFocus(newFocus); } else { Point2D newFocus = new Point2D.Double(currentFocus.getX() + this.scrollSpeed, currentFocus.getY()); Game.world().camera().setFocus(newFocus); } return; } if (Input.keyboard().isPressed(KeyEvent.VK_ALT)) { if (e.getEvent().getWheelRotation() < 0) { Zoom.in(); } else { Zoom.out(); } return; } if (e.getEvent().getWheelRotation() < 0) { Point2D newFocus = new Point2D.Double(currentFocus.getX(), currentFocus.getY() - this.scrollSpeed); Game.world().camera().setFocus(newFocus); } else { Point2D newFocus = new Point2D.Double(currentFocus.getX(), currentFocus.getY() + this.scrollSpeed); Game.world().camera().setFocus(newFocus); } } /*** * Handles the mouse moved event and executes the following: * <ol> * <li>Set cursor image depending on the hovered transform control</li> * <li>Update the currently active transform field.</li> * </ol> * * @param e * The mouse event of the calling {@link GuiComponent} */ private void handleMouseMoved(ComponentMouseEvent e) { Transform.updateTransform(); } private void handleMousePressed(ComponentMouseEvent e) { if (!this.hasFocus() || mapIsNull()) { return; } if (Transform.type() == TransformType.MOVE) { this.setEditMode(EDITMODE_MOVE); } switch (this.editMode) { case EDITMODE_CREATE: case EDITMODE_MOVE: if (SwingUtilities.isLeftMouseButton(e.getEvent())) { this.startPoint = Input.mouse().getMapLocation(); } break; case EDITMODE_EDIT: if (this.isMoving || Transform.type() == TransformType.RESIZE || SwingUtilities.isRightMouseButton(e.getEvent())) { return; } final Point2D mouse = Input.mouse().getMapLocation(); this.startPoint = mouse; break; default: break; } } private void handleMouseDragged(ComponentMouseEvent e) { if (!this.hasFocus() || mapIsNull()) { return; } switch (this.editMode) { case EDITMODE_EDIT: if (Transform.type() == TransformType.RESIZE) { if (!this.isResizing) { this.isResizing = true; UndoManager.instance().mapObjectChanging(this.getFocusedMapObject()); } Transform.resize(); } break; case EDITMODE_MOVE: if (!this.isMoving) { this.isMoving = true; UndoManager.instance().beginOperation(); for (IMapObject selected : this.getSelectedMapObjects()) { UndoManager.instance().mapObjectChanging(selected); } } Transform.move(); break; default: break; } } private void handleMouseReleased(ComponentMouseEvent e) { if (!this.hasFocus() || mapIsNull() || !SwingUtilities.isLeftMouseButton(e.getEvent())) { return; } Transform.resetDragging(); switch (this.editMode) { case EDITMODE_CREATE: if (SwingUtilities.isRightMouseButton(e.getEvent())) { this.setEditMode(EDITMODE_EDIT); break; } IMapObject mo = this.createNewMapObject(UI.getInspector().getObjectType()); this.setFocus(mo, !Input.keyboard().isPressed(KeyEvent.VK_SHIFT)); UI.getInspector().bind(mo); this.setEditMode(EDITMODE_EDIT); break; case EDITMODE_MOVE: if (this.isMoving) { this.isMoving = false; for (IMapObject selected : this.getSelectedMapObjects()) { UndoManager.instance().mapObjectChanged(selected); } UndoManager.instance().endOperation(); this.setEditMode(EDITMODE_EDIT); } else { this.setEditMode(EDITMODE_EDIT); this.evaluateFocus(); } break; case EDITMODE_EDIT: if (this.isMoving || this.isResizing) { this.isMoving = false; this.isResizing = false; UndoManager.instance().mapObjectChanged(this.getFocusedMapObject()); } if (this.startPoint == null) { return; } this.evaluateFocus(); break; default: break; } this.startPoint = null; } private void evaluateFocus() { Rectangle2D rect = this.getMouseSelectArea(false); if (rect == null) { return; } boolean somethingIsFocused = false; boolean currentObjectFocused = false; for (IMapObjectLayer layer : Game.world().environment().getMap().getMapObjectLayers()) { if (layer == null || !layer.isVisible()) { continue; } for (IMapObject mapObject : layer.getMapObjects()) { if (mapObject == null) { continue; } MapObjectType type = MapObjectType.get(mapObject.getType()); if (type == null || !GeometricUtilities.intersects(rect, mapObject.getBoundingBox())) { continue; } if (this.getFocusedMapObject() != null && mapObject.getId() == this.getFocusedMapObject().getId()) { currentObjectFocused = true; continue; } if (somethingIsFocused) { if (rect.getWidth() == 0 && rect.getHeight() == 0) { break; } this.setSelection(mapObject, false); continue; } if (this.getSelectedMapObjects().contains(mapObject)) { this.getSelectedMapObjects().remove(mapObject); } else { this.setFocus(mapObject, !Input.keyboard().isPressed(KeyEvent.VK_SHIFT)); } somethingIsFocused = true; } } if (!somethingIsFocused && !currentObjectFocused) { this.setFocus(null, true); this.setSelection(Collections.emptyList(), true); } } private boolean hasFocus() { if (this.isSuspended() || !this.isVisible()) { return false; } for (GuiComponent comp : this.getComponents()) { if (comp.isHovered() && !comp.isSuspended()) { return false; } } return true; } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package net.maizegenetics.pal.popgen; import java.util.ArrayList; import java.util.Arrays; import java.util.Map; import java.util.TreeMap; import net.maizegenetics.gwas.imputation.EmissionProbability; import net.maizegenetics.gwas.imputation.TransitionProbability; import net.maizegenetics.gwas.imputation.ViterbiAlgorithm; import net.maizegenetics.pal.alignment.*; import net.maizegenetics.pal.distance.IBSDistanceMatrix; import net.maizegenetics.util.BitSet; import net.maizegenetics.util.BitUtil; import net.maizegenetics.util.OpenBitSet; import net.maizegenetics.util.ProgressListener; /** * Imputation methods that relies on an alignment of possible gametes (donorAlign), and optimized for * highly heterozygous samples. It works at the scale of 64 sites to accelerate searching * through all possible parental combinations for a window. * * It only begins each 64 site block and expand outward to find set number of minor * alleles in the target sequence, and then it looks for all possible parents. * * TODO: remove bad sites, add hets back in * 4. Viterbi between sub-chromosome segments * 5. Pre-compute IBD probabilities for different number of sites and divergences * (Doing this by poisson on the fly is too slow, and use this rank best hybrid or inbred * 6. Error rates by taxon * * TESTS: * 1. Do not impute the invariant sites - tested doesn't matter * 2. Change imputation to fixed windows - minor allele is a little more sensitive, but not by much * 3. Change resolve regionally to HMM - it may work better with 2 * * @author edbuckler, kswarts, aromero */ public class MinorWindowViterbiImputation { private Alignment unimpAlign; //the unimputed alignment to be imputed, unphased private Alignment donorAlign; //these are the reference haplotypes, that must be homozygous private int testing=0; //level of reporting to stdout //major and minor alleles can be differ between the donor and unimp alignment //these Bit sets keep track of the differences private OpenBitSet swapMjMnMask, invariantMask, errorMask, goodMask; private boolean isSwapMajorMinor=false; //if swapped try to fix it //variables for tracking accuracy private int totalRight=0, totalWrong=0; //global variables tracking errors on the fly private int[] siteErrors, siteCallCnt; //error recorded by sites private int blocks=-1; //total number 64 site words in the alignment private int minMajorRatioToMinorCnt=10; //refinement of minMinorCnt to account for regions with all major private int maxDonorHypotheses=10; //number of hypotheses of record from an inbred or hybrid search of a focus block private double maximumInbredError=0.02; //inbreds are tested first, if too much error hybrids are tested. // private double maxViterbiErro private int minTestSites=100; //minimum number of compared sites to find a hit //matrix to hold divergence comparisons between the target taxon and donor haplotypes for each block //dimensions: [donor taxa][sites, same count, diff count, het count][blocks] private byte[][][] allDist; //initialize the transition matrix double[][] transition = new double[][] { {.999,.0001,.0003,.0001,.0005}, {.0002,.999,.00005,.00005,.0002}, {.0002,.00005,.999,.00005,.0002}, {.0002,.00005,.00005,.999,.0002}, {.0005,.0001,.0003,.0001,.999} }; //initialize the emission matrix, states (5) in rows, observations (3) in columns double[][] emission = new double[][] { {.98,.001,.001}, {.6,.2,.2}, {.4,.2,.4}, {.2,.2,.6}, {.001,.001,.98} }; TransitionProbability tp = new TransitionProbability(); EmissionProbability ep = new EmissionProbability(); int[] donorIndices; private static int highMask=0xF0; private static int lowMask=0x0F; /** * * @param donorFile should be phased haplotypes * @param unImpTargetFile sites must match exactly with donor file * @param exportFile output file of imputed sites * @param minMinorCnt determines the size of the search window, low recombination 20-30, high recombination 10-15 * @param hybridMode true=do hybrid search */ public MinorWindowViterbiImputation(String donorFile, String unImpTargetFile, String exportFile, int minMinorCnt, int minTestSites, int minSitesPresent, double maxHybridErrorRate, boolean hybridMode) { this.minTestSites=minTestSites; donorAlign=ImportUtils.readFromHapmap(donorFile, false, (ProgressListener)null); donorAlign.optimizeForTaxa(null); System.out.printf("Donor taxa:%d sites:%d %n",donorAlign.getSequenceCount(),donorAlign.getSiteCount()); donorIndices=new int[donorAlign.getSequenceCount()]; for (int i = 0; i < donorIndices.length; i++) {donorIndices[i]=i;} unimpAlign=ImportUtils.readFromHapmap(unImpTargetFile, false, (ProgressListener)null); unimpAlign.optimizeForTaxa(null); siteErrors=new int[unimpAlign.getSiteCount()]; siteCallCnt=new int[unimpAlign.getSiteCount()]; tp.setTransitionProbability(transition); ep.setEmissionProbability(emission); System.out.printf("Unimputed taxa:%d sites:%d %n",unimpAlign.getSequenceCount(),unimpAlign.getSiteCount()); System.out.println("Creating mutable alignment"); blocks=unimpAlign.getAllelePresenceForAllSites(0, 0).getNumWords(); createMaskForAlignmentConflicts(); MutableNucleotideAlignment mna=MutableNucleotideAlignment.getInstance(this.unimpAlign); //output data matrix long time=System.currentTimeMillis(); int countFullLength=0; for (int taxon = 0; taxon < unimpAlign.getSequenceCount(); taxon+=1) { //int hybrid=0; int blocksSolved=0; System.out.println(""); DonorHypoth[][] regionHypth=new DonorHypoth[blocks][maxDonorHypotheses]; String name=unimpAlign.getIdGroup().getIdentifier(taxon).getFullName(); BitSet[] maskedTargetBits=arrangeMajorMinorBtwAlignments(unimpAlign,taxon); System.out.printf("Imputing %d:%s Mj:%d, Mn:%d Unk:%d ... ", taxon,name,maskedTargetBits[0].cardinality(), maskedTargetBits[1].cardinality(), countUnknown(mna,taxon)); if(unimpAlign.getTotalNotMissingForTaxon(taxon)<minSitesPresent) continue; calcInbredDist(maskedTargetBits); for (int focusBlock = 0; focusBlock < blocks; focusBlock++) { int[] resultRange=getBlockWithMinMinorCount(maskedTargetBits[0].getBits(),maskedTargetBits[1].getBits(), focusBlock, minMinorCnt); if(resultRange==null) continue; //no data in the focus Block //search for the best inbred donors for a segment regionHypth[focusBlock]=getBestInbredDonors(taxon, resultRange[0],resultRange[2], focusBlock, donorIndices); } boolean foundit=apply1or2Haplotypes(taxon, regionHypth, mna, maskedTargetBits); if(foundit) { countFullLength++; } else { //System.out.print(".. solveRegionally3 running .."); blocksSolved=solveRegionally3(mna, taxon, regionHypth, hybridMode, maskedTargetBits, minMinorCnt, maxHybridErrorRate); } int unk=countUnknown(mna,taxon); System.out.printf("Viterbi: %s BlocksSolved:%d Done Unk: %d Prop:%g", foundit, blocksSolved, unk, (double)unk/(double)mna.getSiteCount()); } System.out.println(""); System.out.println("Time:"+(time-System.currentTimeMillis())); StringBuilder s=new StringBuilder(); s.append(String.format("%s %s MinMinor:%d ", donorFile, unImpTargetFile, minMinorCnt)); System.out.println(s.toString()); System.out.printf("TotalRight %d TotalWrong %d Rate%n",totalRight, totalWrong); // for (int i = 0; i < siteErrors.length; i++) { // System.out.printf("%d %d %d %g %g %n",i,siteCallCnt[i],siteErrors[i], // (double)siteErrors[i]/(double)siteCallCnt[i], unimpAlign.getMinorAlleleFrequency(i)); ExportUtils.writeToHapmap(mna, false, exportFile, '\t', null); System.out.printf("%d %g %d %n",minMinorCnt, maximumInbredError, maxDonorHypotheses); System.out.printf("Full length imputed %d %n ",countFullLength); } private boolean apply1or2Haplotypes(int taxon, DonorHypoth[][] regionHypth, MutableNucleotideAlignment mna, BitSet[] maskedTargetBits) { DonorHypoth vdh=null; //do flanking search if(testing==1) System.out.println("Starting complete hybrid search"); int[] d=getAllBestDonorsAcrossChromosome(regionHypth,5); DonorHypoth[] best2donors=getBestHybridDonors(taxon, maskedTargetBits[0].getBits(), maskedTargetBits[1].getBits(), 0, blocks-1, blocks/2, d, d, true); if(testing==1) System.out.println(Arrays.toString(best2donors)); if(best2donors[0]==null) return false; if(best2donors[0].getErrorRate()>maximumInbredError) return false; if(best2donors[0].donor1Taxon>=0) { if(best2donors[0].isInbred()){ // System.out.println("vdh says inbred"); vdh=best2donors[0]; } else { vdh=getStateBasedOnViterbi(best2donors[0]); } if(vdh!=null) { setAlignmentWithDonors(new DonorHypoth[] {vdh},false,mna); return true; } } return false; } /** * Create mask for all sites where major & minor are swapped in alignments */ private void createMaskForAlignmentConflicts() { goodMask=new OpenBitSet(unimpAlign.getSiteCount()); errorMask=new OpenBitSet(unimpAlign.getSiteCount()); swapMjMnMask=new OpenBitSet(unimpAlign.getSiteCount()); invariantMask=new OpenBitSet(unimpAlign.getSiteCount()); int siteConflicts=0, swaps=0, invariant=0, good=0; for (int i = 0; i < unimpAlign.getSiteCount(); i++) { /*we have three classes of data: invariant in one alignment, conflicts about minor and minor, *swaps of major and minor. Adding the invariant reduces imputation accuracy. *the major/minor swaps should be flipped in the comparisons */ if(donorAlign.getMinorAllele(i)==Alignment.UNKNOWN_ALLELE) { invariant++; invariantMask.set(i); goodMask.set(i); } else if((donorAlign.getMajorAllele(i)==unimpAlign.getMinorAllele(i))&&(donorAlign.getMinorAllele(i)==unimpAlign.getMajorAllele(i))) { swaps++; swapMjMnMask.set(i); goodMask.set(i); } else if((donorAlign.getMajorAllele(i)!=unimpAlign.getMajorAllele(i))) { siteConflicts++; errorMask.set(i); goodMask.set(i); } } goodMask.not(); System.out.println("invariant in donor:"+invariant+" swapConflicts:"+swaps+" errors:"+siteConflicts); } private int countUnknown(Alignment a, int taxon) { int cnt=0; for (int i = 0; i < a.getSiteCount(); i++) { if(a.getBase(taxon, i)==Alignment.UNKNOWN_DIPLOID_ALLELE) cnt++; } return cnt; } private BitSet[] arrangeMajorMinorBtwAlignments(Alignment unimpAlign, int bt) { OpenBitSet mjTbs=new OpenBitSet(unimpAlign.getAllelePresenceForAllSites(bt, 0)); OpenBitSet mnTbs=new OpenBitSet(unimpAlign.getAllelePresenceForAllSites(bt, 1)); mjTbs.and(goodMask); mnTbs.and(goodMask); if(isSwapMajorMinor) { OpenBitSet newmj=new OpenBitSet(unimpAlign.getAllelePresenceForAllSites(bt, 1)); OpenBitSet newmn=new OpenBitSet(unimpAlign.getAllelePresenceForAllSites(bt, 0)); newmj.and(swapMjMnMask); newmn.and(swapMjMnMask); mjTbs.or(newmj); mnTbs.or(newmn); } BitSet[] result={mjTbs,mnTbs}; return result; } /** * If the target regions has Mendelian errors that it looks for overlapping regional * solutions that are better. * TODO: This can be done much more robustly. * @param mna * @param targetTaxon * @param regionHypth */ private void solveRegionally2(MutableNucleotideAlignment mna, int targetTaxon, DonorHypoth[][] regionHypth, boolean hybridMode, BitSet[] maskedTargetBits, int minMinorCnt) { for (int focusBlock = 0; focusBlock < blocks; focusBlock++) { int[] resultRange=getBlockWithMinMinorCount(maskedTargetBits[0].getBits(),maskedTargetBits[1].getBits(), focusBlock, minMinorCnt); if(resultRange==null) continue; //no data in the focus Block //search for the best hybrid donors for a segment if(hybridMode&&(regionHypth[focusBlock][0]!=null)&&(regionHypth[focusBlock][0].getErrorRate()>maximumInbredError)) { long[] mjTRange=maskedTargetBits[0].getBits(resultRange[0],resultRange[2]); long[] mnTRange=maskedTargetBits[1].getBits(resultRange[0],resultRange[2]); regionHypth[focusBlock]=getBestHybridDonors(targetTaxon, mjTRange, mnTRange, resultRange[0],resultRange[2], focusBlock, regionHypth[focusBlock], false); //hybrid++; } } System.out.println(""); System.out.print("Donors:"); DonorHypoth[][] theLH=new DonorHypoth[blocks][]; theLH[0]=regionHypth[0]; DonorHypoth[][] theRH=new DonorHypoth[blocks][]; theRH[blocks-1]=regionHypth[blocks-1]; for (int focusBlock = 1; focusBlock < blocks; focusBlock++) { if((regionHypth[focusBlock][0]!=null)&&(regionHypth[focusBlock][0].getErrorRate()<this.maximumInbredError)) { theLH[focusBlock]=regionHypth[focusBlock]; } else {theLH[focusBlock]=theLH[focusBlock-1];} } for (int focusBlock = blocks-2; focusBlock >=0; focusBlock if((regionHypth[focusBlock][0]!=null)&&(regionHypth[focusBlock][0].getErrorRate()<this.maximumInbredError)) { theRH[focusBlock]=regionHypth[focusBlock]; } else {theRH[focusBlock]=theRH[focusBlock+1];} } int focusBlockdone=0; for (int focusBlock = 0; focusBlock < blocks; focusBlock++) { if(theLH[focusBlock][0]==null) continue; if(theLH[focusBlock]==theRH[focusBlock]) { // if(theLH[focusBlock][0]!=null) { DonorHypoth[] newHybrid=new DonorHypoth[1]; newHybrid[0]=new DonorHypoth(theLH[focusBlock][0].targetTaxon,theLH[focusBlock][0].donor1Taxon, theLH[focusBlock][0].donor1Taxon, theLH[focusBlock][0].startBlock, focusBlock, theLH[focusBlock][0].endBlock); setAlignmentWithDonors(newHybrid,true,mna); focusBlockdone++; //System.out.print(" "+focusBlock+":"+theLH[focusBlock][0].donor1Taxon+":"+theLH[focusBlock][0].donor2Taxon); } else { if(theRH[focusBlock][0]==null) continue; if(theLH[focusBlock][0].donor1Taxon>=-1) continue; DonorHypoth[] newHybrid=new DonorHypoth[1]; newHybrid[0]=new DonorHypoth(theLH[focusBlock][0].targetTaxon,theLH[focusBlock][0].donor1Taxon, theRH[focusBlock][0].donor1Taxon, theLH[focusBlock][0].startBlock, focusBlock, theRH[focusBlock][0].endBlock); setAlignmentWithDonors(newHybrid,true,mna); focusBlockdone++; //System.out.print(" "+focusBlock+":"+newHybrid[0].donor1Taxon+":"+newHybrid[0].donor2Taxon); } } int leftNullCnt=0; for (DonorHypoth[] dh : theLH) {if(dh[0]==null) leftNullCnt++;} if(testing==1) System.out.printf("block:%d focusBlockdone:%d nullLeft:%d %n",blocks,focusBlockdone, leftNullCnt); } /** * If the target regions has Mendelian errors that it looks for overlapping regional * solutions that are better. * TODO: This can be done much more robustly. * @param mna * @param targetTaxon * @param regionHypth */ private int solveRegionally3(MutableNucleotideAlignment mna, int targetTaxon, DonorHypoth[][] regionHypth, boolean hybridMode, BitSet[] maskedTargetBits, int minMinorCnt, double maxHybridErrorRate) { int focusBlockdone=0, inbred=0, hybrid=0, noData=0; for (int focusBlock = 0; focusBlock < blocks; focusBlock++) { if((regionHypth[focusBlock][0]!=null)&&(regionHypth[focusBlock][0].getErrorRate()<maximumInbredError)) { setAlignmentWithDonors(regionHypth[focusBlock],true,mna); focusBlockdone++; inbred++; } else { int[] resultRange=getBlockWithMinMinorCount(maskedTargetBits[0].getBits(), maskedTargetBits[1].getBits(), focusBlock, minMinorCnt); if(resultRange==null) {noData++; continue; }//no data in the focus Block //search for the best hybrid donors for a segment if(hybridMode&&(regionHypth[focusBlock][0]!=null)&&(regionHypth[focusBlock][0].getErrorRate()>maximumInbredError)) { long[] mjTRange=maskedTargetBits[0].getBits(resultRange[0],resultRange[2]); long[] mnTRange=maskedTargetBits[1].getBits(resultRange[0],resultRange[2]); regionHypth[focusBlock]=getBestHybridDonors(targetTaxon, mjTRange, mnTRange, resultRange[0],resultRange[2], focusBlock, regionHypth[focusBlock], false); } // if((regionHypth[focusBlock][0]!=null)) System.out.printf("%d %d %g %n",targetTaxon, focusBlock, regionHypth[focusBlock][0].getErrorRate() ); if((regionHypth[focusBlock][0]!=null)&&(regionHypth[focusBlock][0].getErrorRate()<maxHybridErrorRate)) { setAlignmentWithDonors(regionHypth[focusBlock],true,mna); focusBlockdone++; hybrid++; } else { if(regionHypth[focusBlock][0]==null) {noData++;} // else{ // System.out.println(regionHypth[focusBlock][0].getErrorRate()); } } } int leftNullCnt=0; for (DonorHypoth[] dh : regionHypth) {if(dh[0]==null) leftNullCnt++;} if(testing==1) System.out.printf("targetTaxon:%d hybridError:%g block:%d focusBlockdone:%d null:%d inbredDone:%d hybridDone:%d noData:%d %n", targetTaxon, maxHybridErrorRate, blocks,focusBlockdone, leftNullCnt, inbred, hybrid, noData); return focusBlockdone; } private DonorHypoth getStateBasedOnViterbi(DonorHypoth dh) { int startSite=dh.startBlock*64; int endSite=(dh.endBlock*64)+63; if(endSite>=unimpAlign.getSiteCount()) endSite=unimpAlign.getSiteCount()-1; int sites=endSite-startSite+1; byte[] calls=new byte[sites]; //System.out.printf("%d %d %d %n",dh.donor1Taxon, startSite, endSite+1); byte[] d1b=donorAlign.getBaseRange(dh.donor1Taxon, startSite, endSite+1); byte[] d2b=donorAlign.getBaseRange(dh.donor2Taxon, startSite, endSite+1); byte[] t1b=unimpAlign.getBaseRange(dh.targetTaxon, startSite, endSite+1); int informSites=0, nonMendel=0; ArrayList<Byte> nonMissingObs = new ArrayList<Byte>(); ArrayList<Integer> snpPositions = new ArrayList<Integer>(); for(int cs=0; cs<sites; cs++) { if(t1b[cs]==Alignment.UNKNOWN_DIPLOID_ALLELE) continue; if(d1b[cs]==Alignment.UNKNOWN_DIPLOID_ALLELE) continue; if(d2b[cs]==Alignment.UNKNOWN_DIPLOID_ALLELE) continue; if(t1b[cs]==NucleotideAlignmentConstants.GAP_DIPLOID_ALLELE) continue; if(d1b[cs]==NucleotideAlignmentConstants.GAP_DIPLOID_ALLELE) continue; if(d2b[cs]==NucleotideAlignmentConstants.GAP_DIPLOID_ALLELE) continue; if(d1b[cs]==d2b[cs]) { if(t1b[cs]!=d1b[cs]) nonMendel++; continue; } informSites++; byte state=1; if(t1b[cs]==d1b[cs]) {state=0;} else if(t1b[cs]==d2b[cs]) {state=2;} nonMissingObs.add(state); snpPositions.add(cs+startSite); } if(informSites<10) return null; double nonMendRate=(double)nonMendel/(double)informSites; if(testing==1) System.out.printf("NonMendel:%d InformSites:%d ErrorRate:%g %n",nonMendel, informSites, nonMendRate); if(nonMendRate>this.maximumInbredError*5) return null; byte[] informStates=new byte[informSites]; for (int i = 0; i < informStates.length; i++) informStates[i]=nonMissingObs.get(i); int[] pos=new int[informSites]; for (int i = 0; i < pos.length; i++) pos[i]=snpPositions.get(i); int chrlength = donorAlign.getPositionInLocus(endSite) - donorAlign.getPositionInLocus(startSite); tp.setAverageSegmentLength( chrlength / sites ); tp.setPositions(pos); double probHeterozygous=0.5; double phom = (1 - probHeterozygous) / 2; double[] pTrue = new double[]{phom, .25*probHeterozygous ,.5 * probHeterozygous, .25*probHeterozygous, phom}; ViterbiAlgorithm va = new ViterbiAlgorithm(informStates, tp, ep, pTrue); va.calculate(); if(testing==1) System.out.println("Input:"+Arrays.toString(informStates)); byte[] resultStates=va.getMostProbableStateSequence(); if(testing==1) System.out.println("Resul:"+Arrays.toString(resultStates)); DonorHypoth dh2=new DonorHypoth(dh.targetTaxon,dh.donor1Taxon, dh.donor2Taxon, dh.startBlock, dh.focusBlock, dh.endBlock); int currPos=0; for(int cs=0; cs<sites; cs++) { calls[cs]=(resultStates[currPos]==1)?(byte)1:(byte)(resultStates[currPos]/2); //converts the scale back to 0,1,2 from 0..4 if((pos[currPos]<cs+startSite)&&(currPos<resultStates.length-1)) currPos++; } dh2.phasedResults=calls; return dh2; } /** * Given a start 64 site block, it expands to the left and right until it hits * the minimum Minor Site count in the target taxon * @param mnT - minor allele bit presence in a series of longs * @param focusBlock * @param minMinorCnt * @return arrays of blocks {startBlock, focusBlock, endBlock} */ private int[] getBlockWithMinMinorCount(long[] mjT, long[] mnT, int focusBlock, int minMinorCnt) { int majorCnt=Long.bitCount(mjT[focusBlock]); int minorCnt=Long.bitCount(mnT[focusBlock]); int endBlock=focusBlock, startBlock=focusBlock; int minMajorCnt=minMinorCnt*minMajorRatioToMinorCnt; while((minorCnt<minMinorCnt)&&(majorCnt<minMajorCnt)) { boolean preferMoveStart=(focusBlock-startBlock<endBlock-focusBlock)?true:false; if(startBlock==0) {preferMoveStart=false;} if(endBlock==blocks-1) {preferMoveStart=true;} if((startBlock==0)&&(endBlock==blocks-1)) break; if(preferMoveStart) {//expand start startBlock minorCnt+=Long.bitCount(mnT[startBlock]); majorCnt+=Long.bitCount(mjT[startBlock]); } else { //expand end endBlock++; minorCnt+=Long.bitCount(mnT[endBlock]); majorCnt+=Long.bitCount(mjT[startBlock]); } } int[] result={startBlock, focusBlock, endBlock}; return result; } /** * Calculates an inbred distance * TODO: Should be converted to the regular same, diff, hets, & sum * @param modBitsOfTarget * @return array with sites, same count, diff count, het count */ private void calcInbredDist(BitSet[] modBitsOfTarget) { allDist=new byte[donorAlign.getSequenceCount()][4][blocks]; long[] iMj=modBitsOfTarget[0].getBits(); long[] iMn=modBitsOfTarget[1].getBits(); for (int donor1 = 0; donor1 < allDist.length; donor1++) { long[] jMj=donorAlign.getAllelePresenceForAllSites(donor1, 0).getBits(); long[] jMn=donorAlign.getAllelePresenceForAllSites(donor1, 1).getBits(); for (int i = 0; i <blocks; i++) { long same = (iMj[i] & jMj[i]) | (iMn[i] & jMn[i]); long diff = (iMj[i] & jMn[i]) | (iMn[i] & jMj[i]); long hets = same & diff; int sameCnt = BitUtil.pop(same); int diffCnt = BitUtil.pop(diff); int hetCnt = BitUtil.pop(hets); int sites = sameCnt + diffCnt - hetCnt; allDist[donor1][2][i]=(byte)diffCnt; allDist[donor1][3][i]=(byte)hetCnt; allDist[donor1][0][i]=(byte)sites; allDist[donor1][1][i]=(byte)sameCnt; } } } /** * Simple algorithm that tests every possible two donor combination to minimize * the number of unmatched informative alleles. Currently, there is litte tie * breaking, longer matches are favored. * @param targetTaxon * @param startBlock * @param endBlock * @param focusBlock * @return int[] array of {donor1, donor2, testSites} */ private DonorHypoth[] getBestInbredDonors(int targetTaxon, int startBlock, int endBlock, int focusBlock, int[] donor1indices) { TreeMap<Double,DonorHypoth> bestDonors=new TreeMap<Double,DonorHypoth>(); double lastKeytestPropUnmatched=1.0; int donorTaxaCnt=donorAlign.getSequenceCount(); for (int d1 : donor1indices) { int testSites=0; int sameCnt = 0, diffCnt = 0, hetCnt = 0; for (int i = startBlock; i <=endBlock; i++) { sameCnt+=allDist[d1][1][i]; diffCnt+=allDist[d1][2][i]; hetCnt+=allDist[d1][3][i]; } testSites= sameCnt + diffCnt - hetCnt; if(testSites<minTestSites) continue; double testPropUnmatched = 1.0-(((double) (sameCnt) - (double)(0.5*hetCnt)) / (double) (testSites)); int totalMendelianErrors=(int)((double)testSites*testPropUnmatched); testPropUnmatched+=(double)d1/(double)(donorTaxaCnt*1000); //this looks strange, but makes the keys unique and ordered if(testPropUnmatched<lastKeytestPropUnmatched) { DonorHypoth theDH=new DonorHypoth(targetTaxon, d1, d1, startBlock, focusBlock, endBlock, testSites, totalMendelianErrors); DonorHypoth prev=bestDonors.put(new Double(testPropUnmatched), theDH); if(prev!=null) System.out.println("Inbred TreeMap index crash:"+testPropUnmatched); if(bestDonors.size()>maxDonorHypotheses) { bestDonors.remove(bestDonors.lastKey()); lastKeytestPropUnmatched=bestDonors.lastKey(); } } } //TODO consider reranking by Poisson. The calculating Poisson on the fly is too slow. DonorHypoth[] result=new DonorHypoth[maxDonorHypotheses]; int count=0; for (DonorHypoth dh : bestDonors.values()) { result[count]=dh; count++; } return result; } private int[] getAllBestDonorsAcrossChromosome(DonorHypoth[][] allDH, int minHypotheses) { TreeMap<Integer,Integer> bd=new TreeMap<Integer,Integer>(); for (int i = 0; i < allDH.length; i++) { DonorHypoth dh=allDH[i][0]; if(dh==null) continue; if(bd.containsKey(dh.donor1Taxon)) { bd.put(dh.donor1Taxon, bd.get(dh.donor1Taxon)+1); } else { bd.put(dh.donor1Taxon, 1); } } if(testing==1) System.out.println(bd.size()+":"+bd.toString()); if(testing==1) System.out.println(""); int highDonors=0; for (int i : bd.values()) {if(i>minHypotheses) highDonors++;} int[] result=new int[highDonors]; highDonors=0; for (Map.Entry<Integer,Integer> e: bd.entrySet()) { if(e.getValue()>minHypotheses) result[highDonors++]=e.getKey();} if(testing==1) System.out.println(Arrays.toString(result)); return result; } private DonorHypoth[] getBestHybridDonors(int targetTaxon, long[] mjT, long[] mnT, int startBlock, int endBlock, int focusBlock, DonorHypoth[] inbredHypoth, boolean compareDonorDist) { int[] inbredIndices=new int[inbredHypoth.length]; for (int i = 0; i < inbredIndices.length; i++) { inbredIndices[i]=inbredHypoth[i].donor1Taxon; } return getBestHybridDonors(targetTaxon, mjT, mnT, startBlock, endBlock, focusBlock, inbredIndices, donorIndices, compareDonorDist); } /** * Simple algorithm that tests every possible two donor combination to minimize * the number of unmatched informative alleles. Currently, there is litte tie * breaking, longer matches are favored. * @param targetTaxon * @param startBlock * @param endBlock * @param focusBlock * @return int[] array of {donor1, donor2, testSites} */ private DonorHypoth[] getBestHybridDonors(int targetTaxon, long[] mjT, long[] mnT, int startBlock, int endBlock, int focusBlock, int[] donor1Indices, int[] donor2Indices, boolean viterbiSearch) { TreeMap<Double,DonorHypoth> bestDonors=new TreeMap<Double,DonorHypoth>(); double lastKeytestPropUnmatched=1.0; double inc=1e-9; double[] donorDist={1.0,100.0}; // Random r=new Random(1); for (int d1: donor1Indices) { long[] mj1=donorAlign.getAllelePresenceForSitesBlock(d1, 0, startBlock, endBlock+1); long[] mn1=donorAlign.getAllelePresenceForSitesBlock(d1, 1, startBlock, endBlock+1); for (int d2 : donor2Indices) { if((!viterbiSearch)&&(d1==d2)) continue; long[] mj2=donorAlign.getAllelePresenceForSitesBlock(d2, 0, startBlock, endBlock+1); long[] mn2=donorAlign.getAllelePresenceForSitesBlock(d2, 1, startBlock, endBlock+1); if(viterbiSearch) { donorDist=IBSDistanceMatrix.computeHetBitDistances(mj1, mn1, mj2, mn2, minTestSites); if((d1!=d2)&&(donorDist[0]<this.maximumInbredError)) continue; } // System.out.printf("%d %d %g %n",d1,d2,donorDist[0]); // if(donorDist[0]<this.maximumInbredError) continue; int[] mendErr=mendelErrorComparison(mjT, mnT, mj1, mn1, mj2, mn2); if(mendErr[1]<minTestSites) continue; double testPropUnmatched=(double)(mendErr[0])/(double)mendErr[1]; inc+=1e-9; testPropUnmatched+=inc; if(testPropUnmatched<lastKeytestPropUnmatched) { DonorHypoth theDH=new DonorHypoth(targetTaxon, d1, d2, startBlock, focusBlock, endBlock, mendErr[1], mendErr[0]); DonorHypoth prev=bestDonors.put(new Double(testPropUnmatched), theDH); if(prev!=null) { System.out.println("Hybrid TreeMap index crash:"+testPropUnmatched); } if(bestDonors.size()>maxDonorHypotheses) { bestDonors.remove(bestDonors.lastKey()); lastKeytestPropUnmatched=bestDonors.lastKey(); } } } } if(bestDonors.size()<2) { System.out.println("Houston problem here"); } DonorHypoth[] result=new DonorHypoth[maxDonorHypotheses]; int count=0; for (DonorHypoth dh : bestDonors.values()) { result[count]=dh; count++; } return result; } private int[] mendelErrorComparison(long[] mjT, long[] mnT, long[] mj1, long[] mn1, long[] mj2, long[] mn2) { int mjUnmatched=0; int mnUnmatched=0; int testSites=0; for (int i = 0; i < mjT.length; i++) { long siteMask=(mjT[i]|mnT[i])&(mj1[i]|mn1[i])&(mj2[i]|mn2[i]); mjUnmatched+=Long.bitCount(siteMask&mjT[i]&(mjT[i]^mj1[i])&(mjT[i]^mj2[i])); mnUnmatched+=Long.bitCount(siteMask&mnT[i]&(mnT[i]^mn1[i])&(mnT[i]^mn2[i])); testSites+=Long.bitCount(siteMask); } int totalMendelianErrors=mjUnmatched+mnUnmatched; // double testPropUnmatched=(double)(totalMendelianErrors)/(double)testSites; return (new int[] {totalMendelianErrors, testSites}); } /** * Takes a donor hypothesis and applies it to the output alignment * @param theDH * @param mna */ private void setAlignmentWithDonors(DonorHypoth[] theDH, boolean setJustFocus, MutableNucleotideAlignment mna) { if(theDH[0].targetTaxon<0) return; boolean print=false; int startSite=(setJustFocus)?theDH[0].getFocusStartSite():theDH[0].startSite; int endSite=(setJustFocus)?theDH[0].getFocusEndSite():theDH[0].endSite; if(endSite>=unimpAlign.getSiteCount()) endSite=unimpAlign.getSiteCount()-1; if (print) System.out.println("B:"+mna.getBaseAsStringRange(theDH[0].targetTaxon, startSite, endSite)); for(int cs=startSite; cs<=endSite; cs++) { byte donorEst=Alignment.UNKNOWN_DIPLOID_ALLELE; for (int i = 0; (i < theDH.length) && (donorEst==Alignment.UNKNOWN_DIPLOID_ALLELE); i++) { if((theDH[i]==null)||(theDH[i].donor1Taxon<0)) continue; if(theDH[i].getErrorRate()>this.maximumInbredError) continue; byte bD1=donorAlign.getBase(theDH[i].donor1Taxon, cs); if(theDH[i].isInbred()||(theDH[i].getPhaseForSite(cs)==0)) { donorEst=bD1;} else { byte bD2=donorAlign.getBase(theDH[i].donor2Taxon, cs); if(theDH[i].getPhaseForSite(cs)==2) { donorEst=bD2;} else if((bD1!=Alignment.UNKNOWN_DIPLOID_ALLELE)&&(bD2!=Alignment.UNKNOWN_DIPLOID_ALLELE)) { donorEst=(byte)((bD1&highMask)|(bD2&lowMask)); } } } byte knownBase=mna.getBase(theDH[0].targetTaxon, cs); if((knownBase!=Alignment.UNKNOWN_DIPLOID_ALLELE)&&(knownBase!=donorEst)&&(donorEst!=Alignment.UNKNOWN_DIPLOID_ALLELE)) { // System.out.printf("Error %d %s %s %n",theDH.targetTaxon, mna.getBaseAsString(theDH.targetTaxon, cs), // NucleotideAlignmentConstants.getNucleotideIUPAC(donorEst)); if(!AlignmentUtils.isHeterozygous(donorEst)) { totalWrong++; siteErrors[cs]++; } } if((knownBase!=Alignment.UNKNOWN_DIPLOID_ALLELE)&&(knownBase==donorEst)&&(donorEst!=Alignment.UNKNOWN_DIPLOID_ALLELE)) { // System.out.printf("Error %d %s %s %n",theDH.targetTaxon, mna.getBaseAsString(theDH.targetTaxon, cs), // NucleotideAlignmentConstants.getNucleotideIUPAC(donorEst)); totalRight++; siteCallCnt[cs]++; } //TODO consider fixing the obvious errors. if(knownBase==Alignment.UNKNOWN_DIPLOID_ALLELE) mna.setBase(theDH[0].targetTaxon, cs, donorEst); } //end of cs loop if (print) System.out.println("E:"+mna.getBaseAsStringRange(theDH[0].targetTaxon, startSite, endSite)); } private static void compareAlignment(String origFile, String maskFile, String impFile) { boolean taxaOut=false; Alignment oA=ImportUtils.readFromHapmap(origFile, false, (ProgressListener)null); System.out.printf("Orig taxa:%d sites:%d %n",oA.getSequenceCount(),oA.getSiteCount()); Alignment mA=ImportUtils.readFromHapmap(maskFile, false, (ProgressListener)null); System.out.printf("Mask taxa:%d sites:%d %n",mA.getSequenceCount(),mA.getSiteCount()); Alignment iA=ImportUtils.readFromHapmap(impFile, false, (ProgressListener)null); System.out.printf("Imp taxa:%d sites:%d %n",iA.getSequenceCount(),iA.getSiteCount()); int correct=0; int errors=0; int unimp=0; int hets=0; int gaps=0; for (int t = 0; t < iA.getSequenceCount(); t++) { int e=0,c=0,u=0,h=0; int oATaxa=oA.getIdGroup().whichIdNumber(iA.getFullTaxaName(t)); for (int s = 0; s < iA.getSiteCount(); s++) { if(oA.getBase(oATaxa, s)!=mA.getBase(t, s)) { byte ib=iA.getBase(t, s); byte ob=oA.getBase(oATaxa, s); if(ib==Alignment.UNKNOWN_DIPLOID_ALLELE) {unimp++; u++;} else if(ib==NucleotideAlignmentConstants.GAP_DIPLOID_ALLELE) {gaps++;} else if(ib==ob) { correct++; c++; } else { if(AlignmentUtils.isHeterozygous(ob)||AlignmentUtils.isHeterozygous(ib)) {hets++; h++;} else {errors++; e++; System.out.printf("%d %d %s %s %n",t,s,oA.getBaseAsString(oATaxa, s), iA.getBaseAsString(t, s)); } } } } if(taxaOut) System.out.printf("%s %d %d %d %d %n",iA.getTaxaName(t),u,h,c,e); } System.out.println("MFile\tIFile\tGap\tUnimp\tHets\tCorrect\tErrors"); System.out.printf("%s\t%s\t%d\t%d\t%d\t%d\t%d%n",maskFile, impFile, gaps, unimp,hets,correct,errors); } /** * * @param args */ public static void main(String[] args) { String root="/Users/edbuckler/SolexaAnal/GBS/build20120701/impResults/"; String rootIn="/Users/edbuckler/SolexaAnal/GBS/build20120701/impOrig/"; // String root="/Volumes/LaCie/build20120701/impResults/"; // String rootIn="/Volumes/LaCie/build20120701/impOrig/"; // String origFile=rootIn+"all25.c10_s4096_s8191.hmp.txt.gz"; // // String donorFile=rootIn+"w4096GapOf4_8KMerge20130507.hmp.txt.gz"; // String donorFile=rootIn+"w4096Of4_8KMerge20130507.hmp.txt.gz"; // String unImpTargetFile=rootIn+"all25.c10_s4096_s8191_masked.hmp.txt.gz"; // String impTargetFile=root+"allInbredtest.c10_s4096_s8191.imp.hmp.txt.gz"; // String impTargetFile2=root+"allHybridTest.c10_s4096_s8191.imp.hmp.txt.gz"; // String donorFile=rootIn+"w4096GapOf24KMerge20130507.hmp.txt.gz"; // unImpTargetFile=donorFile; // String impTargetFile=root+"Donor.imp.hmp.txt.gz"; // String origFile=rootIn+"Z0CNtest.c10_s0_s24575.hmp.txt.gz"; // //String donorFile=rootIn+"w24575Of24KMerge20130513b.hmp.txt.gz"; // String donorFile=rootIn+"IMPw24575Of24KMerge20130513b.hmp.txt.gz"; // String unImpTargetFile=rootIn+"Z0CNtest.c10_s0_s24575_masked.hmp.txt.gz"; // String impTargetFile2=root+"HybridZ0CNtest.imp.hmp.txt.gz"; String origFile=rootIn+"10psample25.c10_s0_s24575.hmp.txt.gz"; String donorFile=rootIn+"IMPw24575Of24KMerge20130513b.hmp.txt.gz"; String unImpTargetFile=rootIn+"10psample25.c10_s0_s24575_masked.hmp.txt.gz"; String impTargetFile=root+"Inbred10psample25.imp.hmp.txt.gz"; String impTargetFile2=root+"Hybrid10psampletest.imp.hmp.txt.gz"; // String origFile=rootIn+"SEEDsamp25.c10_s0_s24575.hmp.txt.gz"; // String donorFile=rootIn+"IMPw24575Of24KMerge20130513b.hmp.txt.gz"; // String unImpTargetFile=rootIn+"SEEDsamp25.c10_s0_s24575_masked.hmp.txt.gz"; // String impTargetFile=root+"InbredSEED25.imp.hmp.txt.gz"; // String impTargetFile2=root+"HybridSEED25.imp.hmp.txt.gz"; // String origFile=rootIn+"10psample25.c10_s0_s24575.hmp.txt.gz"; // String donorFile=rootIn+"Xw24575Of24KMerge20130513b.hmp.txt.gz"; // String impTargetFile2=root+"IMPw24575Of24KMerge20130513b.hmp.txt.gz"; // String origFile=rootIn+"ABQTL25.c10_s0_s24575.hmp.txt.gz"; // String donorFile=rootIn+"w24575Of24KMerge20130513b.hmp.txt.gz"; // String unImpTargetFile=rootIn+"ABQTL25.c10_s0_s24575_masked.hmp.txt.gz"; // String impTargetFile=root+"ABQTLtest.imp.hmp.txt.gz"; // String impTargetFile2=root+"HybridABQTLtest.imp.hmp.txt.gz"; MinorWindowViterbiImputation e64NNI; System.out.println("Resolve Method 0: Minor 20"); // e64NNI=new MinorWindowViterbiImputation(donorFile, unImpTargetFile, impTargetFile, 20, false); // compareAlignment(origFile,unImpTargetFile,impTargetFile); // e64NNI=new MinorWindowViterbiImputation(donorFile, impTargetFile, impTargetFile2, 20, true); // compareAlignment(origFile,unImpTargetFile,impTargetFile2); for (double d = 0.01; d < 0.02; d+=0.01) { System.out.println("MaxHybrid Error Rate:"+d); e64NNI=new MinorWindowViterbiImputation(donorFile, unImpTargetFile, impTargetFile2, 20, 50, 100, d, true); compareAlignment(origFile,unImpTargetFile,impTargetFile2); } // e64NNI=new MinorWindowViterbiImputation(donorFile, unImpTargetFile, impTargetFile2, 20, 100, true); // compareAlignment(origFile,unImpTargetFile,impTargetFile2); } }
package fitnesse.reporting; import java.text.DecimalFormatSymbols; import java.util.Date; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import static util.RegexTestCase.assertHasRegexp; import static util.RegexTestCase.assertSubString; import fitnesse.FitNesseContext; import fitnesse.testrunner.WikiTestPage; import fitnesse.testsystems.TestSummary; import fitnesse.testsystems.TestSystem; import fitnesse.testutil.FitNesseUtil; import fitnesse.wiki.WikiPage; import fitnesse.wiki.WikiPageDummy; import fitnesse.wiki.mem.InMemoryPage; import org.junit.After; import org.junit.Before; import org.junit.Test; import util.Clock; import util.DateAlteringClock; import util.TimeMeasurement; public class SuiteHtmlFormatterTest { private SuiteHtmlFormatter formatter; private StringBuffer pageBuffer = new StringBuffer(); private DateAlteringClock clock; @Before public void setUp() throws Exception { clock = new DateAlteringClock(new Date()).freeze(); FitNesseContext context = FitNesseUtil.makeTestContext(); WikiPage root = InMemoryPage.makeRoot("RooT"); formatter = new SuiteHtmlFormatter(context, root) { @Override protected void writeData(String output) { pageBuffer.append(output); } }; } @After public void restoreDefaultClock() { Clock.restoreDefaultClock(); } @Test public void testTestSummary() throws Exception { formatter.processTestResults("TestName", new TestSummary(49, 0, 0, 0)); formatter.processTestResults("TestName2", new TestSummary(1, 0, 2, 0)); formatter.processTestResults("TestName3", new TestSummary(1, 1, 0, 0)); formatter.finishWritingOutput(); assertSubString("<strong>Test Pages:</strong> 2 right, 1 wrong, 0 ignored, 0 exceptions", pageBuffer.toString()); assertSubString("<strong>Assertions:</strong> 51 right, 1 wrong, 2 ignored, 0 exceptions", pageBuffer.toString()); } private void testSuiteMetaTestSummaryWithTestResults(String pageName) throws Exception { formatter.processTestResults(pageName, new TestSummary(2, 0, 0, 0)); formatter.finishWritingOutput(); assertSubString("<span class=\\\"results pass\\\">2 right, 0 wrong, 0 ignored, 0 exceptions</span>", pageBuffer.toString()); assertSubString("<strong>Test Pages:</strong> 1 right, 0 wrong, 0 ignored, 0 exceptions", pageBuffer.toString()); assertSubString("<strong>Assertions:</strong> 2 right, 0 wrong, 0 ignored, 0 exceptions", pageBuffer.toString()); } @Test public void testSuiteSetUpSummaryWithTestResults() throws Exception { testSuiteMetaTestSummaryWithTestResults("SuiteSetUp"); } @Test public void testSuiteTearDownSummaryWithTestResults() throws Exception { testSuiteMetaTestSummaryWithTestResults("SuiteTearDown"); } private void testSuiteMetaTestSummaryWithoutTestResults(String pageName) throws Exception { formatter.processTestResults(pageName, new TestSummary(0, 0, 0, 0)); formatter.finishWritingOutput(); assertSubString("<span class=\\\"results pass\\\">0 right, 0 wrong, 0 ignored, 0 exceptions</span>", pageBuffer.toString()); assertSubString("<strong>Test Pages:</strong> 1 right, 0 wrong, 0 ignored, 0 exceptions", pageBuffer.toString()); assertSubString("<strong>Assertions:</strong> 0 right, 0 wrong, 0 ignored, 0 exceptions", pageBuffer.toString()); } @Test public void testSuiteSetUpSummaryWithoutTestResults() throws Exception { testSuiteMetaTestSummaryWithoutTestResults("SuiteSetUp"); } @Test public void testSuiteTearDownSummaryWithoutTestResults() throws Exception { testSuiteMetaTestSummaryWithoutTestResults("SuiteTearDown"); } @Test public void testCountsHtml() throws Exception { formatter.processTestResults("RelativePageName", new TestSummary(1, 0, 0, 0)); assertSubString("<span class=\\\"results pass\\\">1 right, 0 wrong, 0 ignored, 0 exceptions</span>", pageBuffer.toString()); assertSubString("<a href=\\\"#RelativePageName0\\\" class=\\\"link\\\">RelativePageName</a>", pageBuffer.toString()); pageBuffer.setLength(0); formatter.processTestResults("AnotherPageName", new TestSummary(0, 1, 0, 0)); assertSubString("<span class=\\\"results fail\\\">0 right, 1 wrong, 0 ignored, 0 exceptions</span>", pageBuffer.toString()); assertSubString("<a href=\\\"#AnotherPageName0\\\" class=\\\"link\\\">AnotherPageName</a>", pageBuffer.toString()); } @Test public void testResultsHtml() throws Exception { TestSystem fitMock = mock(TestSystem.class); when(fitMock.getName()).thenReturn("Fit:laughing.fit"); TestSystem slimMock = mock(TestSystem.class); when(slimMock.getName()).thenReturn("Slim:very.slim"); formatter.testSystemStarted(fitMock); formatter.announceNumberTestsToRun(2); formatter.announceStartNewTest("RelativeName", "FullName"); formatter.testOutputChunk("starting"); formatter.testOutputChunk(" output"); formatter.processTestResults("RelativeName", new TestSummary(1, 0, 0, 0)); formatter.testSystemStarted(slimMock); formatter.announceStartNewTest("NewRelativeName", "NewFullName"); formatter.testOutputChunk("second"); formatter.testOutputChunk(" test"); formatter.processTestResults("NewRelativeName", new TestSummary(0, 1, 0, 0)); formatter.finishWritingOutput(); String results = pageBuffer.toString(); assertSubString("<h2>Test Output</h2>", results); assertSubString("<h2>Test System: Slim:very.slim</h2>", results); assertSubString("<div class=\"test_output_name\">", results); assertSubString("<a href=\"FullName\" id=\"RelativeName1\" class=\"test_name\">RelativeName</a>", results); assertSubString("<div class=\"alternating_block\">starting output</div>", results); assertSubString("<a href=\"NewFullName\" id=\"NewRelativeName2\" class=\"test_name\">NewRelativeName</a>", results); assertSubString("<div class=\"alternating_block\">second test</div>", results); } @Test public void testTestingProgressIndicator() throws Exception { TestSystem fitMock = mock(TestSystem.class); when(fitMock.getName()).thenReturn("Fit:laughing.fit"); formatter.testSystemStarted(fitMock); formatter.announceNumberTestsToRun(20); formatter.announceStartNewTest("RelativeName", "FullName"); assertSubString("<script>document.getElementById(\"test-summary\").innerHTML =" + " \"<div id=\\\"progressBar\\\" class=\\\"pass\\\" style=\\\"width:0.0%\\\">", pageBuffer.toString()); assertSubString("Running&nbsp;tests&nbsp;...&nbsp;(1/20)", pageBuffer.toString()); pageBuffer.setLength(0); formatter.processTestResults("RelativeName", new TestSummary(1, 0, 0, 0)); formatter.announceStartNewTest("RelativeName", "FullName"); assertSubString("<script>document.getElementById(\"test-summary\").innerHTML =" + " \"<div id=\\\"progressBar\\\" class=\\\"pass\\\" style=\\\"width:5.0%\\\">", pageBuffer.toString()); assertSubString("(2/20)", pageBuffer.toString()); pageBuffer.setLength(0); formatter.processTestResults("RelativeName", new TestSummary(1, 0, 0, 0)); formatter.announceStartNewTest("RelativeName", "FullName"); assertSubString("<script>document.getElementById(\"test-summary\").innerHTML =" + " \"<div id=\\\"progressBar\\\" class=\\\"pass\\\" style=\\\"width:10.0%\\\">", pageBuffer.toString()); assertSubString("(3/20)", pageBuffer.toString()); } @Test public void testTotalTimingShouldAppearInSummary() throws Exception { formatter.page = new WikiPageDummy(); formatter.announceNumberTestsToRun(1); WikiTestPage firstPage = new WikiTestPage(new WikiPageDummy("page1", "content")); formatter.testStarted(firstPage); formatter.testComplete(firstPage, new TestSummary(1, 2, 3, 4)); clock.elapse(900); formatter.close(); assertSubString("<strong>Assertions:</strong> 1 right, 2 wrong, 3 ignored, 4 exceptions (0" + getDecimalSeparator() + "900 seconds)", pageBuffer.toString()); } @Test public void testIndividualTestTimingsShouldAppearInSummary() throws Exception { TimeMeasurement totalTimeMeasurement = newConstantElapsedTimeMeasurement(900).start(); formatter.page = new WikiPageDummy(); formatter.announceNumberTestsToRun(2); WikiTestPage firstPage = new WikiTestPage(new WikiPageDummy("page1", "content")); WikiTestPage secondPage = new WikiTestPage(new WikiPageDummy("page2", "content")); formatter.testStarted(firstPage); clock.elapse(670); formatter.testComplete(firstPage, new TestSummary(1, 2, 3, 4)); formatter.testStarted(secondPage); clock.elapse(890); formatter.testComplete(secondPage, new TestSummary(5, 6, 7, 8)); formatter.close(); assertHasRegexp("<li.*\\(page1\\).*<span.*>\\(0(" + getDecimalSeparatorForRegExp() + "){1}670 seconds\\)</span>.*</li>", pageBuffer.toString()); assertHasRegexp("<li.*\\(page2\\).*<span.*>\\(0(" + getDecimalSeparatorForRegExp() + "){1}890 seconds\\)</span>.*</li>", pageBuffer.toString()); } private TimeMeasurement newConstantElapsedTimeMeasurement(final long theElapsedTime) { return new TimeMeasurement() { @Override public long elapsed() { return theElapsedTime; } }; } private String getDecimalSeparator() { return String.valueOf(DecimalFormatSymbols.getInstance().getDecimalSeparator()); } private String getDecimalSeparatorForRegExp() { return getDecimalSeparator().replace(".", "\\."); } }
package brooklyn.util.ssh; import static java.lang.String.format; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.LinkedList; import java.util.List; import java.util.Map; import brooklyn.util.collections.MutableMap; import brooklyn.util.text.Identifiers; import brooklyn.util.text.StringEscapes.BashStringEscapes; import brooklyn.util.text.Strings; import com.google.common.collect.ImmutableList; public class BashCommands { /** * Returns a string for checking whether the given executable is available, * and installing it if necessary. * <p/> * Uses {@link #installPackage} and accepts the same flags e.g. for apt, yum, rpm. */ public static String installExecutable(Map<?,?> flags, String executable) { return onlyIfExecutableMissing(executable, installPackage(flags, executable)); } public static String installExecutable(String executable) { return installExecutable(MutableMap.of(), executable); } /** * Returns a command with all output redirected to /dev/null */ public static String quiet(String command) { return format("(%s > /dev/null 2>&1)", command); } /** * Returns a command that always exits successfully */ public static String ok(String command) { return String.format("(%s || true)", command); } /** * Returns a command for safely running as root, using {@code sudo}. * <p/> * Ensuring non-blocking if password not set by using * {@code -n} which means to exit if password required * (this is unsupported in Ubuntu 8 but all modern OS's seem okay with this!), * and (perhaps unnecessarily ?) * {@code -S} which reads from stdin (routed to {@code /dev/null}, it was claimed here previously, though I'm not sure?). * <p/> * Also specify {@code -E} to pass the parent environment in. * <p/> * If already root, simply runs the command, wrapped in brackets in case it is backgrounded. * <p/> * The command is not quoted or escaped in any ways. * If you are doing privileged redirect you may need to pass e.g. "bash -c 'echo hi > file'". * <p/> * If null is supplied, it is returned (sometimes used to indicate no command desired). */ public static String sudo(String command) { if (command==null) return null; return format("( if test \"$UID\" -eq 0; then ( %s ); else sudo -E -n -S -- %s; fi )", command, command); } /** sudo to a given user and run the indicated command*/ public static String sudoAsUser(String user, String command) { if (command == null) return null; return format("{ sudo -E -n -u %s -s -- %s ; }", user, command); } /** executes a command, then as user tees the output to the given file. * useful e.g. for appending to a file which is only writable by root or a priveleged user. */ public static String executeCommandThenAsUserTeeOutputToFile(String commandWhoseOutputToWrite, String user, String file) { return format("{ %s | sudo -E -n -u %s -s -- tee -a %s ; }", commandWhoseOutputToWrite, user, file); } /** some machines require a tty for sudo; brooklyn by default does not use a tty * (so that it can get separate error+stdout streams); you can enable a tty as an * option to every ssh command, or you can do it once and * modify the machine so that a tty is not subsequently required. * <p> * this command must be run with allocatePTY set as a flag to ssh. see SshTasks.dontRequireTtyForSudo which sets that up. * <p> * (having a tty for sudo seems like another case of imaginary security which is just irritating. * like water restrictions at airport security.) */ public static String dontRequireTtyForSudo() { return ifFileExistsElse0("/etc/sudoers", sudo("sed -i.brooklyn.bak 's/.*requiretty.*/#brooklyn-removed-require-tty/' /etc/sudoers")); } /** * Returns a command that runs only if the operating system is as specified; Checks {@code /etc/issue} for the specified name * @deprecated since 0.6.0 very non-portable */ public static String on(String osName, String command) { return format("( grep \"%s\" /etc/issue && %s )", osName, command); } /** * Returns a command that runs only if the specified file exists * @deprecated since 0.6.0 use {@link #ifFileExistsElse0(String, String)} or {@link #ifFileExistsElse1(String, String)} */ public static String file(String path, String command) { return format("( test -f %s && %s )", path, command); } // TODO a builder would be better than these ifBlahExistsElseBlah methods! // (ideally formatting better also; though maybe SshTasks would be better?) /** * Returns a command that runs only if the specified file (or link or directory) exists; * if the command runs and fails that exit is preserved (but if the file does not exist exit code is zero). * Executed as { { not-file-exists && ok ; } || command ; } for portability. * ("if [ ... ] ; then xxx ; else xxx ; fi" syntax is not quite as portable, I seem to recall (not sure, Alex Aug 2013).) */ public static String ifFileExistsElse0(String path, String command) { return alternativesGroup( chainGroup(format("test ! -e %s", path), "true"), command); } /** as {@link #ifFileExistsElse0(String, String)} but returns non-zero if the test fails (also returns non-zero if the command fails, * so you can't tell the difference :( -- we need if ; then ; else ; fi semantics for that I think, but not sure how portable that is) */ public static String ifFileExistsElse1(String path, String command) { return chainGroup(format("test -e %s", path), command); } /** * Returns a command that runs only if the specified executable is in the path. * If command is null, no command runs (and the script component this creates will return true if the executable). * @deprecated since 0.6.0 use {@link #ifExecutableElse0(String, String)} */ public static String exists(String executable, String ...commands) { String extraCommandsAnded = ""; for (String c: commands) if (c!=null) extraCommandsAnded += " && "+c; return format("( which %s%s )", executable, extraCommandsAnded); } /** * Returns a command that runs only if the specified executable exists on the path (using `which`). * if the command runs and fails that exit is preserved (but if the executable is not on the path exit code is zero). * @see #ifFileExistsElse0(String, String) for implementation discussion, using <code>{ { test -z `which executable` && true ; } || command ; } */ public static String ifExecutableElse0(String executable, String command) { return alternativesGroup( chainGroup(format("test -z `which %s`", executable), "true"), command); } /** as {@link #ifExecutableElse0(String, String)} but returns 1 if the test fails (also returns non-zero if the command fails) */ public static String ifExecutableElse1(String executable, String command) { return chainGroup(format("which %s", executable), command); } /** * Returns a command that runs only if the specified executable is NOT in the path * @deprecated since 0.6.0 use {@link #onlyIfExecutableMissing(String, String)} */ public static String missing(String executable, String command) { return format("( which %s || %s )", executable, command); } /** * Returns a command that runs only if the specified executable exists on the path (using `which`). * if the command runs and fails that exit is preserved (but if the executable is not on the path exit code is zero). * @see #ifFileExistsElse0(String, String) for implementation discussion, using <code>{ { test -z `which executable` && true ; } || command ; } */ public static String onlyIfExecutableMissing(String executable, String command) { return alternativesGroup(format("which %s", executable), command); } /** * Returns a sequence of chained commands that runs until one of them fails (i.e. joined by '&&') * This currently runs as a subshell (so exits are swallowed) but behaviour may be changed imminently. * (Use {@link #chainGroup(Collection)} or {@link #chainSubshell(Collection)} to be clear.) */ public static String chain(Collection<String> commands) { return "( " + Strings.join(commands, " && ") + " )"; } /** Convenience for {@link #chain(Collection)} */ public static String chain(String ...commands) { return "( " + Strings.join(commands, " && ") + " )"; } /** As {@link #chain(Collection)}, but explicitly using { } grouping characters * to ensure exits are propagated. */ public static String chainGroup(Collection<String> commands) { // spaces required around curly braces return "{ " + Strings.join(commands, " && ") + " ; }"; } /** As {@link #chainGroup(Collection)} */ public static String chainGroup(String ...commands) { return "{ " + Strings.join(commands, " && ") + " ; }"; } /** As {@link #chain(Collection)}, but explicitly using ( ) grouping characters * to ensure exits are caught. */ public static String chainSubshell(Collection<String> commands) { // the spaces are not required, but it might be possible that a (( expr )) is interpreted differently // (won't hurt to have the spaces in any case!) return "( " + Strings.join(commands, " && ") + " )"; } /** As {@link #chainSubshell(Collection)} */ public static String chainSubshell(String ...commands) { return "( " + Strings.join(commands, " && ") + " )"; } /** * Returns a sequence of alternative commands that runs until one of the commands succeeds; * or if none succeed, it will run the failure command. * @deprecated since 0.6.0; this method just treats the failure command as another alternative so hardly seems worth it; * prefer {@link #alternatives(Collection)} */ @Deprecated public static String alternatives(Collection<String> commands, String failureCommand) { return format("(%s || %s)", Strings.join(commands, " || "), failureCommand); } /** * Returns a sequence of chained commands that runs until one of them succeeds (i.e. joined by '||'). * This currently runs as a subshell (so exits are swallowed) but behaviour may be changed imminently. * (Use {@link #alternativesGroup(Collection)} or {@link #alternativesSubshell(Collection)} to be clear.) */ public static String alternatives(Collection<String> commands) { return "( " + Strings.join(commands, " || ") + " )"; } /** As {@link #alternatives(Collection)} */ public static String alternatives(String ...commands) { return "( " + Strings.join(commands, " || ") + " )"; } /** As {@link #alternatives(Collection)}, but explicitly using { } grouping characters * to ensure exits are propagated. */ public static String alternativesGroup(Collection<String> commands) { // spaces required around curly braces return "{ " + Strings.join(commands, " || ") + " ; }"; } /** As {@link #alternativesGroup(Collection)} */ public static String alternativesGroup(String ...commands) { return "{ " + Strings.join(commands, " || ") + " ; }"; } /** As {@link #alternatives(Collection)}, but explicitly using ( ) grouping characters * to ensure exits are caught. */ public static String alternativesSubshell(Collection<String> commands) { // the spaces are not required, but it might be possible that a (( expr )) is interpreted differently // (won't hurt to have the spaces in any case!) return "( " + Strings.join(commands, " || ") + " )"; } /** As {@link #alternativesSubshell(Collection)} */ public static String alternativesSubshell(String ...commands) { return "( " + Strings.join(commands, " || ") + " )"; } /** returns the pattern formatted with the given arg if the arg is not null, otherwise returns null */ public static String formatIfNotNull(String pattern, Object arg) { if (arg==null) return null; return format(pattern, arg); } /** * Returns a command for installing the given package. * <p> * Warns, but does not fail or return non-zero if it ultimately fails. * <p> * Flags can contain common overrides for {@code apt}, {@code yum}, {@code port} and {@code brew} * as the package names can be different for each of those. Setting the default package name to * {@literal null} will use only the overridden package manager values. The {@code onlyifmissing} flag * adds a check for an executable, and only attempts to install packages if it is not found. * <pre> * installPackage(ImmutableMap.of("yum", "openssl-devel", "apt", "openssl libssl-dev zlib1g-dev"), "libssl-devel"); * installPackage(ImmutableMap.of("apt", "libaio1"), null); * installPackage(ImmutableMap.of("onlyifmissing", "curl"), "curl"); * </pre> */ public static String installPackage(Map<?,?> flags, String packageDefaultName) { return installPackageOr(flags, packageDefaultName, null); } public static String installPackageOrFail(Map<?,?> flags, String packageDefaultName) { return installPackageOr(flags, packageDefaultName, "exit 9"); } public static String installPackageOr(Map<?,?> flags, String packageDefaultName, String optionalCommandToRunIfNone) { String ifMissing = (String) flags.get("onlyifmissing"); String aptInstall = formatIfNotNull("apt-get install -y --allow-unauthenticated %s", getFlag(flags, "apt", packageDefaultName)); String yumInstall = formatIfNotNull("yum -y --nogpgcheck install %s", getFlag(flags, "yum", packageDefaultName)); String brewInstall = formatIfNotNull("brew install %s", getFlag(flags, "brew", packageDefaultName)); String portInstall = formatIfNotNull("port install %s", getFlag(flags, "port", packageDefaultName)); List<String> commands = new LinkedList<String>(); if (ifMissing != null) commands.add(format("which %s", ifMissing)); if (aptInstall != null) commands.add(ifExecutableElse1("apt-get", chainGroup( "echo apt-get exists, doing update", "export DEBIAN_FRONTEND=noninteractive", ok(sudo("apt-get update")), sudo(aptInstall)))); if (yumInstall != null) commands.add(ifExecutableElse1("yum", sudo(yumInstall))); if (brewInstall != null) commands.add(ifExecutableElse1("brew", brewInstall)); if (portInstall != null) commands.add(ifExecutableElse1("port", sudo(portInstall))); String lastCommand = warn("WARNING: no known/successful package manager to install " + (packageDefaultName!=null ? packageDefaultName : flags.toString()) + ", may fail subsequently"); if (optionalCommandToRunIfNone != null) lastCommand = chain(lastCommand, optionalCommandToRunIfNone); commands.add(lastCommand); return alternatives(commands); } public static String warn(String message) { return "( echo "+BashStringEscapes.wrapBash(message)+" | tee /dev/stderr )"; } /** returns a command which logs a message to stdout and stderr then exits with the given error code */ public static String fail(String message, int code) { return chainGroup(warn(message), "exit "+code); } /** requires the command to have a non-zero exit code; e.g. * <code>require("which foo", "Command foo must be found", 1)</code> */ public static String require(String command, String failureMessage, int exitCode) { return alternativesGroup(command, fail(failureMessage, exitCode)); } /** as {@link #require(String, String, int)} but returning the original exit code */ public static String require(String command, String failureMessage) { return alternativesGroup(command, chainGroup("EXIT_CODE=$?", warn(failureMessage), "exit $EXIT_CODE")); } /** requires the test to pass, as valid bash `test` arguments; e.g. * <code>requireTest("-f /etc/hosts", "Hosts file must exist", 1)</code> */ public static String requireTest(String test, String failureMessage, int exitCode) { return require("test "+test, failureMessage, exitCode); } /** as {@link #requireTest(String, String, int)} but returning the original exit code */ public static String requireTest(String test, String failureMessage) { return require("test "+test, failureMessage); } /** fails with nice error if the given file does not exist */ public static String requireFile(String file) { return requireTest("-f "+BashStringEscapes.wrapBash(file), "The required file \""+file+"\" does not exist"); } /** fails with nice error if the given file does not exist */ public static String requireExecutable(String command) { return require("which "+BashStringEscapes.wrapBash(command), "The required executable \""+command+"\" does not exist"); } public static String installPackage(String packageDefaultName) { return installPackage(MutableMap.of(), packageDefaultName); } public static final String INSTALL_TAR = installExecutable("tar"); public static final String INSTALL_CURL = installExecutable("curl"); public static final String INSTALL_WGET = installExecutable("wget"); public static final String INSTALL_ZIP = installExecutable("zip"); public static final String INSTALL_UNZIP = alternatives(installExecutable("unzip"), installExecutable("zip")); /** * @see downloadUrlAs(Map, String, String, String) * @deprecated since 0.5.0 - Use {@link downloadUrlAs(List<String>, String)}, and rely on {@link DownloadResolverManager} to include the local-repo */ @Deprecated public static List<String> downloadUrlAs(String url, String entityVersionPath, String pathlessFilenameToSaveAs) { return downloadUrlAs(MutableMap.of(), url, entityVersionPath, pathlessFilenameToSaveAs); } /** * Returns command for downloading from a url and saving to a file; * currently using {@code curl}. * <p/> * Will read from a local repository, if files have been copied there * ({@code cp -r /tmp/brooklyn/installs/ ~/.brooklyn/repository/<entityVersionPath>/<pathlessFilenameToSaveAs>}) * unless <em>skipLocalRepo</em> is {@literal true}. * <p/> * Ideally use a blobstore staging area. * * @deprecated since 0.5.0 - Use {@link downloadUrlAs(List, String)}, and rely on {@link DownloadResolverManager} to include the local-repo */ @Deprecated public static List<String> downloadUrlAs(Map<?,?> flags, String url, String entityVersionPath, String pathlessFilenameToSaveAs) { Boolean skipLocalRepo = (Boolean) flags.get("skipLocalRepo"); boolean useLocalRepo = skipLocalRepo!=null?!skipLocalRepo:true; List<String> urls; if (useLocalRepo) { String localRepoFileUrl = format("file://$HOME/.brooklyn/repository/%s/%s", entityVersionPath, pathlessFilenameToSaveAs); urls = ImmutableList.of(localRepoFileUrl, url); } else { urls = ImmutableList.of(url); } return downloadUrlAs(urls, "./"+pathlessFilenameToSaveAs); } /** @deprecated since 0.6.0 use {@link #commandsToDownloadUrlsAs(List, String)} (because method uses a list), * or {@link #commandToDownloadUrlsAs(List, String)} for the single-string variant */ @Deprecated public static List<String> downloadUrlAs(List<String> urls, String saveAs) { return Arrays.asList(INSTALL_CURL, require(simpleDownloadUrlAs(urls, saveAs), "Could not retrieve "+saveAs+" (from "+urls.size()+" sites)", 9)); } /** * Returns commands to download the URL, saving as the given file. Will try each URL in turn until one is successful * (see `curl -f` documentation). */ public static List<String> commandsToDownloadUrlsAs(List<String> urls, String saveAs) { return Arrays.asList(INSTALL_CURL, require(simpleDownloadUrlAs(urls, saveAs), "Could not retrieve "+saveAs+" (from "+urls.size()+" sites)", 9)); } public static String commandToDownloadUrlsAs(List<String> urls, String saveAs) { return chain(INSTALL_CURL, require(simpleDownloadUrlAs(urls, saveAs), "Could not retrieve "+saveAs+" (from "+urls.size()+" sites)", 9)); } public static String commandToDownloadUrlAs(String url, String saveAs) { return chain(INSTALL_CURL, require(simpleDownloadUrlAs(Arrays.asList(url), saveAs), "Could not retrieve "+saveAs+" (from 1 site)", 9)); } /** * Returns command to download the URL, sending the output to stdout -- * suitable for redirect by appending " | tar xvf". * Will try each URL in turn until one is successful */ public static String downloadToStdout(List<String> urls) { return chain( INSTALL_CURL + " > /dev/null", require(simpleDownloadUrlAs(urls, null), "Could not retrieve file (from "+urls.size()+" sites)", 9)); } /** as {@link #downloadToStdout(List)} but varargs for convenience */ public static String downloadToStdout(String ...urls) { return downloadToStdout(Arrays.asList(urls)); } /** * Same as {@link downloadUrlAs(List, String)}, except does not install curl, and does not exit on failure, * and if saveAs is null it downloads it so stdout. */ public static String simpleDownloadUrlAs(List<String> urls, String saveAs) { if (urls.isEmpty()) throw new IllegalArgumentException("No URLs supplied to download "+saveAs); List<String> commands = new ArrayList<String>(); for (String url : urls) { String command = format("curl -f -L \"%s\"", url); if (saveAs!=null) command = command + format(" -o %s", saveAs); commands.add(command); } return alternatives(commands); } private static Object getFlag(Map<?,?> flags, String flagName, Object defaultValue) { Object found = flags.get(flagName); return found == null ? defaultValue : found; } /** * Returns the command that installs Java 1.6. * See also: JavaSoftwareProcessSshDriver.installJava, which does a much more thorough job. * * @return the command that install Java 1.6. * @deprecated since 0.6.0 prefer {@link #installJava6IfPossible()} or {@link #installJava6OrFail()} */ @Deprecated public static String installJava6() { return installJava6IfPossible(); } public static String installJava6IfPossible() { return installPackage(MutableMap.of("apt", "openjdk-6-jdk","yum", "java-1.6.0-openjdk-devel"), null); } public static String installJava6OrFail() { return installPackageOrFail(MutableMap.of("apt", "openjdk-6-jdk","yum", "java-1.6.0-openjdk-devel"), null); } /** cats the given text to the given command, using bash << multi-line input syntax */ public static String pipeTextTo(String text, String command) { String id = Identifiers.makeRandomId(8); return "cat << EOF_"+id+" | "+command+"\n" +text +"\n"+"EOF_"+id+"\n"; } }
package net.meisen.general.genmisc.raster.data.impl; import java.util.HashMap; import java.util.Map; import net.meisen.general.genmisc.raster.data.IModelData; /** * A basic <code>ModelData</code> implementation which is based on a {@link Map} * * @author pmeisen */ public class BaseModelData implements IModelData { // the data collector private final Map<String, Object> values = new HashMap<String, Object>(); @Override public Object getValue(final String name) { return values.get(name); } @Override public boolean hasValue(final String name) { return values.containsKey(name); } /** * Removes a value from the <code>ModelData</code> * * @param name * the value to be removed */ public void removeValue(final String name) { values.remove(name); } /** * Associated a specific value to a specific name * * @param name * the name to associated the passed value to * @param value * the value to be associated * @return the old value that was associated, <code>null</code> if * <code>null</code> or no value was associated prior to the call */ public Object setValue(final String name, final Object value) { return values.put(name, value); } /** * Sets all the specified values. * * @param values * the values to be added */ public void setValues(final Map<String, Object> values) { this.values.putAll(values); } @Override public <T> T get(final String name) { @SuppressWarnings("unchecked") final T val = (T) getValue(name); return val; } @Override public String toString() { return values.toString(); } }
package org.onlab.netty; import java.io.IOException; /** * Internal message representation with additional attributes * for supporting, synchronous request/reply behavior. */ public final class InternalMessage implements Message { private long id; private Endpoint sender; private String type; private Object payload; private transient NettyMessagingService messagingService; public static final String REPLY_MESSAGE_TYPE = "NETTY_MESSAGIG_REQUEST_REPLY"; // Must be created using the Builder. private InternalMessage() {} public long id() { return id; } public String type() { return type; } public Endpoint sender() { return sender; } @Override public Object payload() { return payload; } protected void setMessagingService(NettyMessagingService messagingService) { this.messagingService = messagingService; } @Override public void respond(Object data) throws IOException { Builder builder = new Builder(messagingService); InternalMessage message = builder.withId(this.id) // FIXME: Sender should be messagingService.localEp. .withSender(this.sender) .withPayload(data) .withType(REPLY_MESSAGE_TYPE) .build(); messagingService.sendAsync(sender, message); } /** * Builder for InternalMessages. */ public static final class Builder { private InternalMessage message; public Builder(NettyMessagingService messagingService) { message = new InternalMessage(); message.messagingService = messagingService; } public Builder withId(long id) { message.id = id; return this; } public Builder withType(String type) { message.type = type; return this; } public Builder withSender(Endpoint sender) { message.sender = sender; return this; } public Builder withPayload(Object payload) { message.payload = payload; return this; } public InternalMessage build() { return message; } } }
package net.reliableresponse.notification.web.actions; import java.math.BigInteger; import java.util.List; import java.util.Vector; import java.util.stream.Collectors; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import net.reliableresponse.notification.Notification; import net.reliableresponse.notification.aggregation.Squelcher; import net.reliableresponse.notification.broker.BrokerFactory; import net.reliableresponse.notification.broker.NotificationBroker; import net.reliableresponse.notification.usermgmt.Group; import net.reliableresponse.notification.usermgmt.Member; import net.reliableresponse.notification.usermgmt.Roles; import net.reliableresponse.notification.usermgmt.User; import net.reliableresponse.notification.util.StringUtils; public class IndexAction implements Action { private boolean isVisible(User user, Notification notification) { boolean isAdmin = BrokerFactory.getAuthorizationBroker().isUserInRole(user, Roles.ADMINISTRATOR) || BrokerFactory.getAuthorizationBroker().isUserInRole(user, Roles.OBSERVER); if (isAdmin) return true; Member member = notification.getRecipient(); if (member.getType() == Member.USER) { return member.equals(user); } Group group = (Group)member; return group.isMember(user); } private boolean getIsVisible(ActionRequest actionRequest, String area, String type) { String viewString = actionRequest.getParameter("view_"+area+type); boolean view = true; if (viewString != null) view = viewString.toLowerCase().startsWith("t"); if (actionRequest.getParameter("toggle_"+area+type+".x")!= null) { view = !view; actionRequest.setParameter("view_"+area+type, ""+view); } return view; } private String makeTitle(String prefix, String area, boolean viewActive, boolean viewConfirmed, boolean viewExpired, boolean viewOnhold, long pending, long confirmed, long expired, long onhold, int numHours) { String title = "<font color=\"#17A1e2\">"+prefix+"</font></td>"; title += "<td align=\"right\" class=\"headercell\"><font color=\"#666666\"><input type=\"image\" src=\"images/led_"; title += viewActive?"green":"disabled"; title +=".gif\" width=\"11\" height=\"11\" name=\"toggle_"+area+"active\">&nbsp;active: "; title += pending; title += "&nbsp;&nbsp;&nbsp;<input type=\"image\" src=\"images/led_"; title += viewConfirmed?"yellow":"disabled"; title += ".gif\" width=\"11\" height=\"11\" name=\"toggle_"+area+"confirmed\">&nbsp;confirmed: "; title += confirmed; title += "&nbsp;&nbsp;&nbsp;<input type=\"image\" src=\"images/led_"; title += viewExpired?"red":"disabled"; title += ".gif\" width=\"11\" height=\"11\" name=\"toggle_"+area+"expired\">&nbsp;expired: "; title += expired; title += "&nbsp;&nbsp;&nbsp;<input type=\"image\" src=\"images/led_"; title += viewOnhold?"blue":"disabled"; title += ".gif\" width=\"11\" height=\"11\" name=\"toggle_"+area+"onhold\">&nbsp;on hold: "; title += onhold; title += "</font><img src=\"images/spacer.gif\" width=\"20\" height=\"10\"><font color=\"#000000\"> <span class=\"identity\">display past </span>"; title += "<input name=\"display_"+area+"past\" type=\"text\" class=\"identity\" value=\""; title += numHours; title += "\" size=\"3\" onchange=\"document.mainform.submit();\"><span class=\"identity\">hrs.</span></font>"; return title; } /* (non-Javadoc) * @see net.reliableresponse.notification.web.actions.Action#doAction(javax.servlet.ServletRequest) */ public ServletRequest doAction(ServletRequest request, ServletResponse response) { BrokerFactory.getLoggingBroker().logDebug("Index Action running"); ActionRequest actionRequest = new ActionRequest( (HttpServletRequest) request); // -- Sent To Me section -- // Check to see if the user has update the "display past" setting String displayPast = request.getParameter("display_past"); if ((displayPast != null) && (displayPast.length() > 0)) { try { actionRequest.getSession().setAttribute("notification_hours", displayPast); } catch (NumberFormatException e1) { BrokerFactory.getLoggingBroker().logError(e1); } } // Get the stored "display past" value String numHoursString = (String) actionRequest.getSession() .getAttribute("notification_hours"); if ((numHoursString == null) || (numHoursString.length() == 0)) { numHoursString = "2"; } int numHours = 2; try { numHours = Integer.parseInt(numHoursString); } catch (NumberFormatException e) { BrokerFactory.getLoggingBroker().logError(e); } boolean viewActive = getIsVisible(actionRequest, "", "active"); boolean viewConfirmed = getIsVisible(actionRequest, "", "confirmed"); boolean viewExpired = getIsVisible(actionRequest, "", "expired"); boolean viewOnhold = getIsVisible(actionRequest, "", "onhold"); User user = (User)BrokerFactory.getUserMgmtBroker().getUserByUuid((String)actionRequest.getSession().getAttribute("user")); BrokerFactory.getLoggingBroker().logDebug("Current user = "+user); NotificationBroker broker = BrokerFactory.getNotificationBroker(); BigInteger timeSince = new BigInteger(""+numHours).multiply(new BigInteger("3600")).multiply(new BigInteger("1000")); List<Notification> recentNotifications = broker.getNotificationsSince(timeSince.longValue()).stream().distinct().filter(n -> isVisible(user, n)).collect(Collectors.toList()); // Add all the pending notifications //List<Notification> pendingNotifications = broker.getAllPendingNotifications(); List<Notification> pendingNotifications = broker.getAllPendingNotifications().stream().distinct().filter(n -> isVisible(user, n)).collect(Collectors.toList()); BrokerFactory.getLoggingBroker().logDebug(pendingNotifications.size()+" pending notifs"); long pending = recentNotifications.stream().filter(n->n.getStatus()==Notification.PENDING).count(); pending += recentNotifications.stream().filter(n->n.getStatus()==Notification.NORMAL).count(); long confirmed = recentNotifications.stream().filter(n->n.getStatus()==Notification.CONFIRMED).count(); long expired = recentNotifications.stream().filter(n->n.getStatus()==Notification.EXPIRED).count(); long onhold = recentNotifications.stream().filter(n->n.getStatus()==Notification.ONHOLD).count(); String notifsTitle = makeTitle("Notifications Sent To Me", "", viewActive, viewConfirmed, viewExpired, viewOnhold, pending, confirmed, expired, onhold, numHours); String systemMessage = request .getParameter("pending_notification_message"); if ((systemMessage != null) && (systemMessage.length() > 0)) { notifsTitle += "</tr><tr><td colspan=\"2\" class=\"headercell\" width=\"100%\"><span class=\"systemalert\">"; notifsTitle += systemMessage; notifsTitle += "</span></td>"; } actionRequest.addParameter("notifsTitle", notifsTitle); // -- Sent By Me section -- // Check to see if the user has update the "display past" setting displayPast = request.getParameter("display_byme_past"); if ((displayPast != null) && (displayPast.length() > 0)) { try { actionRequest.getSession().setAttribute("notification_byme_hours", displayPast); } catch (NumberFormatException e1) { BrokerFactory.getLoggingBroker().logError(e1); } } // Get the stored "display past" value numHours = StringUtils.getInteger((String) actionRequest.getSession().getAttribute("notification_byme_hours"), 2); viewActive = getIsVisible(actionRequest, "byme_", "active"); viewConfirmed = getIsVisible(actionRequest, "byme_", "confirmed"); viewExpired = getIsVisible(actionRequest, "byme_", "expired"); viewOnhold = getIsVisible(actionRequest, "byme_", "onhold"); List<Notification> myNotifications = broker.getNotificationsSentBy(user); BrokerFactory.getLoggingBroker().logDebug("We have "+myNotifications.size()+" my notifs"); pending = myNotifications.stream().filter(n->n.getStatus()==Notification.PENDING).count(); pending += myNotifications.stream().filter(n->n.getStatus()==Notification.NORMAL).count(); confirmed = myNotifications.stream().filter(n->n.getStatus()==Notification.CONFIRMED).count(); expired = myNotifications.stream().filter(n->n.getStatus()==Notification.EXPIRED).count(); onhold = myNotifications.stream().filter(n->n.getStatus()==Notification.ONHOLD).count(); String sentNotifsTitle = makeTitle("Notifications Sent By Me", "byme_", viewActive, viewConfirmed, viewExpired, viewOnhold, pending, confirmed, expired, onhold, numHours); systemMessage = request .getParameter("sent_notification_message"); if ((systemMessage != null) && (systemMessage.length() > 0)) { sentNotifsTitle += "</tr><tr><td colspan=\"2\" class=\"headercell\" width=\"100%\"><span class=\"systemalert\">"; sentNotifsTitle += systemMessage; sentNotifsTitle += "</span></td>"; } actionRequest.addParameter("sentNotifsTitle", sentNotifsTitle); viewActive = getIsVisible(actionRequest, "squelched_", "active"); viewConfirmed = getIsVisible(actionRequest, "squelched_", "confirmed"); viewExpired = getIsVisible(actionRequest, "squelched_", "expired"); viewOnhold = getIsVisible(actionRequest, "squelched_", "onhold"); // -- Squelched notifications -- displayPast = request.getParameter("display_squelched_past"); if ((displayPast != null) && (displayPast.length() > 0)) { try { actionRequest.getSession().setAttribute("notification_squelched_hours", displayPast); } catch (NumberFormatException e1) { BrokerFactory.getLoggingBroker().logError(e1); } } int squelchedHours = StringUtils.getInteger((String) actionRequest.getSession().getAttribute("notification_squelched_hours"), 2); List<Notification> squelchedNotifications = Squelcher.getSquelcherNotifications(user).stream().filter(n->n.getTime().getTime()>System.currentTimeMillis()-(squelchedHours*3600000)).collect(Collectors.toList()); BrokerFactory.getLoggingBroker().logDebug(pendingNotifications.size()+" pending notifs"); viewActive = getIsVisible(actionRequest, "squelched_", "active"); viewConfirmed = getIsVisible(actionRequest, "squelched_", "confirmed"); viewExpired = getIsVisible(actionRequest, "squelched_", "expired"); viewOnhold = getIsVisible(actionRequest, "squelched_", "onhold"); pending = squelchedNotifications.stream().filter(n->n.getStatus()==Notification.PENDING).count(); pending += squelchedNotifications.stream().filter(n->n.getStatus()==Notification.NORMAL).count(); confirmed = squelchedNotifications.stream().filter(n->n.getStatus()==Notification.CONFIRMED).count(); expired = squelchedNotifications.stream().filter(n->n.getStatus()==Notification.EXPIRED).count(); onhold = squelchedNotifications.stream().filter(n->n.getStatus()==Notification.ONHOLD).count(); String squelchedNotifsTitle = makeTitle("Squelched Notifications", "squelched_", viewActive, viewConfirmed, viewExpired, viewOnhold, pending, confirmed, expired, onhold, squelchedHours); systemMessage = request.getParameter("squelched_notification_message"); if (!StringUtils.isEmpty(systemMessage)) { squelchedNotifsTitle += "</tr><tr><td colspan=\"2\" class=\"headercell\" width=\"100%\"><span class=\"systemalert\">"; squelchedNotifsTitle += systemMessage; squelchedNotifsTitle += "</span></td>"; } actionRequest.addParameter("squelchedNotifsTitle", squelchedNotifsTitle); // Handle the send title String sendTitle = "<font color=\"#17A1e2\">Send A New Notification</font></td>"; systemMessage = actionRequest.getParameter("send_system_message"); if ((systemMessage != null) && (systemMessage.length() > 0)) { sendTitle += "<td class=\"headercell\"><span class=\"systemalert\">"; sendTitle += systemMessage; sendTitle += "</span></td>"; } else { sendTitle += "<td class=\"headercell\"></td>"; } actionRequest.addParameter("sendTitle", sendTitle); return actionRequest; } }
package org.bouncycastle.openpgp; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Collection; import java.util.Date; import java.util.Iterator; import java.util.List; import org.bouncycastle.asn1.x9.ECNamedCurveTable; import org.bouncycastle.asn1.x9.X9ECParameters; import org.bouncycastle.bcpg.BCPGKey; import org.bouncycastle.bcpg.BCPGOutputStream; import org.bouncycastle.bcpg.ContainedPacket; import org.bouncycastle.bcpg.DSAPublicBCPGKey; import org.bouncycastle.bcpg.ECPublicBCPGKey; import org.bouncycastle.bcpg.ElGamalPublicBCPGKey; import org.bouncycastle.bcpg.PublicKeyAlgorithmTags; import org.bouncycastle.bcpg.PublicKeyPacket; import org.bouncycastle.bcpg.RSAPublicBCPGKey; import org.bouncycastle.bcpg.SignatureSubpacketTags; import org.bouncycastle.bcpg.TrustPacket; import org.bouncycastle.bcpg.UserAttributePacket; import org.bouncycastle.bcpg.UserIDPacket; import org.bouncycastle.openpgp.operator.KeyFingerPrintCalculator; import org.bouncycastle.util.Arrays; /** * general class to handle a PGP public key object. */ public class PGPPublicKey implements PublicKeyAlgorithmTags { private static final int[] MASTER_KEY_CERTIFICATION_TYPES = new int[] { PGPSignature.POSITIVE_CERTIFICATION, PGPSignature.CASUAL_CERTIFICATION, PGPSignature.NO_CERTIFICATION, PGPSignature.DEFAULT_CERTIFICATION, PGPSignature.DIRECT_KEY }; PublicKeyPacket publicPk; TrustPacket trustPk; List<PGPSignature> keySigs = new ArrayList(); List ids = new ArrayList(); List<TrustPacket> idTrusts = new ArrayList(); List<List<PGPSignature>> idSigs = new ArrayList(); List<PGPSignature> subSigs = null; private long keyID; private byte[] fingerprint; private int keyStrength; private void init(KeyFingerPrintCalculator fingerPrintCalculator) throws PGPException { BCPGKey key = publicPk.getKey(); this.fingerprint = fingerPrintCalculator.calculateFingerprint(publicPk); if (publicPk.getVersion() <= 3) { RSAPublicBCPGKey rK = (RSAPublicBCPGKey)key; this.keyID = rK.getModulus().longValue(); this.keyStrength = rK.getModulus().bitLength(); } else { this.keyID = ((long)(fingerprint[fingerprint.length - 8] & 0xff) << 56) | ((long)(fingerprint[fingerprint.length - 7] & 0xff) << 48) | ((long)(fingerprint[fingerprint.length - 6] & 0xff) << 40) | ((long)(fingerprint[fingerprint.length - 5] & 0xff) << 32) | ((long)(fingerprint[fingerprint.length - 4] & 0xff) << 24) | ((long)(fingerprint[fingerprint.length - 3] & 0xff) << 16) | ((long)(fingerprint[fingerprint.length - 2] & 0xff) << 8) | ((fingerprint[fingerprint.length - 1] & 0xff)); if (key instanceof RSAPublicBCPGKey) { this.keyStrength = ((RSAPublicBCPGKey)key).getModulus().bitLength(); } else if (key instanceof DSAPublicBCPGKey) { this.keyStrength = ((DSAPublicBCPGKey)key).getP().bitLength(); } else if (key instanceof ElGamalPublicBCPGKey) { this.keyStrength = ((ElGamalPublicBCPGKey)key).getP().bitLength(); } else if (key instanceof ECPublicBCPGKey) { X9ECParameters ecParameters = ECNamedCurveTable.getByOID(((ECPublicBCPGKey)key).getCurveOID()); if (ecParameters != null) { this.keyStrength = ecParameters.getCurve().getFieldSize(); } else { this.keyStrength = -1; // unknown } } } } /** * Create a PGP public key from a packet descriptor using the passed in fingerPrintCalculator to do calculate * the fingerprint and keyID. * * @param publicKeyPacket packet describing the public key. * @param fingerPrintCalculator calculator providing the digest support ot create the key fingerprint. * @throws PGPException if the packet is faulty, or the required calculations fail. */ public PGPPublicKey(PublicKeyPacket publicKeyPacket, KeyFingerPrintCalculator fingerPrintCalculator) throws PGPException { this.publicPk = publicKeyPacket; this.ids = new ArrayList(); this.idSigs = new ArrayList(); init(fingerPrintCalculator); } /* * Constructor for a sub-key. */ PGPPublicKey( PublicKeyPacket publicPk, TrustPacket trustPk, List sigs, KeyFingerPrintCalculator fingerPrintCalculator) throws PGPException { this.publicPk = publicPk; this.trustPk = trustPk; this.subSigs = sigs; init(fingerPrintCalculator); } PGPPublicKey( PGPPublicKey key, TrustPacket trust, List subSigs) { this.publicPk = key.publicPk; this.trustPk = trust; this.subSigs = subSigs; this.fingerprint = key.fingerprint; this.keyID = key.keyID; this.keyStrength = key.keyStrength; } /** * Copy constructor. * @param pubKey the public key to copy. */ PGPPublicKey( PGPPublicKey pubKey) { this.publicPk = pubKey.publicPk; this.keySigs = new ArrayList(pubKey.keySigs); this.ids = new ArrayList(pubKey.ids); this.idTrusts = new ArrayList(pubKey.idTrusts); this.idSigs = new ArrayList(pubKey.idSigs.size()); for (int i = 0; i != pubKey.idSigs.size(); i++) { this.idSigs.add(new ArrayList((ArrayList)pubKey.idSigs.get(i))); } if (pubKey.subSigs != null) { this.subSigs = new ArrayList(pubKey.subSigs.size()); for (int i = 0; i != pubKey.subSigs.size(); i++) { this.subSigs.add(pubKey.subSigs.get(i)); } } this.fingerprint = pubKey.fingerprint; this.keyID = pubKey.keyID; this.keyStrength = pubKey.keyStrength; } PGPPublicKey( PublicKeyPacket publicPk, TrustPacket trustPk, List keySigs, List ids, List idTrusts, List idSigs, KeyFingerPrintCalculator fingerPrintCalculator) throws PGPException { this.publicPk = publicPk; this.trustPk = trustPk; this.keySigs = keySigs; this.ids = ids; this.idTrusts = idTrusts; this.idSigs = idSigs; init(fingerPrintCalculator); } /** * @return the version of this key. */ public int getVersion() { return publicPk.getVersion(); } /** * @return creation time of key. */ public Date getCreationTime() { return publicPk.getTime(); } /** * @return number of valid days from creation time - zero means no * expiry. * @deprecated use getValidSeconds(): greater than version 3 keys may be valid for less than a day. */ public int getValidDays() { if (publicPk.getVersion() > 3) { long delta = this.getValidSeconds() % (24 * 60 * 60); int days = (int)(this.getValidSeconds() / (24 * 60 * 60)); if (delta > 0 && days == 0) { return 1; } else { return days; } } else { return publicPk.getValidDays(); } } /** * Return the trust data associated with the public key, if present. * @return a byte array with trust data, null otherwise. */ public byte[] getTrustData() { if (trustPk == null) { return null; } return Arrays.clone(trustPk.getLevelAndTrustAmount()); } /** * @return number of valid seconds from creation time - zero means no * expiry. */ public long getValidSeconds() { if (publicPk.getVersion() > 3) { if (this.isMasterKey()) { for (int i = 0; i != MASTER_KEY_CERTIFICATION_TYPES.length; i++) { long seconds = getExpirationTimeFromSig(true, MASTER_KEY_CERTIFICATION_TYPES[i]); if (seconds >= 0) { return seconds; } } } else { long seconds = getExpirationTimeFromSig(false, PGPSignature.SUBKEY_BINDING); if (seconds >= 0) { return seconds; } seconds = getExpirationTimeFromSig(false, PGPSignature.DIRECT_KEY); if (seconds >= 0) { return seconds; } } return 0; } else { return (long)publicPk.getValidDays() * 24 * 60 * 60; } } private long getExpirationTimeFromSig( boolean selfSigned, int signatureType) { Iterator signatures = this.getSignaturesOfType(signatureType); long expiryTime = -1; long lastDate = -1; while (signatures.hasNext()) { PGPSignature sig = (PGPSignature)signatures.next(); if (!selfSigned || sig.getKeyID() == this.getKeyID()) { PGPSignatureSubpacketVector hashed = sig.getHashedSubPackets(); if (hashed == null) { continue; } if (!hashed.hasSubpacket(SignatureSubpacketTags.KEY_EXPIRE_TIME)) { continue; } long current = hashed.getKeyExpirationTime(); if (sig.getKeyID() == this.getKeyID()) { if (sig.getCreationTime().getTime() > lastDate) { lastDate = sig.getCreationTime().getTime(); expiryTime = current; } } else { if (current == 0 || current > expiryTime) { expiryTime = current; } } } } return expiryTime; } /** * Return the keyID associated with the public key. * * @return long */ public long getKeyID() { return keyID; } /** * Return the fingerprint of the key. * * @return key fingerprint. */ public byte[] getFingerprint() { byte[] tmp = new byte[fingerprint.length]; System.arraycopy(fingerprint, 0, tmp, 0, tmp.length); return tmp; } /** * Return true if this key has an algorithm type that makes it suitable to use for encryption. * <p> * Note: with version 4 keys KeyFlags subpackets should also be considered when present for * determining the preferred use of the key. * * @return true if the key algorithm is suitable for encryption. */ public boolean isEncryptionKey() { int algorithm = publicPk.getAlgorithm(); return ((algorithm == RSA_GENERAL) || (algorithm == RSA_ENCRYPT) || (algorithm == ELGAMAL_ENCRYPT) || (algorithm == ELGAMAL_GENERAL) || (algorithm == DIFFIE_HELLMAN) || (algorithm == ECDH)); } /** * Return true if this could be a master key. * @return true if a master key. */ public boolean isMasterKey() { return (subSigs == null) && !(this.isEncryptionKey() && publicPk.getAlgorithm() != PublicKeyAlgorithmTags.RSA_GENERAL); } /** * Return the algorithm code associated with the public key. * * @return int */ public int getAlgorithm() { return publicPk.getAlgorithm(); } /** * Return the strength of the key in bits. * * @return bit strength of key. */ public int getBitStrength() { return keyStrength; } /** * Return any userIDs associated with the key. * * @return an iterator of Strings. */ public Iterator<String> getUserIDs() { List temp = new ArrayList(); for (int i = 0; i != ids.size(); i++) { if (ids.get(i) instanceof UserIDPacket) { temp.add(((UserIDPacket)ids.get(i)).getID()); } } return temp.iterator(); } /** * Return any userIDs associated with the key in raw byte form. No attempt is made * to convert the IDs into Strings. * * @return an iterator of Strings. */ public Iterator<byte[]> getRawUserIDs() { List temp = new ArrayList(); for (int i = 0; i != ids.size(); i++) { if (ids.get(i) instanceof UserIDPacket) { temp.add(((UserIDPacket)ids.get(i)).getRawID()); } } return temp.iterator(); } /** * Return any user attribute vectors associated with the key. * * @return an iterator of PGPUserAttributeSubpacketVector objects. */ public Iterator<PGPUserAttributeSubpacketVector> getUserAttributes() { List temp = new ArrayList(); for (int i = 0; i != ids.size(); i++) { if (ids.get(i) instanceof PGPUserAttributeSubpacketVector) { temp.add(ids.get(i)); } } return temp.iterator(); } /** * Return any signatures associated with the passed in id. * * @param id the id to be matched. * @return an iterator of PGPSignature objects. */ public Iterator<PGPSignature> getSignaturesForID( String id) { return getSignaturesForID(new UserIDPacket(id)); } /** * Return any signatures associated with the passed in id. * * @param rawID the id to be matched in raw byte form. * @return an iterator of PGPSignature objects. */ public Iterator<PGPSignature> getSignaturesForID( byte[] rawID) { return getSignaturesForID(new UserIDPacket(rawID)); } /** * Return any signatures associated with the passed in key identifier keyID. * * @param keyID the key id to be matched. * @return an iterator of PGPSignature objects issued by the key with keyID. */ public Iterator<PGPSignature> getSignaturesForKeyID( long keyID) { List sigs = new ArrayList(); for (Iterator it = getSignatures(); it.hasNext();) { PGPSignature sig = (PGPSignature)it.next(); if (sig.getKeyID() == keyID) { sigs.add(sig); } } return sigs.iterator(); } private Iterator<PGPSignature> getSignaturesForID( UserIDPacket id) { List<PGPSignature> signatures = new ArrayList<>(); boolean userIdFound = false; for (int i = 0; i != ids.size(); i++) { if (id.equals(ids.get(i))) { userIdFound = true; signatures.addAll(idSigs.get(i)); } } return userIdFound ? signatures.iterator() : null; } /** * Return an iterator of signatures associated with the passed in user attributes. * * @param userAttributes the vector of user attributes to be matched. * @return an iterator of PGPSignature objects. */ public Iterator<PGPSignature> getSignaturesForUserAttribute( PGPUserAttributeSubpacketVector userAttributes) { List<PGPSignature> signatures = new ArrayList<>(); boolean attributeFound = false; for (int i = 0; i != ids.size(); i++) { if (userAttributes.equals(ids.get(i))) { attributeFound = true; signatures.addAll(idSigs.get(i)); } } return attributeFound ? signatures.iterator() : null; } /** * Return signatures of the passed in type that are on this key. * * @param signatureType the type of the signature to be returned. * @return an iterator (possibly empty) of signatures of the given type. */ public Iterator<PGPSignature> getSignaturesOfType( int signatureType) { List<PGPSignature> l = new ArrayList<PGPSignature>(); Iterator<PGPSignature> it = this.getSignatures(); while (it.hasNext()) { PGPSignature sig = (PGPSignature)it.next(); if (sig.getSignatureType() == signatureType) { l.add(sig); } } return l.iterator(); } /** * Return all signatures/certifications associated with this key. * * @return an iterator (possibly empty) with all signatures/certifications. */ public Iterator<PGPSignature> getSignatures() { if (subSigs == null) { List sigs = new ArrayList(); sigs.addAll(keySigs); for (int i = 0; i != idSigs.size(); i++) { sigs.addAll((Collection)idSigs.get(i)); } return sigs.iterator(); } else { return subSigs.iterator(); } } /** * Return all signatures/certifications directly associated with this key (ie, not to a user id). * * @return an iterator (possibly empty) with all signatures/certifications. */ public Iterator<PGPSignature> getKeySignatures() { if (subSigs == null) { List<PGPSignature> sigs = new ArrayList<PGPSignature>(); sigs.addAll(keySigs); return sigs.iterator(); } else { return subSigs.iterator(); } } public PublicKeyPacket getPublicKeyPacket() { return publicPk; } public byte[] getEncoded() throws IOException { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); this.encode(bOut, false); return bOut.toByteArray(); } /** * Return an encoding of the key, with trust packets stripped out if forTransfer is true. * * @param forTransfer if the purpose of encoding is to send key to other users. * @return a encoded byte array representing the key. * @throws IOException in case of encoding error. */ public byte[] getEncoded(boolean forTransfer) throws IOException { ByteArrayOutputStream bOut = new ByteArrayOutputStream(); this.encode(bOut, forTransfer); return bOut.toByteArray(); } public void encode( OutputStream outStream) throws IOException { encode(outStream, false); } /** * Encode the key to outStream, with trust packets stripped out if forTransfer is true. * * @param outStream stream to write the key encoding to. * @param forTransfer if the purpose of encoding is to send key to other users. * @throws IOException in case of encoding error. */ public void encode( OutputStream outStream, boolean forTransfer) throws IOException { BCPGOutputStream out; if (outStream instanceof BCPGOutputStream) { out = (BCPGOutputStream)outStream; } else { out = new BCPGOutputStream(outStream); } out.writePacket(publicPk); if (!forTransfer && trustPk != null) { out.writePacket(trustPk); } if (subSigs == null) // not a sub-key { for (int i = 0; i != keySigs.size(); i++) { ((PGPSignature)keySigs.get(i)).encode(out); } for (int i = 0; i != ids.size(); i++) { if (ids.get(i) instanceof UserIDPacket) { UserIDPacket id = (UserIDPacket)ids.get(i); out.writePacket(id); } else { PGPUserAttributeSubpacketVector v = (PGPUserAttributeSubpacketVector)ids.get(i); out.writePacket(new UserAttributePacket(v.toSubpacketArray())); } if (!forTransfer && idTrusts.get(i) != null) { out.writePacket((ContainedPacket)idTrusts.get(i)); } List sigs = (List)idSigs.get(i); for (int j = 0; j != sigs.size(); j++) { ((PGPSignature)sigs.get(j)).encode(out, forTransfer); } } } else { for (int j = 0; j != subSigs.size(); j++) { ((PGPSignature)subSigs.get(j)).encode(out, forTransfer); } } } /** * Check whether this (sub)key has a revocation signature on it. * * @return boolean indicating whether this (sub)key has been revoked. * @deprecated this method is poorly named, use hasRevocation(). */ public boolean isRevoked() { return hasRevocation(); } /** * Check whether this (sub)key has a revocation signature on it. * * @return boolean indicating whether this (sub)key has had a (possibly invalid) revocation attached.. */ public boolean hasRevocation() { int ns = 0; boolean revoked = false; if (this.isMasterKey()) // Master key { while (!revoked && (ns < keySigs.size())) { if (((PGPSignature)keySigs.get(ns++)).getSignatureType() == PGPSignature.KEY_REVOCATION) { revoked = true; } } } else // Sub-key { while (!revoked && (ns < subSigs.size())) { if (((PGPSignature)subSigs.get(ns++)).getSignatureType() == PGPSignature.SUBKEY_REVOCATION) { revoked = true; } } } return revoked; } /** * Add a certification for an id to the given public key. * * @param key the key the certification is to be added to. * @param rawID the raw bytes making up the user id.. * @param certification the new certification. * @return the re-certified key. */ public static PGPPublicKey addCertification( PGPPublicKey key, byte[] rawID, PGPSignature certification) { return addCert(key, new UserIDPacket(rawID), certification); } /** * Add a certification for an id to the given public key. * * @param key the key the certification is to be added to. * @param id the id the certification is associated with. * @param certification the new certification. * @return the re-certified key. */ public static PGPPublicKey addCertification( PGPPublicKey key, String id, PGPSignature certification) { return addCert(key, new UserIDPacket(id), certification); } /** * Add a certification for the given UserAttributeSubpackets to the given public key. * * @param key the key the certification is to be added to. * @param userAttributes the attributes the certification is associated with. * @param certification the new certification. * @return the re-certified key. */ public static PGPPublicKey addCertification( PGPPublicKey key, PGPUserAttributeSubpacketVector userAttributes, PGPSignature certification) { return addCert(key, userAttributes, certification); } private static PGPPublicKey addCert( PGPPublicKey key, Object id, PGPSignature certification) { PGPPublicKey returnKey = new PGPPublicKey(key); List sigList = null; for (int i = 0; i != returnKey.ids.size(); i++) { if (id.equals(returnKey.ids.get(i))) { sigList = (List)returnKey.idSigs.get(i); } } if (sigList != null) { sigList.add(certification); } else { sigList = new ArrayList(); sigList.add(certification); returnKey.ids.add(id); returnKey.idTrusts.add(null); returnKey.idSigs.add(sigList); } return returnKey; } /** * Remove any certifications associated with a given user attribute subpacket * on a key. * * @param key the key the certifications are to be removed from. * @param userAttributes the attributes to be removed. * @return the re-certified key, null if the user attribute subpacket was not found on the key. */ public static PGPPublicKey removeCertification( PGPPublicKey key, PGPUserAttributeSubpacketVector userAttributes) { return removeCert(key, userAttributes); } /** * Remove any certifications associated with a given id on a key. * * @param key the key the certifications are to be removed from. * @param id the id that is to be removed. * @return the re-certified key, null if the id was not found on the key. */ public static PGPPublicKey removeCertification( PGPPublicKey key, String id) { return removeCert(key, new UserIDPacket(id)); } /** * Remove any certifications associated with a given id on a key. * * @param key the key the certifications are to be removed from. * @param rawID the id that is to be removed in raw byte form. * @return the re-certified key, null if the id was not found on the key. */ public static PGPPublicKey removeCertification( PGPPublicKey key, byte[] rawID) { return removeCert(key, new UserIDPacket(rawID)); } private static PGPPublicKey removeCert( PGPPublicKey key, Object id) { PGPPublicKey returnKey = new PGPPublicKey(key); boolean found = false; for (int i = 0; i < returnKey.ids.size(); i++) { if (id.equals(returnKey.ids.get(i))) { found = true; returnKey.ids.remove(i); returnKey.idTrusts.remove(i); returnKey.idSigs.remove(i); } } if (!found) { return null; } return returnKey; } /** * Remove a certification associated with a given id on a key. * * @param key the key the certifications are to be removed from. * @param id the id that the certification is to be removed from (in its raw byte form) * @param certification the certification to be removed. * @return the re-certified key, null if the certification was not found. */ public static PGPPublicKey removeCertification( PGPPublicKey key, byte[] id, PGPSignature certification) { return removeCert(key, new UserIDPacket(id), certification); } /** * Remove a certification associated with a given id on a key. * * @param key the key the certifications are to be removed from. * @param id the id that the certification is to be removed from. * @param certification the certification to be removed. * @return the re-certified key, null if the certification was not found. */ public static PGPPublicKey removeCertification( PGPPublicKey key, String id, PGPSignature certification) { return removeCert(key, new UserIDPacket(id), certification); } /** * Remove a certification associated with a given user attributes on a key. * * @param key the key the certifications are to be removed from. * @param userAttributes the user attributes that the certification is to be removed from. * @param certification the certification to be removed. * @return the re-certified key, null if the certification was not found. */ public static PGPPublicKey removeCertification( PGPPublicKey key, PGPUserAttributeSubpacketVector userAttributes, PGPSignature certification) { return removeCert(key, userAttributes, certification); } private static PGPPublicKey removeCert( PGPPublicKey key, Object id, PGPSignature certification) { PGPPublicKey returnKey = new PGPPublicKey(key); boolean found = false; for (int i = 0; i < returnKey.ids.size(); i++) { if (id.equals(returnKey.ids.get(i))) { found = ((List)returnKey.idSigs.get(i)).remove(certification); } } if (!found) { return null; } return returnKey; } /** * Add a revocation or some other key certification to a key. * * @param key the key the revocation is to be added to. * @param certification the key signature to be added. * @return the new changed public key object. */ public static PGPPublicKey addCertification( PGPPublicKey key, PGPSignature certification) { if (key.isMasterKey()) { if (certification.getSignatureType() == PGPSignature.SUBKEY_REVOCATION) { throw new IllegalArgumentException("signature type incorrect for master key revocation."); } } else { if (certification.getSignatureType() == PGPSignature.KEY_REVOCATION) { throw new IllegalArgumentException("signature type incorrect for sub-key revocation."); } } PGPPublicKey returnKey = new PGPPublicKey(key); if (returnKey.subSigs != null) { returnKey.subSigs.add(certification); } else { returnKey.keySigs.add(certification); } return returnKey; } /** * Remove a certification from the key. * * @param key the key the certifications are to be removed from. * @param certification the certification to be removed. * @return the modified key, null if the certification was not found. */ public static PGPPublicKey removeCertification( PGPPublicKey key, PGPSignature certification) { PGPPublicKey returnKey = new PGPPublicKey(key); boolean found; if (returnKey.subSigs != null) { found = returnKey.subSigs.remove(certification); } else { found = returnKey.keySigs.remove(certification); } if (!found) { for (Iterator it = key.getRawUserIDs(); it.hasNext();) { byte[] rawID = (byte[])it.next(); for (Iterator sIt = key.getSignaturesForID(rawID); sIt.hasNext();) { if (certification == sIt.next()) { found = true; returnKey = PGPPublicKey.removeCertification(returnKey, rawID, certification); } } } if (!found) { for (Iterator it = key.getUserAttributes(); it.hasNext();) { PGPUserAttributeSubpacketVector id = (PGPUserAttributeSubpacketVector)it.next(); for (Iterator sIt = key.getSignaturesForUserAttribute(id); sIt.hasNext();) { if (certification == sIt.next()) { found = true; returnKey = PGPPublicKey.removeCertification(returnKey, id, certification); } } } } } return returnKey; } }
package VASSAL.configure; import java.awt.Component; import java.awt.Dimension; import java.io.File; import java.io.InputStream; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import javax.swing.BoxLayout; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import VASSAL.build.GameModule; import VASSAL.i18n.Resources; import VASSAL.tools.AudioClip; import VASSAL.tools.AudioSystemClip; import VASSAL.tools.Mp3AudioClip; import VASSAL.tools.ReadErrorDialog; import VASSAL.tools.URLUtils; import VASSAL.tools.filechooser.AudioFileFilter; import VASSAL.tools.filechooser.FileChooser; /** * Configurer for specifying a Clip. This class is intended to allow * players to override a default sound with their own sound file on their * local file system. */ public class SoundConfigurer extends Configurer { public static final String DEFAULT = "default"; //NON-NLS private String defaultResource; private String clipName; private JPanel controls; private JTextField textField; private AudioClipFactory clipFactory; //FIXME this needs some i18n scheme and preferably the display version should be [disabled] while leaving file version alone. private static final String NO_VALUE = "<disabled>"; public SoundConfigurer(String key, String name, String defaultResource) { super(key, name); this.defaultResource = defaultResource; clipFactory = createAudioClipFactory(); setValue(DEFAULT); } @Override public Component getControls() { if (controls == null) { controls = new JPanel(); controls.setLayout(new BoxLayout(controls, BoxLayout.X_AXIS)); controls.add(new JLabel(name)); JButton b = new JButton(Resources.getString("Editor.SoundConfigurer.play")); b.addActionListener(e -> play()); controls.add(b); b = new JButton(Resources.getString("Editor.SoundConfigurer.default")); b.addActionListener(e -> setValue(DEFAULT)); controls.add(b); b = new JButton(Resources.getString("Editor.SoundConfigurer.select")); b.addActionListener(e -> chooseClip()); controls.add(b); textField = new JTextField(); textField.setMaximumSize( new Dimension(textField.getMaximumSize().width, textField.getPreferredSize().height)); textField.setEditable(false); textField.setText(DEFAULT.equals(clipName) ? defaultResource : clipName); controls.add(textField); } return controls; } @Override public String getValueString() { String s = NO_VALUE; if (clipName != null) { s = clipName; } return s; } @Override public void setValue(String s) { if (clipFactory == null) { return; } URL url = null; if (DEFAULT.equals(s)) { url = getClass().getResource("/images/" + defaultResource); //NON-NLS clipName = s; } else if (NO_VALUE.equals(s)) { clipName = s; } else if (s != null) { try { url = URLUtils.toURL(new File(s)); clipName = s; } catch (MalformedURLException e) { ReadErrorDialog.error(e, s); clipName = null; } } if (textField != null) { textField.setText(DEFAULT.equals(clipName) ? defaultResource : clipName); } if (url != null) { try { setValue(clipFactory.getAudioClip(url)); } catch (IOException e) { ReadErrorDialog.error(e, url.toString()); } } else { if (textField != null) { textField.setText(null); } setValue((Object) null); } } @FunctionalInterface protected interface AudioClipFactory { AudioClip getAudioClip(URL url) throws IOException; } protected AudioClipFactory createAudioClipFactory() { return url -> { if (url.toString().toLowerCase().endsWith(".mp3")) { //NON-NLS return new Mp3AudioClip(url); } else { try (InputStream in = url.openStream()) { return new AudioSystemClip(in); } catch (IOException e) { return null; } } }; } public void play() { final AudioClip clip = (AudioClip) getValue(); if (clip != null) { clip.play(); } } public void chooseClip() { final FileChooser fc = GameModule.getGameModule().getFileChooser(); fc.setFileFilter(new AudioFileFilter()); if (fc.showOpenDialog(getControls()) != FileChooser.APPROVE_OPTION) { setValue(NO_VALUE); } else { File f = fc.getSelectedFile(); setValue(f.getName()); } } }
package org.hollowcraft.server.persistence; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.util.Map; import org.hollowcraft.server.model.Player; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.thoughtworks.xstream.XStream; /** * A persistence request which loads the specified player. * @author Graham Edgecombe * @author Caleb Champlin * */ public class LoadPersistenceRequest extends PersistenceRequest { private static final Logger logger = LoggerFactory.getLogger(LoadPersistenceRequest.class); /** * Creates the load request. * @param player The player to load. */ public LoadPersistenceRequest(Player player) { super(player); } @SuppressWarnings("unchecked") public void perform() throws IOException { final SavedGameManager mgr = SavedGameManager.getSavedGameManager(); final Player player = getPlayer(); final XStream xs = mgr.getXStream(); final File file = new File(mgr.getPath(player)); if(file.exists()) { try { Map<String, Object> attributes = (Map<String, Object>) xs.fromXML(new FileInputStream(file)); for(Map.Entry<String, Object> entry : attributes.entrySet()) { player.setAttribute(entry.getKey(), entry.getValue(),true); } } catch (RuntimeException ex) { throw new IOException(ex.getMessage()); } } player.getSession().setReady(); player.getWorld().completeRegistration(player.getSession()); } }
// FEIReader.java package loci.formats.in; import java.io.IOException; import loci.common.RandomAccessInputStream; import loci.formats.FormatException; import loci.formats.FormatReader; import loci.formats.FormatTools; import loci.formats.MetadataTools; import loci.formats.meta.FilterMetadata; import loci.formats.meta.MetadataStore; public class FEIReader extends FormatReader { // -- Constants -- public static final String FEI_MAGIC_STRING = "XL"; private static final int INVALID_PIXELS = 112; // -- Fields -- private int headerSize; // -- Constructor -- /** Constructs a new FEI reader. */ public FEIReader() { super("FEI/Philips", "img"); suffixSufficient = false; domains = new String[] {FormatTools.SEM_DOMAIN}; } // -- IFormatReader API methods -- /* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */ public boolean isThisType(RandomAccessInputStream stream) throws IOException { final int blockLen = 2; if (!FormatTools.validStream(stream, blockLen, false)) return false; return stream.readString(blockLen).startsWith(FEI_MAGIC_STRING); } /** * @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); in.seek(headerSize); byte[] segment = new byte[getSizeX() / 2]; // interlace frames - there are four rows of two columns int halfRow = getSizeX() / 2; for (int q=0; q<4; q++) { for (int row=q; row<h; row+=4) { for (int s=0; s<2; s++) { in.read(segment); in.skipBytes(INVALID_PIXELS / 2); for (int col=s; col<w; col+=2) { buf[row*w + col] = segment[col / 2]; } } } } return buf; } /* @see loci.formats.IFormatReader#close(boolean) */ public void close(boolean fileOnly) throws IOException { super.close(fileOnly); if (!fileOnly) { headerSize = 0; } } // -- Internal FormatReader API methods -- /* @see loci.formats.FormatReader#initFile(String) */ protected void initFile(String id) throws FormatException, IOException { debug("FEIReader.initFile(" + id + ")"); super.initFile(id); in = new RandomAccessInputStream(id); in.order(true); status("Reading file header"); in.skipBytes(44); float magnification = in.readFloat(); float kV = in.readFloat() / 1000; float wd = in.readFloat(); in.skipBytes(12); float spot = in.readFloat(); in.seek(514); core[0].sizeX = in.readShort() - INVALID_PIXELS; core[0].sizeY = in.readShort(); in.skipBytes(4); headerSize = in.readShort(); // always one grayscale plane per file core[0].sizeZ = 1; core[0].sizeC = 1; core[0].sizeT = 1; core[0].imageCount = 1; core[0].littleEndian = true; core[0].pixelType = FormatTools.UINT8; core[0].rgb = false; core[0].indexed = false; core[0].interleaved = false; core[0].dimensionOrder = "XYCZT"; MetadataStore store = new FilterMetadata(getMetadataStore(), isMetadataFiltered()); MetadataTools.populatePixels(store, this); MetadataTools.setDefaultCreationDate(store, id, 0); } }
package loci.formats.in; import java.io.IOException; import ome.xml.model.primitives.Timestamp; import loci.common.DataTools; import loci.common.DateTools; import loci.common.RandomAccessInputStream; import loci.formats.CoreMetadata; import loci.formats.FormatException; import loci.formats.FormatReader; import loci.formats.FormatTools; import loci.formats.MetadataTools; import loci.formats.codec.BitBuffer; import loci.formats.meta.MetadataStore; public class HISReader extends FormatReader { // -- Constants -- public static final String HIS_MAGIC_STRING = "IM"; // -- Fields -- /** Offsets to pixel data for each series. */ private long[] pixelOffset; // -- Constructor -- /** Constructs a new Hamamatsu .his reader. */ public HISReader() { super("Hamamatsu HIS", "his"); domains = new String[] {FormatTools.SEM_DOMAIN}; } // -- IFormatReader API methods -- /* @see loci.formats.IFormatReader#isThisType(RandomAccessInputStream) */ public boolean isThisType(RandomAccessInputStream stream) throws IOException { final int blockLen = 2; if (!FormatTools.validStream(stream, blockLen, false)) return false; return (stream.readString(blockLen)).indexOf(HIS_MAGIC_STRING) >= 0; } /** * @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); in.seek(pixelOffset[getSeries()]); if ((getBitsPerPixel() % 8) == 0) { readPlane(in, x, y, w, h, buf); } else { int bits = getBitsPerPixel(); int bpp = FormatTools.getBytesPerPixel(getPixelType()); byte[] b = new byte[(getSizeX() * getSizeY() * getSizeC() * bits) / 8]; in.read(b); BitBuffer bb = new BitBuffer(b); bb.skipBits(y * getSizeX() * getSizeC() * bits); for (int row=0; row<h; row++) { int rowOffset = row * w * getSizeC() * bpp; bb.skipBits(x * getSizeC() * bits); for (int col=0; col<w; col++) { int colOffset = col * getSizeC() * bpp; for (int c=0; c<getSizeC(); c++) { int sample = bb.getBits(bits); DataTools.unpackBytes(sample, buf, rowOffset + colOffset + c * bpp, bpp, isLittleEndian()); } } bb.skipBits(getSizeC() * bits * (getSizeX() - w - x)); } } return buf; } // -- 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); in.order(true); in.skipBytes(14); int nSeries = in.readShort(); pixelOffset = new long[nSeries]; core = new CoreMetadata[nSeries]; String[] date = new String[nSeries]; String[] binning = new String[nSeries]; double[] offset = new double[nSeries]; double[] exposureTime = new double[nSeries]; boolean adjustedBitDepth = false; in.seek(0); for (int i=0; i<nSeries; i++) { core[i] = new CoreMetadata(); String checkString = in.readString(2); if (!checkString.equals("IM") && i > 0) { if (getBitsPerPixel() == 12) { core[i - 1].bitsPerPixel = 16; int prevSkip = (getSizeX() * getSizeY() * getSizeC() * 12) / 8; int totalBytes = FormatTools.getPlaneSize(this); in.skipBytes(totalBytes - prevSkip); adjustedBitDepth = true; } } setSeries(i); int commentBytes = in.readShort(); core[i].sizeX = in.readShort(); core[i].sizeY = in.readShort(); in.skipBytes(4); int dataType = in.readShort(); switch (dataType) { case 1: core[i].pixelType = FormatTools.UINT8; break; case 2: core[i].pixelType = FormatTools.UINT16; break; case 6: core[i].pixelType = FormatTools.UINT16; core[i].bitsPerPixel = adjustedBitDepth ? 16 : 12; break; case 11: core[i].pixelType = FormatTools.UINT8; core[i].sizeC = 3; break; case 12: core[i].pixelType = FormatTools.UINT16; core[i].sizeC = 3; break; case 14: core[i].pixelType = FormatTools.UINT16; core[i].sizeC = 3; core[i].bitsPerPixel = adjustedBitDepth ? 16 : 12; break; } in.skipBytes(50); String comment = in.readString(commentBytes); if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) { String[] data = comment.split(";"); for (String token : data) { int eq = token.indexOf("="); if (eq != -1) { String key = token.substring(0, eq); String value = token.substring(eq + 1); addSeriesMeta(key, value); if (key.equals("vDate")) { date[i] = value; } else if (key.equals("vTime")) { date[i] += " " + value; date[i] = DateTools.formatDate(date[i], "yyyy/MM/dd HH:mm:ss"); } else if (key.equals("vOffset")) { offset[i] = Double.parseDouble(value); } else if (key.equals("vBinX")) { binning[i] = value; } else if (key.equals("vBinY")) { binning[i] += "x" + value; } else if (key.equals("vExpTim1")) { exposureTime[i] = Double.parseDouble(value) * 100; } } } } pixelOffset[i] = in.getFilePointer(); core[i].littleEndian = true; if (core[i].sizeC == 0) core[i].sizeC = 1; core[i].sizeT = 1; core[i].sizeZ = 1; core[i].imageCount = 1; core[i].rgb = core[i].sizeC > 1; core[i].interleaved = isRGB(); core[i].dimensionOrder = "XYCZT"; in.skipBytes( (getSizeX() * getSizeY() * getSizeC() * getBitsPerPixel()) / 8); } MetadataStore store = makeFilterMetadata(); MetadataTools.populatePixels(store, this, true); String instrumentID = MetadataTools.createLSID("Instrument", 0); store.setInstrumentID(instrumentID, 0); if (getMetadataOptions().getMetadataLevel() != MetadataLevel.MINIMUM) { for (int i=0; i<nSeries; i++) { store.setImageInstrumentRef(instrumentID, i); if (date[i] != null) { store.setImageAcquisitionDate(new Timestamp(date[i]), i); } store.setPlaneExposureTime(exposureTime[i], i, 0); String detectorID = MetadataTools.createLSID("Detector", 0, i); store.setDetectorID(detectorID, 0, i); store.setDetectorOffset(offset[i], 0, i); store.setDetectorType(getDetectorType("Other"), 0, i); store.setDetectorSettingsID(detectorID, i, 0); store.setDetectorSettingsBinning(getBinning(binning[i]), i, 0); } } } }
package io.vertx.ext.auth; import io.vertx.core.Vertx; import io.vertx.core.json.JsonArray; import io.vertx.core.json.JsonObject; import io.vertx.ext.auth.impl.jose.JWK; import io.vertx.ext.auth.impl.jose.JWT; import org.junit.Test; import static org.junit.Assert.*; import static org.junit.Assume.*; public class JWKTest { @Test public void publicRSA() { JsonObject jwk = new JsonObject() .put("kty", "RSA") .put("n", "0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMstn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbISD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqbw0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw") .put("e", "AQAB") .put("alg", "RS256") .put("kid", "2011-04-29"); new JWK(jwk); } @Test public void publicEC() { JsonObject jwk = new JsonObject() .put("kty", "EC") .put("crv", "P-256") .put("x", "MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4") .put("y", "4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM") // .put("use", "enc") .put("kid", "1"); new JWK(jwk); } @Test public void privateEC() { JsonObject jwk = new JsonObject() .put("kty", "EC") .put("crv", "P-256") .put("x", "MKBCTNIcKUSDii11ySs3526iDZ8AiTo7Tu6KPAqv7D4") .put("y", "4Etl6SRW2YiLUrN5vfvVHuhp7x8PxltmWWlbbM4IFyM") .put("d", "870MB6gfuTJ4HtUnUvYMyJpr5eUZNP4Bk43bVdj3eAE") // .put("use", "enc") .put("kid", "1"); new JWK(jwk); } @Test public void privateRSA() { JsonObject jwk = new JsonObject() .put("kty", "RSA") .put("n", "0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMstn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbISD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqbw0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw") .put("e", "AQAB") .put("d", "X4cTteJY_gn4FYPsXB8rdXix5vwsg1FLN5E3EaG6RJoVH-HLLKD9M7dx5oo7GURknchnrRweUkC7hT5fJLM0WbFAKNLWY2vv7B6NqXSzUvxT0_YSfqijwp3RTzlBaCxWp4doFk5N2o8Gy_nHNKroADIkJ46pRUohsXywbReAdYaMwFs9tv8d_cPVY3i07a3t8MN6TNwm0dSawm9v47UiCl3Sk5ZiG7xojPLu4sbg1U2jx4IBTNBznbJSzFHK66jT8bgkuqsk0GjskDJk19Z4qwjwbsnn4j2WBii3RL-Us2lGVkY8fkFzme1z0HbIkfz0Y6mqnOYtqc0X4jfcKoAC8Q") .put("p", "83i-7IvMGXoMXCskv73TKr8637FiO7Z27zv8oj6pbWUQyLPQBQxtPVnwD20R-60eTDmD2ujnMt5PoqMrm8RfmNhVWDtjjMmCMjOpSXicFHj7XOuVIYQyqVWlWEh6dN36GVZYk93N8Bc9vY41xy8B9RzzOGVQzXvNEvn7O0nVbfs") .put("q", "3dfOR9cuYq-0S-mkFLzgItgMEfFzB2q3hWehMuG0oCuqnb3vobLyumqjVZQO1dIrdwgTnCdpYzBcOfW5r370AFXjiWft_NGEiovonizhKpo9VVS78TzFgxkIdrecRezsZ-1kYd_s1qDbxtkDEgfAITAG9LUnADun4vIcb6yelxk") .put("dp", "G4sPXkc6Ya9y8oJW9_ILj4xuppu0lzi_H7VTkS8xj5SdX3coE0oimYwxIi2emTAue0UOa5dpgFGyBJ4c8tQ2VF402XRugKDTP8akYhFo5tAA77Qe_NmtuYZc3C3m3I24G2GvR5sSDxUyAN2zq8Lfn9EUms6rY3Ob8YeiKkTiBj0") .put("dq", "s9lAH9fggBsoFR8Oac2R_E2gw282rT2kGOAhvIllETE1efrA6huUUvMfBcMpn8lqeW6vzznYY5SSQF7pMdC_agI3nG8Ibp1BUb0JUiraRNqUfLhcQb_d9GF4Dh7e74WbRsobRonujTYN1xCaP6TO61jvWrX-L18txXw494Q_cgk") .put("qi", "GyM_p6JrXySiz1toFgKbWV-JdI3jQ4ypu9rbMWx3rQJBfmt0FoYzgUIZEVFEcOqwemRN81zoDAaa-Bk0KWNGDjJHZDdDmFhW3AN7lI-puxk_mHZGJ11rxyR8O55XLSe3SPmRfKwZI6yU24ZxvQKFYItdldUKGzO6Ia6zTKhAVRU") .put("alg", "RS256") .put("kid", "2011-04-29"); new JWK(jwk); } @Test public void keycloakRSA() { JsonObject jwk = new JsonObject() .put("kty", "RSA") .put("n", "m8fbXeoEBu1eRE1Tsgq_L414mbiNPOhFNT20jKM-rd6nspp-7xoCsuYfuqUwEgAYAB_kRnTwcZj_SZXiQvauvM4-Howa6VpwPriZc3BRpzT4LBiskYBqoXslmRq7KMrNi0X-NKw4U1GIVfbYSSeoODpVj2IvC8hYUvzRF8w989DNHlduFyHweXcsOmGlHb9KZNyYy5N2zGNy5WHdtRuwGie7J5yKsJ4y0-YsJQG2GrkgDCa1ulS961KIrqLCEdLkoTsvJvnGPEXbajOQ2tIuh3iiIXY3QfMF05908Mhr0vzdApeHSdYrvv6WTyu66xj6prm_TaWcyfCqubYb53MIqQ") .put("alg", "RS256") .put("e", "AQAB") .put("use", "sig") .put("kid", "-s66_hGKPJ6ISSKeQyxslRl-cjQaqvcxoUlqIWj4CxM"); JWK key = new JWK(jwk); } @Test public void x509CertChain() { JWT jwt = new JWT(); try { // this certificate is expired // it should be ignored from the final list jwt.addJWK(new JWK(new JsonObject() .put("kty", "RSA") .put("alg", "RS256") .put("x5c", new JsonArray().add( "MIIDJjCCAg6gAwIBAgIIZtJv8PyRUgowDQYJKoZIhvcNAQEFBQAwNjE0MDIGA1UEAxMrZmVkZXJhdGVkLXNpZ25vbi5zeXN0ZW0uZ3NlcnZpY2VhY2NvdW50LmNvbTAeFw0xNzEwMDgxMTQzMzRaFw0xNzEwMTExMjEzMzRaMDYxNDAyBgNVBAMTK2ZlZGVyYXRlZC1zaWdub24uc3lzdGVtLmdzZXJ2aWNlYWNjb3VudC5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC6fNn5kfLZQ43Z+ZTqFMUF+dN2L2BphQKzgaWCsyzyJYwEySgMxbO8cQgTlgZzcC1Rt6phWHMBkFQQNykSk/K0A8xaaNqFNNVzeszR+XJ3IvCQGo8rS2K/LrNofGZrph00k6DZ7XJsWav0GotAwDd0H6IsNbFHCyRJ75ASzZr8fT8RJ9bQeTLoCsmwPXYBPeSvoWgZzOypbmLhohw0J7fBUbgVZ8fR3crhv6RDOp4/fDALWxCVPptFn0hMPeT2Dla9kbnPfVSWtciyvty5JJXnpuoqA6rLfEpMGYnMSk+SbD2R0W9O2LMRfoJ52qml+2s/aLpNKGJc2vLzDyH7CiavAgMBAAGjODA2MAwGA1UdEwEB/wQCMAAwDgYDVR0PAQH/BAQDAgeAMBYGA1UdJQEB/wQMMAoGCCsGAQUFBwMCMA0GCSqGSIb3DQEBBQUAA4IBAQAlDoCH/E43ruorgPIATCO++dOfOIb/n+NgE727UeK1acELi+dUjSdYEe+WXdY2sichgE1JqPrsMWFHCwHTUfVubmku5BTklj9k6F9jKc+XDMra1w0KGSGrxwSqwYhkhSdMOGGa9C3td+s7M/E4JV+XoQXAY3uEaB0lO4c+pckDwU/LAGrMldogT3+zE+4NRS7p8dstnww3OIHUCFfytbhcY8sH4VjqdMWGrv8R/1L0jXok8vFPEAwvXzVc3NeUClio0hOEmhTjbLgebsgToB1aNC1pnzmHTclVndTwDcnDkhImpvuWE1lX+KPkFJ54ixS4Bi2cqWud1aQ2Mqi7KHfK" )))); fail("Should fail to load this certificate because it expired in 2017"); } catch (RuntimeException e) { } try { // this certificate is expired // it should be ignored from the final list jwt.addJWK(new JWK(new JsonObject() .put("kty", "RSA") .put("alg", "RS256") .put("x5c", new JsonArray().add( "MIIDJjCCAg6gAwIBAgIIeABc0/4wb7AwDQYJKoZIhvcNAQEFBQAwNjE0MDIGA1UEAxMrZmVkZXJhdGVkLXNpZ25vbi5zeXN0ZW0uZ3NlcnZpY2VhY2NvdW50LmNvbTAeFw0xNzEwMDkxMTQzMzRaFw0xNzEwMTIxMjEzMzRaMDYxNDAyBgNVBAMTK2ZlZGVyYXRlZC1zaWdub24uc3lzdGVtLmdzZXJ2aWNlYWNjb3VudC5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC3ICz+C7FKE4jbsRh/cZK1I9M5lXGlyvk8c72BuK3/uLwnRH5eSrooA1LEqwVdKV5MOTuHHnxWFb57yyBl8Ld3CGK/aeZYIGd6iV8ym/jw6rCdJhkL6yCZ3/Xj3+Un+5Vf+ObjHd04X/GbwleFRcldJilpgwtt0PKT/JBl/lKqTzzH/HWzdp3tj5gfVJzj1NxfN4K0GSFDy/5pRYsT9NebFC/JoBgSXrEEZXaigqQsYiI+lTDL59TLq8XaaT0V1sfoHnspu3DikgO51eJBP3c0wB2CvXxk+vMlSQMsnDcsztiijGPwrpxrLwDyzsm3Rs7WI9kDHPeUeKhGX0/s9AnBAgMBAAGjODA2MAwGA1UdEwEB/wQCMAAwDgYDVR0PAQH/BAQDAgeAMBYGA1UdJQEB/wQMMAoGCCsGAQUFBwMCMA0GCSqGSIb3DQEBBQUAA4IBAQAiZt536sXwNXqUs92edWsQ+uiraJblATuMSslrQhGJjUebmlpIUMe8Dv2dj+/bYK7gZyjUQKwjmtCJ+U8Z2Ec/v9yEqKpyzfYIOTF/17d31OvisnccIbjBL2X+b/OHsFDjaY5hZrs0mczr1ePaYlE/EsyIFEZCwGbgarp7FxlRrdJEBN8jnjUgK6Kig2GLtcQcHfkIjxmVDzgS47TAtxPNTBGQypWubALTWt+WTAFpQGcW6pj9nOxuV2XB4RkFg7XrHtnBvad4/KAD/kp2if6BFyvwWcyQzKqqKcjJHinaGWf7qlBLBJTQcZcWPJEzFdwBsHHejgU8vy9hR97rvU8s" )))); fail("Should fail to load this certificate because it expired in 2017"); } catch (RuntimeException e) { } try { // this certificate is expired // it should be ignored from the final list jwt.addJWK(new JWK(new JsonObject() .put("kty", "RSA") .put("alg", "RS256") .put("x5c", new JsonArray().add( "MIIDJjCCAg6gAwIBAgIIcz32mW0b5V8wDQYJKoZIhvcNAQEFBQAwNjE0MDIGA1UEAxMrZmVkZXJhdGVkLXNpZ25vbi5zeXN0ZW0uZ3NlcnZpY2VhY2NvdW50LmNvbTAeFw0xNzEwMDcxMTQzMzRaFw0xNzEwMTAxMjEzMzRaMDYxNDAyBgNVBAMTK2ZlZGVyYXRlZC1zaWdub24uc3lzdGVtLmdzZXJ2aWNlYWNjb3VudC5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDDmL6MaLATK497Ce9H6UVx4FFiHiDH3X44UtonDCvzIKtJVzMCDJzXDLAUEKxQEMGEekpJWKWogYbZ8iqF1fb8gUn47Fi9cOYm1gXr2RZNp9mMW2cCXwR0iqPVf7LfU+b2BgP+th4sbcJmE0uMgT/L1+Tn8xs45zRn5uvj/DOKeDod8REhNsA4B8J3xGLT+1cOpiCL4LUL+CzYeF5gQhaqlnax7xSwa8iDa5484JXwbdrR+6+HqGCO62yl8n9Ufd54fBjDJjOJ6r6wNZzJXmoaWcmn1NmVn3PbjZZ1gePcLaS501NSDvqnqy9uzpy7VmJkD1ZmRov13yFZ4ni0tCDdAgMBAAGjODA2MAwGA1UdEwEB/wQCMAAwDgYDVR0PAQH/BAQDAgeAMBYGA1UdJQEB/wQMMAoGCCsGAQUFBwMCMA0GCSqGSIb3DQEBBQUAA4IBAQAfVSQFYR21K1IynPE/g0aYueSQHvbo7SaT/iCmLS4g4EXqpGFGSMgQZWe9FckFYqAkJZ8AS2BtlzflfNYBH9K6V++sm5xxhsH+DmS/dXUQrSWuwKc5sS385D5kg2vJlqO1snCYOg1iEMkvU36mEO3o0kAi+2g1NWOWiCFLLqoC4onmwDKv/K5qpwb2n3+IUbaS8R/cgGsq6B7ohCSrdHfErOOitNsynLO733lcFJKYxrYu4/OpvGkKBaxGf8h1BsDmNfenfYq4ak0N+8nTxPfc0fARyCkHSJPQ5WWMfi14d7J6hjc8qZHIDsAiJ50LB36Nk9p+KEQT5yh3UFbPXJO6" )))); fail("Should fail to load this certificate because it expired in 2017"); } catch (RuntimeException e) { } try { jwt.decode("eyJhbGciOiJSUzI1NiIsImtpZCI6Ijc0MjQzMGI2ZDRkZjQxMzVlM2JkOTgyYWM2YmVjNDNhMTE4ODhkMWIifQ.eyJhenAiOiI1ODUyMDUyMjk1NzctZGlxZ2l1NWkwbjNoN2hzZmF0cG91MzY0OXVvaGduOWkuYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJhdWQiOiI1ODUyMDUyMjk1NzctZGlxZ2l1NWkwbjNoN2hzZmF0cG91MzY0OXVvaGduOWkuYXBwcy5nb29nbGV1c2VyY29udGVudC5jb20iLCJzdWIiOiIxMDI1ODI3NDEyNjA5NDc1ODQxNDQiLCJhdF9oYXNoIjoicGJWZE1Nb3l6UDl5UU9sMk54bkJDUSIsImlzcyI6ImFjY291bnRzLmdvb2dsZS5jb20iLCJpYXQiOjE1MDc1NzgyMDMsImV4cCI6MTUwNzU4MTgwM30.cU21Gu1jEcAONlQ0vf0ju8W7gsdyzPo-U3U6JCFaVqYqF5J2JmhCSk_-kJcY19WKyg8iwibOSNuuQE8PP0eCiIWDY-fq_3wOoO4IBUa5zlmTMNdz9Af4vH2h-optaG89tXE89J_-D2TjkKDdu1nPVLefX6E95vjb3P9LP5LfFJV53zT_deacFn4XiyCVMBl7sfNE0A6YG3PmZkVNgyIYJCv21bB5N_YtWTSEV_8YSFaJwDcEihqBGiFe3fO3k9-A237HuKevBRfo_xAyIQXnCHiLg8eETGTK3sfRh_ugxMI0jvgt4hBZQTioGjnaMRmQxaiJ_3IOrpSJeMu_JIg8-g"); fail("Should not decode because the certificates are expired"); } catch (RuntimeException e) { } } @Test public void symmetricHMAC() { JsonObject jwk = new JsonObject() .put("kty", "oct") .put("k", "AyM1SysPpbyDfgZld3umj1qzKObwVMkoqQ-EstJQLr_T-1qS0gZH75aKtMN3Yj0iPS4hcgUuTwjAzZr1Z9CAow"); new JWK(jwk); } @Test public void publicECK() { JsonObject jwk = new JsonObject() .put("kty", "EC") .put("crv", "secp256k1") .put("x", "ELZhvOXbbuPdoPq0H1dTq1rvR4v6ddu00sewn6fw-ow") .put("y", "nY56UtXSG-G2wbCzByDlVezHiPj_D8j-7xq1qFhZ_Bs") // .put("use", "enc") .put("kid", "1"); new JWK(jwk); } @Test public void loadAzure() { Vertx vertx = Vertx.vertx(); JsonObject azure = new JsonObject(vertx.fileSystem() .readFileBlocking("azure.json")); JWK key = new JWK(azure.getJsonArray("keys").getJsonObject(1)); JWT jwt = new JWT() .addJWK(key) .nonceAlgorithm("SHA-256"); System.out.println( jwt.decode("eyJ0eXAiOiJKV1QiLCJub25jZSI6InM5TzdaZ2F6WVJEd2VCZzZhbDNWVkhuZFFOQ0JHSVZZaDMxTDZRVFljTDAiLCJhbGciOiJSUzI1NiIsIng1dCI6Im5PbzNaRHJPRFhFSzFqS1doWHNsSFJfS1hFZyIsImtpZCI6Im5PbzNaRHJPRFhFSzFqS1doWHNsSFJfS1hFZyJ9.eyJhdWQiOiIwMDAwMDAwMy0wMDAwLTAwMDAtYzAwMC0wMDAwMDAwMDAwMDAiLCJpc3MiOiJodHRwczovL3N0cy53aW5kb3dzLm5ldC9mY2FhZjcxMC03YzllLTRjYTAtOWNkYS02OTczOWZhZmJhNGIvIiwiaWF0IjoxNjExNjg3NDE1LCJuYmYiOjE2MTE2ODc0MTUsImV4cCI6MTYxMTY5MTMxNSwiYWNjdCI6MCwiYWNyIjoiMSIsImFjcnMiOlsidXJuOnVzZXI6cmVnaXN0ZXJzZWN1cml0eWluZm8iLCJ1cm46bWljcm9zb2Z0OnJlcTEiLCJ1cm46bWljcm9zb2Z0OnJlcTIiLCJ1cm46bWljcm9zb2Z0OnJlcTMiLCJjMSIsImMyIiwiYzMiLCJjNCIsImM1IiwiYzYiLCJjNyIsImM4IiwiYzkiLCJjMTAiLCJjMTEiLCJjMTIiLCJjMTMiLCJjMTQiLCJjMTUiLCJjMTYiLCJjMTciLCJjMTgiLCJjMTkiLCJjMjAiLCJjMjEiLCJjMjIiLCJjMjMiLCJjMjQiLCJjMjUiXSwiYWlvIjoiQVVRQXUvOFNBQUFBMFYwa0M4S25EM01RbUJ0WGk4OG9lT3NzT2xzU0JLZ1Rld1diQ1RnV2x0MEZ4dG9POVZtVjVjOGRLTStNckE1MXJoZW1Ebm9HMGJGUkRJWkpnM3Izb0E9PSIsImFtciI6WyJwd2QiLCJtZmEiXSwiYXBwX2Rpc3BsYXluYW1lIjoicG9iLXNlcnZlciIsImFwcGlkIjoiMTNjOWUxMTItYjE1OC00YjE5LThkNTctZTFmMzg4MWM0MzgzIiwiYXBwaWRhY3IiOiIxIiwiZmFtaWx5X25hbWUiOiJMb3BlcyIsImdpdmVuX25hbWUiOiJQYXVsbyIsImlkdHlwIjoidXNlciIsImlwYWRkciI6IjIxNy4xMDIuMTY1LjQ2IiwibmFtZSI6IkxhYiBQYXVsbyBMb3BlcyIsIm9pZCI6IjUyYmY4YWMyLTNlODMtNGNmNC04MTYxLTBiMTM1YWUwNjk4YiIsInBsYXRmIjoiMTQiLCJwdWlkIjoiMTAwMzIwMDEwRjQzQjcyRSIsInJoIjoiMC5BQUFBRVBlcV9KNThvRXljMm1sem42LTZTeExoeVJOWXNSbExqVmZoODRnY1E0TjVBRHMuIiwic2NwIjoiZW1haWwgb3BlbmlkIHByb2ZpbGUgVXNlci5SZWFkIiwic2lnbmluX3N0YXRlIjpbImttc2kiXSwic3ViIjoiWXltcTZLUmlLMHVUX1NVZ0JzYWUtaElIRE5VX0FLQVpvRG5TTWwxR3VpZyIsInRlbmFudF9yZWdpb25fc2NvcGUiOiJFVSIsInRpZCI6ImZjYWFmNzEwLTdjOWUtNGNhMC05Y2RhLTY5NzM5ZmFmYmE0YiIsInVuaXF1ZV9uYW1lIjoicGF1bG9AbGFiLnRlbnRpeG8uY29tIiwidXBuIjoicGF1bG9AbGFiLnRlbnRpeG8uY29tIiwidXRpIjoiZGNzM1ZzMXk5VW1SOXBzV05JaUxBQSIsInZlciI6IjEuMCIsIndpZHMiOlsiNjJlOTAzOTQtNjlmNS00MjM3LTkxOTAtMDEyMTc3MTQ1ZTEwIiwiYjc5ZmJmNGQtM2VmOS00Njg5LTgxNDMtNzZiMTk0ZTg1NTA5Il0sInhtc19zdCI6eyJzdWIiOiJiNGRXNmVuWk9fRGhFLUMyZE1Qdks5Y1JXcW8zXy1FQVc5MVJ4WmRKNnNVIn0sInhtc190Y2R0IjoxNjEwOTEyOTM2fQ.M4dXPZszAsL_rnceagjZnmd8yzbbB3hou4L6vVLGzqAt4wVg8KwQKxcxIGqBqgDWRlBvLYqWs61dvt8vSa-9GaMJifHwmfWoXPvyVzdxhx3qrqgHdsz1HWX5WzcDlEbHrPXZGE8KM-0czE67rePMxEHK7vLf5TbmERLGJt4QDOGZxVHYvnplIrIM1eGjANIeWYTyW5g-YDx3VX6yVl5QHvP4CFdINhDV7i-L3bjmV4M8F6wYs7Xs7nIrKYEiyjTrpXGUL7u29eHXgzeGlSxfXeqTdYmgEt6lFOxx-fZzO0m92AhPGGAe6IB85FtqSi5T95Nif3pHPsouryhDco8y3g") ); } private static int getVersion() { String version = System.getProperty("java.version"); if(version.startsWith("1.")) { version = version.substring(2, 3); } else { int dot = version.indexOf("."); if(dot != -1) { version = version.substring(0, dot); } } return Integer.parseInt(version); } @Test public void testOKP() { assumeTrue("JVM doesn't support EdDSA", getVersion() >= 15); JsonObject jwk = new JsonObject() .put("kty", "OKP") .put("alg", "EdDSA") .put("crv", "Ed25519") .put("x", "UUFFMkomijuOugmzEIiRfEpV-iV78ELK9XNGorZMIl0") .put("d", "Qmdi9hWKKno_Ml4pfvSzyEUYrRwvGom-J0EwKcACWPU") .put("use", "sig") .put("kid", "1"); JWT jwt = new JWT().addJWK(new JWK(jwk)); String token = jwt.sign(new JsonObject().put("hello", "world"), new JWTOptions().setAlgorithm("EdDSA")); JsonObject decoded = jwt.decode(token); assertEquals("world", decoded.getString("hello")); } @Test public void testOKPInterop() { assumeTrue("JVM doesn't support EdDSA", getVersion() >= 15); // this key and token were generated from // com.nimbusds.jose.* JsonObject jwk = new JsonObject() .put("kty", "OKP") .put("alg", "EdDSA") .put("crv", "Ed25519") .put("x", "CIvYtKVA8ul314zLdxRJwwmWEyAj1j0rm6-7Ii6a74E") .put("use", "sig") .put("kid", "123"); JWT jwt = new JWT().addJWK(new JWK(jwk)); String token = "eyJraWQiOiIxMjMiLCJ0eXAiOiJKV1QiLCJhbGciOiJFZERTQSJ9.eyJhdWQiOiJ5b3UiLCJzdWIiOiJib2IiLCJpc3MiOiJtZSIsImV4cCI6MTYxNzk3Mjk1M30.diKQd6G1dA72XxHNqN9UaYWTgqcZxRaZh9sxN3eFfc7Tlkqk1APU9Qkj8X96gABZxnYx0Djf7nK6YJf6VpcBBA"; JsonObject decoded = jwt.decode(token); assertEquals("you", decoded.getString("aud")); assertEquals("bob", decoded.getString("sub")); assertEquals("me", decoded.getString("iss")); assertNotNull(decoded.getInteger("exp")); } }
package rhomobile.mapview; import java.util.Enumeration; import java.util.Hashtable; import java.util.Vector; import com.rho.RhoEmptyLogger; import com.rho.RhoLogger; import com.rho.rubyext.WebView; import net.rim.device.api.system.Application; import net.rim.device.api.system.Bitmap; import net.rim.device.api.system.Display; import net.rim.device.api.system.KeypadListener; import net.rim.device.api.ui.Color; import net.rim.device.api.ui.Graphics; import net.rim.device.api.ui.MenuItem; import net.rim.device.api.ui.TouchEvent; import net.rim.device.api.ui.UiApplication; import net.rim.device.api.ui.container.MainScreen; public class MapViewScreen extends MainScreen { private static final RhoLogger LOG = RhoLogger.RHO_STRIP_LOG ? new RhoEmptyLogger() : new RhoLogger("MapViewScreen"); private static final int PAN_MODE = 1; private static final int ZOOM_MODE = 2; private static final int MIN_MOVE_STEP = 1; private static final int MAX_MOVE_STEP = 8; private static final int MOVE_TIMEOUT_DOUBLING = 300; // Sensivity of annotations area (in pixels) private static final int ANNOTATION_SENSIVITY_AREA_RADIUS = 16; private static final MapProvider[] providers = { new GoogleMapProvider(), new ESRIMapProvider() }; private MapViewParent parent; private MapProvider mapProvider; private RhoMapField mapField; private GeoCoding mapGeoCoding; private Vector annotations = new Vector(); private Annotation mSelectedAnnotation; private int mode; private long prevMoveTime = 0; private int prevDx = 0; private int prevDy = 0; private Bitmap mapPinImage; private boolean mTouchDown = false; private int mTouchX; private int mTouchY; private class PanModeMenuItem extends MenuItem { private MapViewScreen screen; public PanModeMenuItem(MapViewScreen scr, int ordinal, int priority) { super("Pan mode", ordinal, priority); screen = scr; } public void run() { screen.setMode(MapViewScreen.PAN_MODE); } }; private class ZoomModeMenuItem extends MenuItem { private MapViewScreen screen; public ZoomModeMenuItem(MapViewScreen scr, int ordinal, int priority) { super("Zoom mode", ordinal, priority); screen = scr; } public void run() { screen.setMode(MapViewScreen.ZOOM_MODE); } }; MapViewScreen(MapViewParent p, String providerName, Hashtable settings, Vector annotations) { super(DEFAULT_MENU | DEFAULT_CLOSE); addMenuItem(new PanModeMenuItem(this, 0, 100)); addMenuItem(new ZoomModeMenuItem(this, 1, 100)); mapPinImage = Bitmap.getBitmapResource("mappin.png"); mapParent = p; createMapProvider(providerName); mapGeoCoding = new GoogleGeoCoding(); createUI(settings); this.annotations = annotations; handleAnnotations(); } public void close() { mapField.close(); mapGeoCoding.stop(); mapParent.onChildClosed(); super.close(); parent.childClosed(); } private void setMode(int m) { mode = m; mapField.redraw(); } private void createMapProvider(String providerName) { mapProvider = null; for (int i = 0; i != providers.length; ++i) { if (providers[i].accept(providerName)) { mapProvider = providers[i]; break; } } if (mapProvider == null) throw new IllegalArgumentException("Unknown map provider: " + providerName); } private void createUI(Hashtable settings) { synchronized (Application.getEventLock()) { mapField = mapProvider.createMap(); mapField.setPreferredSize(Display.getWidth(), Display.getHeight()); add(mapField.getBBField()); } // Set map type String map_type = (String)settings.get("map_type"); if (map_type == null) map_type = "roadmap"; mapField.setMapType(map_type); Hashtable region = (Hashtable)settings.get("region"); if (region != null) { // Set coordinates Double lat = (Double)region.get("latitude"); Double lon = (Double)region.get("longitude"); if (lat != null && lon != null) mapField.moveTo(lat.doubleValue(), lon.doubleValue()); // Set zoom Double latDelta = (Double)region.get("latDelta"); Double lonDelta = (Double)region.get("lonDelta"); if (latDelta != null && lonDelta != null) { int zoom = mapField.calculateZoom(latDelta.doubleValue(), lonDelta.doubleValue()); mapField.setZoom(zoom); } } Double radius = (Double)settings.get("radius"); if (radius != null) { int zoom = mapField.calculateZoom(radius.doubleValue(), radius.doubleValue()); mapField.setZoom(zoom); } String center = (String)settings.get("center"); if (center != null) { mapGeoCoding.resolve(center, new GeoCoding.OnGeocodingDone() { public void onSuccess(double latitude, double longitude) { mapField.moveTo(latitude, longitude); } public void onError(String description) {} }); } mode = PAN_MODE; mapField.redraw(); } private void handleAnnotations() { Enumeration e = annotations.elements(); while (e.hasMoreElements()) { final Annotation ann = (Annotation)e.nextElement(); if (ann == null) continue; if (ann.street_address == null && ann.coordinates == null) continue; if (ann.street_address != null && ann.street_address.length() > 0) mapGeoCoding.resolve(ann.street_address, new GeoCoding.OnGeocodingDone() { public void onSuccess(double latitude, double longitude) { ann.coordinates = new Annotation.Coordinates(latitude, longitude); UiApplication.getUiApplication().invokeLater(new Runnable() { public void run() { invalidate(); } }); } public void onError(String description) { ann.street_address = null; } }); } } /** * Handle trackball click events. * @see net.rim.device.api.ui.Screen#invokeAction(int) */ protected boolean invokeAction(int action) { boolean handled = super.invokeAction(action); if(!handled) { switch(action) { case ACTION_INVOKE: // Trackball click. { return true; } } } return handled; } protected void paint(Graphics graphics) { super.paint(graphics); // Draw annotations int pinWidth = mapPinImage.getWidth(); int pinHeight = mapPinImage.getHeight(); Enumeration e = annotations.elements(); while (e.hasMoreElements()) { Annotation ann = (Annotation)e.nextElement(); if (ann == null || ann.coordinates == null) continue; long x = mapField.toScreenCoordinateX(ann.coordinates.longitude); if (x + pinWidth/2 < 0 || x - pinWidth/2 > mapField.getWidth()) continue; long y = mapField.toScreenCoordinateY(ann.coordinates.latitude); if (y + pinHeight/2 < 0 || y - pinHeight/2 > mapField.getHeight()) continue; graphics.drawBitmap((int)(x - pinWidth/2), (int)(y - pinHeight/2), pinWidth, pinHeight, mapPinImage, 0, 0); } if (mSelectedAnnotation != null) drawTitle(graphics, mSelectedAnnotation); graphics.setColor(Color.BLACK); // Draw current mode String strMode = null; if (mode == PAN_MODE) strMode = "Pan mode"; else if (mode == ZOOM_MODE) strMode = "Zoom mode"; if (strMode != null) { // Detect drawn text size int tw = graphics.getFont().getAdvance(strMode); int th = graphics.getFont().getHeight(); // Actual drawing int x = mapField.getLeft() + mapField.getWidth()/2 - tw/2; int y = mapField.getTop() + mapField.getHeight() - th - 10; tw = graphics.drawText(strMode, x, y); } } private void fillRectWithRoundedCorners(Graphics graphics, int left, int top, int width, int height, int roundRadius) { final int r = roundRadius; final int d = r*2; final int right = left + width; final int bottom = top + height; graphics.fillArc(left - r, top - r, d, d, 90, 90); graphics.fillArc(left - r, bottom - r, d, d, 180, 90); graphics.fillArc(right - r, bottom - r, d, d, 270, 90); graphics.fillArc(right - r, top - r, d, d, 0, 90); graphics.fillRect(left - r, top, r, bottom - top); graphics.fillRect(right, top, r, bottom - top); graphics.fillRect(left, top - r, right - left, r); graphics.fillRect(left, bottom, right - left, r); graphics.fillRect(left, top, right - left, bottom - top); } private void drawRectWithRoundedCorners(Graphics graphics, int left, int top, int width, int height, int roundRadius) { final int r = roundRadius; final int d = r*2; final int right = left + width; final int bottom = top + height; graphics.drawArc(left - r, top - r, d, d, 90, 90); graphics.drawArc(left - r, bottom - r, d, d, 180, 90); graphics.drawArc(right - r, bottom - r, d, d, 270, 90); graphics.drawArc(right - r, top - r, d, d, 0, 90); graphics.drawLine(left - r, top, left - r, bottom); graphics.drawLine(right + r, top, right + r, bottom); graphics.drawLine(left, top - r, right, top - r); graphics.drawLine(left, bottom + r, right, bottom + r); } private void drawTitle(Graphics graphics, Annotation ann) { String textToDraw = ann.title; int width = graphics.getFont().getAdvance(textToDraw); int height = graphics.getFont().getHeight(); int annX = (int)mapField.toScreenCoordinateX(ann.coordinates.longitude); int annY = (int)mapField.toScreenCoordinateY(ann.coordinates.latitude); int left = annX - width/2; int top = annY - height/2 - mapPinImage.getHeight()/2; final int roundRadius = 6; // Shadow graphics.setColor(Color.GRAY); fillRectWithRoundedCorners(graphics, left + 4, top + 4, width, height, roundRadius); // Actual shape graphics.setColor(Color.WHITE); fillRectWithRoundedCorners(graphics, left, top, width, height, roundRadius); graphics.setColor(Color.BLACK); drawRectWithRoundedCorners(graphics, left, top, width, height, roundRadius); graphics.setColor(Color.BLACK); graphics.drawText(textToDraw, left, top); } private int calcDxSmooth(int dx, long curTime) { int newDx; if (curTime > prevMoveTime + MOVE_TIMEOUT_DOUBLING) { newDx = dx; } else { if (dx == 0) newDx = 0; else { newDx = dx < 0 ? (prevDx < 0 ? prevDx*2 : -MIN_MOVE_STEP) : (prevDx > 0 ? prevDx*2 : MIN_MOVE_STEP); if (newDx < -MAX_MOVE_STEP) newDx = -MAX_MOVE_STEP; else if (newDx > MAX_MOVE_STEP) newDx = MAX_MOVE_STEP; } } prevDx = newDx; return newDx; } private int calcDySmooth(int dy, long curTime) { int newDy; if (curTime > prevMoveTime + MOVE_TIMEOUT_DOUBLING) { newDy = dy; } else { if (dy == 0) newDy = 0; else { newDy = dy < 0 ? (prevDy < 0 ? prevDy*2 : -MIN_MOVE_STEP) : (prevDy > 0 ? prevDy*2 : MIN_MOVE_STEP); if (newDy < -MAX_MOVE_STEP) newDy = -MAX_MOVE_STEP; else if (newDy > MAX_MOVE_STEP) newDy = MAX_MOVE_STEP; } } prevDy = newDy; return newDy; } private int calcDx(int dx, long curTime) { //return dx*2; return calcDxSmooth(dx, curTime); } private int calcDy(int dy, long curTime) { //return dy*2; return calcDySmooth(dy, curTime); } private void handleMove(int dx, int dy) { if (mode == PAN_MODE) { //LOG.TRACE("Scroll by " + dx + "," + dy); mapField.move(dx, dy); mapField.redraw(); } else if (mode == ZOOM_MODE && dy != 0) { int currentZoom = mapField.getZoom(); int minZoom = mapField.getMinZoom(); int maxZoom = mapField.getMaxZoom(); int newZoom; if (dy > 0) { newZoom = Math.max(currentZoom - 1, minZoom); } else { newZoom = Math.min(currentZoom + 1, maxZoom); } //LOG.TRACE("Set zoom to " + newZoom + " (was " + currentZoom + ")"); mapField.setZoom(newZoom); mapField.redraw(); } } private void handleClick(int x, int y) { Annotation a = getCurrentAnnotation(x, y); Annotation selectedAnnotation = mSelectedAnnotation; mSelectedAnnotation = a; if (a != null && selectedAnnotation != null && selectedAnnotation.equals(a)) { // We have clicked already selected annotation WebView.navigate(a.url); mapParent.close(); mSelectedAnnotation = null; } invalidate(); } protected boolean navigationMovement(int dx, int dy, int status, int time) { if ((status & KeypadListener.STATUS_TRACKWHEEL) == 0 && (status & KeypadListener.STATUS_FOUR_WAY) == 0) return false; if (mode == PAN_MODE) { long curTime = System.currentTimeMillis(); dx = calcDx(dx, curTime); dy = calcDy(dy, curTime); prevMoveTime = curTime; } handleMove(dx, dy); return true; } protected boolean trackwheelClick(int status, int time) { int x = getWidth()/2; int y = getHeight()/2; handleClick(x, y); return true; } protected boolean touchEvent(TouchEvent message) { switch (message.getEvent()) { case TouchEvent.CLICK: handleClick(message.getX(1), message.getY(1)); return true; case TouchEvent.DOWN: mTouchDown = true; mTouchX = message.getX(1); mTouchY = message.getY(1); break; case TouchEvent.UP: mTouchDown = false; break; case TouchEvent.MOVE: if (mTouchDown) { int x = message.getX(1); int y = message.getY(1); int dx = x - mTouchX; int dy = y - mTouchY; if (mode == PAN_MODE) { dx = -dx; dy = -dy; } handleMove(dx, dy); mTouchX = x; mTouchY = y; return true; } } return super.touchEvent(message); } public double getCenterLatitude() { return mapField.getCenterLatitude(); } public double getCenterLongitude() { return mapField.getCenterLongitude(); } private Annotation getCurrentAnnotation(int x, int y) { // return current annotation (point we are under now) Enumeration e = annotations.elements(); while (e.hasMoreElements()) { Annotation a = (Annotation)e.nextElement(); Annotation.Coordinates coords = a.coordinates; if (coords == null) continue; long annX = mapField.toScreenCoordinateX(coords.longitude); long annY = mapField.toScreenCoordinateY(coords.latitude); annY -= mapPinImage.getHeight()/2; long deltaX = (long)x - annX; long deltaY = (long)y - annY; double distance = MapTools.math_sqrt(deltaX*deltaX + deltaY*deltaY); if ((int)distance > ANNOTATION_SENSIVITY_AREA_RADIUS) continue; return a; } return null; } }
package org.callimachusproject.api; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.Authenticator; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.PasswordAuthentication; import java.net.ProtocolException; import java.net.URL; import java.util.LinkedHashMap; import java.util.Map; import junit.framework.TestCase; import junit.framework.TestSuite; public class BLOBCreateTest extends TestCase { private static Map<String, String[]> parameters = new LinkedHashMap<String, String[]>() { private static final long serialVersionUID = -4308917786147773821L; { put("article", new String[] { "article.docbook", "application/docbook+xml", "<section id=\"ls\"> \n <title>LS command</title> \n " + "<para>This command is a synonym for <link linkend=\"dir\"> <command>DIR</command></link> command. \n" + "</para> \n </section>" }); put("font", new String[] { "font.woff", "application/font-woff", "@font-face { \n font-family: GentiumTest; \n" + "src: url(fonts/GenR102.woff) format(\"woff\")," + "url(fonts/GenR102.ttf) format(\"truetype\"); }" }); put("namedGraph", new String[] { "named.xml", "application/rdf+xml", "<rdf:RDF \n" + "xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns "xmlns:dcterms=\"http://purl.org/dc/terms/\"> \n" + "<rdf:Description rdf:about=\"urn:x-states:New%20York\"> \n" + "<dcterms:alternative>NY</dcterms:alternative> \n" + "</rdf:Description> \n" + "</rdf:RDF>" }); put("namedQuery", new String[] { "query.sparql", "application/sparql-query", "SELECT ?title WHERE { \n" + "<http: "}" }); put("page", new String[] { "page.xhtml", "application/xhtml+xml", "<?xml version=\"1.0\" encoding=\"iso-8859-1\"?> <!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \n " + "\"http: "<html xmlns=\"http: "<head> <title> Wikipedia </title> </head> \n" + "<body> <p> Wikipedia is a great website. </p> </body> </html>" }); put("animatedGraphic", new String[] { "graphic.gif", "image/gif", "binary" }); put("photo", new String[] { "photo.jpeg", "image/jpeg", "binary" }); put("networkGraphic", new String[] { "network.png", "image/png", "binary" }); put("vectorGraphic", new String[] { "vector.svg", "image/svg+xml", "<svg xmlns=\"http: "<circle cx=\"100\" cy=\"50\" r=\"40\" stroke=\"black\"" + "stroke-width=\"2\" fill=\"red\" /> </svg> \n " }); put("iconGraphic", new String[] { "logo.image", "image/vnd.microsoft.icon", "binary" }); put("style", new String[] { "style.css", "text/css", "hr {color:sienna;} \n" + "p {margin-left:20px;} \n" + "body {background-color:blue}" }); put("hypertext", new String[] { "file.html", "text/html", "<html><head><title>Output Page</title></head><body></body></html>", }); put("script", new String[] { "script.js", "text/javascript", "if (response == true) { \n" + "return true; \n" + "}" }); put("text", new String[] { "file.txt", "text/plain", "Body of a text document" }); put("graphDocument", new String[] { "file.txt", "text/turtle", "@prefix foaf: <http://xmlns.com/foaf/0.1/> . \n" + "<http://example.org/joe#me> a foaf:Person . \n" + "<http://example.org/joe "<http://example.org/joe#me> foaf:mbox <mailto:joe@example.org> . \n" + "<http://example.org/joe#me> foaf:name \"Joe Lambda\" ." }); put("transform", new String[] { "transform.xsl", "text/xsl", "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?> \n" + "<xsl:template match=\"/\"> <html> <body> <h2>My CD Collection</h2> \n" + "<table border=\"1\"> <tr bgcolor=\"#9acd32\"> <th>Title</th> \n" + "<th>Artist</th> </tr> </table> </body> </html> </xsl:template> \n" + "</xsl:stylesheet>" }); } }; public static TestSuite suite() throws Exception{ TestSuite suite = new TestSuite(BLOBCreateTest.class.getName()); for (String name : parameters.keySet()) { suite.addTest(new BLOBCreateTest(name)); } return suite; } private static TemporaryServer temporaryServer = TemporaryServer.newInstance();; private String requestSlug; private String requestContentType; private String outputString; public BLOBCreateTest(String name) throws Exception { super(name); String [] args = parameters.get(name); requestSlug = args[0]; requestContentType = args[1]; outputString = args[2]; } public void setUp() throws Exception { super.setUp(); temporaryServer.resume(); Authenticator.setDefault(new Authenticator() { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(temporaryServer.getUsername(), temporaryServer.getPassword()); } }); } public void tearDown() throws Exception { super.tearDown(); temporaryServer.pause(); } private String getCollection() throws Exception { String contents = getRelContents(); URL contentsURL = new java.net.URL(contents); HttpURLConnection contentsConnection = (HttpURLConnection) contentsURL.openConnection(); contentsConnection.setRequestMethod("GET"); contentsConnection.setRequestProperty("ACCEPT", "application/atom+xml"); assertEquals(contentsConnection.getResponseMessage(), 200, contentsConnection.getResponseCode()); InputStream stream = contentsConnection.getInputStream(); String text = new java.util.Scanner(stream).useDelimiter("\\A").next(); int app = text.indexOf("<app:collection"); int start = text.indexOf("\"", app); int stop = text.indexOf("\"", start + 1); String result = text.substring(start + 1, stop); return result; } private String getRelContents() throws MalformedURLException, IOException, ProtocolException { URL url = new java.net.URL(temporaryServer.getOrigin() + "/"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("OPTIONS"); assertEquals(connection.getResponseMessage(), 204, connection.getResponseCode()); String header = connection.getHeaderField("LINK"); int rel = header.indexOf("rel=\"contents\""); int end = header.lastIndexOf(">", rel); int start = header.lastIndexOf("<", rel); String contents = header.substring(start + 1, end); return contents; } public void runTest() throws MalformedURLException, Exception { URL url = new java.net.URL(getCollection()); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("POST"); connection.setRequestProperty("Slug", requestSlug); connection.setRequestProperty("Content-Type", requestContentType); connection.setDoOutput(true); OutputStream output = connection.getOutputStream(); output.write(outputString.getBytes()); output.close(); assertEquals(connection.getResponseMessage(), 201, connection.getResponseCode()); } }
/* * $Id: TestOpenUrlResolver.java,v 1.14 2011-11-01 11:44:43 pgust Exp $ */ package org.lockss.daemon; import java.io.*; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.*; import javax.sql.DataSource; import org.lockss.config.*; import org.lockss.extractor.ArticleMetadata; import org.lockss.extractor.ArticleMetadataExtractor; import org.lockss.extractor.MetadataField; import org.lockss.extractor.MetadataTarget; import org.lockss.plugin.ArchivalUnit; import org.lockss.plugin.ArticleFiles; import org.lockss.plugin.ArticleIteratorFactory; import org.lockss.plugin.PluginManager; import org.lockss.plugin.PluginTestUtil; import org.lockss.plugin.SubTreeArticleIterator; import org.lockss.plugin.simulated.*; import org.lockss.repository.*; import org.lockss.util.*; import org.lockss.test.*; //import TestBePressMetadataExtractor.MySimulatedPlugin; /** * Test class for org.lockss.daemon.MetadataManager * * @author Philip Gust * @version 1.0 */ public class TestOpenUrlResolver extends LockssTestCase { static Logger log = Logger.getLogger("TestOpenUrlResolver"); private SimulatedArchivalUnit sau0, sau1, sau2, sau3; private MockLockssDaemon theDaemon; private MetadataManager metadataManager; private PluginManager pluginManager; private OpenUrlResolver openUrlResolver; private boolean disableMetadataManager = false; /** set of AUs reindexed by the MetadataManager */ Set<String> ausReindexed = new HashSet<String>(); public void setUp() throws Exception { super.setUp(); final String tempDirPath = getTempDir().getAbsolutePath(); // set derby database log System.setProperty("derby.stream.error.file", new File(tempDirPath,"derby.log").getAbsolutePath()); theDaemon = getMockLockssDaemon(); theDaemon.getAlertManager(); pluginManager = theDaemon.getPluginManager(); pluginManager.setLoadablePluginsReady(true); theDaemon.setDaemonInited(true); pluginManager.startService(); theDaemon.getCrawlManager(); String paramIndexingEnabled = Boolean.toString(!disableMetadataManager && true); Properties props = new Properties(); props.setProperty(MetadataManager.PARAM_INDEXING_ENABLED, paramIndexingEnabled); props.setProperty(LockssRepositoryImpl.PARAM_CACHE_LOCATION, tempDirPath); ConfigurationUtil.setCurrentConfigFromProps(props); Configuration config = ConfigurationUtil.fromProps(props); Tdb tdb = new Tdb(); // create Tdb for testing purposes Properties tdbProps = new Properties(); tdbProps = new Properties(); tdbProps.setProperty("title", "Title[10.0135/12345678]"); tdbProps.setProperty("isbn", "976-1-58562-317-7"); tdbProps.setProperty("journalTitle", "Journal[10.0135/12345678]"); tdbProps.setProperty("attributes.publisher", "Publisher[10.0135/12345678]"); tdbProps.setProperty("plugin", "org.lockss.daemon.TestOpenUrlResolver$MySimulatedPlugin3"); tdbProps.setProperty("param.1.key", "base_url"); tdbProps.setProperty("param.1.value", "http: tdb.addTdbAuFromProperties(tdbProps); tdbProps = new Properties(); tdbProps.setProperty("title", "Title[Manual of Clinical Psychopharmacology]"); tdbProps.setProperty("isbn", "978-1-58562-317-4"); tdbProps.setProperty("journalTitle", "Manual of Clinical Psychopharmacology"); tdbProps.setProperty("attributes.publisher", "Publisher[Manual of Clinical Psychopharmacology]"); tdbProps.setProperty("plugin", "org.lockss.daemon.TestOpenUrlResolver$MySimulatedPlugin2"); tdbProps.setProperty("param.1.key", "base_url"); tdbProps.setProperty("param.1.value", "http: tdbProps.setProperty("attributes.year", "1993"); tdb.addTdbAuFromProperties(tdbProps); tdbProps = new Properties(); tdbProps.setProperty("title", "Title[10.2468/24681357]"); tdbProps.setProperty("issn", "1144-875X"); tdbProps.setProperty("eissn", "7744-6521"); tdbProps.setProperty("attributes.volume", "42"); tdbProps.setProperty("attributes."+OpenUrlResolver.AU_FEATURE_KEY, "key1"); tdbProps.setProperty("journalTitle", "Journal[10.2468/24681357]"); tdbProps.setProperty("attributes.publisher", "Publisher[10.2468/24681357]"); tdbProps.setProperty("plugin", "org.lockss.daemon.TestOpenUrlResolver$MySimulatedPlugin1"); tdbProps.setProperty("param.1.key", "base_url"); tdbProps.setProperty("param.1.value", "http: tdb.addTdbAuFromProperties(tdbProps); tdbProps = new Properties(); tdbProps.setProperty("title", "Title[10.1234/12345678]"); tdbProps.setProperty("issn", "0740-2783"); tdbProps.setProperty("attributes.volume", "XI"); tdbProps.setProperty("journalTitle", "Journal[10.1234/12345678]"); tdbProps.setProperty("attributes.publisher", "Publisher[10.1234/12345678]"); tdbProps.setProperty("plugin", "org.lockss.daemon.TestOpenUrlResolver$MySimulatedPlugin0"); tdbProps.setProperty("param.1.key", "base_url"); tdbProps.setProperty("param.1.value", "http: tdb.addTdbAuFromProperties(tdbProps); config.setTdb(tdb); ConfigurationUtil.installConfig(config); config = simAuConfig(tempDirPath + "/0"); config.put("volume", "XI"); config.put("base_url", "http: sau0 = PluginTestUtil.createAndStartSimAu(MySimulatedPlugin0.class, config); config = simAuConfig(tempDirPath + "/1"); config.put("base_url", "http: sau1 = PluginTestUtil.createAndStartSimAu(MySimulatedPlugin1.class, config); config = simAuConfig(tempDirPath + "/2"); config.put("base_url", "http: sau2 = PluginTestUtil.createAndStartSimAu(MySimulatedPlugin2.class, config); config = simAuConfig(tempDirPath + "/3"); config.put("base_url", "http: sau3 = PluginTestUtil.createAndStartSimAu(MySimulatedPlugin3.class, config); PluginTestUtil.crawlSimAu(sau0); PluginTestUtil.crawlSimAu(sau1); PluginTestUtil.crawlSimAu(sau2); PluginTestUtil.crawlSimAu(sau3); ausReindexed.clear(); metadataManager = new MetadataManager() { public Connection newConnection() throws SQLException { if (disableMetadataManager) { throw new IllegalArgumentException("MetadataManager is disabled"); } return super.newConnection(); } /** * Get the db root directory for testing. * @return the db root directory */ protected String getDbRootDirectory() { return tempDirPath; } /** * Notify listeners that an AU is being reindexed. * * @param au */ protected void notifyStartReindexingAu(ArchivalUnit au) { log.debug("Start reindexing au " + au); } /** * Notify listeners that an AU is finshed being reindexed. * * @param au */ protected void notifyFinishReindexingAu(ArchivalUnit au, ReindexingStatus status) { log.debug("Finished reindexing au (" + status + ") " + au); if (status != ReindexingStatus.rescheduled) { synchronized (ausReindexed) { ausReindexed.add(au.getAuId()); ausReindexed.notifyAll(); } } } }; theDaemon.setMetadataManager(metadataManager); metadataManager.initService(theDaemon); try { metadataManager.startService(); } catch (IllegalArgumentException ex) { // ignored } theDaemon.setAusStarted(true); if ("true".equals(paramIndexingEnabled)) { int expectedAuCount = 4; assertEquals(expectedAuCount, pluginManager.getAllAus().size()); long maxWaitTime = expectedAuCount * 20000; // 20 sec. per au int ausCount = waitForReindexing(expectedAuCount, maxWaitTime); assertEquals(expectedAuCount, ausCount); } // override to eliminate URL resolution for testing openUrlResolver = new OpenUrlResolver(theDaemon) { public String resolveFromUrl(String url) { return url; } }; } Configuration simAuConfig(String rootPath) { Configuration conf = ConfigManager.newConfiguration(); conf.put("root", rootPath); conf.put("depth", "2"); conf.put("branch", "1"); conf.put("numFiles", "3"); conf.put("fileTypes", "" + (SimulatedContentGenerator.FILE_TYPE_PDF + SimulatedContentGenerator.FILE_TYPE_HTML)); conf.put("binFileSize", "7"); return conf; } public void tearDown() throws Exception { sau0.deleteContentTree(); sau1.deleteContentTree(); sau2.deleteContentTree(); theDaemon.stopDaemon(); super.tearDown(); } public void createMetadata() throws Exception { // reset set of reindexed aus ausReindexed.clear(); metadataManager.restartService(); theDaemon.setAusStarted(true); DataSource ds = metadataManager.getDataSource(); assertNotNull(ds); int expectedAuCount = 4; assertEquals(expectedAuCount, pluginManager.getAllAus().size()); Connection con = ds.getConnection(); long maxWaitTime = expectedAuCount * 20000; // 20 sec. per au int ausCount = waitForReindexing(expectedAuCount, maxWaitTime); assertEquals(expectedAuCount, ausCount); assertEquals(0, metadataManager.reindexingTasks.size()); assertEquals(0, metadataManager.getAusToReindex(con, Integer.MAX_VALUE).size()); String query = "select access_url from " + MetadataManager.METADATA_TABLE; Statement stmt = con.createStatement(); ResultSet resultSet = stmt.executeQuery(query); if (!resultSet.next()) { fail("No entries in metadata table"); } String url = resultSet.getString(1); log.debug("url from metadata table: " + url); con.rollback(); con.commit(); } /** * Waits a specified period for a specified number of AUs to finish * being reindexed. Returns the actual number of AUs reindexed. * * @param auCount the expected AU count * @param maxWaitTime the maximum time to wait * @return the number of AUs reindexed */ private int waitForReindexing(int auCount, long maxWaitTime) { long startTime = System.currentTimeMillis(); synchronized (ausReindexed) { while ( (System.currentTimeMillis()-startTime < maxWaitTime) && (ausReindexed.size() < auCount)) { try { ausReindexed.wait(maxWaitTime); } catch (InterruptedException ex) { } } } return ausReindexed.size(); } public static class MySubTreeArticleIteratorFactory implements ArticleIteratorFactory { String pat; public MySubTreeArticleIteratorFactory(String pat) { this.pat = pat; } /** * Create an Iterator that iterates through the AU's articles, pointing * to the appropriate CachedUrl of type mimeType for each, or to the * plugin's choice of CachedUrl if mimeType is null * @param au the ArchivalUnit to iterate through * @return the ArticleIterator */ @Override public Iterator<ArticleFiles> createArticleIterator(ArchivalUnit au, MetadataTarget target) throws PluginException { Iterator<ArticleFiles> ret; SubTreeArticleIterator.Spec spec = new SubTreeArticleIterator.Spec().setTarget(target); if (pat != null) { spec.setPattern(pat); } ret = new SubTreeArticleIterator(au, spec); log.debug( "creating article iterator for au " + au.getName() + " hasNext: " + ret.hasNext()); return ret; } } public static class MySimulatedPlugin extends SimulatedPlugin { ArticleMetadataExtractor simulatedArticleMetadataExtractor = null; /** * Returns the article iterator factory for the mime type, if any * @param contentType the content type * @return the ArticleIteratorFactory */ @Override public ArticleIteratorFactory getArticleIteratorFactory() { MySubTreeArticleIteratorFactory ret = new MySubTreeArticleIteratorFactory(null); //"branch1/branch1"); return ret; } @Override public ArticleMetadataExtractor getArticleMetadataExtractor(MetadataTarget target, ArchivalUnit au) { return simulatedArticleMetadataExtractor; } } public static class MySimulatedPlugin0 extends MySimulatedPlugin { public MySimulatedPlugin0() { simulatedArticleMetadataExtractor = new ArticleMetadataExtractor() { int articleNumber = 0; public void extract(MetadataTarget target, ArticleFiles af, Emitter emitter) throws IOException, PluginException { ArticleMetadata md = new ArticleMetadata(); articleNumber++; md.put(MetadataField.FIELD_ISSN,"0740-2783"); md.put(MetadataField.FIELD_VOLUME,"XI"); if (articleNumber < 10) { md.put(MetadataField.FIELD_ISSUE,"1st Quarter"); md.put(MetadataField.FIELD_DATE,"2010-Q1"); md.put(MetadataField.FIELD_START_PAGE,"" + articleNumber); } else { md.put(MetadataField.FIELD_ISSUE,"2nd Quarter"); md.put(MetadataField.FIELD_DATE,"2010-Q2"); md.put(MetadataField.FIELD_START_PAGE,"" + (articleNumber-9)); } String doiPrefix = "10.1234/12345678"; String doi = doiPrefix + "." + md.get(MetadataField.FIELD_DATE) + "." + md.get(MetadataField.FIELD_START_PAGE); md.put(MetadataField.FIELD_DOI, doi); md.put(MetadataField.FIELD_JOURNAL_TITLE,"Journal[" + doiPrefix + "]"); md.put(MetadataField.FIELD_ARTICLE_TITLE,"Title[" + doi + "]"); md.put(MetadataField.FIELD_AUTHOR,"Author[" + doi + "]"); md.put(MetadataField.FIELD_ACCESS_URL, "http: + md.get(MetadataField.FIELD_ISSUE) +"/p" + md.get(MetadataField.FIELD_START_PAGE)); emitter.emitMetadata(af, md); } }; } public ExternalizableMap getDefinitionMap() { ExternalizableMap map = new ExternalizableMap(); map.putString("au_start_url", "\"%splugin0/%s\", base_url, volume"); map.putString("au_volume_url", "\"%splugin0/%s/toc\", base_url, volume"); map.putString("au_issue_url", "\"%splugin0/%s/%s/toc\", base_url, volume, issue"); map.putString("au_title_url", "\"%splugin0/toc\", base_url"); return map; } } public static class MySimulatedPlugin1 extends MySimulatedPlugin { public MySimulatedPlugin1() { simulatedArticleMetadataExtractor = new ArticleMetadataExtractor() { int articleNumber = 0; public void extract(MetadataTarget target, ArticleFiles af, Emitter emitter) throws IOException, PluginException { articleNumber++; ArticleMetadata md = new ArticleMetadata(); md.put(MetadataField.FIELD_ISSN,"1144-875X"); md.put(MetadataField.FIELD_EISSN, "7744-6521"); md.put(MetadataField.FIELD_VOLUME,"42"); if (articleNumber < 10) { md.put(MetadataField.FIELD_ISSUE,"Summer"); md.put(MetadataField.FIELD_DATE,"2010-S2"); md.put(MetadataField.FIELD_START_PAGE,"" + articleNumber); } else { md.put(MetadataField.FIELD_ISSUE,"Fall"); md.put(MetadataField.FIELD_DATE,"2010-S3"); md.put(MetadataField.FIELD_START_PAGE, "" + (articleNumber-9)); } String doiPrefix = "10.2468/28681357"; String doi = doiPrefix + "." + md.get(MetadataField.FIELD_DATE) + "." + md.get(MetadataField.FIELD_START_PAGE); md.put(MetadataField.FIELD_DOI, doi); md.put(MetadataField.FIELD_JOURNAL_TITLE, "Journal[" + doiPrefix + "]"); md.put(MetadataField.FIELD_ARTICLE_TITLE, "Title[" + doi + "]"); md.put(MetadataField.FIELD_AUTHOR, "Author1[" + doi + "]"); md.put(MetadataField.FIELD_ACCESS_URL, "http: + "i_" + md.get(MetadataField.FIELD_ISSUE) +"/p_" + md.get(MetadataField.FIELD_START_PAGE)); emitter.emitMetadata(af, md); } }; } public ExternalizableMap getDefinitionMap() { ExternalizableMap map = new ExternalizableMap(); map.putString("au_start_url", "\"%splugin1/v_%s/toc\", base_url, volume"); Map<String,Object> map1 = new HashMap<String,Object>(); map.putMap("au_feature_urls", map1); Map<String,String> map2 = new HashMap<String,String>(); map1.put("au_title", "\"%splugin1/toc\", base_url"); map1.put("au_issue", map2); map2.put("key1", "\"%splugin1/v_%s/i_%s/key1/toc\", base_url, volume, issue"); map2.put("key2;*", "\"%splugin1/v_%s/i_%s/key2/toc\", base_url, volume, issue"); return map; } } public static class MySimulatedPlugin2 extends MySimulatedPlugin { public MySimulatedPlugin2() { simulatedArticleMetadataExtractor = new ArticleMetadataExtractor() { int articleNumber = 0; public void extract(MetadataTarget target, ArticleFiles af, Emitter emitter) throws IOException, PluginException { org.lockss.extractor.ArticleMetadata md = new ArticleMetadata(); articleNumber++; String doi = "10.1357/9781585623174." + articleNumber; md.put(MetadataField.FIELD_DOI,doi); md.put(MetadataField.FIELD_ISBN,"978-1-58562-317-4"); md.put(MetadataField.FIELD_DATE,"1993"); md.put(MetadataField.FIELD_START_PAGE,"" + articleNumber); md.put(MetadataField.FIELD_JOURNAL_TITLE,"Manual of Clinical Psychopharmacology"); md.put(MetadataField.FIELD_ARTICLE_TITLE,"Title[" + doi + "]"); md.put(MetadataField.FIELD_AUTHOR,"Author1[" + doi + "]"); md.put(MetadataField.FIELD_AUTHOR,"Author2[" + doi + "]"); md.put(MetadataField.FIELD_AUTHOR,"Author3[" + doi + "]"); md.put(MetadataField.FIELD_ACCESS_URL, "http: emitter.emitMetadata(af, md); } }; } public ExternalizableMap getDefinitionMap() { ExternalizableMap map = new ExternalizableMap(); map.putString("au_start_url", "\"%splugin2/%s\", base_url, year"); return map; } } public static class MySimulatedPlugin3 extends MySimulatedPlugin { public MySimulatedPlugin3() { simulatedArticleMetadataExtractor = new ArticleMetadataExtractor() { int articleNumber = 0; public void extract(MetadataTarget target, ArticleFiles af, Emitter emitter) throws IOException, PluginException { org.lockss.extractor.ArticleMetadata md = new ArticleMetadata(); articleNumber++; String doiPrefix = "10.0135/12345678.1999-11.12"; String doi = doiPrefix + "." + articleNumber; md.put(MetadataField.FIELD_DOI,doi); md.put(MetadataField.FIELD_ISBN,"976-1-58562-317-7"); md.put(MetadataField.FIELD_DATE,"1999"); md.put(MetadataField.FIELD_START_PAGE,"" + articleNumber); md.put(MetadataField.FIELD_JOURNAL_TITLE,"Journal[" + doiPrefix + "]"); md.put(MetadataField.FIELD_ARTICLE_TITLE,"Title[" + doi + "]"); md.put(MetadataField.FIELD_AUTHOR,"Author1[" + doi + "]"); md.put(MetadataField.FIELD_ACCESS_URL, "http: emitter.emitMetadata(af, md); } }; } public ExternalizableMap getDefinitionMap() { ExternalizableMap map = new ExternalizableMap(); map.putString("au_start_url", "\"%splugin3/%s\", base_url, year"); return map; } } /* * Test resolving a journal article using the DOI of the article. */ public void testResolveFromRftIdDoi() { // from SimulatedPlugin0 // expect url for article with specified DOI Map<String,String> params = new HashMap<String,String>(); if (disableMetadataManager) { // use real DOI so test doesn't take so long to time out params.put("rft_id", "info:doi/" + "10.3789/isqv22n3.2010.04"); String url = openUrlResolver.resolveOpenUrl(params); assertEquals("http: } else { params.put("rft_id", "info:doi/" + "10.1234/12345678.2010-Q1.1"); String url = openUrlResolver.resolveOpenUrl(params); assertEquals("http: } } /** * Test resolving a book chapter using an ISBN plus either * the page, the article number, the author, or the article title. */ public void testResolveFromIsbn() { String url; Map<String,String> params = new HashMap<String,String>(); // from SimulatedPlugin2 with ISBN and start page // expect url for specified chapter of the book params.clear(); params.put("rft.isbn", "978-1-58562-317-4"); params.put("rft.spage", "4"); url = openUrlResolver.resolveOpenUrl(params); if (disableMetadataManager) { assertEquals("http: } else { assertEquals("http: } // from SimulatedPlugin2 with ISBN and bad start page // expect landing page since the page number is bad params.clear(); params.put("rft.isbn", "978-1-58562-317-4"); params.put("rft.spage", "bad"); url = openUrlResolver.resolveOpenUrl(params); assertEquals("http: // from SimulatedPlugin2 with ISBN and article number // expect url for specified chapter params.clear(); params.put("rft.isbn", "978-1-58562-317-4"); params.put("rft.artnum", "2"); url = openUrlResolver.resolveOpenUrl(params); if (disableMetadataManager) { assertEquals("http: } else { assertEquals("http: } // from SimulatedPlugin2 with ISBN and author // expect url for author's chapter of the book params.clear(); params.put("rft.isbn", "978-1-58562-317-4"); params.put("rft.au", "Author2[10.1357/9781585623174.1]"); url = openUrlResolver.resolveOpenUrl(params); if (disableMetadataManager) { assertEquals("http: } else { assertEquals("http: } // from SimulatedPlugin2 with ISBN only // expect url for specified article of the book params.clear(); params.put("rft.isbn", "978-1-58562-317-4"); params.put("rft.atitle", "Title[10.1357/9781585623174.1]"); url = openUrlResolver.resolveOpenUrl(params); if (disableMetadataManager) { assertEquals("http: } else { assertEquals("http: } // from SimulatedPlugin2 with ISBN, start page, author, and title // expect url for specified article for author and page number params.clear(); params.put("rft.isbn", "978-1-58562-317-4"); params.put("rft.atitle", "Title[10.1357/9781585623174.1]"); params.put("rft.au", "Author2[10.1357/9781585623174.1]"); params.put("rft.spage", "1"); url = openUrlResolver.resolveOpenUrl(params); if (disableMetadataManager) { assertEquals("http: } else { assertEquals("http: } // from SimulatedPlugin2 with ISBN, start page, author, and title // expect url for specified article for author and page number params.clear(); params.put("rft.isbn", "978-1-58562-317-4"); params.put("rft.date", "1993"); url = openUrlResolver.resolveOpenUrl(params); if (disableMetadataManager) { assertEquals("http: } else { assertEquals("http: } } /** * Test resolving a book chapter using the publisher and book title. */ public void testResolveFromBookTitle() { // these tests require a TDB if (ConfigManager.getCurrentConfig().getTdb() == null) { return; } Map<String,String> params; String url; // from SimulatedPlugin2 with book publisher, title with start page // expect url for chapter on specified page params = new HashMap<String,String>(); params.put("rft.pub", "Publisher[Manual of Clinical Psychopharmacology]"); params.put("rft.btitle", "Manual of Clinical Psychopharmacology"); params.put("rft.spage", "1"); url = openUrlResolver.resolveOpenUrl(params); if (disableMetadataManager) { assertEquals("http: } else { assertEquals("http: } // from SimulatedPlugin2 book title and page only, without publisher // expect url for chapter on specified page params.clear(); params.put("rft.btitle", "Manual of Clinical Psychopharmacology"); params.put("rft.spage", "1"); url = openUrlResolver.resolveOpenUrl(params); if (disableMetadataManager) { assertEquals("http: } else { assertEquals("http: } // from SimulatedPlugin2 book title and page only, without publisher // expect url for specified article params.clear(); params.put("rft.btitle", "Manual of Clinical Psychopharmacology"); params.put("rft.atitle", "Title[10.1357/9781585623174.1]"); url = openUrlResolver.resolveOpenUrl(params); if (disableMetadataManager) { assertEquals("http: } else { assertEquals("http: } // from SimulatedPlugin2 book title only // expect url of book landing page params.clear(); params.put("rft.btitle", "Manual of Clinical Psychopharmacology"); url = openUrlResolver.resolveOpenUrl(params); assertEquals("http: // from SimulatedPlugin2 book title and year // expect url of book landing page params.clear(); params.put("rft.btitle", "Manual of Clinical Psychopharmacology"); params.put("rft.date", "1993"); url = openUrlResolver.resolveOpenUrl(params); assertEquals("http: } /** * Test resolving a book chapter using an ISBN plus either * the page, the article number, the author, or the article title. */ public void testResolveFromIssn() { String url; Map<String,String> params = new HashMap<String,String>(); // from SimulatedPlugin1, journal ISSN only // expect base_url params.put("rft.issn", "1144-875X"); url = openUrlResolver.resolveOpenUrl(params); assertEquals("http: // from SimulatedPlugin1, journal EISSN only // expect base_url (eventually title TOC) params.clear(); params.put("rft.eissn", "7744-6521"); url = openUrlResolver.resolveOpenUrl(params); assertEquals("http: // from SimulatedPlugin1, journal ISSN and article number only // expect base_url (eventually title TOC) since article number is not unique params.clear(); params.put("rft.issn", "1144-875X"); params.put("rft.artnum", "1"); url = openUrlResolver.resolveOpenUrl(params); assertEquals("http: // from SimulatedPlugin1, journal ISSN, volume, issue, and article title // expect article URL params.clear(); params.put("rft.issn", "1144-875X"); params.put("rft.volume", "42"); params.put("rft.issue", "Summer"); params.put("rft.atitle", "Title[10.2468/28681357.2010-S2.1]"); url = openUrlResolver.resolveOpenUrl(params); if (disableMetadataManager) { System.out.println(url); assertEquals("http: } else { assertEquals("http: } // from SimulatedPlugin1, journal ISSN, volume, issue, and article author // expect article URL params.clear(); params.put("rft.issn", "1144-875X"); params.put("rft.volume", "42"); params.put("rft.issue", "Summer"); params.put("rft.au", "Author1[10.2468/28681357.2010-S2.1]"); url = openUrlResolver.resolveOpenUrl(params); if (disableMetadataManager) { assertEquals("http: } else { assertEquals("http: } // from SimulatedPlugin1, journal ISSN, volume, issue, and start page // expect article URL params.clear(); params.put("rft.issn", "1144-875X"); params.put("rft.volume", "42"); params.put("rft.issue", "Summer"); params.put("rft.spage", "1"); url = openUrlResolver.resolveOpenUrl(params); if (disableMetadataManager) { assertEquals("http: } else { assertEquals("http: } // from SimulatedPlugin1, journal ISSN, and article title only // expect article URL because article title is unique across the journal params.clear(); params.put("rft.issn", "1144-875X"); params.put("rft.atitle", "Title[10.2468/28681357.2010-S2.1]"); url = openUrlResolver.resolveOpenUrl(params); if (disableMetadataManager) { assertEquals("http: } else { assertEquals("http: } // from SimulatedPlugin1, journal ISSN, and article article author only // expect article_url because author only wrote one article for this journal params.clear(); params.put("rft.issn", "1144-875X"); params.put("rft.au", "Author1[10.2468/28681357.2010-S2.1]"); url = openUrlResolver.resolveOpenUrl(params); if (disableMetadataManager) { assertEquals("http: } else { assertEquals("http: } } /** * Test resolving a book chapter using the publisher and book title. */ public void testResolveFromJournalTitle() { // these tests require a TDB if (ConfigManager.getCurrentConfig().getTdb() == null) { return; } String url; // from SimulatedPlugin1 // journal title with publisher and page // expect base_url because start page not unique across issues Map<String,String> params = new HashMap<String,String>(); params.put("rft.pub", "Publisher[10.2468/24681357]"); params.put("rft.jtitle", "Journal[10.2468/24681357]"); params.put("rft.spage", "1"); url = openUrlResolver.resolveOpenUrl(params); assertEquals("http: // from SimulatedPlugin1 // journal title and page only, without publisher // expect base_url because start page not unique across issues params.clear(); params.put("rft.jtitle", "Journal[10.2468/24681357]"); params.put("rft.spage", "1"); url = openUrlResolver.resolveOpenUrl(params); assertEquals("http: // from SimulatedPlugin1 // journal title and invalid page only, without publisher // expect base_url because start page not unique across issue params.clear(); params.put("rft.jtitle", "Journal[10.2468/24681357]"); params.put("rft.spage", "1"); url = openUrlResolver.resolveOpenUrl(params); assertEquals("http: // from SimulatedPlugin1 // journal title and invalid page only, without publisher // expect volume url params.clear(); params.put("rft.jtitle", "Journal[10.2468/24681357]"); params.put("rft.volume", "42"); url = openUrlResolver.resolveOpenUrl(params); assertEquals("http: // from SimulatedPlugin3 // book title and page only, without publisher // expect article url because start page is unique within the book params.clear(); params.put("rft.btitle", "Journal[10.0135/12345678]"); params.put("rft.spage", "1"); url = openUrlResolver.resolveOpenUrl(params); if (disableMetadataManager) { assertEquals("http: } else { assertEquals("http: } // from SimulatedPlugin3 // book title only, without publisher // expect au url for book params.clear(); params.put("rft.btitle", "Journal[10.0135/12345678]"); url = openUrlResolver.resolveOpenUrl(params); assertEquals("http: } }
package com.yahoo.osgi; import com.yahoo.component.ComponentSpecification; import com.yahoo.component.Version; import com.yahoo.container.bundle.BundleInstantiationSpecification; import com.yahoo.jdisc.application.OsgiFramework; import org.osgi.framework.Bundle; import org.osgi.framework.BundleException; import org.osgi.framework.launch.Framework; import java.util.Collection; import java.util.List; import java.util.logging.Logger; /** * @author Tony Vaagenes * @author bratseth * @author gjoranv */ public class OsgiImpl implements Osgi { private static final Logger log = Logger.getLogger(OsgiImpl.class.getName()); private final OsgiFramework jdiscOsgi; // The initial bundles are never scheduled for uninstall private final List<Bundle> initialBundles; private final Bundle systemBundle; // An initial bundle that is not the framework, and can hence be used to look up current bundles private final Bundle alwaysCurrentBundle; public OsgiImpl(OsgiFramework jdiscOsgi) { this.jdiscOsgi = jdiscOsgi; this.initialBundles = jdiscOsgi.bundles(); if (initialBundles.isEmpty()) throw new IllegalStateException("No initial bundles!"); systemBundle = getSystemBundle(initialBundles); alwaysCurrentBundle = firstNonFrameworkBundle(initialBundles); if (alwaysCurrentBundle == null) throw new IllegalStateException("The initial bundles only contained the framework bundle!"); log.info("Using " + alwaysCurrentBundle + " to lookup current bundles."); } @Override public Bundle[] getBundles() { List<Bundle> bundles = jdiscOsgi.bundles(); return bundles.toArray(new Bundle[bundles.size()]); } @Override public List<Bundle> getCurrentBundles() { return jdiscOsgi.getBundles(alwaysCurrentBundle); } public Class<Object> resolveClass(BundleInstantiationSpecification spec) { Bundle bundle = getBundle(spec.bundle); if (bundle != null) { return resolveFromBundle(spec, bundle); } else { return resolveFromThisBundleOrSystemBundle(spec); } } /** * Tries to resolve the given class from this class' bundle classloader. * If unsuccessful, resolves the class from . */ @SuppressWarnings("unchecked") private Class<Object> resolveFromThisBundleOrSystemBundle(BundleInstantiationSpecification spec) { log.fine(() -> "Resolving class from container-disc: " + spec.classId.getName()); try { return (Class<Object>) Class.forName(spec.classId.getName()); } catch (ClassNotFoundException e) { log.fine(() -> "Resolving class from the system bundle (jdisc core): " + spec.classId.getName()); try { return (Class<Object>) systemBundle.loadClass(spec.classId.getName()); } catch (ClassNotFoundException e2) { throw new IllegalArgumentException( "Could not create a component with id '" + spec.classId.getName() + "'. Tried to load class directly, since no bundle was found for spec: " + spec.bundle + ". If a bundle with the same name is installed, there is a either a version mismatch" + " or the installed bundle's version contains a qualifier string."); } } } @SuppressWarnings("unchecked") private static Class<Object> resolveFromBundle(BundleInstantiationSpecification spec, Bundle bundle) { try { ensureBundleActive(bundle); return (Class<Object>) bundle.loadClass(spec.classId.getName()); } catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not load class '" + spec.classId.getName() + "' from bundle " + bundle, e); } } private static void ensureBundleActive(Bundle bundle) throws IllegalStateException { int state = bundle.getState(); Throwable cause = null; if (state != Bundle.ACTIVE) { try { // Get the reason why the bundle isn't active. // Do not change this method to not fail if start is successful without carefully analyzing // why there are non-active bundles. bundle.start(); } catch (BundleException e) { cause = e; } throw new IllegalStateException("Bundle " + bundle + " is not active. State=" + state + ".", cause); } } /** * Returns the bundle of a given name having the highest matching version * * @param id the id of the component to return. May not include a version, or include * an underspecified version, in which case the highest (matching) version which * does not contain a qualifier is returned * @return the bundle match having the highest version, or null if there was no matches */ public Bundle getBundle(ComponentSpecification id) { log.fine(() -> "Getting bundle for component " + id + ". Set of current bundles: " + getCurrentBundles()); Bundle highestMatch = null; for (Bundle bundle : getCurrentBundles()) { assert bundle.getSymbolicName() != null : "ensureHasBundleSymbolicName not called during installation"; if ( ! bundle.getSymbolicName().equals(id.getName())) continue; if ( ! id.getVersionSpecification().matches(versionOf(bundle))) continue; if (highestMatch == null || versionOf(highestMatch).compareTo(versionOf(bundle)) < 0) highestMatch = bundle; } return highestMatch; } /** Returns the version of a bundle, as specified by Bundle-Version in the manifest */ private static Version versionOf(Bundle bundle) { Object bundleVersion = bundle.getHeaders().get("Bundle-Version"); if (bundleVersion == null) return Version.emptyVersion; return new Version(bundleVersion.toString()); } @Override public List<Bundle> install(String absolutePath) { try { return jdiscOsgi.installBundle(normalizeLocation(absolutePath)); } catch (BundleException e) { throw new RuntimeException(e); } } private static String normalizeLocation(String location) { if (location.indexOf(':') < 0) location = "file:" + location; return location; } @Override public void allowDuplicateBundles(Collection<Bundle> bundles) { jdiscOsgi.allowDuplicateBundles(bundles); } @Override public boolean hasFelixFramework() { return jdiscOsgi.isFelixFramework(); } private static Bundle getSystemBundle(List<Bundle> bundles ) { for (Bundle b : bundles) { if (b instanceof Framework) return b; } throw new IllegalStateException("No system bundle in " + bundles); } private static Bundle firstNonFrameworkBundle(List<Bundle> bundles) { for (Bundle b : bundles) { if (! (b instanceof Framework)) return b; } return null; } }
package org.broadinstitute.sting.utils.baq; import net.sf.picard.reference.IndexedFastaSequenceFile; import net.sf.picard.reference.ReferenceSequence; import net.sf.samtools.CigarElement; import net.sf.samtools.CigarOperator; import net.sf.samtools.SAMRecord; import net.sf.samtools.SAMUtils; import org.broadinstitute.sting.utils.collections.Pair; import org.broadinstitute.sting.utils.exceptions.ReviewedStingException; import org.broadinstitute.sting.utils.exceptions.UserException; import org.broadinstitute.sting.utils.sam.ReadUtils; /* The topology of the profile HMM: /\ /\ /\ /\ I[1] I[k-1] I[k] I[L] ^ \ \ ^ \ ^ \ \ ^ | \ \ | \ | \ \ | M[0] M[1] -> ... -> M[k-1] -> M[k] -> ... -> M[L] M[L+1] \ \/ \/ \/ / \ /\ /\ /\ / -> D[k-1] -> D[k] -> M[0] points to every {M,I}[k] and every {M,I}[k] points M[L+1]. On input, _ref is the reference sequence and _query is the query sequence. Both are sequences of 0/1/2/3/4 where 4 stands for an ambiguous residue. iqual is the base quality. c sets the gap open probability, gap extension probability and band width. On output, state and q are arrays of length l_query. The higher 30 bits give the reference position the query base is matched to and the lower two bits can be 0 (an alignment match) or 1 (an insertion). q[i] gives the phred scaled posterior probability of state[i] being wrong. */ public class BAQ { private final static boolean DEBUG = false; public enum CalculationMode { OFF, // don't apply BAQ at all, the default CALCULATE_AS_NECESSARY, // do HMM BAQ calculation on the fly, as necessary, if there's no tag RECALCULATE // do HMM BAQ calculation on the fly, regardless of whether there's a tag present } /** these are features that only the walker can override */ public enum QualityMode { ADD_TAG, // calculate the BAQ, but write it into the reads as the BAQ tag, leaving QUAL field alone OVERWRITE_QUALS, // overwrite the quality field directly DONT_MODIFY // do the BAQ, but don't modify the quality scores themselves, just return them in the function. } public enum ApplicationTime { FORBIDDEN, // Walker does not tolerate BAQ input ON_INPUT, // apply the BAQ calculation to the incoming reads, the default ON_OUTPUT, // apply the BAQ calculation to outgoing read streams HANDLED_IN_WALKER // the walker will deal with the BAQ calculation status itself } public static final String BAQ_TAG = "BQ"; private static double[] qual2prob = new double[256]; static { for (int i = 0; i < 256; ++i) qual2prob[i] = Math.pow(10, -i/10.); } // Phred scaled now (changed 1/10/2011) public static double DEFAULT_GOP = 40; /* Takes a Phred Scale quality score and returns the error probability. * * Quick conversion function to maintain internal structure of BAQ calculation on * probability scale, but take the user entered parameter in phred-scale. * * @param x phred scaled score * @return probability of incorrect base call */ private double convertFromPhredScale(double x) { return (Math.pow(10,(-x)/10.));} public double cd = -1; // gap open probability [1e-3] private double ce = 0.1; // gap extension probability [0.1] private int cb = 7; // band width [7] private boolean includeClippedBases = false; public byte getMinBaseQual() { return minBaseQual; } /** * Any bases with Q < MIN_BASE_QUAL are raised up to this base quality */ private byte minBaseQual = 4; public double getGapOpenProb() { return cd; } public double getGapExtensionProb() { return ce; } public int getBandWidth() { return cb; } /** * Use defaults for everything */ public BAQ() { cd = convertFromPhredScale(DEFAULT_GOP); initializeCachedData(); } /** * Create a new HmmGlocal object with specified parameters * * @param d gap open prob (not phred scaled!). * @param e gap extension prob. * @param b band width * @param minBaseQual All bases with Q < minBaseQual are up'd to this value */ public BAQ(final double d, final double e, final int b, final byte minBaseQual, boolean includeClippedBases) { cd = d; ce = e; cb = b; this.minBaseQual = minBaseQual; this.includeClippedBases = includeClippedBases; initializeCachedData(); } private final static double EM = 0.33333333333; private final static double EI = 0.25; private double[][][] EPSILONS = new double[256][256][SAMUtils.MAX_PHRED_SCORE+1]; private void initializeCachedData() { for ( int i = 0; i < 256; i++ ) for ( int j = 0; j < 256; j++ ) for ( int q = 0; q <= SAMUtils.MAX_PHRED_SCORE; q++ ) { EPSILONS[i][j][q] = 1.0; } for ( char b1 : "ACGTacgt".toCharArray() ) { for ( char b2 : "ACGTacgt".toCharArray() ) { for ( int q = 0; q <= SAMUtils.MAX_PHRED_SCORE; q++ ) { double qual = qual2prob[q < minBaseQual ? minBaseQual : q]; double e = Character.toLowerCase(b1) == Character.toLowerCase(b2) ? 1 - qual : qual * EM; EPSILONS[(byte)b1][(byte)b2][q] = e; } } } } private double calcEpsilon( byte ref, byte read, byte qualB ) { return EPSILONS[ref][read][qualB]; } // // NOTE -- THIS CODE IS SYNCHRONIZED WITH CODE IN THE SAMTOOLS REPOSITORY. CHANGES TO THIS CODE SHOULD BE // NOTE -- PUSHED BACK TO HENG LI // public int hmm_glocal(final byte[] ref, final byte[] query, int qstart, int l_query, final byte[] _iqual, int[] state, byte[] q) { if ( ref == null ) throw new ReviewedStingException("BUG: ref sequence is null"); if ( query == null ) throw new ReviewedStingException("BUG: query sequence is null"); if ( _iqual == null ) throw new ReviewedStingException("BUG: query quality vector is null"); if ( query.length != _iqual.length ) throw new ReviewedStingException("BUG: read sequence length != qual length"); if ( l_query < 1 ) throw new ReviewedStingException("BUG: length of query sequence < 0: " + l_query); if ( qstart < 0 ) throw new ReviewedStingException("BUG: query sequence start < 0: " + qstart); //if ( q != null && q.length != state.length ) throw new ReviewedStingException("BUG: BAQ quality length != read sequence length"); //if ( state != null && state.length != l_query ) throw new ReviewedStingException("BUG: state length != read sequence length"); int i, k; /*** initialization ***/ // change coordinates int l_ref = ref.length; // set band width int bw2, bw = l_ref > l_query? l_ref : l_query; if (cb < Math.abs(l_ref - l_query)) { bw = Math.abs(l_ref - l_query) + 3; //System.out.printf("SC cb=%d, bw=%d%n", cb, bw); } if (bw > cb) bw = cb; if (bw < Math.abs(l_ref - l_query)) { //int bwOld = bw; bw = Math.abs(l_ref - l_query); //System.out.printf("old bw is %d, new is %d%n", bwOld, bw); } //System.out.printf("c->bw = %d, bw = %d, l_ref = %d, l_query = %d\n", cb, bw, l_ref, l_query); bw2 = bw * 2 + 1; // allocate the forward and backward matrices f[][] and b[][] and the scaling array s[] double[][] f = new double[l_query+1][bw2*3 + 6]; double[][] b = new double[l_query+1][bw2*3 + 6]; double[] s = new double[l_query+2]; // initialize transition probabilities double sM, sI, bM, bI; sM = sI = 1. / (2 * l_query + 2); bM = (1 - cd) / l_ref; bI = cd / l_ref; // (bM+bI)*l_ref==1 double[] m = new double[9]; m[0*3+0] = (1 - cd - cd) * (1 - sM); m[0*3+1] = m[0*3+2] = cd * (1 - sM); m[1*3+0] = (1 - ce) * (1 - sI); m[1*3+1] = ce * (1 - sI); m[1*3+2] = 0.; m[2*3+0] = 1 - ce; m[2*3+1] = 0.; m[2*3+2] = ce; /*** forward ***/ f[0][set_u(bw, 0, 0)] = s[0] = 1.; { double[] fi = f[1]; double sum; int beg = 1, end = l_ref < bw + 1? l_ref : bw + 1, _beg, _end; for (k = beg, sum = 0.; k <= end; ++k) { int u; double e = calcEpsilon(ref[k-1], query[qstart], _iqual[qstart]); u = set_u(bw, 1, k); fi[u+0] = e * bM; fi[u+1] = EI * bI; sum += fi[u] + fi[u+1]; } // rescale s[1] = sum; _beg = set_u(bw, 1, beg); _end = set_u(bw, 1, end); _end += 2; for (k = _beg; k <= _end; ++k) fi[k] /= sum; } // f[2..l_query] for (i = 2; i <= l_query; ++i) { double[] fi = f[i], fi1 = f[i-1]; double sum; int beg = 1, end = l_ref, x, _beg, _end; byte qyi = query[qstart+i-1]; x = i - bw; beg = beg > x? beg : x; // band start x = i + bw; end = end < x? end : x; // band end for (k = beg, sum = 0.; k <= end; ++k) { int u, v11, v01, v10; double e = calcEpsilon(ref[k-1], qyi, _iqual[qstart+i-1]); u = set_u(bw, i, k); v11 = set_u(bw, i-1, k-1); v10 = set_u(bw, i-1, k); v01 = set_u(bw, i, k-1); fi[u+0] = e * (m[0] * fi1[v11+0] + m[3] * fi1[v11+1] + m[6] * fi1[v11+2]); fi[u+1] = EI * (m[1] * fi1[v10+0] + m[4] * fi1[v10+1]); fi[u+2] = m[2] * fi[v01+0] + m[8] * fi[v01+2]; sum += fi[u] + fi[u+1] + fi[u+2]; //System.out.println("("+i+","+k+";"+u+"): "+fi[u]+","+fi[u+1]+","+fi[u+2]); } // rescale s[i] = sum; _beg = set_u(bw, i, beg); _end = set_u(bw, i, end); _end += 2; for (k = _beg, sum = 1./sum; k <= _end; ++k) fi[k] *= sum; } { // f[l_query+1] double sum; for (k = 1, sum = 0.; k <= l_ref; ++k) { int u = set_u(bw, l_query, k); if (u < 3 || u >= bw2*3+3) continue; sum += f[l_query][u+0] * sM + f[l_query][u+1] * sI; } s[l_query+1] = sum; // the last scaling factor } //gdbebug+ /* double cac=0.; // undo scaling of forward probabilities to obtain plain probability of observation given model double[] su = new double[f[l_query].length]; { double sum = 0.; double[] logs = new double[s.length]; for (k=0; k < logs.length; k++) { logs[k] = Math.log10(s[k]); sum += logs[k]; } for (k=0; k < f[l_query].length; k++) su[k]= Math.log10(f[l_query][k])+ sum; cac = MathUtils.softMax(su); } System.out.format("s:%f\n",cac); // gdebug- */ /*** backward ***/ // b[l_query] (b[l_query+1][0]=1 and thus \tilde{b}[][]=1/s[l_query+1]; this is where s[l_query+1] comes from) for (k = 1; k <= l_ref; ++k) { int u = set_u(bw, l_query, k); double[] bi = b[l_query]; if (u < 3 || u >= bw2*3+3) continue; bi[u+0] = sM / s[l_query] / s[l_query+1]; bi[u+1] = sI / s[l_query] / s[l_query+1]; } // b[l_query-1..1] for (i = l_query - 1; i >= 1; --i) { int beg = 1, end = l_ref, x, _beg, _end; double[] bi = b[i], bi1 = b[i+1]; double y = (i > 1)? 1. : 0.; byte qyi1 = query[qstart+i]; x = i - bw; beg = beg > x? beg : x; x = i + bw; end = end < x? end : x; for (k = end; k >= beg; --k) { int u, v11, v01, v10; u = set_u(bw, i, k); v11 = set_u(bw, i+1, k+1); v10 = set_u(bw, i+1, k); v01 = set_u(bw, i, k+1); double e = (k >= l_ref? 0 : calcEpsilon(ref[k], qyi1, _iqual[qstart+i])) * bi1[v11]; bi[u+0] = e * m[0] + EI * m[1] * bi1[v10+1] + m[2] * bi[v01+2]; // bi1[v11] has been foled into e. bi[u+1] = e * m[3] + EI * m[4] * bi1[v10+1]; bi[u+2] = (e * m[6] + m[8] * bi[v01+2]) * y; } // rescale _beg = set_u(bw, i, beg); _end = set_u(bw, i, end); _end += 2; for (k = _beg, y = 1./s[i]; k <= _end; ++k) bi[k] *= y; } double pb; { int beg = 1, end = l_ref < bw + 1? l_ref : bw + 1; double sum = 0.; for (k = end; k >= beg; --k) { int u = set_u(bw, 1, k); double e = calcEpsilon(ref[k-1], query[qstart], _iqual[qstart]); if (u < 3 || u >= bw2*3+3) continue; sum += e * b[1][u+0] * bM + EI * b[1][u+1] * bI; } pb = b[0][set_u(bw, 0, 0)] = sum / s[0]; // if everything works as is expected, pb == 1.0 } /*** MAP ***/ for (i = 1; i <= l_query; ++i) { double sum = 0., max = 0.; double[] fi = f[i], bi = b[i]; int beg = 1, end = l_ref, x, max_k = -1; x = i - bw; beg = beg > x? beg : x; x = i + bw; end = end < x? end : x; for (k = beg; k <= end; ++k) { int u = set_u(bw, i, k); double z; sum += (z = fi[u+0] * bi[u+0]); if (z > max) { max = z; max_k = (k-1)<<2 | 0; } sum += (z = fi[u+1] * bi[u+1]); if (z > max) { max = z; max_k = (k-1)<<2 | 1; } } max /= sum; sum *= s[i]; // if everything works as is expected, sum == 1.0 if (state != null) state[qstart+i-1] = max_k; if (q != null) { k = (int)(-4.343 * Math.log(1. - max) + .499); // = 10*log10(1-max) q[qstart+i-1] = (byte)(k > 100? 99 : (k < minBaseQual ? minBaseQual : k)); } //System.out.println("("+pb+","+sum+")"+" ("+(i-1)+","+(max_k>>2)+","+(max_k&3)+","+max+")"); } return 0; } // Helper routines /** decode the bit encoded state array values */ public static boolean stateIsIndel(int state) { return (state & 3) != 0; } /** decode the bit encoded state array values */ public static int stateAlignedPosition(int state) { return state >> 2; } /** * helper routine for hmm_glocal * * @param b * @param i * @param k * @return */ private static int set_u(final int b, final int i, final int k) { int x = i - b; x = x > 0 ? x : 0; return (k + 1 - x) * 3; } // Actually working with the BAQ tag now /** * Get the BAQ attribute from the tag in read. Returns null if no BAQ tag is present. * @param read * @return */ public static byte[] getBAQTag(SAMRecord read) { String s = read.getStringAttribute(BAQ_TAG); return s != null ? s.getBytes() : null; } public static String encodeBQTag(SAMRecord read, byte[] baq) { // Offset to base alignment quality (BAQ), of the same length as the read sequence. // At the i-th read base, BAQi = Qi - (BQi - 64) where Qi is the i-th base quality. // so BQi = Qi - BAQi + 64 byte[] bqTag = new byte[baq.length]; for ( int i = 0; i < bqTag.length; i++) { int bq = (int)read.getBaseQualities()[i] + 64; int baq_i = (int)baq[i]; int tag = bq - baq_i; if ( tag < 0 ) throw new ReviewedStingException("BAQ tag calculation error. BAQ value above base quality at " + read); bqTag[i] = (byte)tag; } return new String(bqTag); } public static void addBAQTag(SAMRecord read, byte[] baq) { read.setAttribute(BAQ_TAG, encodeBQTag(read, baq)); } /** * Returns true if the read has a BAQ tag, or false otherwise * @param read * @return */ public static boolean hasBAQTag(SAMRecord read) { return read.getStringAttribute(BAQ_TAG) != null; } public static byte[] calcBAQFromTag(SAMRecord read, boolean overwriteOriginalQuals, boolean useRawQualsIfNoBAQTag) { byte[] rawQuals = read.getBaseQualities(); byte[] newQuals = rawQuals; byte[] baq = getBAQTag(read); if ( baq != null ) { // Offset to base alignment quality (BAQ), of the same length as the read sequence. // At the i-th read base, BAQi = Qi - (BQi - 64) where Qi is the i-th base quality. newQuals = overwriteOriginalQuals ? rawQuals : new byte[rawQuals.length]; for ( int i = 0; i < rawQuals.length; i++) { int rawQual = (int)rawQuals[i]; int baq_delta = (int)baq[i] - 64; int newval = rawQual - baq_delta; if ( newval < 0 ) throw new UserException.MalformedBAM(read, "BAQ tag error: the BAQ value is larger than the base quality"); newQuals[i] = (byte)newval; } } else if ( ! useRawQualsIfNoBAQTag ) { throw new IllegalStateException("Required BAQ tag to be present, but none was on read " + read.getReadName()); } return newQuals; } public static byte calcBAQFromTag(SAMRecord read, int offset, boolean useRawQualsIfNoBAQTag) { byte rawQual = read.getBaseQualities()[offset]; byte newQual = rawQual; byte[] baq = getBAQTag(read); if ( baq != null ) { // Offset to base alignment quality (BAQ), of the same length as the read sequence. // At the i-th read base, BAQi = Qi - (BQi - 64) where Qi is the i-th base quality. int baq_delta = (int)baq[offset] - 64; int newval = rawQual - baq_delta; if ( newval < 0 ) throw new UserException.MalformedBAM(read, "BAQ tag error: the BAQ value is larger than the base quality"); newQual = (byte)newval; } else if ( ! useRawQualsIfNoBAQTag ) { throw new IllegalStateException("Required BAQ tag to be present, but none was on read " + read.getReadName()); } return newQual; } public static class BAQCalculationResult { public byte[] refBases, rawQuals, readBases, bq; public int[] state; public BAQCalculationResult(SAMRecord read, byte[] ref) { this(read.getBaseQualities(), read.getReadBases(), ref); } public BAQCalculationResult(byte[] bases, byte[] quals, byte[] ref) { // prepares data for calculation rawQuals = quals; readBases = bases; // now actually prepare the data structures, and fire up the hmm bq = new byte[rawQuals.length]; state = new int[rawQuals.length]; this.refBases = ref; } } public BAQCalculationResult calcBAQFromHMM(SAMRecord read, IndexedFastaSequenceFile refReader) { // start is alignment start - band width / 2 - size of first I element, if there is one. Stop is similar int offset = getBandWidth() / 2; long readStart = includeClippedBases ? read.getUnclippedStart() : read.getAlignmentStart(); long start = Math.max(readStart - offset - ReadUtils.getFirstInsertionOffset(read), 0); long stop = (includeClippedBases ? read.getUnclippedEnd() : read.getAlignmentEnd()) + offset + ReadUtils.getLastInsertionOffset(read); if ( stop > refReader.getSequenceDictionary().getSequence(read.getReferenceName()).getSequenceLength() ) { return null; } else { // now that we have the start and stop, get the reference sequence covering it ReferenceSequence refSeq = refReader.getSubsequenceAt(read.getReferenceName(), start, stop); return calcBAQFromHMM(read, refSeq.getBases(), (int)(start - readStart)); } } public BAQCalculationResult calcBAQFromHMM(byte[] ref, byte[] query, byte[] quals, int queryStart, int queryEnd ) { if ( queryStart < 0 ) throw new ReviewedStingException("BUG: queryStart < 0: " + queryStart); if ( queryEnd < 0 ) throw new ReviewedStingException("BUG: queryEnd < 0: " + queryEnd); if ( queryEnd < queryStart ) throw new ReviewedStingException("BUG: queryStart < queryEnd : " + queryStart + " end =" + queryEnd); // note -- assumes ref is offset from the *CLIPPED* start BAQCalculationResult baqResult = new BAQCalculationResult(query, quals, ref); int queryLen = queryEnd - queryStart; hmm_glocal(baqResult.refBases, baqResult.readBases, queryStart, queryLen, baqResult.rawQuals, baqResult.state, baqResult.bq); return baqResult; } /** * Determine the appropriate start and stop offsets in the reads for the bases given the cigar string * @param read * @return */ private final Pair<Integer,Integer> calculateQueryRange(SAMRecord read) { int queryStart = -1, queryStop = -1; int readI = 0; // iterate over the cigar elements to determine the start and stop of the read bases for the BAQ calculation for ( CigarElement elt : read.getCigar().getCigarElements() ) { switch (elt.getOperator()) { case N: return null; // cannot handle these case H : case P : case D: break; // ignore pads, hard clips, and deletions case I : case S: case M: int prev = readI; readI += elt.getLength(); if ( includeClippedBases || elt.getOperator() != CigarOperator.S) { if ( queryStart == -1 ) queryStart = prev; queryStop = readI; } // in the else case we aren't including soft clipped bases, so we don't update // queryStart or queryStop break; default: throw new ReviewedStingException("BUG: Unexpected CIGAR element " + elt + " in read " + read.getReadName()); } } if ( queryStop == queryStart ) { // this read is completely clipped away, and yet is present in the file for some reason // usually they are flagged as non-PF, but it's possible to push them through the BAM //System.err.printf("WARNING -- read is completely clipped away: " + read.format()); return null; } return new Pair<Integer, Integer>(queryStart, queryStop); } // we need to pad ref by at least the bandwidth / 2 on either side public BAQCalculationResult calcBAQFromHMM(SAMRecord read, byte[] ref, int refOffset) { // todo -- need to handle the case where the cigar sum of lengths doesn't cover the whole read Pair<Integer, Integer> queryRange = calculateQueryRange(read); if ( queryRange == null ) return null; // read has Ns, or is completely clipped away int queryStart = queryRange.getFirst(); int queryEnd = queryRange.getSecond(); BAQCalculationResult baqResult = calcBAQFromHMM(ref, read.getReadBases(), read.getBaseQualities(), queryStart, queryEnd); // cap quals int readI = 0, refI = 0; for ( CigarElement elt : read.getCigar().getCigarElements() ) { int l = elt.getLength(); switch (elt.getOperator()) { case N: // cannot handle these return null; case H : case P : // ignore pads and hard clips break; case S : refI += l; // move the reference too, in addition to I case I : // todo -- is it really the case that we want to treat I and S the same? for ( int i = readI; i < readI + l; i++ ) baqResult.bq[i] = baqResult.rawQuals[i]; readI += l; break; case D : refI += l; break; case M : for (int i = readI; i < readI + l; i++) { int expectedPos = refI - refOffset + (i - readI); baqResult.bq[i] = capBaseByBAQ( baqResult.rawQuals[i], baqResult.bq[i], baqResult.state[i], expectedPos ); } readI += l; refI += l; break; default: throw new ReviewedStingException("BUG: Unexpected CIGAR element " + elt + " in read " + read.getReadName()); } } if ( readI != read.getReadLength() ) // odd cigar string System.arraycopy(baqResult.rawQuals, 0, baqResult.bq, 0, baqResult.bq.length); return baqResult; } public byte capBaseByBAQ( byte oq, byte bq, int state, int expectedPos ) { byte b; boolean isIndel = stateIsIndel(state); int pos = stateAlignedPosition(state); if ( isIndel || pos != expectedPos ) // we are an indel or we don't align to our best current position b = minBaseQual; // just take b = minBaseQuality else b = bq < oq ? bq : oq; return b; } /** * Modifies read in place so that the base quality scores are capped by the BAQ calculation. Uses the BAQ * tag if present already and alwaysRecalculate is false, otherwise fires up the HMM and does the BAQ on the fly * using the refReader to obtain the reference bases as needed. * * @param read * @param refReader * @param calculationType * @return BQ qualities for use, in case qmode is DONT_MODIFY */ public byte[] baqRead(SAMRecord read, IndexedFastaSequenceFile refReader, CalculationMode calculationType, QualityMode qmode ) { if ( DEBUG ) System.out.printf("BAQ %s read %s%n", calculationType, read.getReadName()); byte[] BAQQuals = read.getBaseQualities(); // in general we are overwriting quals, so just get a pointer to them if ( calculationType == CalculationMode.OFF) { // we don't want to do anything ; // just fall though } else if ( excludeReadFromBAQ(read) ) { ; // just fall through } else { if ( calculationType == CalculationMode.RECALCULATE || ! hasBAQTag(read) ) { if ( DEBUG ) System.out.printf(" Calculating BAQ on the fly%n"); BAQCalculationResult hmmResult = calcBAQFromHMM(read, refReader); if ( hmmResult != null ) { switch ( qmode ) { case ADD_TAG: addBAQTag(read, hmmResult.bq); break; case OVERWRITE_QUALS: System.arraycopy(hmmResult.bq, 0, read.getBaseQualities(), 0, hmmResult.bq.length); break; case DONT_MODIFY: BAQQuals = hmmResult.bq; break; default: throw new ReviewedStingException("BUG: unexpected qmode " + qmode); } } } else if ( qmode == QualityMode.OVERWRITE_QUALS ) { // only makes sense if we are overwriting quals if ( DEBUG ) System.out.printf(" Taking BAQ from tag%n"); // this overwrites the original qualities calcBAQFromTag(read, true, false); } } return BAQQuals; } /** * Returns true if we don't think this read is eligable for the BAQ calculation. Examples include non-PF reads, * duplicates, or unmapped reads. Used by baqRead to determine if a read should fall through the calculation. * * @param read * @return */ public boolean excludeReadFromBAQ(SAMRecord read) { // keeping mapped reads, regardless of pairing status, or primary alignment status. return read.getReadUnmappedFlag() || read.getReadFailsVendorQualityCheckFlag() || read.getDuplicateReadFlag(); } }
package com.mysema.query; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import com.mysema.query.grammar.OrderSpecifier; import com.mysema.query.grammar.Types.Expr; import com.mysema.query.grammar.Types.ExprBoolean; import com.mysema.query.grammar.Types.ExprEntity; /** * QueryBase provides a basic implementation of the Query interface * * @author tiwe * @version $Id$ */ @SuppressWarnings("unchecked") public class QueryBase<A extends QueryBase<A>> implements Query<A> { protected final List<Expr<?>> groupBy = new ArrayList<Expr<?>>(); protected final List<ExprBoolean> having = new ArrayList<ExprBoolean>(); protected final List<JoinExpression> joins = new ArrayList<JoinExpression>(); protected final List<OrderSpecifier<?>> orderBy = new ArrayList<OrderSpecifier<?>>(); protected final List<Expr<?>> select = new ArrayList<Expr<?>>(); protected final List<ExprBoolean> where = new ArrayList<ExprBoolean>(); protected void clear(){ joins.clear(); groupBy.clear(); having.clear(); orderBy.clear(); select.clear(); where.clear(); } public A from(ExprEntity<?>... o) { for (ExprEntity<?> expr : o){ joins.add(new JoinExpression(JoinType.DEFAULT,expr)); } return (A) this; } public A groupBy(Expr<?>... o) { groupBy.addAll(Arrays.asList(o)); return (A) this; } public A having(ExprBoolean... o) { having.addAll(Arrays.asList(o)); return (A) this; } public A innerJoin(ExprEntity<?> o) { joins.add(new JoinExpression(JoinType.INNERJOIN,o)); return (A) this; } public A fullJoin(ExprEntity<?> o) { joins.add(new JoinExpression(JoinType.FULLJOIN,o)); return (A) this; } public A join(ExprEntity<?> o) { joins.add(new JoinExpression(JoinType.JOIN,o)); return (A) this; } public A leftJoin(ExprEntity<?> o) { joins.add(new JoinExpression(JoinType.LEFTJOIN,o)); return (A) this; } public A orderBy(OrderSpecifier<?>... o) { orderBy.addAll(Arrays.asList(o)); return (A) this; } public A select(Expr<?>... o) { select.addAll(Arrays.asList(o)); return (A) this; } public A where(ExprBoolean... o) { where.addAll(Arrays.asList(o)); return (A) this; } public A with(ExprBoolean... o) { if (!joins.isEmpty()){ joins.get(joins.size()-1).setConditions(o); } return (A) this; } }
package railo.runtime.type; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInput; import java.io.ObjectOutput; import java.io.Reader; import java.io.StringReader; import java.io.UnsupportedEncodingException; import java.math.BigDecimal; import java.net.URL; import java.sql.Blob; import java.sql.Clob; import java.sql.NClob; import java.sql.PreparedStatement; import java.sql.Ref; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.RowId; import java.sql.SQLException; import java.sql.SQLWarning; import java.sql.SQLXML; import java.sql.Statement; import java.sql.Time; import java.sql.Timestamp; import java.sql.Types; import java.util.Arrays; import java.util.Calendar; import java.util.Comparator; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import railo.commons.db.DBUtil; import railo.commons.io.IOUtil; import railo.commons.lang.SizeOf; import railo.commons.lang.StringUtil; import railo.commons.sql.SQLUtil; import railo.loader.engine.CFMLEngineFactory; import railo.runtime.PageContext; import railo.runtime.converter.ScriptConverter; import railo.runtime.db.CFTypes; import railo.runtime.db.DataSource; import railo.runtime.db.DataSourceUtil; import railo.runtime.db.DatasourceConnection; import railo.runtime.db.DatasourceConnectionImpl; import railo.runtime.db.DatasourceConnectionPro; import railo.runtime.db.SQL; import railo.runtime.db.SQLCaster; import railo.runtime.db.SQLItem; import railo.runtime.dump.DumpData; import railo.runtime.dump.DumpProperties; import railo.runtime.dump.DumpRow; import railo.runtime.dump.DumpTable; import railo.runtime.dump.DumpTablePro; import railo.runtime.dump.DumpUtil; import railo.runtime.dump.SimpleDumpData; import railo.runtime.engine.ThreadLocalPageContext; import railo.runtime.exp.DatabaseException; import railo.runtime.exp.ExpressionException; import railo.runtime.exp.PageException; import railo.runtime.functions.arrays.ArrayFind; import railo.runtime.interpreter.CFMLExpressionInterpreter; import railo.runtime.op.Caster; import railo.runtime.op.Decision; import railo.runtime.op.ThreadLocalDuplication; import railo.runtime.op.date.DateCaster; import railo.runtime.query.caster.Cast; import railo.runtime.reflection.Reflector; import railo.runtime.timer.Stopwatch; import railo.runtime.type.comparator.NumberSortRegisterComparator; import railo.runtime.type.comparator.SortRegister; import railo.runtime.type.comparator.SortRegisterComparator; import railo.runtime.type.dt.DateTime; import railo.runtime.type.dt.DateTimeImpl; import railo.runtime.type.it.CollectionIterator; import railo.runtime.type.it.KeyIterator; import railo.runtime.type.sql.BlobImpl; import railo.runtime.type.sql.ClobImpl; import railo.runtime.type.util.ArrayUtil; import railo.runtime.type.util.CollectionUtil; /** * implementation of the query interface */ public class QueryImpl implements QueryPro,Objects,Sizeable { private static final long serialVersionUID = 1035795427320192551L; /** * @return the template */ public String getTemplate() { return template; } public static final Collection.Key COLUMNS = KeyImpl.intern("COLUMNS"); public static final Collection.Key SQL = KeyImpl.intern("SQL"); public static final Collection.Key EXECUTION_TIME = KeyImpl.intern("executionTime"); public static final Collection.Key RECORDCOUNT = KeyImpl.intern("RECORDCOUNT"); public static final Collection.Key CACHED = KeyImpl.intern("cached"); public static final Collection.Key COLUMNLIST = KeyImpl.intern("COLUMNLIST"); public static final Collection.Key CURRENTROW = KeyImpl.intern("CURRENTROW"); public static final Collection.Key IDENTITYCOL = KeyImpl.intern("IDENTITYCOL"); public static final Collection.Key GENERATED_KEYS = KeyImpl.intern("GENERATED_KEYS"); //private static int count=0; private QueryColumnImpl[] columns; private Collection.Key[] columnNames; private SQL sql; private ArrayInt arrCurrentRow=new ArrayInt(); private int recordcount=0; private int columncount; private long exeTime=0; private boolean isCached=false; private String name; private int updateCount; private QueryImpl generatedKeys; private String template; /** * @return return execution time to get query */ public int executionTime() { return (int) exeTime; } /** * create a QueryImpl from a SQL Resultset * @param result SQL Resultset * @param maxrow * @param name * @throws PageException */ public QueryImpl(ResultSet result, int maxrow, String name) throws PageException { this.name=name; Stopwatch stopwatch=new Stopwatch(); stopwatch.start(); try { fillResult(null,result,maxrow,false,false); } catch (SQLException e) { throw new DatabaseException(e,null); } catch (IOException e) { throw Caster.toPageException(e); } exeTime=stopwatch.time(); } /** * Constructor of the class * only for internal usage (cloning/deserialize) */ public QueryImpl() { } public QueryImpl(ResultSet result, String name) throws PageException { this.name=name; try { fillResult(null,result,-1,true,false); } catch (SQLException e) { throw new DatabaseException(e,null); } catch (Exception e) { throw Caster.toPageException(e); } } /** * constructor of the class, to generate a resultset from a sql query * @param dc Connection to a database * @param name * @param sql sql to execute * @param maxrow maxrow for the resultset * @throws PageException */ public QueryImpl(DatasourceConnection dc,SQL sql,int maxrow, int fetchsize,int timeout, String name) throws PageException { this(dc, sql, maxrow, fetchsize, timeout, name,null,false); } public QueryImpl(DatasourceConnection dc,SQL sql,int maxrow, int fetchsize,int timeout, String name,String template) throws PageException { this(dc, sql, maxrow, fetchsize, timeout, name,template,false); } public QueryImpl(DatasourceConnection dc,SQL sql,int maxrow, int fetchsize,int timeout, String name,String template,boolean createUpdateData) throws PageException { this.name=name; this.template=template; this.sql=sql; //ResultSet result=null; Statement stat=null; // check SQL Restrictions if(dc.getDatasource().hasSQLRestriction()) { checkSQLRestriction(dc,sql); } // check if datasource support Generated Keys boolean createGeneratedKeys=createUpdateData; if(createUpdateData){ DatasourceConnectionImpl dci=(DatasourceConnectionImpl) dc; dci.supportsGetGeneratedKeys(); if(!dci.supportsGetGeneratedKeys())createGeneratedKeys=false; } Stopwatch stopwatch=new Stopwatch(); stopwatch.start(); boolean hasResult=false; boolean closeStatement=true; try { SQLItem[] items=sql.getItems(); if(items.length==0) { stat=dc.getConnection().createStatement(); setAttributes(stat,maxrow,fetchsize,timeout); // some driver do not support second argument hasResult=createGeneratedKeys?stat.execute(sql.getSQLString(),Statement.RETURN_GENERATED_KEYS):stat.execute(sql.getSQLString()); } else { // some driver do not support second argument PreparedStatement preStat = ((DatasourceConnectionPro)dc).getPreparedStatement(sql, createGeneratedKeys); closeStatement=false; stat=preStat; setAttributes(preStat,maxrow,fetchsize,timeout); setItems(preStat,items); hasResult=preStat.execute(); } int uc; ResultSet res; do { if(hasResult) { res=stat.getResultSet(); if(fillResult(dc,res, maxrow, true,createGeneratedKeys))break; } else if((uc=setUpdateCount(stat))!=-1){ if(uc>0 && createGeneratedKeys)setGeneratedKeys(dc, stat); } else break; hasResult=stat.getMoreResults(Statement.CLOSE_CURRENT_RESULT); } while(true); } catch (SQLException e) { throw new DatabaseException(e,sql,dc); } catch (Throwable e) { throw Caster.toPageException(e); } finally { if(closeStatement)DBUtil.closeEL(stat); } exeTime=stopwatch.time(); } private int setUpdateCount(Statement stat) { try{ int uc=stat.getUpdateCount(); if(uc>-1){ updateCount+=uc; return uc; } } catch(Throwable t){} return -1; } private boolean setGeneratedKeys(DatasourceConnection dc,Statement stat) { try{ ResultSet rs = stat.getGeneratedKeys(); setGeneratedKeys(dc, rs); return true; } catch(Throwable t) { return false; } } private void setGeneratedKeys(DatasourceConnection dc,ResultSet rs) throws PageException { generatedKeys=new QueryImpl(rs,""); if(DataSourceUtil.isMSSQL(dc)) generatedKeys.renameEL(GENERATED_KEYS,IDENTITYCOL); } /*private void setUpdateData(Statement stat, boolean createGeneratedKeys, boolean createUpdateCount) { // update Count if(createUpdateCount){ try{ updateCount=stat.getUpdateCount(); } catch(Throwable t){ t.printStackTrace(); } } // generated keys if(createGeneratedKeys){ try{ ResultSet rs = stat.getGeneratedKeys(); generatedKeys=new QueryImpl(rs,""); } catch(Throwable t){ t.printStackTrace(); } } }*/ private void setItems(PreparedStatement preStat, SQLItem[] items) throws DatabaseException, PageException, SQLException { for(int i=0;i<items.length;i++) { SQLCaster.setValue(preStat,i+1,items[i]); } } public int getUpdateCount() { return updateCount; } public Query getGeneratedKeys() { return generatedKeys; } private void setAttributes(Statement stat,int maxrow, int fetchsize,int timeout) throws SQLException { if(maxrow>-1) stat.setMaxRows(maxrow); if(fetchsize>0)stat.setFetchSize(fetchsize); if(timeout>0)stat.setQueryTimeout(timeout); } private ResultSet getResultSetEL(Statement stat) { try { return stat.getResultSet(); } catch(SQLException sqle) { return null; } } /** * check if there is a sql restriction * @param ds * @param sql * @throws PageException */ private static void checkSQLRestriction(DatasourceConnection dc, SQL sql) throws PageException { Array sqlparts = List.listToArrayRemoveEmpty( SQLUtil.removeLiterals(sql.getSQLString()) ," \t"+System.getProperty("line.separator")); //print.ln(List.toStringArray(sqlparts)); DataSource ds = dc.getDatasource(); if(!ds.hasAllow(DataSource.ALLOW_ALTER)) checkSQLRestriction(dc,"alter",sqlparts,sql); if(!ds.hasAllow(DataSource.ALLOW_CREATE)) checkSQLRestriction(dc,"create",sqlparts,sql); if(!ds.hasAllow(DataSource.ALLOW_DELETE)) checkSQLRestriction(dc,"delete",sqlparts,sql); if(!ds.hasAllow(DataSource.ALLOW_DROP)) checkSQLRestriction(dc,"drop",sqlparts,sql); if(!ds.hasAllow(DataSource.ALLOW_GRANT)) checkSQLRestriction(dc,"grant",sqlparts,sql); if(!ds.hasAllow(DataSource.ALLOW_INSERT)) checkSQLRestriction(dc,"insert",sqlparts,sql); if(!ds.hasAllow(DataSource.ALLOW_REVOKE)) checkSQLRestriction(dc,"revoke",sqlparts,sql); if(!ds.hasAllow(DataSource.ALLOW_SELECT)) checkSQLRestriction(dc,"select",sqlparts,sql); if(!ds.hasAllow(DataSource.ALLOW_UPDATE)) checkSQLRestriction(dc,"update",sqlparts,sql); } private static void checkSQLRestriction(DatasourceConnection dc, String keyword, Array sqlparts, SQL sql) throws PageException { if(ArrayFind.find(sqlparts,keyword,false)>0) { throw new DatabaseException("access denied to execute \""+StringUtil.ucFirst(keyword)+"\" SQL statment for datasource "+dc.getDatasource().getName(),null,sql,dc); } } private boolean fillResult(DatasourceConnection dc, ResultSet result, int maxrow, boolean closeResult,boolean createGeneratedKeys) throws SQLException, IOException, PageException { if(result==null) return false; recordcount=0; ResultSetMetaData meta = result.getMetaData(); columncount=meta.getColumnCount(); // set header arrays Collection.Key[] tmpColumnNames = new Collection.Key[columncount]; int count=0; Collection.Key key; String columnName; for(int i=0;i<columncount;i++) { columnName=meta.getColumnName(i+1); if(StringUtil.isEmpty(columnName))columnName="column_"+i; key=KeyImpl.init(columnName); int index=getIndexFrom(tmpColumnNames,key,0,i); if(index==-1) { tmpColumnNames[i]=key; count++; } } columncount=count; columnNames=new Collection.Key[columncount]; columns=new QueryColumnImpl[columncount]; Cast[] casts = new Cast[columncount]; // get all used ints int[] usedColumns=new int[columncount]; count=0; for(int i=0;i<tmpColumnNames.length;i++) { if(tmpColumnNames[i]!=null) { usedColumns[count++]=i; } } // set used column names int[] types=new int[columns.length]; for(int i=0;i<usedColumns.length;i++) { columnNames[i]=tmpColumnNames[usedColumns[i]]; columns[i]=new QueryColumnImpl(this,columnNames[i],types[i]=meta.getColumnType(usedColumns[i]+1)); if(types[i]==Types.TIMESTAMP) casts[i]=Cast.TIMESTAMP; else if(types[i]==Types.TIME) casts[i]=Cast.TIME; else if(types[i]==Types.DATE) casts[i]=Cast.DATE; else if(types[i]==Types.CLOB) casts[i]=Cast.CLOB; else if(types[i]==Types.BLOB) casts[i]=Cast.BLOB; else if(types[i]==Types.BIT) casts[i]=Cast.BIT; else if(types[i]==Types.ARRAY) casts[i]=Cast.ARRAY; //else if(types[i]==Types.TINYINT) casts[i]=Cast.ARRAY; else if(types[i]==CFTypes.OPAQUE){ if(SQLUtil.isOracle(result.getStatement().getConnection())) casts[i]=Cast.ORACLE_OPAQUE; else casts[i]=Cast.OTHER; } else casts[i]=Cast.OTHER; } if(createGeneratedKeys && columncount==1 && columnNames[0].equals(GENERATED_KEYS) && dc!=null && DataSourceUtil.isMSSQLDriver(dc)) { columncount=0; columnNames=null; columns=null; setGeneratedKeys(dc, result); return false; } // fill data //Object o; while(result.next()) { if(maxrow>-1 && recordcount>=maxrow) { break; } for(int i=0;i<usedColumns.length;i++) { columns[i].add(casts[i].toCFType(types[i], result, usedColumns[i]+1)); } ++recordcount; } if(closeResult)result.close(); return true; } private Object toBytes(Blob blob) throws IOException, SQLException { return IOUtil.toBytes((blob).getBinaryStream()); } private static Object toString(Clob clob) throws IOException, SQLException { return IOUtil.toString(clob.getCharacterStream()); } private int getIndexFrom(Collection.Key[] tmpColumnNames, Collection.Key key, int from, int to) { for(int i=from;i<to;i++) { if(tmpColumnNames[i]!=null && tmpColumnNames[i].equalsIgnoreCase(key))return i; } return -1; } /** * constructor of the class, to generate a empty resultset (no database execution) * @param strColumns columns for the resultset * @param rowNumber count of rows to generate (empty fields) * @param name */ public QueryImpl(String[] strColumns, int rowNumber,String name) { this.name=name; columncount=strColumns.length; recordcount=rowNumber; columnNames=new Collection.Key[columncount]; columns=new QueryColumnImpl[columncount]; for(int i=0;i<strColumns.length;i++) { columnNames[i]=KeyImpl.init(strColumns[i].trim()); columns[i]=new QueryColumnImpl(this,columnNames[i],Types.OTHER,recordcount); } } /** * constructor of the class, to generate a empty resultset (no database execution) * @param strColumns columns for the resultset * @param rowNumber count of rows to generate (empty fields) * @param name */ public QueryImpl(Collection.Key[] columnKeys, int rowNumber,String name) { this.name=name; columncount=columnKeys.length; recordcount=rowNumber; columnNames=new Collection.Key[columncount]; columns=new QueryColumnImpl[columncount]; for(int i=0;i<columnKeys.length;i++) { columnNames[i]=columnKeys[i]; columns[i]=new QueryColumnImpl(this,columnNames[i],Types.OTHER,recordcount); } } /** * constructor of the class, to generate a empty resultset (no database execution) * @param strColumns columns for the resultset * @param strTypes array of the types * @param rowNumber count of rows to generate (empty fields) * @param name * @throws DatabaseException */ public QueryImpl(String[] strColumns, String[] strTypes, int rowNumber, String name) throws DatabaseException { this.name=name; columncount=strColumns.length; if(strTypes.length!=columncount) throw new DatabaseException("columns and types has not the same count",null,null,null); recordcount=rowNumber; columnNames=new Collection.Key[columncount]; columns=new QueryColumnImpl[columncount]; for(int i=0;i<strColumns.length;i++) { columnNames[i]=KeyImpl.init(strColumns[i].trim()); columns[i]=new QueryColumnImpl(this,columnNames[i],SQLCaster.toIntType(strTypes[i]),recordcount); } } /** * constructor of the class, to generate a empty resultset (no database execution) * @param strColumns columns for the resultset * @param strTypes array of the types * @param rowNumber count of rows to generate (empty fields) * @param name * @throws DatabaseException */ public QueryImpl(Collection.Key[] columnNames, String[] strTypes, int rowNumber, String name) throws DatabaseException { this.name=name; this.columnNames=columnNames; columncount=columnNames.length; if(strTypes.length!=columncount) throw new DatabaseException("columns and types has not the same count",null,null,null); recordcount=rowNumber; columns=new QueryColumnImpl[columncount]; for(int i=0;i<columnNames.length;i++) { columns[i]=new QueryColumnImpl(this,columnNames[i],SQLCaster.toIntType(strTypes[i]),recordcount); } } /** * constructor of the class, to generate a empty resultset (no database execution) * @param arrColumns columns for the resultset * @param rowNumber count of rows to generate (empty fields) * @param name */ public QueryImpl(Array arrColumns, int rowNumber, String name) { this.name=name; columncount=arrColumns.size(); recordcount=rowNumber; columnNames=new Collection.Key[columncount]; columns=new QueryColumnImpl[columncount]; for(int i=0;i<columncount;i++) { columnNames[i]=KeyImpl.init(arrColumns.get(i+1,"").toString().trim()); columns[i]=new QueryColumnImpl(this,columnNames[i],Types.OTHER,recordcount); } } /** * constructor of the class, to generate a empty resultset (no database execution) * @param arrColumns columns for the resultset * @param arrTypes type of the columns * @param rowNumber count of rows to generate (empty fields) * @param name * @throws PageException */ public QueryImpl(Array arrColumns, Array arrTypes, int rowNumber, String name) throws PageException { this.name=name; columncount=arrColumns.size(); if(arrTypes.size()!=columncount) throw new DatabaseException("columns and types has not the same count",null,null,null); recordcount=rowNumber; columnNames=new Collection.Key[columncount]; columns=new QueryColumnImpl[columncount]; for(int i=0;i<columncount;i++) { columnNames[i]=KeyImpl.init(arrColumns.get(i+1,"").toString().trim()); columns[i]=new QueryColumnImpl(this,columnNames[i],SQLCaster.toIntType(Caster.toString(arrTypes.get(i+1,""))),recordcount); } } /** * constructor of the class * @param columnNames columns definition as String Array * @param arrColumns values * @param name * @throws DatabaseException */ public QueryImpl(String[] strColumnNames, Array[] arrColumns, String name) throws DatabaseException { this(_toKeys(strColumnNames),arrColumns,name); } private static Collection.Key[] _toKeys(String[] strColumnNames) { Collection.Key[] columnNames=new Collection.Key[strColumnNames.length]; for(int i=0 ;i<columnNames.length;i++) { columnNames[i]=KeyImpl.init(strColumnNames[i].trim()); } return columnNames; } private static String[] _toStringKeys(Collection.Key[] columnNames) { String[] strColumnNames=new String[columnNames.length]; for(int i=0 ;i<strColumnNames.length;i++) { strColumnNames[i]=columnNames[i].getString(); } return strColumnNames; } /*public QueryImpl(Collection.Key[] columnNames, QueryColumn[] columns, String name,long exeTime, boolean isCached,SQL sql) throws DatabaseException { this.columnNames=columnNames; this.columns=columns; this.exeTime=exeTime; this.isCached=isCached; this.name=name; this.columncount=columnNames.length; this.recordcount=columns.length==0?0:columns[0].size(); this.sql=sql; }*/ public QueryImpl(Collection.Key[] columnNames, Array[] arrColumns, String name) throws DatabaseException { this.name=name; if(columnNames.length!=arrColumns.length) throw new DatabaseException("invalid parameter for query, not the same count from names and columns","names:"+columnNames.length+";columns:"+arrColumns.length,null,null,null); int len=0; columns=new QueryColumnImpl[arrColumns.length]; if(arrColumns.length>0) { // test columns len=arrColumns[0].size(); for(int i=0;i<arrColumns.length;i++) { if(arrColumns[i].size()!=len) throw new DatabaseException("invalid parameter for query, all columns must have the same size","column[1]:"+len+"<>column["+(i+1)+"]:"+arrColumns[i].size(),null,null,null); //columns[i]=new QueryColumnTypeFlex(arrColumns[i]); columns[i]=new QueryColumnImpl(this,columnNames[i],arrColumns[i],Types.OTHER); } // test keys Map testMap=new HashMap(); for(int i=0 ;i<columnNames.length;i++) { if(!Decision.isSimpleVariableName(columnNames[i])) throw new DatabaseException("invalid column name ["+columnNames[i]+"] for query", "column names must start with a letter and can be followed by letters numbers and underscores [_]. RegExp:[a-zA-Z][a-zA-Z0-9_]*",null,null,null); if(testMap.containsKey(columnNames[i].getLowerString())) throw new DatabaseException("invalid parameter for query, ambiguous column name "+columnNames[i],"columnNames: "+List.arrayToListTrim( _toStringKeys(columnNames),","),null,null,null); testMap.put(columnNames[i].getLowerString(),"set"); } } columncount=columns.length; recordcount=len; this.columnNames=columnNames; } /** * constructor of the class * @param columnList * @param data * @param name */ public QueryImpl(String[] strColumnList, Object[][] data,String name) { this(toCollKeyArr(strColumnList),data.length,name); for(int iRow=0;iRow<data.length;iRow++) { Object[] row=data[iRow]; for(int iCol=0;iCol<row.length;iCol++) { //print.ln(columnList[iCol]+":"+iRow+"="+row[iCol]); setAtEL(columnNames[iCol],iRow+1,row[iCol]); } } } private static Collection.Key[] toCollKeyArr(String[] strColumnList) { Collection.Key[] columnList=new Collection.Key[strColumnList.length]; for(int i=0 ;i<columnList.length;i++) { columnList[i]=KeyImpl.init(strColumnList[i].trim()); } return columnList; } /** * @see railo.runtime.type.Collection#size() */ public int size() { return columncount; } /** * @see railo.runtime.type.Collection#keys() */ public Collection.Key[] keys() { return columnNames; } /** * @see railo.runtime.type.Collection#keysAsString() */ public String[] keysAsString() { return toString(columnNames); } private String[] toString(Collection.Key[] keys) { if(keys==null) return new String[0]; String[] strKeys=new String[keys.length]; for(int i=0 ;i<columns.length;i++) { strKeys[i]=keys[i].getString(); } return strKeys; } /** * @see railo.runtime.type.Collection#removeEL(java.lang.String) */ public synchronized Object removeEL(String key) { return setEL(key,null); /*int index=getIndexFromKey(key); if(index!=-1) _removeEL(index); return null;*/ } /** * @see railo.runtime.type.Collection#removeEL(railo.runtime.type.Collection.Key) */ public Object removeEL(Collection.Key key) { return setEL(key,null); /*int index=getIndexFromKey(key); if(index!=-1) return _removeEL(index); return null;*/ } /*private QueryColumn _removeEL(int index) { QueryColumnImpl[] qc=new QueryColumnImpl[--columncount]; Collection.Key[] names=new Collection.Key[columncount]; int count=0; QueryColumn removed=null; for(int i=0;i<columns.length;i++) { if(index!=i){ names[count]=columnNames[i]; qc[count++]=columns[i]; } else { removed=columns[i]; } } columnNames=names; columns=qc; return removed; }*/ /** * @see railo.runtime.type.Collection#remove(java.lang.String) */ public synchronized Object remove(String key) throws PageException { return set(key,null); /*int index=getIndexFromKey(key); if(index!=-1) return _removeEL(index); throw new ExpressionException("can't remove column with name ["+key+"], column doesn't exist");*/ } /** * @throws PageException * @see railo.runtime.type.Collection#remove(railo.runtime.type.Collection.Key) */ public Object remove(Collection.Key key) throws PageException { return set(key,null); /*int index=getIndexFromKey(key); if(index!=-1) return _removeEL(index); throw new ExpressionException("can't remove column with name ["+key+"], column doesn't exist");*/ } /** * @see railo.runtime.type.Collection#clear() */ public void clear() { for(int i=0;i<columns.length;i++) { columns[i].clear(); } recordcount=0; //columns=new QueryColumnImpl[0]; //columnNames=new Collection.Key[0]; //columncount=0; } /** * * @see railo.runtime.type.Collection#get(java.lang.String, java.lang.Object) */ public Object get(String key, Object defaultValue) { return getAt(key, arrCurrentRow.get(getPid(), 1), defaultValue); } //private static int pidc=0; private int getPid() { PageContext pc = ThreadLocalPageContext.get(); if(pc==null) { pc=CFMLEngineFactory.getInstance().getThreadPageContext(); if(pc==null)throw new RuntimeException("cannot get pid for current thread"); } return pc.getId(); } /** * * @see railo.runtime.type.Collection#get(railo.runtime.type.Collection.Key, java.lang.Object) */ public Object get(Collection.Key key, Object defaultValue) { return getAt(key, arrCurrentRow.get(getPid(), 1), defaultValue); } /** * @see railo.runtime.type.Collection#get(java.lang.String) */ public Object get(String key) throws PageException { return getAt(key, arrCurrentRow.get(getPid(), 1) ); } /** * @see railo.runtime.type.Collection#get(railo.runtime.type.Collection.Key) */ public Object get(Collection.Key key) throws PageException { return getAt(key, arrCurrentRow.get(getPid(), 1) ); } /** * * @see railo.runtime.type.Query#getAt(java.lang.String, int, java.lang.Object) */ public Object getAt(String key, int row, Object defaultValue) { int index=getIndexFromKey(key); if(index!=-1) { return columns[index].get(row,defaultValue); } if(key.length()>0) { char c=key.charAt(0); if(c=='r' || c=='R') { if(key.equalsIgnoreCase("recordcount")) return new Double(getRecordcount()); } if(c=='c' || c=='C') { if(key.equalsIgnoreCase("currentrow")) return new Double(row); else if(key.equalsIgnoreCase("columnlist")) return getColumnlist(true); } } return null; } public Object getAt(Collection.Key key, int row, Object defaultValue) { int index=getIndexFromKey(key); if(index!=-1) { return columns[index].get(row,defaultValue); } if(key.getString().length()>0) { char c=key.lowerCharAt(0); if(c=='r') { if(key.equals(RECORDCOUNT)) return new Double(getRecordcount()); } else if(c=='c') { if(key.equals(CURRENTROW)) return new Double(row); else if(key.equals(COLUMNLIST)) return getColumnlist(true); } } return null; } /** * @see railo.runtime.type.Query#getAt(java.lang.String, int) */ public Object getAt(String key, int row) throws PageException { //print.err("str:"+key); int index=getIndexFromKey(key); if(index!=-1) { return columns[index].get(row); } if(key.length()>0){ char c=key.charAt(0); if(c=='r' || c=='R') { if(key.equalsIgnoreCase("recordcount")) return new Double(getRecordcount()); } else if(c=='c' || c=='C') { if(key.equalsIgnoreCase("currentrow")) return new Double(row); else if(key.equalsIgnoreCase("columnlist")) return getColumnlist(true); } } throw new DatabaseException("column ["+key+"] not found in query, columns are ["+getColumnlist(false)+"]",null,sql,null); } /** * @see railo.runtime.type.Query#getAt(railo.runtime.type.Collection.Key, int) */ public Object getAt(Collection.Key key, int row) throws PageException { int index=getIndexFromKey(key); if(index!=-1) { return columns[index].get(row); } if(key.getString().length()>0) { char c=key.lowerCharAt(0); if(c=='r') { if(key.equals(RECORDCOUNT)) return new Double(getRecordcount()); } else if(c=='c') { if(key.equals(CURRENTROW)) return new Double(row); else if(key.equals(COLUMNLIST)) return getColumnlist(true); } } throw new DatabaseException("column ["+key+"] not found in query, columns are ["+getColumnlist(false)+"]",null,sql,null); } /** * @see railo.runtime.type.Query#removeRow(int) */ public synchronized int removeRow(int row) throws PageException { //disconnectCache(); for(int i=0;i<columns.length;i++) { columns[i].removeRow(row); } return --recordcount; } /** * @see railo.runtime.type.Query#removeRowEL(int) */ public int removeRowEL(int row) { //disconnectCache(); try { return removeRow(row); } catch (PageException e) { return recordcount; } } /** * @see railo.runtime.type.Query#removeColumn(java.lang.String) */ public QueryColumn removeColumn(String key) throws DatabaseException { //disconnectCache(); QueryColumn removed = removeColumnEL(key); if(removed==null) { if(key.equalsIgnoreCase("recordcount") || key.equalsIgnoreCase("currentrow") || key.equalsIgnoreCase("columnlist")) throw new DatabaseException("can't remove "+key+" this is not a row","existing rows are ["+getColumnlist(false)+"]",null,null,null); throw new DatabaseException("can't remove row ["+key+"], this row doesn't exist", "existing rows are ["+getColumnlist(false)+"]",null,null,null); } return removed; } /** * @see railo.runtime.type.Query#removeColumn(railo.runtime.type.Collection.Key) */ public QueryColumn removeColumn(Collection.Key key) throws PageException { //disconnectCache(); QueryColumn removed = removeColumnEL(key); if(removed==null) { if(key.equals(RECORDCOUNT) || key.equals(CURRENTROW) || key.equals(COLUMNLIST)) throw new DatabaseException("can't remove "+key+" this is not a row","existing rows are ["+getColumnlist(false)+"]",null,null,null); throw new DatabaseException("can't remove row ["+key+"], this row doesn't exist", "existing rows are ["+getColumnlist(false)+"]",null,null,null); } return removed; } /** * @see railo.runtime.type.Query#removeColumnEL(java.lang.String) */ public synchronized QueryColumn removeColumnEL(String key) { //disconnectCache(); int index=getIndexFromKey(key); if(index!=-1) { int current=0; QueryColumn removed=null; Collection.Key[] newColumnNames=new Collection.Key[columnNames.length-1]; QueryColumnImpl[] newColumns=new QueryColumnImpl[columns.length-1]; for(int i=0;i<columns.length;i++) { if(i==index) { removed=columns[i]; } else { newColumnNames[current]=columnNames[i]; newColumns[current++]=columns[i]; } } columnNames=newColumnNames; columns=newColumns; columncount return removed; } return null; } public QueryColumn removeColumnEL(Collection.Key key) { //disconnectCache(); int index=getIndexFromKey(key); if(index!=-1) { int current=0; QueryColumn removed=null; Collection.Key[] newColumnNames=new Collection.Key[columnNames.length-1]; QueryColumnImpl[] newColumns=new QueryColumnImpl[columns.length-1]; for(int i=0;i<columns.length;i++) { if(i==index) { removed=columns[i]; } else { newColumnNames[current]=columnNames[i]; newColumns[current++]=columns[i]; } } columnNames=newColumnNames; columns=newColumns; columncount return removed; } return null; } /** * @see railo.runtime.type.Collection#setEL(java.lang.String, java.lang.Object) */ public Object setEL(String key, Object value) { return setAtEL(key, arrCurrentRow.get(getPid(), 1), value); } /** * @see railo.runtime.type.Collection#setEL(railo.runtime.type.Collection.Key, java.lang.Object) */ public Object setEL(Collection.Key key, Object value) { return setAtEL(key, arrCurrentRow.get(getPid(), 1), value); } /** * @see railo.runtime.type.Collection#set(java.lang.String, java.lang.Object) */ public Object set(String key, Object value) throws PageException { return setAt(key, arrCurrentRow.get(getPid(), 1), value); } /** * @see railo.runtime.type.Collection#set(railo.runtime.type.Collection.Key, java.lang.Object) */ public Object set(Collection.Key key, Object value) throws PageException { return setAt(key, arrCurrentRow.get(getPid(), 1), value); } /** * @see railo.runtime.type.Query#setAt(java.lang.String, int, java.lang.Object) */ public Object setAt(String key,int row, Object value) throws PageException { //disconnectCache(); int index=getIndexFromKey(key); if(index!=-1) { return columns[index].set(row,value); } throw new DatabaseException("column ["+key+"] does not exist","columns are ["+getColumnlist(false)+"]",null,sql,null); } public Object setAt(Collection.Key key, int row, Object value) throws PageException { //disconnectCache(); int index=getIndexFromKey(key); if(index!=-1) { return columns[index].set(row,value); } throw new DatabaseException("column ["+key+"] does not exist","columns are ["+getColumnlist(false)+"]",null,sql,null); } /** * @see railo.runtime.type.Query#setAtEL(java.lang.String, int, java.lang.Object) */ public Object setAtEL(String key,int row, Object value) { //disconnectCache(); int index=getIndexFromKey(key); if(index!=-1) { return columns[index].setEL(row,value); } return null; } public Object setAtEL(Collection.Key key, int row, Object value) { //disconnectCache(); int index=getIndexFromKey(key); if(index!=-1) { return columns[index].setEL(row,value); } return null; } /** * @see railo.runtime.type.Iterator#next() */ public boolean next() { return next(getPid()); } /** * @see railo.runtime.type.Iterator#next(int) */ public boolean next(int pid) { if(recordcount>=(arrCurrentRow.set(pid,arrCurrentRow.get(pid,0)+1))) { return true; } arrCurrentRow.set(pid,0); return false; } /** * @see railo.runtime.type.Iterator#reset() */ public void reset() { reset(getPid()); } public void reset(int pid) { arrCurrentRow.set(pid,0); } /** * @see railo.runtime.type.Iterator#getRecordcount() */ public int getRecordcount() { return recordcount; } /** * @see railo.runtime.type.Iterator#getCurrentrow() * FUTURE set this to deprectaed */ public int getCurrentrow() { return getCurrentrow(getPid()); } /** * @see railo.runtime.type.QueryPro#getCurrentrow(int) */ public int getCurrentrow(int pid) { return arrCurrentRow.get(pid,1); } /** * return a string list of all columns * @return string list */ public String getColumnlist(boolean upperCase) { StringBuffer sb=new StringBuffer(); for(int i=0;i<columnNames.length;i++) { if(i>0)sb.append(','); sb.append(upperCase?columnNames[i].getString().toUpperCase():columnNames[i].getString());// FUTURE getUpperString } return sb.toString(); } public String getColumnlist() { return getColumnlist(true); } /** * @deprecated use instead go(int,int) * @see railo.runtime.type.Iterator#go(int) */ public boolean go(int index) { return go(index,getPid()); } public boolean go(int index, int pid) { if(index>0 && index<=recordcount) { arrCurrentRow.set(pid, index); return true; } arrCurrentRow.set(pid, 0); return false; } /** * @see railo.runtime.type.Iterator#isEmpty() */ public boolean isEmpty() { return recordcount+columncount==0; } /** * @see railo.runtime.dump.Dumpable#toDumpData(railo.runtime.PageContext, int) */ public DumpData toDumpData(PageContext pageContext, int maxlevel, DumpProperties dp) { maxlevel String[] keys=keysAsString(); DumpData[] heads=new DumpData[keys.length+1]; //int tmp=1; heads[0]=new SimpleDumpData(""); for(int i=0;i<keys.length;i++) { heads[i+1]=new SimpleDumpData(keys[i]); } StringBuilder comment=new StringBuilder(); //table.appendRow(1, new SimpleDumpData("SQL"), new SimpleDumpData(sql.toString())); if(!StringUtil.isEmpty(template)) comment.append("Template:").append(template).append("\n"); //table.appendRow(1, new SimpleDumpData("Template"), new SimpleDumpData(template)); comment.append("Execution Time (ms):").append(Caster.toString(exeTime)).append("\n"); comment.append("Recordcount:").append(Caster.toString(getRecordcount())).append("\n"); comment.append("Cached:").append(isCached()?"Yes\n":"No\n"); if(sql!=null) comment.append("SQL:").append("\n").append(StringUtil.suppressWhiteSpace(sql.toString().trim())).append("\n"); //table.appendRow(1, new SimpleDumpData("Execution Time (ms)"), new SimpleDumpData(exeTime)); //table.appendRow(1, new SimpleDumpData("recordcount"), new SimpleDumpData(getRecordcount())); //table.appendRow(1, new SimpleDumpData("cached"), new SimpleDumpData(isCached()?"Yes":"No")); DumpTable recs=new DumpTablePro("query","#cc99cc","#ffccff","#000000"); recs.setTitle("Query"); if(dp.getMetainfo())recs.setComment(comment.toString()); recs.appendRow(new DumpRow(-1,heads)); // body DumpData[] items; for(int i=0;i<recordcount;i++) { items=new DumpData[columncount+1]; items[0]=new SimpleDumpData(i+1); for(int y=0;y<keys.length;y++) { try { Object o=getAt(keys[y],i+1); if(o instanceof String)items[y+1]=new SimpleDumpData(o.toString()); else if(o instanceof Number) items[y+1]=new SimpleDumpData(Caster.toString(((Number)o).doubleValue())); else if(o instanceof Boolean) items[y+1]=new SimpleDumpData(((Boolean)o).booleanValue()); else if(o instanceof Date) items[y+1]=new SimpleDumpData(Caster.toString(o)); else if(o instanceof Clob) items[y+1]=new SimpleDumpData(Caster.toString(o)); else items[y+1]=DumpUtil.toDumpData(o, pageContext,maxlevel,dp); } catch (PageException e) { items[y+1]=new SimpleDumpData("[empty]"); } } recs.appendRow(new DumpRow(1,items)); } if(!dp.getMetainfo()) return recs; //table.appendRow(1, new SimpleDumpData("result"), recs); return recs; } /** * sorts a query by a column * @param column colun to sort * @throws PageException */ public void sort(String column) throws PageException { sort(column,Query.ORDER_ASC); } /** * @see railo.runtime.type.Query#sort(railo.runtime.type.Collection.Key) */ public void sort(Collection.Key column) throws PageException { sort(column,Query.ORDER_ASC); } /** * sorts a query by a column * @param strColumn column to sort * @param order sort type (Query.ORDER_ASC or Query.ORDER_DESC) * @throws PageException */ public synchronized void sort(String strColumn, int order) throws PageException { //disconnectCache(); sort(getColumn(strColumn),order); } /** * @see railo.runtime.type.Query#sort(railo.runtime.type.Collection.Key, int) */ public synchronized void sort(Collection.Key keyColumn, int order) throws PageException { //disconnectCache(); sort(getColumn(keyColumn),order); } private void sort(QueryColumn column, int order) throws PageException { int type = column.getType(); SortRegister[] arr= ArrayUtil.toSortRegisterArray(column); Arrays.sort(arr, ( type==Types.BIGINT || type==Types.BIT || type==Types.INTEGER || type==Types.SMALLINT || type==Types.TINYINT || type==Types.DECIMAL || type==Types.DOUBLE || type==Types.NUMERIC || type==Types.REAL)? (Comparator)new NumberSortRegisterComparator(order==ORDER_ASC):(Comparator)new SortRegisterComparator(order==ORDER_ASC,true) ); for(int i=0;i<columns.length;i++) { column=columns[i]; int len=column.size(); QueryColumnImpl newCol=new QueryColumnImpl(this,columnNames[i],columns[i].getType(),len); for(int y=1;y<=len;y++) { newCol.set(y,column.get(arr[y-1].getOldPosition()+1)); } columns[i]=newCol; } } /** * @see railo.runtime.type.Query#addRow(int) */ public synchronized boolean addRow(int count) { //disconnectCache(); for(int i=0;i<columns.length;i++) { QueryColumnImpl column = columns[i]; column.addRow(count); } recordcount+=count; return true; } /** * @see railo.runtime.type.Query#addColumn(java.lang.String, railo.runtime.type.Array) */ public boolean addColumn(String columnName, Array content) throws DatabaseException { return addColumn(columnName,content,Types.OTHER); } public boolean addColumn(Collection.Key columnName, Array content) throws PageException { return addColumn(columnName,content,Types.OTHER); } /** * @throws DatabaseException * @see railo.runtime.type.Query#addColumn(java.lang.String, railo.runtime.type.Array, int) */ public synchronized boolean addColumn(String columnName, Array content, int type) throws DatabaseException { return addColumn(KeyImpl.init(columnName.trim()), content, type); } /** * @see railo.runtime.type.Query#addColumn(railo.runtime.type.Collection.Key, railo.runtime.type.Array, int) */ public boolean addColumn(Collection.Key columnName, Array content, int type) throws DatabaseException { //disconnectCache(); // TODO Meta type content=(Array) content.duplicate(false); if(getIndexFromKey(columnName)!=-1) throw new DatabaseException("column name ["+columnName.getString()+"] already exist",null,sql,null); if(content.size()!=getRecordcount()) { //throw new DatabaseException("array for the new column has not the same size like the query (arrayLen!=query.recordcount)"); if(content.size()>getRecordcount()) addRow(content.size()-getRecordcount()); else content.setEL(getRecordcount(),""); } QueryColumnImpl[] newColumns=new QueryColumnImpl[columns.length+1]; Collection.Key[] newColumnNames=new Collection.Key[columns.length+1]; for(int i=0;i<columns.length;i++) { newColumns[i]=columns[i]; newColumnNames[i]=columnNames[i]; } newColumns[columns.length]=new QueryColumnImpl(this,columnName,content,type ); newColumnNames[columns.length]=columnName; columns=newColumns; columnNames=newColumnNames; columncount++; return true; } /* * * if this query is still connected with cache (same query also in cache) * it will disconnetd from cache (clone object and add clone to cache) */ //protected void disconnectCache() {} /** * @see railo.runtime.type.Query#clone() */ public Object clone() { return cloneQuery(true); } /** * @see railo.runtime.type.Collection#duplicate(boolean) */ public Collection duplicate(boolean deepCopy) { return cloneQuery(true); } /** * @return clones the query object */ public QueryImpl cloneQuery(boolean deepCopy) { QueryImpl newResult=new QueryImpl(); ThreadLocalDuplication.set(this, newResult); try{ if(columnNames!=null){ newResult.columnNames=new Collection.Key[columnNames.length]; newResult.columns=new QueryColumnImpl[columnNames.length]; for(int i=0;i<columnNames.length;i++) { newResult.columnNames[i]=columnNames[i]; newResult.columns[i]=columns[i].cloneColumn(newResult,deepCopy); } } newResult.sql=sql; newResult.template=template; newResult.recordcount=recordcount; newResult.columncount=columncount; newResult.isCached=isCached; newResult.name=name; newResult.exeTime=exeTime; newResult.updateCount=updateCount; if(generatedKeys!=null)newResult.generatedKeys=generatedKeys.cloneQuery(false); return newResult; } finally { ThreadLocalDuplication.remove(this); } } /** * @see railo.runtime.type.Query#getTypes() */ public synchronized int[] getTypes() { int[] types=new int[columns.length]; for(int i=0;i<columns.length;i++) { types[i]=columns[i].getType(); } return types; } /** * @see railo.runtime.type.Query#getTypesAsMap() */ public synchronized Map getTypesAsMap() { Map map=new HashMap(); for(int i=0;i<columns.length;i++) { map.put(columnNames[i],columns[i].getTypeAsString()); } return map; } /** * @see railo.runtime.type.Query#getColumn(java.lang.String) */ public QueryColumn getColumn(String key) throws DatabaseException { return getColumn(KeyImpl.init(key.trim())); } /** * @see railo.runtime.type.Query#getColumn(railo.runtime.type.Collection.Key) */ public QueryColumn getColumn(Collection.Key key) throws DatabaseException { int index=getIndexFromKey(key); if(index!=-1) return columns[index]; if(key.getString().length()>0) { char c=key.lowerCharAt(0); if(c=='r') { if(key.equals(RECORDCOUNT)) return new QueryColumnRef(this,key,Types.INTEGER); } if(c=='c') { if(key.equals(CURRENTROW)) return new QueryColumnRef(this,key,Types.INTEGER); else if(key.equals(COLUMNLIST)) return new QueryColumnRef(this,key,Types.INTEGER); } } throw new DatabaseException("key ["+key.getString()+"] not found in query, columns are ["+getColumnlist(false)+"]",null,sql,null); } private void renameEL(Collection.Key src, Collection.Key trg) { int index=getIndexFromKey(src); if(index!=-1){ columnNames[index]=trg; columns[index].setKey(trg); } } public synchronized void rename(Collection.Key columnName,Collection.Key newColumnName) throws ExpressionException { int index=getIndexFromKey(columnName); if(index==-1) throw new ExpressionException("invalid column name definitions"); columnNames[index]=newColumnName; columns[index].setKey(newColumnName); } /** * * @see railo.runtime.type.Query#getColumn(java.lang.String, railo.runtime.type.QueryColumn) */ public QueryColumn getColumn(String key, QueryColumn defaultValue) { return getColumn(KeyImpl.init(key.trim()),defaultValue); } /** * @see railo.runtime.type.Query#getColumn(railo.runtime.type.Collection.Key, railo.runtime.type.QueryColumn) */ public QueryColumn getColumn(Collection.Key key, QueryColumn defaultValue) { int index=getIndexFromKey(key); if(index!=-1) return columns[index]; if(key.getString().length()>0) {//FUTURE add length method to Key Interface char c=key.lowerCharAt(0); if(c=='r') { if(key.equals(RECORDCOUNT)) return new QueryColumnRef(this,key,Types.INTEGER); } if(c=='c') { if(key.equals(CURRENTROW)) return new QueryColumnRef(this,key,Types.INTEGER); else if(key.equals(COLUMNLIST)) return new QueryColumnRef(this,key,Types.INTEGER); } } return defaultValue; } /** * @see java.lang.Object#toString() */ public String toString() { String[] keys=keysAsString(); StringBuffer sb=new StringBuffer(); sb.append("Query\n"); sb.append(" if(sql!=null) { sb.append(sql+"\n"); sb.append(" } if(exeTime>0) { sb.append("Execution Time: "+exeTime+"\n"); sb.append(" } sb.append("Recordcount: "+getRecordcount()+"\n"); sb.append(" String trenner=""; for(int i=0;i<keys.length;i++) { trenner+="+ } trenner+="+\n"; sb.append(trenner); // Header for(int i=0;i<keys.length;i++) { sb.append(getToStringField(keys[i])); } sb.append("|\n"); sb.append(trenner); sb.append(trenner); // body for(int i=0;i<recordcount;i++) { for(int y=0;y<keys.length;y++) { try { Object o=getAt(keys[y],i+1); if(o instanceof String)sb.append(getToStringField(o.toString())); else if(o instanceof Number) sb.append(getToStringField(Caster.toString(((Number)o).doubleValue()))); else if(o instanceof Clob) sb.append(getToStringField(Caster.toString(o))); else sb.append(getToStringField(o.toString())); } catch (PageException e) { sb.append(getToStringField("[empty]")); } } sb.append("|\n"); sb.append(trenner); } return sb.toString(); } private String getToStringField(String str) { if(str==null) return "| "; else if(str.length()<21) { String s="|"+str; for(int i=str.length();i<21;i++)s+=" "; return s; } else if(str.length()==21) return "|"+str; else return "|"+str.substring(0,18)+"..."; } /** * * @param type * @return return String represetation of a Type from int type */ public static String getColumTypeName(int type) { switch(type) { case Types.ARRAY: return "OBJECT"; case Types.BIGINT: return "BIGINT"; case Types.BINARY: return "BINARY"; case Types.BIT: return "BIT"; case Types.BLOB: return "OBJECT"; case Types.BOOLEAN: return "BOOLEAN"; case Types.CHAR: return "CHAR"; case Types.NCHAR: return "NCHAR"; case Types.CLOB: return "OBJECT"; case Types.NCLOB: return "OBJECT"; case Types.DATALINK: return "OBJECT"; case Types.DATE: return "DATE"; case Types.DECIMAL: return "DECIMAL"; case Types.DISTINCT: return "OBJECT"; case Types.DOUBLE: return "DOUBLE"; case Types.FLOAT: return "DOUBLE"; case Types.INTEGER: return "INTEGER"; case Types.JAVA_OBJECT: return "OBJECT"; case Types.LONGVARBINARY: return "LONGVARBINARY"; case Types.LONGVARCHAR: return "LONGVARCHAR"; case Types.NULL: return "OBJECT"; case Types.NUMERIC: return "NUMERIC"; case Types.OTHER: return "OBJECT"; case Types.REAL: return "REAL"; case Types.REF: return "OBJECT"; case Types.SMALLINT: return "SMALLINT"; case Types.STRUCT: return "OBJECT"; case Types.TIME: return "TIME"; case Types.TIMESTAMP: return "TIMESTAMP"; case Types.TINYINT: return "TINYINT"; case Types.VARBINARY: return "VARBINARY"; case Types.NVARCHAR: return "NVARCHAR"; case Types.VARCHAR: return "VARCHAR"; default : return "VARCHAR"; } } private int getIndexFromKey(String key) { String lc = StringUtil.toLowerCase(key); for(int i=0;i<columnNames.length;i++) { if(columnNames[i].getLowerString().equals(lc)) return i; } return -1; } private int getIndexFromKey(Collection.Key key) { for(int i=0;i<columnNames.length;i++) { if(columnNames[i].equalsIgnoreCase(key)) return i; } return -1; } /** * @see railo.runtime.type.Query#setExecutionTime(long) */ public void setExecutionTime(long exeTime) { this.exeTime=exeTime; } /** * @param maxrows * @return has cutted or not */ public synchronized boolean cutRowsTo(int maxrows) { //disconnectCache(); if(maxrows>-1 && maxrows<getRecordcount()) { for(int i=0;i<columns.length;i++) { QueryColumn column = columns[i]; column.cutRowsTo(maxrows); } recordcount=maxrows; return true; } return false; } /** * @see railo.runtime.type.Query#setCached(boolean) */ public void setCached(boolean isCached) { this.isCached=isCached; } /** * @see railo.runtime.type.Query#isCached() */ public boolean isCached() { return isCached; } /** * @see com.allaire.cfx.Query#addRow() */ public int addRow() { addRow(1); return getRecordcount(); } public Key getColumnName(int columnIndex) { Key[] keys = keys(); if(columnIndex<1 || columnIndex>keys.length) return null; return keys[columnIndex-1]; } /** * @see com.allaire.cfx.Query#getColumnIndex(java.lang.String) */ public int getColumnIndex(String coulmnName) { String[] keys = keysAsString(); for(int i=0;i<keys.length;i++) { if(keys[i].equalsIgnoreCase(coulmnName)) return i+1; } return -1; } /** * @see com.allaire.cfx.Query#getColumns() */ public String[] getColumns() { return getColumnNamesAsString(); } /** * @see railo.runtime.type.QueryPro#getColumnNames() */ public Collection.Key[] getColumnNames() { Collection.Key[] keys = keys(); Collection.Key[] rtn=new Collection.Key[keys.length]; System.arraycopy(keys,0,rtn,0,keys.length); return rtn; } public void setColumnNames(Collection.Key[] trg) throws PageException { columncount=trg.length; Collection.Key[] src = keys(); // target < source if(trg.length<src.length){ this.columnNames=new Collection.Key[trg.length]; QueryColumnImpl[] tmp=new QueryColumnImpl[trg.length]; for(int i=0;i<trg.length;i++){ this.columnNames[i]=trg[i]; tmp[i]=this.columns[i]; tmp[i].setKey(trg[i]); } this.columns=tmp; return; } if(trg.length>src.length){ int recordcount=getRecordcount(); for(int i=src.length;i<trg.length;i++){ Array arr=new ArrayImpl(); for(int r=1;r<=recordcount;r++){ arr.setE(i,""); } addColumn(trg[i], arr); } src = keys(); } for(int i=0;i<trg.length;i++){ this.columnNames[i]=trg[i]; this.columns[i].setKey(trg[i]); } } /** * @see railo.runtime.type.QueryPro#getColumnNamesAsString() */ public String[] getColumnNamesAsString() { String[] keys = keysAsString(); String[] rtn=new String[keys.length]; System.arraycopy(keys,0,rtn,0,keys.length); return rtn; } /** * @see com.allaire.cfx.Query#getData(int, int) */ public String getData(int row, int col) throws IndexOutOfBoundsException { String[] keys = keysAsString(); if(col<1 || col>keys.length) { new IndexOutOfBoundsException("invalid column index to retrieve Data from query, valid index goes from 1 to "+keys.length); } Object o=getAt(keys[col-1],row,null); if(o==null) throw new IndexOutOfBoundsException("invalid row index to retrieve Data from query, valid index goes from 1 to "+getRecordcount()); return Caster.toString( o,"" ); } /** * @see com.allaire.cfx.Query#getName() */ public String getName() { return this.name; } /** * @see com.allaire.cfx.Query#getRowCount() */ public int getRowCount() { return getRecordcount(); } /** * @see com.allaire.cfx.Query#setData(int, int, java.lang.String) */ public void setData(int row, int col, String value) throws IndexOutOfBoundsException { String[] keys = keysAsString(); if(col<1 || col>keys.length) { new IndexOutOfBoundsException("invalid column index to retrieve Data from query, valid index goes from 1 to "+keys.length); } try { setAt(keys[col-1],row,value); } catch (PageException e) { throw new IndexOutOfBoundsException("invalid row index to retrieve Data from query, valid index goes from 1 to "+getRecordcount()); } } /** * @see railo.runtime.type.Collection#containsKey(java.lang.String) */ public boolean containsKey(String key) { return getColumn(key,null)!=null; } /** * * @see railo.runtime.type.Collection#containsKey(railo.runtime.type.Collection.Key) */ public boolean containsKey(Collection.Key key) { return getColumn(key,null)!=null; } /** * @see railo.runtime.op.Castable#castToString() */ public String castToString() throws ExpressionException { throw new ExpressionException("Can't cast Complex Object Type Query to String", "Use Build-In-Function \"serialize(Query):String\" to create a String from Query"); } /** * @see railo.runtime.op.Castable#castToString(java.lang.String) */ public String castToString(String defaultValue) { return defaultValue; } /** * @see railo.runtime.op.Castable#castToBooleanValue() */ public boolean castToBooleanValue() throws ExpressionException { throw new ExpressionException("Can't cast Complex Object Type Query to a boolean value"); } /** * @see railo.runtime.op.Castable#castToBoolean(java.lang.Boolean) */ public Boolean castToBoolean(Boolean defaultValue) { return defaultValue; } /** * @see railo.runtime.op.Castable#castToDoubleValue() */ public double castToDoubleValue() throws ExpressionException { throw new ExpressionException("Can't cast Complex Object Type Query to a number value"); } /** * @see railo.runtime.op.Castable#castToDoubleValue(double) */ public double castToDoubleValue(double defaultValue) { return defaultValue; } /** * @see railo.runtime.op.Castable#castToDateTime() */ public DateTime castToDateTime() throws ExpressionException { throw new ExpressionException("Can't cast Complex Object Type Query to a Date"); } /** * @see railo.runtime.op.Castable#castToDateTime(railo.runtime.type.dt.DateTime) */ public DateTime castToDateTime(DateTime defaultValue) { return defaultValue; } /** * @see railo.runtime.op.Castable#compare(boolean) */ public int compareTo(boolean b) throws ExpressionException { throw new ExpressionException("can't compare Complex Object Type Query with a boolean value"); } /** * @see railo.runtime.op.Castable#compareTo(railo.runtime.type.dt.DateTime) */ public int compareTo(DateTime dt) throws PageException { throw new ExpressionException("can't compare Complex Object Type Query with a DateTime Object"); } /** * @see railo.runtime.op.Castable#compareTo(double) */ public int compareTo(double d) throws PageException { throw new ExpressionException("can't compare Complex Object Type Query with a numeric value"); } /** * @see railo.runtime.op.Castable#compareTo(java.lang.String) */ public int compareTo(String str) throws PageException { throw new ExpressionException("can't compare Complex Object Type Query with a String"); } public synchronized Array getMetaDataSimple() { Array cols=new ArrayImpl(); Struct column; for(int i=0;i<columns.length;i++) { column=new StructImpl(); column.setEL("name",columnNames[i].getString()); column.setEL("isCaseSensitive",Boolean.FALSE); column.setEL("typeName",columns[i].getTypeAsString()); cols.appendEL(column); } return cols; } public synchronized Struct _getMetaData() { Struct cols=new StructImpl(); for(int i=0;i<columns.length;i++) { cols.setEL(columnNames[i],columns[i].getTypeAsString()); } Struct sct=new StructImpl(); sct.setEL(KeyImpl.NAME_UC,getName()); sct.setEL(COLUMNS,cols); sct.setEL(SQL,sql==null?"":sql.toString()); sct.setEL(EXECUTION_TIME,new Double(exeTime)); sct.setEL(RECORDCOUNT,new Double(getRowCount())); sct.setEL(CACHED,Caster.toBoolean(isCached())); return sct; } /** * @return the sql */ public SQL getSql() { return sql; } /** * @param sql the sql to set */ public void setSql(SQL sql) { this.sql = sql; } /** * @see java.sql.ResultSet#getObject(java.lang.String) */ public Object getObject(String columnName) throws SQLException { int currentrow; if((currentrow=arrCurrentRow.get(getPid(),0))==0) return null; try { return getAt(columnName,currentrow); } catch (PageException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#getObject(int) */ public Object getObject(int columnIndex) throws SQLException { if(columnIndex>0 && columnIndex<=columncount) return getObject(this.columnNames[columnIndex-1].getString()); return null; } /** * @see java.sql.ResultSet#getString(int) */ public String getString(int columnIndex) throws SQLException { Object rtn = getObject(columnIndex); if(rtn==null)return null; if(Decision.isCastableToString(rtn)) return Caster.toString(rtn,null); throw new SQLException("can't cast value to string"); } /** * @see java.sql.ResultSet#getString(java.lang.String) */ public String getString(String columnName) throws SQLException { Object rtn = getObject(columnName); if(rtn==null)return null; if(Decision.isCastableToString(rtn)) return Caster.toString(rtn,null); throw new SQLException("can't cast value to string"); } /** * @see java.sql.ResultSet#getBoolean(int) */ public boolean getBoolean(int columnIndex) throws SQLException { Object rtn = getObject(columnIndex); if(rtn==null)return false; if(rtn!=null && Decision.isCastableToBoolean(rtn)) return Caster.toBooleanValue(rtn,false); throw new SQLException("can't cast value to boolean"); } /** * @see java.sql.ResultSet#getBoolean(java.lang.String) */ public boolean getBoolean(String columnName) throws SQLException { Object rtn = getObject(columnName); if(rtn==null)return false; if(rtn!=null && Decision.isCastableToBoolean(rtn)) return Caster.toBooleanValue(rtn,false); throw new SQLException("can't cast value to boolean"); } /** * * @see railo.runtime.type.Objects#call(railo.runtime.PageContext, java.lang.String, java.lang.Object[]) */ public Object call(PageContext pc, String methodName, Object[] arguments) throws PageException { return Reflector.callMethod(this,methodName,arguments); } /** * * @see railo.runtime.type.Objects#call(railo.runtime.PageContext, railo.runtime.type.Collection.Key, java.lang.Object[]) */ public Object call(PageContext pc, Key methodName, Object[] arguments) throws PageException { return Reflector.callMethod(this,methodName,arguments); } /** * * @see railo.runtime.type.Objects#callWithNamedValues(railo.runtime.PageContext, java.lang.String, railo.runtime.type.Struct) */ public Object callWithNamedValues(PageContext pc, String methodName,Struct args) throws PageException { throw new ExpressionException("No matching Method/Function ["+methodName+"] for call with named arguments found"); } /** * @see railo.runtime.type.Objects#callWithNamedValues(railo.runtime.PageContext, railo.runtime.type.Collection.Key, railo.runtime.type.Struct) */ public Object callWithNamedValues(PageContext pc, Key methodName, Struct args) throws PageException { throw new ExpressionException("No matching Method/Function ["+methodName.getString()+"] for call with named arguments found"); } /** * @see railo.runtime.type.Objects#get(railo.runtime.PageContext, java.lang.String, java.lang.Object) */ public Object get(PageContext pc, String key, Object defaultValue) { return getAt(key,arrCurrentRow.get(pc.getId(),1),defaultValue); } /** * @see railo.runtime.type.Objects#get(railo.runtime.PageContext, railo.runtime.type.Collection.Key, java.lang.Object) */ public Object get(PageContext pc, Key key, Object defaultValue) { return getAt(key,arrCurrentRow.get( pc.getId(),1),defaultValue); } /** * @see railo.runtime.type.Objects#get(railo.runtime.PageContext, java.lang.String) */ public Object get(PageContext pc, String key) throws PageException { return getAt(key,arrCurrentRow.get(pc.getId(),1)); } /** * @see railo.runtime.type.Objects#get(railo.runtime.PageContext, railo.runtime.type.Collection.Key) */ public Object get(PageContext pc, Key key) throws PageException { return getAt(key,arrCurrentRow.get(pc.getId(),1)); } /** * @see railo.runtime.type.Objects#isInitalized() */ public boolean isInitalized() { return true; } /** * @see railo.runtime.type.Objects#set(railo.runtime.PageContext, java.lang.String, java.lang.Object) */ public Object set(PageContext pc, String propertyName, Object value) throws PageException { return setAt(propertyName,arrCurrentRow.get(pc.getId(),1),value); } /** * @see railo.runtime.type.Objects#set(railo.runtime.PageContext, railo.runtime.type.Collection.Key, java.lang.Object) */ public Object set(PageContext pc, Key propertyName, Object value) throws PageException { return setAt(propertyName,arrCurrentRow.get(pc.getId(),1),value); } /** * @see railo.runtime.type.Objects#setEL(railo.runtime.PageContext, java.lang.String, java.lang.Object) */ public Object setEL(PageContext pc, String propertyName, Object value) { return setAtEL(propertyName,arrCurrentRow.get(pc.getId(),1),value); } /** * @see railo.runtime.type.Objects#setEL(railo.runtime.PageContext, railo.runtime.type.Collection.Key, java.lang.Object) */ public Object setEL(PageContext pc, Key propertyName, Object value) { return setAtEL(propertyName,arrCurrentRow.get(pc.getId(),1),value); } /** * @see java.sql.ResultSet#wasNull() */ public boolean wasNull() { return false; } /** * @see java.sql.ResultSet#absolute(int) */ public boolean absolute(int row) throws SQLException { if(recordcount==0) { if(row!=0) throw new SQLException("invalid row ["+row+"], query is Empty"); return false; } //row=row%recordcount; if(row>0) arrCurrentRow.set(getPid(),row); else arrCurrentRow.set(getPid(),(recordcount+1)+row); return true; } /** * @see java.sql.ResultSet#afterLast() */ public void afterLast() throws SQLException { arrCurrentRow.set(getPid(),recordcount+1); } /** * @see java.sql.ResultSet#beforeFirst() */ public void beforeFirst() throws SQLException { arrCurrentRow.set(getPid(),0); } /** * @see java.sql.ResultSet#cancelRowUpdates() */ public void cancelRowUpdates() throws SQLException { // ignored } /** * @see java.sql.ResultSet#clearWarnings() */ public void clearWarnings() throws SQLException { // ignored } /** * @see java.sql.ResultSet#close() */ public void close() throws SQLException { // ignored } /** * @see java.sql.ResultSet#deleteRow() */ public void deleteRow() throws SQLException { try { removeRow(arrCurrentRow.get(getPid())); } catch (Exception e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#findColumn(java.lang.String) */ public int findColumn(String columnName) throws SQLException { int index= getColumnIndex(columnName); if(index==-1) throw new SQLException("invald column definitions ["+columnName+"]"); return index; } /** * @see java.sql.ResultSet#first() */ public boolean first() throws SQLException { return absolute(1); } public java.sql.Array getArray(int i) throws SQLException { throw new SQLException("method is not implemented"); } public java.sql.Array getArray(String colName) throws SQLException { throw new SQLException("method is not implemented"); } /** * @see java.sql.ResultSet#getAsciiStream(int) */ public InputStream getAsciiStream(int columnIndex) throws SQLException { String res = getString(columnIndex); if(res==null)return null; return new ByteArrayInputStream(res.getBytes()); } /** * @see java.sql.ResultSet#getAsciiStream(java.lang.String) */ public InputStream getAsciiStream(String columnName) throws SQLException { String res = getString(columnName); if(res==null)return null; return new ByteArrayInputStream(res.getBytes()); } /** * @see java.sql.ResultSet#getBigDecimal(int) */ public BigDecimal getBigDecimal(int columnIndex) throws SQLException { return new BigDecimal(getDouble(columnIndex)); } /** * @see java.sql.ResultSet#getBigDecimal(java.lang.String) */ public BigDecimal getBigDecimal(String columnName) throws SQLException { return new BigDecimal(getDouble(columnName)); } /** * @see java.sql.ResultSet#getBigDecimal(int, int) */ public BigDecimal getBigDecimal(int columnIndex, int scale) throws SQLException { return new BigDecimal(getDouble(columnIndex)); } /** * @see java.sql.ResultSet#getBigDecimal(java.lang.String, int) */ public BigDecimal getBigDecimal(String columnName, int scale) throws SQLException { return new BigDecimal(getDouble(columnName)); } /** * @see java.sql.ResultSet#getBinaryStream(int) */ public InputStream getBinaryStream(int columnIndex) throws SQLException { Object obj = getObject(columnIndex); if(obj==null)return null; try { return Caster.toBinaryStream(obj); } catch (Exception e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#getBinaryStream(java.lang.String) */ public InputStream getBinaryStream(String columnName) throws SQLException { Object obj = getObject(columnName); if(obj==null)return null; try { return Caster.toBinaryStream(obj); } catch (Exception e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#getBlob(int) */ public Blob getBlob(int i) throws SQLException { byte[] bytes = getBytes(i); if(bytes==null) return null; try { return BlobImpl.toBlob(bytes); } catch (PageException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#getBlob(java.lang.String) */ public Blob getBlob(String colName) throws SQLException { byte[] bytes = getBytes(colName); if(bytes==null) return null; try { return BlobImpl.toBlob(bytes); } catch (PageException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#getByte(int) */ public byte getByte(int columnIndex) throws SQLException { Object obj = getObject(columnIndex); if(obj==null) return (byte)0; try { return Caster.toByteValue(obj); } catch (PageException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#getByte(java.lang.String) */ public byte getByte(String columnName) throws SQLException { Object obj = getObject(columnName); if(obj==null) return (byte)0; try { return Caster.toByteValue(obj); } catch (PageException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#getBytes(int) */ public byte[] getBytes(int columnIndex) throws SQLException { Object obj = getObject(columnIndex); if(obj==null) return null; try { return Caster.toBytes(obj); } catch (Exception e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#getBytes(java.lang.String) */ public byte[] getBytes(String columnName) throws SQLException { Object obj = getObject(columnName); if(obj==null) return null; try { return Caster.toBytes(obj); } catch (Exception e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#getCharacterStream(int) */ public Reader getCharacterStream(int columnIndex) throws SQLException { String str=getString(columnIndex); if(str==null) return null; return new StringReader(str); } /** * @see java.sql.ResultSet#getCharacterStream(java.lang.String) */ public Reader getCharacterStream(String columnName) throws SQLException { String str=getString(columnName); if(str==null) return null; return new StringReader(str); } /** * @see java.sql.ResultSet#getClob(int) */ public Clob getClob(int i) throws SQLException { String str=getString(i); if(str==null) return null; return ClobImpl.toClob(str); } /** * @see java.sql.ResultSet#getClob(java.lang.String) */ public Clob getClob(String colName) throws SQLException { String str=getString(colName); if(str==null) return null; return ClobImpl.toClob(str); } /** * @see java.sql.ResultSet#getConcurrency() */ public int getConcurrency() throws SQLException { return 0; } /** * @see java.sql.ResultSet#getCursorName() */ public String getCursorName() throws SQLException { return null; } /** * @see java.sql.ResultSet#getDate(int) */ public java.sql.Date getDate(int columnIndex) throws SQLException { Object obj=getObject(columnIndex); if(obj==null) return null; try { return new java.sql.Date(Caster.toDate(obj, false, null).getTime()); } catch (PageException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#getDate(java.lang.String) */ public java.sql.Date getDate(String columnName) throws SQLException { Object obj=getObject(columnName); if(obj==null) return null; try { return new java.sql.Date(Caster.toDate(obj, false, null).getTime()); } catch (PageException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#getDate(int, java.util.Calendar) */ public java.sql.Date getDate(int columnIndex, Calendar cal)throws SQLException { return getDate(columnIndex); // TODO impl } /** * @see java.sql.ResultSet#getDate(java.lang.String, java.util.Calendar) */ public java.sql.Date getDate(String columnName, Calendar cal) throws SQLException { return getDate(columnName);// TODO impl } /** * @see java.sql.ResultSet#getDouble(int) */ public double getDouble(int columnIndex) throws SQLException { Object obj=getObject(columnIndex); if(obj==null) return 0; try { return Caster.toDoubleValue(obj); } catch (PageException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#getDouble(java.lang.String) */ public double getDouble(String columnName) throws SQLException { Object obj=getObject(columnName); if(obj==null) return 0; try { return Caster.toDoubleValue(obj); } catch (PageException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#getFetchDirection() */ public int getFetchDirection() throws SQLException { return 1000; } /** * @see java.sql.ResultSet#getFetchSize() */ public int getFetchSize() throws SQLException { return 0; } /** * @see java.sql.ResultSet#getFloat(int) */ public float getFloat(int columnIndex) throws SQLException { Object obj=getObject(columnIndex); if(obj==null) return 0; try { return Caster.toFloatValue(obj); } catch (PageException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#getFloat(java.lang.String) */ public float getFloat(String columnName) throws SQLException { Object obj=getObject(columnName); if(obj==null) return 0; try { return Caster.toFloatValue(obj); } catch (PageException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#getInt(int) */ public int getInt(int columnIndex) throws SQLException { Object obj=getObject(columnIndex); if(obj==null) return 0; try { return Caster.toIntValue(obj); } catch (PageException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#getInt(java.lang.String) */ public int getInt(String columnName) throws SQLException { Object obj=getObject(columnName); if(obj==null) return 0; try { return Caster.toIntValue(obj); } catch (PageException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#getLong(int) */ public long getLong(int columnIndex) throws SQLException { Object obj=getObject(columnIndex); if(obj==null) return 0; try { return Caster.toLongValue(obj); } catch (PageException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#getLong(java.lang.String) */ public long getLong(String columnName) throws SQLException { Object obj=getObject(columnName); if(obj==null) return 0; try { return Caster.toLongValue(obj); } catch (PageException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#getObject(int, java.util.Map) */ public Object getObject(int i, Map map) throws SQLException { throw new SQLException("method is not implemented"); } /** * @see java.sql.ResultSet#getObject(java.lang.String, java.util.Map) */ public Object getObject(String colName, Map map) throws SQLException { throw new SQLException("method is not implemented"); } /** * @see java.sql.ResultSet#getRef(int) */ public Ref getRef(int i) throws SQLException { throw new SQLException("method is not implemented"); } /** * @see java.sql.ResultSet#getRef(java.lang.String) */ public Ref getRef(String colName) throws SQLException { throw new SQLException("method is not implemented"); } /** * @see java.sql.ResultSet#getRow() */ public int getRow() throws SQLException { return arrCurrentRow.get(getPid(),0); } /** * @see java.sql.ResultSet#getShort(int) */ public short getShort(int columnIndex) throws SQLException { Object obj=getObject(columnIndex); if(obj==null) return 0; try { return Caster.toShortValue(obj); } catch (PageException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#getShort(java.lang.String) */ public short getShort(String columnName) throws SQLException { Object obj=getObject(columnName); if(obj==null) return 0; try { return Caster.toShortValue(obj); } catch (PageException e) { throw new SQLException(e.getMessage()); } } public Statement getStatement() throws SQLException { throw new SQLException("method is not implemented"); } /** * @see java.sql.ResultSet#getTime(int) */ public Time getTime(int columnIndex) throws SQLException { Object obj=getObject(columnIndex); if(obj==null) return null; try { return new Time(DateCaster.toTime(null, obj).getTime()); } catch (PageException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#getTime(java.lang.String) */ public Time getTime(String columnName) throws SQLException { Object obj=getObject(columnName); if(obj==null) return null; try { return new Time(DateCaster.toTime(null, obj).getTime()); } catch (PageException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#getTime(int, java.util.Calendar) */ public Time getTime(int columnIndex, Calendar cal) throws SQLException { return getTime(columnIndex);// TODO impl } /** * @see java.sql.ResultSet#getTime(java.lang.String, java.util.Calendar) */ public Time getTime(String columnName, Calendar cal) throws SQLException { return getTime(columnName);// TODO impl } /** * @see java.sql.ResultSet#getTimestamp(int) */ public Timestamp getTimestamp(int columnIndex) throws SQLException { Object obj=getObject(columnIndex); if(obj==null) return null; try { return new Timestamp(DateCaster.toTime(null, obj).getTime()); } catch (PageException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#getTimestamp(java.lang.String) */ public Timestamp getTimestamp(String columnName) throws SQLException { Object obj=getObject(columnName); if(obj==null) return null; try { return new Timestamp(DateCaster.toTime(null, obj).getTime()); } catch (PageException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#getTimestamp(int, java.util.Calendar) */ public Timestamp getTimestamp(int columnIndex, Calendar cal) throws SQLException { return getTimestamp(columnIndex);// TODO impl } /** * @see java.sql.ResultSet#getTimestamp(java.lang.String, java.util.Calendar) */ public Timestamp getTimestamp(String columnName, Calendar cal) throws SQLException { return getTimestamp(columnName);// TODO impl } /** * @see java.sql.ResultSet#getType() */ public int getType() throws SQLException { return 0; } /** * @see java.sql.ResultSet#getURL(int) */ public URL getURL(int columnIndex) throws SQLException { throw new SQLException("method is not implemented"); } /** * @see java.sql.ResultSet#getURL(java.lang.String) */ public URL getURL(String columnName) throws SQLException { throw new SQLException("method is not implemented"); } /** * @see java.sql.ResultSet#getUnicodeStream(int) */ public InputStream getUnicodeStream(int columnIndex) throws SQLException { String str=getString(columnIndex); if(str==null) return null; try { return new ByteArrayInputStream(str.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#getUnicodeStream(java.lang.String) */ public InputStream getUnicodeStream(String columnName) throws SQLException { String str=getString(columnName); if(str==null) return null; try { return new ByteArrayInputStream(str.getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#getWarnings() */ public SQLWarning getWarnings() throws SQLException { throw new SQLException("method is not implemented"); } /** * @see java.sql.ResultSet#insertRow() */ public void insertRow() throws SQLException { throw new SQLException("method is not implemented"); } /** * @see java.sql.ResultSet#isAfterLast() */ public boolean isAfterLast() throws SQLException { return getCurrentrow()>recordcount; } /** * @see java.sql.ResultSet#isBeforeFirst() */ public boolean isBeforeFirst() throws SQLException { return arrCurrentRow.get(getPid(),0)==0; } /** * @see java.sql.ResultSet#isFirst() */ public boolean isFirst() throws SQLException { return arrCurrentRow.get(getPid(),0)==1; } public boolean isLast() throws SQLException { return arrCurrentRow.get(getPid(),0)==recordcount; } public boolean last() throws SQLException { return absolute(recordcount); } public void moveToCurrentRow() throws SQLException { // ignore } public void moveToInsertRow() throws SQLException { // ignore } public boolean previous() { return previous(getPid()); } public boolean previous(int pid) { if(0<(arrCurrentRow.set(pid,arrCurrentRow.get(pid,0)-1))) { return true; } arrCurrentRow.set(pid,0); return false; } public void refreshRow() throws SQLException { // ignore } /** * @see java.sql.ResultSet#relative(int) */ public boolean relative(int rows) throws SQLException { return absolute(getRow()+rows); } /** * @see java.sql.ResultSet#rowDeleted() */ public boolean rowDeleted() throws SQLException { return false; } /** * @see java.sql.ResultSet#rowInserted() */ public boolean rowInserted() throws SQLException { return false; } /** * @see java.sql.ResultSet#rowUpdated() */ public boolean rowUpdated() throws SQLException { return false; } public void setFetchDirection(int direction) throws SQLException { // ignore } public void setFetchSize(int rows) throws SQLException { // ignore } /** * @see java.sql.ResultSet#updateArray(int, java.sql.Array) */ public void updateArray(int columnIndex, java.sql.Array x)throws SQLException { updateObject(columnIndex, x.getArray()); } /** * @see java.sql.ResultSet#updateArray(java.lang.String, java.sql.Array) */ public void updateArray(String columnName, java.sql.Array x)throws SQLException { updateObject(columnName, x.getArray()); } /** * @see java.sql.ResultSet#updateAsciiStream(int, java.io.InputStream, int) */ public void updateAsciiStream(int columnIndex, InputStream x, int length)throws SQLException { updateBinaryStream(columnIndex, x, length); } /** * @see java.sql.ResultSet#updateAsciiStream(java.lang.String, java.io.InputStream, int) */ public void updateAsciiStream(String columnName, InputStream x, int length)throws SQLException { updateBinaryStream(columnName, x, length); } /** * @see java.sql.ResultSet#updateBigDecimal(int, java.math.BigDecimal) */ public void updateBigDecimal(int columnIndex, BigDecimal x)throws SQLException { updateObject(columnIndex, x.toString()); } /** * @see java.sql.ResultSet#updateBigDecimal(java.lang.String, java.math.BigDecimal) */ public void updateBigDecimal(String columnName, BigDecimal x) throws SQLException { updateObject(columnName, x.toString()); } /** * @see java.sql.ResultSet#updateBinaryStream(int, java.io.InputStream, int) */ public void updateBinaryStream(int columnIndex, InputStream x, int length) throws SQLException { try { updateObject(columnIndex, IOUtil.toBytesMax(x, length)); } catch (IOException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#updateBinaryStream(java.lang.String, java.io.InputStream, int) */ public void updateBinaryStream(String columnName, InputStream x, int length) throws SQLException { try { updateObject(columnName, IOUtil.toBytesMax(x, length)); } catch (IOException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#updateBlob(int, java.sql.Blob) */ public void updateBlob(int columnIndex, Blob x) throws SQLException { try { updateObject(columnIndex, toBytes(x)); } catch (IOException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#updateBlob(java.lang.String, java.sql.Blob) */ public void updateBlob(String columnName, Blob x) throws SQLException { try { updateObject(columnName, toBytes(x)); } catch (IOException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#updateBoolean(int, boolean) */ public void updateBoolean(int columnIndex, boolean x) throws SQLException { updateObject(columnIndex, Caster.toBoolean(x)); } /** * @see java.sql.ResultSet#updateBoolean(java.lang.String, boolean) */ public void updateBoolean(String columnName, boolean x) throws SQLException { updateObject(columnName, Caster.toBoolean(x)); } /** * @see java.sql.ResultSet#updateByte(int, byte) */ public void updateByte(int columnIndex, byte x) throws SQLException { updateObject(columnIndex, new Byte(x)); } /** * @see java.sql.ResultSet#updateByte(java.lang.String, byte) */ public void updateByte(String columnName, byte x) throws SQLException { updateObject(columnName, new Byte(x)); } /** * @see java.sql.ResultSet#updateBytes(int, byte[]) */ public void updateBytes(int columnIndex, byte[] x) throws SQLException { updateObject(columnIndex, x); } /** * @see java.sql.ResultSet#updateBytes(java.lang.String, byte[]) */ public void updateBytes(String columnName, byte[] x) throws SQLException { updateObject(columnName, x); } /** * @see java.sql.ResultSet#updateCharacterStream(int, java.io.Reader, int) */ public void updateCharacterStream(int columnIndex, Reader reader, int length)throws SQLException { try { updateObject(columnIndex, IOUtil.toString(reader)); } catch (Exception e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#updateCharacterStream(java.lang.String, java.io.Reader, int) */ public void updateCharacterStream(String columnName, Reader reader,int length) throws SQLException { try { updateObject(columnName, IOUtil.toString(reader)); } catch (Exception e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#updateClob(int, java.sql.Clob) */ public void updateClob(int columnIndex, Clob x) throws SQLException { try { updateObject(columnIndex, toString(x)); } catch (IOException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#updateClob(java.lang.String, java.sql.Clob) */ public void updateClob(String columnName, Clob x) throws SQLException { try { updateObject(columnName, toString(x)); } catch (IOException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#updateDate(int, java.sql.Date) */ public void updateDate(int columnIndex, java.sql.Date x)throws SQLException { updateObject(columnIndex, Caster.toDate(x, false, null, null)); } /** * @see java.sql.ResultSet#updateDate(java.lang.String, java.sql.Date) */ public void updateDate(String columnName, java.sql.Date x)throws SQLException { updateObject(columnName, Caster.toDate(x, false, null, null)); } /** * @see java.sql.ResultSet#updateDouble(int, double) */ public void updateDouble(int columnIndex, double x) throws SQLException { updateObject(columnIndex, Caster.toDouble(x)); } /** * @see java.sql.ResultSet#updateDouble(java.lang.String, double) */ public void updateDouble(String columnName, double x) throws SQLException { updateObject(columnName, Caster.toDouble(x)); } /** * @see java.sql.ResultSet#updateFloat(int, float) */ public void updateFloat(int columnIndex, float x) throws SQLException { updateObject(columnIndex, Caster.toDouble(x)); } /** * @see java.sql.ResultSet#updateFloat(java.lang.String, float) */ public void updateFloat(String columnName, float x) throws SQLException { updateObject(columnName, Caster.toDouble(x)); } /** * @see java.sql.ResultSet#updateInt(int, int) */ public void updateInt(int columnIndex, int x) throws SQLException { updateObject(columnIndex, Caster.toDouble(x)); } /** * @see java.sql.ResultSet#updateInt(java.lang.String, int) */ public void updateInt(String columnName, int x) throws SQLException { updateObject(columnName, Caster.toDouble(x)); } /** * @see java.sql.ResultSet#updateLong(int, long) */ public void updateLong(int columnIndex, long x) throws SQLException { updateObject(columnIndex, Caster.toDouble(x)); } /** * @see java.sql.ResultSet#updateLong(java.lang.String, long) */ public void updateLong(String columnName, long x) throws SQLException { updateObject(columnName, Caster.toDouble(x)); } /** * @see java.sql.ResultSet#updateNull(int) */ public void updateNull(int columnIndex) throws SQLException { updateObject(columnIndex, null); } /** * @see java.sql.ResultSet#updateNull(java.lang.String) */ public void updateNull(String columnName) throws SQLException { updateObject(columnName, null); } /** * @see java.sql.ResultSet#updateObject(int, java.lang.Object) */ public void updateObject(int columnIndex, Object x) throws SQLException { try { set(getColumnName(columnIndex), x); } catch (PageException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#updateObject(java.lang.String, java.lang.Object) */ public void updateObject(String columnName, Object x) throws SQLException { try { set(KeyImpl.init(columnName), x); } catch (PageException e) { throw new SQLException(e.getMessage()); } } /** * @see java.sql.ResultSet#updateObject(int, java.lang.Object, int) */ public void updateObject(int columnIndex, Object x, int scale)throws SQLException { updateObject(columnIndex, x); } /** * @see java.sql.ResultSet#updateObject(java.lang.String, java.lang.Object, int) */ public void updateObject(String columnName, Object x, int scale)throws SQLException { updateObject(columnName, x); } /** * @see java.sql.ResultSet#updateRef(int, java.sql.Ref) */ public void updateRef(int columnIndex, Ref x) throws SQLException { updateObject(columnIndex, x.getObject()); } /** * @see java.sql.ResultSet#updateRef(java.lang.String, java.sql.Ref) */ public void updateRef(String columnName, Ref x) throws SQLException { updateObject(columnName, x.getObject()); } public void updateRow() throws SQLException { throw new SQLException("method is not implemented"); } /** * @see java.sql.ResultSet#updateShort(int, short) */ public void updateShort(int columnIndex, short x) throws SQLException { updateObject(columnIndex, Caster.toDouble(x)); } /** * @see java.sql.ResultSet#updateShort(java.lang.String, short) */ public void updateShort(String columnName, short x) throws SQLException { updateObject(columnName, Caster.toDouble(x)); } /** * @see java.sql.ResultSet#updateString(int, java.lang.String) */ public void updateString(int columnIndex, String x) throws SQLException { updateObject(columnIndex, x); } /** * @see java.sql.ResultSet#updateString(java.lang.String, java.lang.String) */ public void updateString(String columnName, String x) throws SQLException { updateObject(columnName, x); } /** * @see java.sql.ResultSet#updateTime(int, java.sql.Time) */ public void updateTime(int columnIndex, Time x) throws SQLException { updateObject(columnIndex, new DateTimeImpl(x.getTime(),false)); } /** * @see java.sql.ResultSet#updateTime(java.lang.String, java.sql.Time) */ public void updateTime(String columnName, Time x) throws SQLException { updateObject(columnName, new DateTimeImpl(x.getTime(),false)); } /** * @see java.sql.ResultSet#updateTimestamp(int, java.sql.Timestamp) */ public void updateTimestamp(int columnIndex, Timestamp x) throws SQLException { updateObject(columnIndex, new DateTimeImpl(x.getTime(),false)); } /** * @see java.sql.ResultSet#updateTimestamp(java.lang.String, java.sql.Timestamp) */ public void updateTimestamp(String columnName, Timestamp x) throws SQLException { updateObject(columnName, new DateTimeImpl(x.getTime(),false)); } public ResultSetMetaData getMetaData() throws SQLException { throw new SQLException("method is not implemented"); } /** * @see railo.runtime.type.Collection#keyIterator() */ public Iterator keyIterator() { return new KeyIterator(keys()); } /** * @see railo.runtime.type.Iteratorable#iterator() */ public Iterator iterator() { return keyIterator(); } public Iterator valueIterator() { return new CollectionIterator(keys(),this); } public void readExternal(ObjectInput in) throws IOException { try { QueryImpl other=(QueryImpl) new CFMLExpressionInterpreter().interpret(ThreadLocalPageContext.get(),in.readUTF()); this.arrCurrentRow=other.arrCurrentRow; this.columncount=other.columncount; this.columnNames=other.columnNames; this.columns=other.columns; this.exeTime=other.exeTime; this.generatedKeys=other.generatedKeys; this.isCached=other.isCached; this.name=other.name; this.recordcount=other.recordcount; this.sql=other.sql; this.updateCount=other.updateCount; } catch (PageException e) { throw new IOException(e.getMessage()); } } public void writeExternal(ObjectOutput out) { try { out.writeUTF(new ScriptConverter().serialize(this)); } catch (Throwable t) {} } /** * @see railo.runtime.type.Sizeable#sizeOf() */ public long sizeOf(){ long size=SizeOf.size(this.exeTime)+ SizeOf.size(this.isCached)+ SizeOf.size(this.arrCurrentRow)+ SizeOf.size(this.columncount)+ SizeOf.size(this.generatedKeys)+ SizeOf.size(this.name)+ SizeOf.size(this.recordcount)+ SizeOf.size(this.sql)+ SizeOf.size(this.template)+ SizeOf.size(this.updateCount); for(int i=0;i<columns.length;i++){ size+=this.columns[i].sizeOf(); } return size; } public boolean equals(Object obj){ if(!(obj instanceof Collection)) return false; return CollectionUtil.equals(this,(Collection)obj); } public int getHoldability() throws SQLException { throw notSupported(); } public boolean isClosed() throws SQLException { return false; } public void updateNString(int columnIndex, String nString)throws SQLException { updateString(columnIndex, nString); } public void updateNString(String columnLabel, String nString)throws SQLException { updateString(columnLabel, nString); } public String getNString(int columnIndex) throws SQLException { return getString(columnIndex); } public String getNString(String columnLabel) throws SQLException { return getString(columnLabel); } public Reader getNCharacterStream(int columnIndex) throws SQLException { return getCharacterStream(columnIndex); } public Reader getNCharacterStream(String columnLabel) throws SQLException { return getCharacterStream(columnLabel); } public void updateNCharacterStream(int columnIndex, Reader x, long length)throws SQLException { updateCharacterStream(columnIndex, x, length); } public void updateNCharacterStream(String columnLabel, Reader reader,long length) throws SQLException { throw notSupported(); } public void updateAsciiStream(int columnIndex, InputStream x, long length)throws SQLException { throw notSupported(); } public void updateBinaryStream(int columnIndex, InputStream x, long length)throws SQLException { throw notSupported(); } public void updateCharacterStream(int columnIndex, Reader x, long length) throws SQLException { throw notSupported(); } public void updateAsciiStream(String columnLabel, InputStream x, long length)throws SQLException { throw notSupported(); } public void updateBinaryStream(String columnLabel, InputStream x,long length) throws SQLException { throw notSupported(); } public void updateCharacterStream(String columnLabel, Reader reader,long length) throws SQLException { throw notSupported(); } public void updateBlob(int columnIndex, InputStream inputStream, long length) throws SQLException { throw notSupported(); } public void updateBlob(String columnLabel, InputStream inputStream,long length) throws SQLException { throw notSupported(); } public void updateClob(int columnIndex, Reader reader, long length) throws SQLException { throw notSupported(); } public void updateClob(String columnLabel, Reader reader, long length) throws SQLException { throw notSupported(); } public void updateNClob(int columnIndex, Reader reader, long length) throws SQLException { updateClob(columnIndex, reader, length); } public void updateNClob(String columnLabel, Reader reader, long length) throws SQLException { updateClob(columnLabel, reader,length); } public void updateNCharacterStream(int columnIndex, Reader x) throws SQLException { updateCharacterStream(columnIndex, x); } public void updateNCharacterStream(String columnLabel, Reader reader)throws SQLException { throw notSupported(); } public void updateAsciiStream(int columnIndex, InputStream x)throws SQLException { throw notSupported(); } public void updateBinaryStream(int columnIndex, InputStream x)throws SQLException { throw notSupported(); } public void updateCharacterStream(int columnIndex, Reader x) throws SQLException { throw notSupported(); } public void updateAsciiStream(String columnLabel, InputStream x) throws SQLException { throw notSupported(); } public void updateBinaryStream(String columnLabel, InputStream x) throws SQLException { throw notSupported(); } public void updateCharacterStream(String columnLabel, Reader reader) throws SQLException { throw notSupported(); } public void updateBlob(int columnIndex, InputStream inputStream) throws SQLException { throw notSupported(); } public void updateBlob(String columnLabel, InputStream inputStream) throws SQLException { throw notSupported(); } public void updateClob(int columnIndex, Reader reader) throws SQLException { throw notSupported(); } public void updateClob(String columnLabel, Reader reader) throws SQLException { throw notSupported(); } public void updateNClob(int columnIndex, Reader reader) throws SQLException { updateClob(columnIndex, reader); } public void updateNClob(String columnLabel, Reader reader) throws SQLException { updateClob(columnLabel, reader); } public <T> T unwrap(Class<T> iface) throws SQLException { throw notSupported(); } public boolean isWrapperFor(Class<?> iface) throws SQLException { throw notSupported(); } //JDK6: uncomment this for compiling with JDK6 public void updateNClob(int columnIndex, NClob nClob) throws SQLException { throw notSupported(); } public void updateNClob(String columnLabel, NClob nClob) throws SQLException { throw notSupported(); } public NClob getNClob(int columnIndex) throws SQLException { throw notSupported(); } public NClob getNClob(String columnLabel) throws SQLException { throw notSupported(); } public SQLXML getSQLXML(int columnIndex) throws SQLException { throw notSupported(); } public SQLXML getSQLXML(String columnLabel) throws SQLException { throw notSupported(); } public void updateSQLXML(int columnIndex, SQLXML xmlObject) throws SQLException { throw notSupported(); } public void updateSQLXML(String columnLabel, SQLXML xmlObject) throws SQLException { throw notSupported(); } public RowId getRowId(int columnIndex) throws SQLException { throw notSupported(); } public RowId getRowId(String columnLabel) throws SQLException { throw notSupported(); } public void updateRowId(int columnIndex, RowId x) throws SQLException { throw notSupported(); } public void updateRowId(String columnLabel, RowId x) throws SQLException { throw notSupported(); } private SQLException notSupported() { return new SQLException("this feature is not supported"); } private RuntimeException notSupportedEL() { return new RuntimeException(new SQLException("this feature is not supported")); } }
package org.spine3.server.storage.jdbc; /** * Set o enums and utilities for constructing the SQL sentences. * // TODO:13-01-17:dmytro.dashenkov: Javadoc. * * @author Dmytro Dashenkov */ public class Sql { public static String nPlaceholders(int n) { final StringBuilder result = new StringBuilder(n * 2 + 1); result.append(Common.BRACKET_OPEN); for (int i = 0; i < n; i++) { result.append(Query.PLACEHOLDER); if (i - 1 != n) { // Unless last iteration result.append(Common.COMMA); } } result.append(Common.BRACKET_CLOSE); return result.toString(); } public enum Type { BLOB("BLOB"), INT("INT"), BIGINT("BIGINT"), VARCHAR_512("VARCHAR(512)"), VARCHAR_999("VARCHAR(999)"); private final String token; Type(String token) { this.token = token; } @Override public String toString() { return ' ' + token + ' '; } } public enum Query { CREATE_TABLE("CREATE TABLE"), CREATE_IF_MISSING("CREATE IF NOT EXISTS"), DROP_TABLE("DROP TABLE"), PRIMARY_KEY("PRIMARY KEY"), INSERT_INTO("INSERT INTO"), SELECT, UPDATE, DELETE_FROM("DELETE FROM"), ALL_ATTRIBUTES("*"), FROM, DISTINCT, WHERE, SET, VALUES, AND, OR, NULL, LIKE, NOT, IN, EXISTS, BETWEEN, PLACEHOLDER("?"), GROUP_BY("GROUP BY"), ORDER_BY("ORDER BY"), HAVING, ASC, DESC; private final String token; Query(String token) { this.token = token; } Query() { this.token = name(); } @Override public String toString() { return ' ' + token + ' '; } } public enum Function { MIN, MAX, COUNT, AVG, SUM; @Override public String toString() { return ' ' + name() + ' '; } } public enum Common { COMMA(","), BRACKET_OPEN("("), BRACKET_CLOSE(")"), EQUAL("="), NOT_EQUAL("<>"), GT(">"), GE(">="), LT("<"), LE("<="), SEMICOLON(";"); private final String token; Common(String token) { this.token = token; } @Override public String toString() { return ' ' + token + ' '; } } }
package org.yamcs.tctm; import org.hornetq.api.core.HornetQException; import org.hornetq.api.core.SimpleString; import org.hornetq.api.core.client.ClientMessage; import org.hornetq.api.core.client.MessageHandler; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.yamcs.ConfigurationException; import org.yamcs.api.Protocol; import org.yamcs.api.YamcsApiException; import org.yamcs.api.YamcsClient; import org.yamcs.api.YamcsSession; import org.yamcs.hornetq.StreamAdapter; import org.yamcs.protobuf.Pvalue.ParameterData; import org.yamcs.xtce.XtceDb; import org.yamcs.xtceproc.XtceDbFactory; import com.google.common.util.concurrent.AbstractService; /** * receives data from HornetQ and publishes it into a yamcs stream * * @author nm * */ public class HornetQPpProvider extends AbstractService implements PpProvider, MessageHandler { protected volatile long totalPpCount = 0; protected volatile boolean disabled=false; protected Logger log=LoggerFactory.getLogger(this.getClass().getName()); private PpListener ppListener; YamcsSession yamcsSession; final private YamcsClient msgClient; final XtceDb ppdb; public HornetQPpProvider(String instance, String name, String hornetAddress) throws ConfigurationException { SimpleString queue=new SimpleString(hornetAddress+"-HornetQPpProvider"); ppdb=XtceDbFactory.getInstance(instance); try { yamcsSession=YamcsSession.newBuilder().build(); msgClient=yamcsSession.newClientBuilder().setDataProducer(false).setDataConsumer(new SimpleString(hornetAddress), queue). setFilter(new SimpleString(StreamAdapter.UNIQUEID_HDR_NAME+"<>"+StreamAdapter.UNIQUEID)). build(); } catch (Exception e) { throw new ConfigurationException(e.getMessage(),e); } } @Override public void setPpListener(PpListener ppListener) { this.ppListener=ppListener; } @Override public String getLinkStatus() { if (disabled) { return "DISABLED"; } else { return "OK"; } } @Override public void disable() { disabled=true; } @Override public void enable() { disabled=false; } @Override public boolean isDisabled() { return disabled; } @Override public String getDetailedStatus() { if(disabled) { return "DISABLED"; } else { return "OK"; } } @Override public long getDataCount() { return totalPpCount; } @Override public void onMessage(ClientMessage msg) { if(disabled) return; try { ParameterData pd = (ParameterData)Protocol.decode(msg, ParameterData.newBuilder()); totalPpCount += pd.getParameterCount(); ppListener.updateParams(pd.getGenerationTime(), pd.getGroup(), pd.getSeqNum(), pd.getParameterList()); } catch(Exception e){ log.warn( "{} for message: {}", e.getMessage(), msg); } } @Override protected void doStart() { try { msgClient.dataConsumer.setMessageHandler(this); notifyStarted(); } catch (HornetQException e) { log.error("Failed to set message handler"); notifyFailed(e); } } @Override protected void doStop() { try { msgClient.close(); notifyStopped(); } catch (HornetQException e) { log.error("Got exception when quiting:", e); notifyFailed(e); } } }
package com.enigmabridge; import com.enigmabridge.create.Constants; import org.json.JSONObject; import java.io.Serializable; import java.math.BigInteger; public class UserObjectType implements Serializable{ public static final long INVALID_TYPE = -1; protected static final int TYPE_MASK = 0xffff; // Request type from the lower bytes. public static final int TYPE_INVALID = -1; public static final int TYPE_HMAC = 0x0001; public static final int TYPE_SCRAMBLE = 0x0002; public static final int TYPE_ENSCRAMBLE = 0x0003; public static final int TYPE_PLAINAES = 0x0004; public static final int TYPE_RSA1024DECRYPT_NOPAD = 0x0005; public static final int TYPE_RSA2048DECRYPT_NOPAD = 0x0006; public static final int TYPE_EC_FP192SIGN = 0x0007; public static final int TYPE_AUTH_HOTP = 0x0008; public static final int TYPE_AUTH_NEW_USER_CTX = 0x0009; public static final int TYPE_AUTH_PASSWORD = 0x000a; public static final int TYPE_AUTH_UPDATE_USER_CTX = 0x000b; public static final int TYPE_TOKENIZE = 0x000c; public static final int TYPE_DETOKENIZE = 0x000d; public static final int TYPE_TOKENIZEWRAP = 0x000e; public static final int TYPE_PLAINAESDECRYPT = 0x000f; public static final int TYPE_RANDOMDATA = 0x0010; public static final int TYPE_CREATENEWUO = 0x0011; public static final int TYPE_RSA1024ENCRYPT_NOPAD = 0x0012; public static final int TYPE_RSA2048ENCRYPT_NOPAD = 0x0013; public static final UserObjectType OBJ_PLAINAES = UserObjectType.valueOf(TYPE_PLAINAES); public static final UserObjectType OBJ_PLAINAESDECRYPT = UserObjectType.valueOf(TYPE_PLAINAESDECRYPT); public static final UserObjectType OBJ_RSA1024 = UserObjectType.valueOf(TYPE_RSA1024DECRYPT_NOPAD); public static final UserObjectType OBJ_RSA2048 = UserObjectType.valueOf(TYPE_RSA2048DECRYPT_NOPAD); public static final UserObjectType OBJ_RANDOM = UserObjectType.valueOf(TYPE_RANDOMDATA); public static final UserObjectType INVALID = UserObjectType.valueOf(INVALID_TYPE); // For forward compatibility we store UO type in the composite field // as EB can add another bit field in the future. protected long typeValue = 0; public static abstract class AbstractBuilder<T extends UserObjectType, B extends AbstractBuilder> { public B setUoTypeFunction(int type) { getObj().setUoTypeFunction(type); return getThisBuilder(); } public B setAppKeyGenerationType(int gen) { if (gen < 0 || gen > Constants.GENKEY_ENROLL_DERIVED){ throw new IllegalArgumentException("Illegal argument for app key generation type"); } getObj().setAppKeyGenerationType(gen); return getThisBuilder(); } public B setComKeyGenerationType(int gen) { if (gen != Constants.GENKEY_LEGACY_ENROLL_RANDOM && gen != Constants.GENKEY_CLIENT){ throw new IllegalArgumentException("Illegal argument for comm key generation type"); } getObj().setComKeyGenerationType(gen); return getThisBuilder(); } public B setUoType(long buffer){ getObj().setValue(buffer); return getThisBuilder(); } public T build(){ return getObj(); } public abstract B getThisBuilder(); public abstract T getObj(); } public static class Builder extends AbstractBuilder<UserObjectType, Builder> { private final UserObjectType parent = new UserObjectType(); @Override public Builder getThisBuilder() { return this; } @Override public UserObjectType getObj() { return parent; } @Override public UserObjectType build() { super.build(); return parent; } } UserObjectType() { } public UserObjectType(long serialized) { setValue(serialized); } public UserObjectType(int function, int appKeyClientGenerated, int comKeyClientGenerated){ setUoTypeFunction(function); setAppKeyGenerationType(appKeyClientGenerated); setComKeyGenerationType(comKeyClientGenerated); } protected void setUoTypeFunction(int function){ if ((function & TYPE_MASK) != function){ throw new IllegalArgumentException("Illegal function argument"); } this.typeValue &= ~TYPE_MASK; this.typeValue |= function & TYPE_MASK; } protected void setAppKeyGenerationType(int gen){ if ((gen & 0x7) != gen){ throw new IllegalArgumentException("Illegal function argument"); } this.typeValue &= ~(0x7 << 21); this.typeValue |= gen << 21; } protected void setComKeyGenerationType(int gen){ if ((gen & 0x1) != gen){ throw new IllegalArgumentException("Illegal function argument"); } this.typeValue &= ~(0x1 << 20); this.typeValue |= gen << 20; } /** * Builder from the backing buffer. * @param buffer * @return */ public static UserObjectType valueOf(long buffer){ return new UserObjectType(buffer); } /** * Returns request type encoded in the UO. * * @return uo type function */ public int getUoTypeFunction(){ return (int) (typeValue & TYPE_MASK); } public static String getUoTypeFunctionString(int uoType){ switch(uoType) { case TYPE_HMAC: return "HMAC"; case TYPE_SCRAMBLE: return "SCRAMBLE"; case TYPE_ENSCRAMBLE: return "ENSCRAMBLE"; case TYPE_PLAINAES: return "PLAINAES"; case TYPE_RSA1024DECRYPT_NOPAD: return "RSA1024DECRYPT_NOPAD"; case TYPE_RSA2048DECRYPT_NOPAD: return "RSA2048DECRYPT_NOPAD"; case TYPE_EC_FP192SIGN: return "EC_FP192SIGN"; case TYPE_AUTH_HOTP: return "AUTH_HOTP"; case TYPE_AUTH_NEW_USER_CTX: return "AUTH_NEW_USER_CTX"; case TYPE_AUTH_PASSWORD: return "AUTH_PASSWORD"; case TYPE_AUTH_UPDATE_USER_CTX: return "AUTH_UPDATE_USER_CTX"; case TYPE_TOKENIZE: return "TOKENIZE"; case TYPE_DETOKENIZE: return "DETOKENIZE"; case TYPE_TOKENIZEWRAP: return "TOKENIZEWRAP"; case TYPE_PLAINAESDECRYPT: return "PLAINAESDECRYPT"; case TYPE_RANDOMDATA: return "RANDOMDATA"; case TYPE_CREATENEWUO: return "CREATENEWUO"; case TYPE_RSA1024ENCRYPT_NOPAD: return "RSA1024ENCRYPT_NOPAD"; case TYPE_RSA2048ENCRYPT_NOPAD: return "RSA2048ENCRYPT_NOPAD"; default: return "PROCESSDATA"; } } public String getUoTypeFunctionString(){ return getUoTypeFunctionString(getUoTypeFunction()); } /** * Returns algorithm for given UO. * May Return AES, RSA, ... null if undefined for this user object. * @return key algorithm, if key */ public String getAlgorithm(){ switch (getUoTypeFunction()){ case TYPE_PLAINAES: case TYPE_PLAINAESDECRYPT: return "AES"; case TYPE_RSA1024DECRYPT_NOPAD: case TYPE_RSA1024ENCRYPT_NOPAD: case TYPE_RSA2048DECRYPT_NOPAD: case TYPE_RSA2048ENCRYPT_NOPAD: return "RSA"; default: return null; } } /** * Returns key type, if represents key. * @return key type (secret/public/private) */ public UserObjectKeyType getKeyType(){ switch (getUoTypeFunction()){ case TYPE_PLAINAES: case TYPE_PLAINAESDECRYPT: return UserObjectKeyType.SECRET; case TYPE_RSA1024DECRYPT_NOPAD: case TYPE_RSA1024ENCRYPT_NOPAD: case TYPE_RSA2048DECRYPT_NOPAD: case TYPE_RSA2048ENCRYPT_NOPAD: return UserObjectKeyType.PRIVATE; default: return null; } } /** * Returns key length in bits if the UO represents cipher key. * @return key lenght in bits, 0 if not applicable. */ public int keyLength(){ switch (getUoTypeFunction()){ case TYPE_PLAINAES: case TYPE_PLAINAESDECRYPT: return 256; case TYPE_RSA1024DECRYPT_NOPAD: case TYPE_RSA1024ENCRYPT_NOPAD: return 1024; case TYPE_RSA2048DECRYPT_NOPAD: case TYPE_RSA2048ENCRYPT_NOPAD: return 2048; default: return 0; } } /** * Returns true if the UO represents encryption key. * @return true if encryption key */ public boolean isCipherObject(boolean forEncryption){ switch (getUoTypeFunction()){ case TYPE_PLAINAES: case TYPE_RSA1024ENCRYPT_NOPAD: case TYPE_RSA2048ENCRYPT_NOPAD: return forEncryption; case TYPE_PLAINAESDECRYPT: case TYPE_RSA1024DECRYPT_NOPAD: case TYPE_RSA2048DECRYPT_NOPAD: return !forEncryption; default: throw new EBInvalidException("UO does not represent encryption"); } } /** * Returns true if the UO represents encryption key. * @return true if encryption key */ public boolean isEncryptionObject(){ return isCipherObject(true); } /** * Returns true if the UO represents decryption key. * @return true if decryption key */ public boolean isDecryptionObject(){ return isCipherObject(false); } /** * If UO type represents encryption this function returns UO type function * representing inversion encryption operation than current one. * * @return inversion cipher operation to the current one. TYPE_INVALID on error */ public int getInversionUoTypeFunction(){ switch (getUoTypeFunction()){ case TYPE_PLAINAES: return TYPE_PLAINAESDECRYPT; case TYPE_PLAINAESDECRYPT: return TYPE_PLAINAES; case TYPE_RSA1024DECRYPT_NOPAD: return TYPE_RSA1024ENCRYPT_NOPAD; case TYPE_RSA1024ENCRYPT_NOPAD: return TYPE_RSA1024DECRYPT_NOPAD; case TYPE_RSA2048DECRYPT_NOPAD: return TYPE_RSA2048ENCRYPT_NOPAD; case TYPE_RSA2048ENCRYPT_NOPAD: return TYPE_RSA2048DECRYPT_NOPAD; default: return TYPE_INVALID; } } public static long getValue(int function, int appKeyClientGenerated, int comKeyClientGenerated){ long type = function & TYPE_MASK; if (comKeyClientGenerated != Constants.GENKEY_LEGACY_ENROLL_RANDOM && comKeyClientGenerated != Constants.GENKEY_CLIENT){ throw new IllegalArgumentException("Illegal argument for comm key generation type"); } if (appKeyClientGenerated < 0 || appKeyClientGenerated > Constants.GENKEY_ENROLL_DERIVED){ throw new IllegalArgumentException("Illegal argument for app key generation type"); } type |= (appKeyClientGenerated & 0x7) << 21; type |= (comKeyClientGenerated & 0x1) << 20; return type; } public int getComKeyGenerationType() { return (int) ((typeValue >> 20) & 0x1); } public int getAppKeyGenerationType() { return (int) ((typeValue >> 21) & 0x7); } public long getValue() { return typeValue; } protected void setValue(long value){ this.typeValue = value; } /** * Serializes to JSON. * @param parent * @param key * @return */ public Object toJSON(JSONObject parent, String key){ if (parent == null){ return getValue(); } parent.put(key, getValue()); return getValue(); } public static UserObjectType fromJSON(JSONObject parent, String key){ if (parent == null || !parent.has(key)){ return null; } return valueOf(parent.getLong(key)); } @Override public String toString() { return "{" + Long.toHexString(getValue()) + "}"; } /** * Returns either TYPE_RSA2048DECRYPT_NOPAD or TYPE_RSA1024DECRYPT_NOPAD depending on the bitLength of the modulus. * * @param modulus modulus of the RSA private key * @return TYPE_RSA2048DECRYPT_NOPAD or TYPE_RSA1024DECRYPT_NOPAD */ public static int getRSADecryptFunctionFromModulus(BigInteger modulus){ // 1048 is on purpose, not exact 1024, what if implementation generated modulus of bitLength 1025? return modulus.bitLength() > 1048 ? UserObjectType.TYPE_RSA2048DECRYPT_NOPAD : UserObjectType.TYPE_RSA1024DECRYPT_NOPAD; } }
package com.buschmais.cdo.neo4j.test.embedded.issues.initialize_primitive_values; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.nullValue; import static org.junit.Assert.assertThat; import org.junit.Test; import com.buschmais.cdo.api.CdoManager; import com.buschmais.cdo.neo4j.test.embedded.AbstractEmbeddedCdoManagerTest; import com.buschmais.cdo.neo4j.test.embedded.issues.initialize_primitive_values.composite.A; public class InitializePrimitiveValuesTest extends AbstractEmbeddedCdoManagerTest { @Override protected Class<?>[] getTypes() { return new Class<?>[] { A.class }; } @Test public void test() { CdoManager cdoManager = getCdoManager(); cdoManager.currentTransaction().begin(); A a = cdoManager.create(A.class); cdoManager.currentTransaction().commit(); cdoManager.currentTransaction().begin(); assertThat(a.getB(), nullValue()); assertThat(a.isBoolean(), is(false)); assertThat(a.getInt(), is(0)); cdoManager.currentTransaction().commit(); } }
package org.metaborg.spoofax.meta.core.stratego.primitive; import java.io.File; import java.io.IOException; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import org.apache.commons.vfs2.AllFileSelector; import org.apache.commons.vfs2.FileObject; import org.metaborg.core.MetaborgException; import org.metaborg.core.build.paths.ILanguagePathService; import org.metaborg.core.config.ConfigException; import org.metaborg.core.context.IContext; import org.metaborg.core.project.IProject; import org.metaborg.core.resource.IResourceService; import org.metaborg.spoofax.core.SpoofaxConstants; import org.metaborg.spoofax.core.stratego.primitive.generic.ASpoofaxContextPrimitive; import org.metaborg.spoofax.meta.core.build.SpoofaxLangSpecCommonPaths; import org.metaborg.spoofax.meta.core.config.ISpoofaxLanguageSpecConfig; import org.metaborg.spoofax.meta.core.pluto.build.main.GenerateSourcesBuilder; import org.metaborg.spoofax.meta.core.pluto.build.main.IPieProvider; import org.metaborg.spoofax.meta.core.project.ISpoofaxLanguageSpec; import org.metaborg.spoofax.meta.core.project.ISpoofaxLanguageSpecService; import org.metaborg.util.cmd.Arguments; import org.metaborg.util.log.ILogger; import org.metaborg.util.log.LoggerUtils; import org.spoofax.interpreter.core.Tools; import org.spoofax.interpreter.stratego.Strategy; import org.spoofax.interpreter.terms.IStrategoAppl; import org.spoofax.interpreter.terms.IStrategoTerm; import org.spoofax.interpreter.terms.ITermFactory; import org.spoofax.jsglr.client.imploder.ImploderAttachment; import org.spoofax.terms.attachments.OriginAttachment; import com.google.inject.Inject; import com.google.inject.Provider; import mb.flowspec.terms.B; import mb.flowspec.terms.StrategoArrayList; import mb.pie.api.ExecException; import mb.pie.api.PieSession; import mb.pie.api.STask; import mb.pie.api.Task; import mb.resource.ResourceKey; import mb.resource.fs.FSPath; import mb.stratego.build.strincr.Analysis; import mb.stratego.build.strincr.Analysis.Output; import mb.stratego.build.strincr.Message; import mb.stratego.build.strincr.StrIncrAnalysis; public class StrategoPieAnalyzePrimitive extends ASpoofaxContextPrimitive implements AutoCloseable { private static final ILogger logger = LoggerUtils.logger(StrategoPieAnalyzePrimitive.class); @Inject private static Provider<ISpoofaxLanguageSpecService> languageSpecServiceProvider; @Inject private static Provider<IPieProvider> pieProviderProvider; // Using provider to break cycle between StrIncrAnalysis -> Stratego runtime -> all primitives -> this primitive private final Provider<StrIncrAnalysis> strIncrAnalysisProvider; private final ILanguagePathService languagePathService; private final IResourceService resourceService; @Inject public StrategoPieAnalyzePrimitive(Provider<StrIncrAnalysis> strIncrAnalysisProvider, ILanguagePathService languagePathService, IResourceService resourceService) { super("stratego_pie_analyze", 0, 0); this.strIncrAnalysisProvider = strIncrAnalysisProvider; this.languagePathService = languagePathService; this.resourceService = resourceService; } @Override protected IStrategoTerm call(IStrategoTerm current, Strategy[] svars, IStrategoTerm[] tvars, ITermFactory factory, IContext context) throws MetaborgException, IOException { @SuppressWarnings("unused") final IStrategoAppl ast = Tools.applAt(current, 0); final String path = Tools.javaStringAt(current, 1); @SuppressWarnings("unused") final String projectPath = Tools.javaStringAt(current, 2); // if(!(ast.getName().equals("Module") && ast.getSubtermCount() == 2)) { // throw new MetaborgException("Input AST for Stratego analysis not Module/2."); // final String moduleName = Tools.javaStringAt(ast, 0); final IProject project = context.project(); if(project == null) { logger.debug("Cannot find project for opened file, cancelling analysis. "); return null; } if(languageSpecServiceProvider == null || pieProviderProvider == null) { // Indicates that meta-Spoofax is not available (ISpoofaxLanguageSpecService cannot be injected), but this // should never happen because this primitive is inside meta-Spoofax. Check for null just in case. logger.error("Spoofax meta services is not available; static injection failed"); return null; } final ISpoofaxLanguageSpec languageSpec = getLanguageSpecification(project); final ISpoofaxLanguageSpecConfig config = languageSpec.config(); final FileObject baseLoc = languageSpec.location(); final SpoofaxLangSpecCommonPaths paths = new SpoofaxLangSpecCommonPaths(baseLoc); final String strModule = config.strategoName(); final Iterable<FileObject> strRoots = languagePathService.sourcePaths(project, SpoofaxConstants.LANG_STRATEGO_NAME); final File strFile; final FileObject strFileCandidate = paths.findStrMainFile(strRoots, strModule); if(strFileCandidate != null && strFileCandidate.exists()) { strFile = resourceService.localPath(strFileCandidate); if(!strFile.exists()) { throw new IOException("Main Stratego file at " + strFile + " does not exist"); } } else { throw new IOException("Main Stratego file does not exist"); } final String strExternalJarFlags = config.strExternalJarFlags(); final Iterable<FileObject> strIncludePaths = languagePathService.sourceAndIncludePaths(languageSpec, SpoofaxConstants.LANG_STRATEGO_NAME); final FileObject strjIncludesReplicateDir = paths.replicateDir().resolveFile("strj-includes"); strjIncludesReplicateDir.delete(new AllFileSelector()); final List<File> strjIncludeDirs = new ArrayList<>(); final List<File> strjIncludeFiles = new ArrayList<>(); for(FileObject strIncludePath : strIncludePaths) { if(!strIncludePath.exists()) { continue; } if(strIncludePath.isFolder()) { strjIncludeDirs.add(resourceService.localFile(strIncludePath, strjIncludesReplicateDir)); } if(strIncludePath.isFile()) { strjIncludeFiles.add(resourceService.localFile(strIncludePath, strjIncludesReplicateDir)); } } final Arguments extraArgs = new Arguments(); extraArgs.addAll(config.strArgs()); extraArgs.add("-la", "java-front"); if(strExternalJarFlags != null) { extraArgs.addLine(strExternalJarFlags); } final File projectLocation = resourceService.localPath(paths.root()); assert projectLocation != null; final List<STask> sdfTasks = Collections.emptyList(); // Gather all Stratego files to be checked for changes final Set<Path> changedFiles = GenerateSourcesBuilder.getChangedFiles(projectLocation); final Set<ResourceKey> changedResources = new HashSet<>(changedFiles.size() * 2); for(Path changedFile : changedFiles) { changedResources.add(new FSPath(changedFile)); } final Arguments newArgs = new Arguments(); final List<String> builtinLibs = GenerateSourcesBuilder.splitOffBuiltinLibs(extraArgs, newArgs); Collection<STask> originTasks = sdfTasks; Analysis.Input strIncrAnalysisInput = new Analysis.Input(strFile, strjIncludeDirs, builtinLibs, originTasks, projectLocation); final Task<Output> strIncrAnalysisTask = strIncrAnalysisProvider.get().createTask(strIncrAnalysisInput); try { GenerateSourcesBuilder.initCompiler(pieProviderProvider.get(), strIncrAnalysisTask); } catch(ExecException e) { throw new MetaborgException("Initial Stratego build failed", e); } final ArrayList<IStrategoTerm> errors = new ArrayList<>(); final ArrayList<IStrategoTerm> warnings = new ArrayList<>(); final ArrayList<IStrategoTerm> notes = new ArrayList<>(); try(final PieSession pieSession = pieProviderProvider.get().pie().newSession()) { Analysis.Output analysisInformation = pieSession.require(strIncrAnalysisTask); for(Message message : analysisInformation.messages) { if(message.moduleFilePath.equals(path)) { final ImploderAttachment imploderAttachment = ImploderAttachment.get(OriginAttachment.tryGetOrigin(message.name)); if(imploderAttachment == null) { logger.debug("No origins for message: " + message); } errors.add(B.tuple(message.name, B.string(message.getMessage()))); } } } catch(ExecException e) { throw new MetaborgException("Incremental Stratego build failed", e); } return B.tuple(StrategoArrayList.fromList(errors), StrategoArrayList.fromList(warnings), StrategoArrayList.fromList(notes)); } private ISpoofaxLanguageSpec getLanguageSpecification(IProject project) throws MetaborgException { if(languageSpecServiceProvider == null) { // Indicates that meta-Spoofax is not available (ISpoofaxLanguageSpecService cannot be injected), but this // should never happen because this primitive is inside meta-Spoofax. Check for null just in case. logger.error("Language specification service is not available; static injection failed"); return null; } final ISpoofaxLanguageSpecService languageSpecService = languageSpecServiceProvider.get(); if(!languageSpecService.available(project)) { return null; } final ISpoofaxLanguageSpec languageSpec; try { languageSpec = languageSpecService.get(project); } catch(ConfigException e) { throw new MetaborgException("Unable to get language specification configuration for " + project, e); } return languageSpec; } @Override public void close() throws Exception { pieProviderProvider = null; languageSpecServiceProvider = null; } }
package org.intermine.web; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.actions.DispatchAction; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import java.util.Map; /** * Implementation of <strong>Action</strong> that set the current Query for * the session from a saved Query. * * @author Richard Smith * @author Kim Rutherford */ public class LoadQueryAction extends DispatchAction { /** * Process the specified HTTP request, and create the corresponding HTTP * response (or forward to another web component that will create it). * Return an <code>ActionForward</code> instance describing where and how * control should be forwarded, or <code>null</code> if the response has * already been completed. * * @param mapping The ActionMapping used to select this instance * @param form The optional ActionForm bean for this request (if any) * @param request The HTTP request we are processing * @param response The HTTP response we are creating * @return an ActionForward object defining where control goes next * * @exception Exception if the application business logic throws * an exception */ public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); Map savedQueries = (Map) session.getAttribute(Constants.SAVED_QUERIES); String queryName = (String) request.getParameter("queryName"); if (savedQueries != null && savedQueries.containsKey(queryName)) { QueryInfo queryInfo = (QueryInfo) savedQueries.get(queryName); session.setAttribute(Constants.QUERY, queryInfo.getQuery()); session.setAttribute(Constants.VIEW, queryInfo.getView()); } session.removeAttribute("path"); session.removeAttribute("prefix"); return mapping.findForward("buildquery"); } }
package org.voltdb.planner; import java.util.ArrayList; import java.util.List; import org.voltdb.plannodes.AbstractPlanNode; import org.voltdb.plannodes.DeletePlanNode; import org.voltdb.plannodes.IndexScanPlanNode; import org.voltdb.plannodes.InsertPlanNode; import org.voltdb.plannodes.OrderByPlanNode; import org.voltdb.plannodes.ReceivePlanNode; import org.voltdb.plannodes.SendPlanNode; import org.voltdb.plannodes.SeqScanPlanNode; import org.voltdb.plannodes.UpdatePlanNode; import org.voltdb.types.PlanNodeType; import java.util.Arrays; public class TestPlansDML extends PlannerTestCase { List<AbstractPlanNode> pns; public void testBasicUpdateAndDelete() { // select * with ON clause should return all columns from all tables AbstractPlanNode n; AbstractPlanNode pn; pns = compileToFragments("UPDATE R1 SET C = 1 WHERE C = 0"); pn = pns.get(0); System.out.println(pn.toExplainPlanString()); n = pn.getChild(0).getChild(0); assertTrue(n instanceof ReceivePlanNode); pn = pns.get(1); n = pn.getChild(0); assertTrue(n instanceof UpdatePlanNode); pns = compileToFragments("DELETE FROM R1 WHERE C = 0"); pn = pns.get(0); System.out.println(pn.toExplainPlanString()); n = pn.getChild(0).getChild(0); assertTrue(n instanceof ReceivePlanNode); pn = pns.get(1); n = pn.getChild(0); assertTrue(n instanceof DeletePlanNode); pns = compileToFragments("INSERT INTO R1 VALUES (1, 2, 3)"); pn = pns.get(0); System.out.println(pn.toExplainPlanString()); n = pn.getChild(0).getChild(0); assertTrue(n instanceof ReceivePlanNode); pn = pns.get(1); n = pn.getChild(0); assertTrue(n instanceof InsertPlanNode); pns = compileToFragments("UPDATE P1 SET C = 1 WHERE C = 0"); pn = pns.get(0); System.out.println(pn.toExplainPlanString()); n = pn.getChild(0).getChild(0); assertTrue(n instanceof ReceivePlanNode); pn = pns.get(1); n = pn.getChild(0); assertTrue(n instanceof UpdatePlanNode); pns = compileToFragments("DELETE FROM P1 WHERE C = 0"); pn = pns.get(0); System.out.println(pn.toExplainPlanString()); n = pn.getChild(0).getChild(0); assertTrue(n instanceof ReceivePlanNode); pn = pns.get(1); n = pn.getChild(0); assertTrue(n instanceof DeletePlanNode); pns = compileToFragments("UPDATE P1 SET C = 1 WHERE A = 0"); pn = pns.get(0); System.out.println(pn.toExplainPlanString()); //n = pn.getChild(0); assertTrue(pn instanceof UpdatePlanNode); pns = compileToFragments("DELETE FROM P1 WHERE A = 0"); pn = pns.get(0); System.out.println(pn.toExplainPlanString()); //n = pn.getChild(0); assertTrue(pn instanceof DeletePlanNode); pns = compileToFragments("INSERT INTO P1 VALUES (1, 2)"); pn = pns.get(0); System.out.println(pn.toExplainPlanString()); //n = pn.getChild(0).getChild(0); assertTrue(pn instanceof InsertPlanNode); } public void testTruncateTable() { String tbs[] = {"R1", "P1"}; for (String tb: tbs) { pns = compileToFragments("Truncate table " + tb); checkTruncateFlag(); pns = compileToFragments("DELETE FROM " + tb); checkTruncateFlag(); } } public void testInsertIntoSelectPlan() { System.out.println("\n\n\nRUNNING testInsertIntoSelectPlan\n\n"); // This should be inferred as single-partition pns = compileToFragments("INSERT INTO P1 SELECT * FROM P2 WHERE A = ?"); // One fragment means a single-partition plan assertEquals(1, pns.size()); // But this should be multi-partition pns = compileToFragments("INSERT INTO P1 SELECT * FROM P2"); assertEquals(2, pns.size()); // Single-partition pns = compileToFragments("INSERT INTO P1 " + "SELECT P2.A, P3.F " + "FROM P2 INNER JOIN P3 ON P2.A = P3.A " + "WHERE P3.A = ?"); assertEquals(1, pns.size()); // Multi-partition pns = compileToFragments("INSERT INTO P1 " + "SELECT P2.A, P3.F " + "FROM P2 INNER JOIN P3 ON P2.A = P3.A "); assertEquals(2, pns.size()); pns = compileToFragments("INSERT INTO P1 " + "SELECT sq.sqa, 7 " + "FROM (SELECT P2.A AS sqa FROM P2) AS sq;"); assertEquals(2, pns.size()); pns = compileToFragments("INSERT INTO P1 " + "SELECT sq.sqa, 9 " + "FROM (SELECT P2.A AS sqa FROM P2 WHERE P2.A = 9) AS sq;"); assertEquals(1, pns.size()); pns = compileToFragments("INSERT INTO P1 " + "SELECT sq.sqa, 9 " + "FROM (SELECT P2.A AS sqa FROM P2) AS sq " + "WHERE sq.sqa = 10;"); assertEquals(1, pns.size()); pns = compileToFragments( "INSERT INTO P1 " + "select P2_subq.Asq, P3_subq.Fsq " + "from (select 7, P2_subq_subq.Esqsq as Esq, P2_subq_subq.Asqsq as Asq from " + " (select P2.E as Esqsq, P2.A as Asqsq from P2) as P2_subq_subq) as P2_subq " + "inner join " + "(select P3.A as Asq, P3.F as Fsq from P3) as P3_subq " + "on P3_subq.Asq = P2_subq.Asq;"); assertEquals(2, pns.size()); pns = compileToFragments( "INSERT INTO P1 " + "select P2_subq.Asq, P3_subq.Fsq " + "from (select 7, P2_subq_subq.Esqsq as Esq, P2_subq_subq.Asqsq as Asq from " + " (select P2.E as Esqsq, P2.A as Asqsq from P2 " + " where P2.A = ?) as P2_subq_subq) as P2_subq " + "inner join " + "(select P3.A as Asq, P3.F as Fsq from P3) as P3_subq " + "on P3_subq.Asq = P2_subq.Asq;"); assertEquals(1, pns.size()); } public void testInsertSingleRowPlan() { System.out.println("\n\n\nRUNNING testInsertSingleRowPlan\n\n"); // These test cases are from ENG-5929. // This should be inferred as single-partition: pns = compileToFragments("INSERT INTO P1 (a, c) values(100, cast(? + 1 as integer))"); // One fragment means a single-partition plan assertEquals(1, pns.size()); // But this should be multi-partition: // Cannot evaluate expression except in EE. pns = compileToFragments("INSERT INTO P1 (a, c) values(cast(? + 1 as integer), 100)"); assertEquals(2, pns.size()); } private void verifyPlan(List<Class<? extends AbstractPlanNode>> expectedClasses, AbstractPlanNode actualNode) { AbstractPlanNode pn = actualNode; for (Class<? extends AbstractPlanNode> c : expectedClasses) { assertFalse("Actual plan shorter than expected", pn == null); assertTrue("Expected plan to contain an instance of " + c.getSimpleName() +", " + "instead found " + pn.getClass().getSimpleName(), c.isInstance(pn)); if (pn.getChildCount() > 0) pn = pn.getChild(0); else pn = null; } assertTrue("Actual plan longer than expected", pn == null); } public void testDeleteOrderByPlan() { System.out.println("\n\n\nRUNNING testDeleteOrderByPlan\n\n"); pns = compileToFragments("DELETE FROM R5 ORDER BY A LIMIT ?"); assertEquals(2, pns.size()); // There is a PK index on A, but we don't use it // for sort order here. We should! AbstractPlanNode collectorRoot = pns.get(1); verifyPlan(Arrays.asList( SendPlanNode.class, DeletePlanNode.class, OrderByPlanNode.class, SeqScanPlanNode.class), collectorRoot ); pns = compileToFragments("DELETE FROM R5 WHERE A = 1 ORDER BY A LIMIT ?"); assertEquals(2, pns.size()); // The ORDER BY is unnecessary here, since rows are already sorted due // to the index scan. collectorRoot = pns.get(1); verifyPlan(Arrays.asList( SendPlanNode.class, DeletePlanNode.class, OrderByPlanNode.class, IndexScanPlanNode.class), collectorRoot ); } private void checkTruncateFlag() { assertTrue(pns.size() == 2); ArrayList<AbstractPlanNode> deletes = pns.get(1).findAllNodesOfType(PlanNodeType.DELETE); assertTrue(deletes.size() == 1); assertTrue(((DeletePlanNode) deletes.get(0) ).isTruncate()); } @Override protected void setUp() throws Exception { setupSchema(TestJoinOrder.class.getResource("testplans-join-ddl.sql"), "testplansjoin", false); } }
package edu.northwestern.bioinformatics.studycalendar.utility.osgimosis; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Constructor; import java.util.Arrays; import java.util.Collection; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Set; import java.util.Map; /** * @author Rhett Sutphin */ @SuppressWarnings({ "RawUseOfParameterizedType" }) public class DefaultEncapsulatorCreator { private final Logger log = LoggerFactory.getLogger(getClass()); private Membrane membrane; private Class farClass; private ClassLoader nearClassLoader; private ClassLoader farClassLoader; private Map<String, Object[]> proxyConstructorParams; public DefaultEncapsulatorCreator(Membrane membrane, Class farClass, ClassLoader nearClassLoader, ClassLoader farClassLoader, Map<String, Object[]> proxyConstructorParams) { this.membrane = membrane; this.farClass = farClass; this.nearClassLoader = nearClassLoader; this.farClassLoader = farClassLoader; this.proxyConstructorParams = proxyConstructorParams; } public Encapsulator create() { if (List.class.isAssignableFrom(farClass)) { return new ListEncapsulator(membrane); } else if (Collection.class.isAssignableFrom(farClass)) { return new CollectionEncapsulator(membrane); } else if (farClass.isArray()) { log.trace(" - Encapsulating array with components {}", farClass.getComponentType()); Encapsulator componentEncapsulator = new DefaultEncapsulatorCreator( membrane, farClass.getComponentType(), nearClassLoader, farClassLoader, proxyConstructorParams).create(); if (componentEncapsulator == null) { return null; } else if (componentEncapsulator instanceof ArrayCapableEncapsulator) { return new ArrayEncapsulator((ArrayCapableEncapsulator) componentEncapsulator); } else { throw new MembraneException("Cannot encapsulate array; component type is not array capable"); } } else if (nearClassLoader == null) { log.trace(" - Not proxying object from bootstrap classloader"); return null; } else { Class base = sharedBaseClass(); List<Class> interfaces = sharedInterfaces(); if (base != null || !interfaces.isEmpty()) { return new ProxyEncapsulator( membrane, nearClassLoader, base, base == null ? null : proxyConstructorParams.get(base.getName()), interfaces, farClassLoader ); } else { log.trace(" - No shared base class or interfaces; not encapsulatable"); } } return null; } private Class targetClass(Class sourceClass) { try { return nearClassLoader.loadClass(sourceClass.getName()); } catch (ClassNotFoundException ex) { log.debug("Was not able to find a class matching {} in the target class loader {}", sourceClass.getName(), nearClassLoader); return null; } } private Class sharedBaseClass() { Class base = null; Class sourceClass = farClass; while (sourceClass != null && base == null) { if (isInSharedPackage(sourceClass) && proxyConstructable(sourceClass) && !hasFinalMethods(sourceClass)) { base = targetClass(sourceClass); } sourceClass = sourceClass.getSuperclass(); } log.trace("Base class will be {}", base); return base; } private boolean hasFinalMethods(Class sourceClass) { for (Method method : sourceClass.getDeclaredMethods()) { if (Modifier.isFinal(method.getModifiers())) return true; } return false; } private boolean proxyConstructable(Class<?> clazz) { if (proxyConstructorParams == null || proxyConstructorParams.get(clazz.getName()) == null) { try { Constructor<?> defaultConstructor = clazz.getDeclaredConstructor(); return !Modifier.isPrivate(defaultConstructor.getModifiers()); } catch (NoSuchMethodException e) { return false; } } else { return true; } } private List<Class> sharedInterfaces() { Set<Class> result = new LinkedHashSet<Class>(); Class[] allInterfaces = ReflectionTools.getAllInterfaces(farClass); log.trace("All interfaces are {}", Arrays.asList(allInterfaces)); for (Class<?> interfac : allInterfaces) { if (isInSharedPackage(interfac) && isAvailableInTargetClassLoader(interfac)) { Class target = targetClass(interfac); if (target != null) result.add(target); } } log.trace("Selected interfaces are {}", result); return new LinkedList<Class>(result); } private boolean isInSharedPackage(Class<?> interfac) { return membrane.getSharedPackages().contains(ReflectionTools.getPackageName(interfac)); } private boolean isAvailableInTargetClassLoader(Class<?> sourceClass) { try { nearClassLoader.loadClass(sourceClass.getName()); return true; } catch (ClassNotFoundException e) { log.debug("{} is in a shared package, but is not available from {}. Skipping.", sourceClass, nearClassLoader); return false; } } }
package com.github.sarxos.webcam.ds.gstreamer; import java.awt.Dimension; import java.awt.image.BufferedImage; import java.awt.image.DataBufferInt; import java.nio.IntBuffer; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import org.gstreamer.Caps; import org.gstreamer.Element; import org.gstreamer.ElementFactory; import org.gstreamer.Pad; import org.gstreamer.Pipeline; import org.gstreamer.State; import org.gstreamer.Structure; import org.gstreamer.elements.RGBDataSink; import com.github.sarxos.webcam.WebcamDevice; import com.github.sarxos.webcam.WebcamResolution; public class GStreamerDevice implements WebcamDevice, RGBDataSink.Listener { /** * Limit the lateness of frames to no more than 20ms (half a frame at 25fps) */ private static final long LATENESS = 20; private static final String FORMAT = "video/x-raw-yuv"; private final String name; private final Dimension[] resolutions; private Pipeline pipe = null; private Element source = null; private Element filter = null; private RGBDataSink sink = null; private BufferedImage image = null; private Caps caps = null; private AtomicBoolean open = new AtomicBoolean(false); private AtomicBoolean disposed = new AtomicBoolean(false); private Dimension resolution = WebcamResolution.VGA.getSize(); protected GStreamerDevice(String name) { this.name = name; pipe = new Pipeline(name); sink = new RGBDataSink(name, this); sink.setPassDirectBuffer(true); sink.getSinkElement().setMaximumLateness(LATENESS, TimeUnit.MILLISECONDS); sink.getSinkElement().setQOSEnabled(true); source = ElementFactory.make("dshowvideosrc", "source"); source.set("device-name", name); filter = ElementFactory.make("capsfilter", "filter"); resolutions = parseResolutions(source.getPads().get(0)); } private static final Dimension[] parseResolutions(Pad pad) { List<Dimension> dimensions = new ArrayList<Dimension>(); Caps caps = pad.getCaps(); Structure structure = null; String format = null; int n = caps.size(); int i = 0; int w = -1; int h = -1; do { structure = caps.getStructure(i++); format = structure.getName(); if (format.equals(FORMAT)) { w = structure.getRange("width").getMinInt(); h = structure.getRange("height").getMinInt(); dimensions.add(new Dimension(w, h)); } } while (i < n); return dimensions.toArray(new Dimension[dimensions.size()]); } @Override public String getName() { return name; } @Override public Dimension[] getResolutions() { return resolutions; } @Override public Dimension getResolution() { return resolution; } @Override public void setResolution(Dimension size) { this.resolution = size; } @Override public BufferedImage getImage() { return image; } @Override public void open() { if (!open.compareAndSet(false, true)) { return; } Dimension size = getResolution(); image = new BufferedImage(size.width, size.height, BufferedImage.TYPE_INT_RGB); image.setAccelerationPriority(0); image.flush(); if (caps != null) { caps.dispose(); } caps = Caps.fromString(String.format("%s,width=%d,height=%d", FORMAT, size.width, size.height)); filter.setCaps(caps); pipe.addMany(source, filter, sink); Element.linkMany(source, filter, sink); pipe.setState(State.PLAYING); } @Override public void close() { if (!open.compareAndSet(true, false)) { return; } pipe.setState(State.NULL); Element.unlinkMany(source, filter, sink); pipe.removeMany(source, filter, sink); } @Override public void dispose() { if (!disposed.compareAndSet(false, true)) { return; } close(); filter.dispose(); source.dispose(); sink.dispose(); pipe.dispose(); caps.dispose(); } @Override public boolean isOpen() { return open.get(); } @Override public void rgbFrame(boolean preroll, int width, int height, IntBuffer rgb) { BufferedImage tmp = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); tmp.setAccelerationPriority(0); tmp.flush(); rgb.get(((DataBufferInt) tmp.getRaster().getDataBuffer()).getData(), 0, width * height); image = tmp; } }
package org.lxp.java8; import static java.util.Comparator.comparingInt; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collectors; import java.util.stream.Stream; import org.lxp.vo.Student; public class StudyStream { public static List<Student> collect(List<Student> list, Predicate<Student> predicate) { return list.stream().filter(predicate).collect(Collectors.toList()); } public static String findFirst(List<Student> list, Predicate<Student> predicate) { return list.stream().filter(predicate).findFirst().get().getName(); } public static Student orElse(List<Student> list, Predicate<Student> predicate) { return list.stream().filter(predicate).findFirst().orElse(null); } public static List<String> map(List<Student> list, Function<Student, String> function) { return list.stream().map(function).collect(Collectors.toList()); } public static Set<String> map(List<Student> list, Predicate<Student> predicate, Function<Student, String> function) { return list.stream().filter(predicate).map(function).collect(Collectors.toSet()); } public static List<Student> sort(List<Student> list) { list.sort(comparingInt(Student::getAge).thenComparing(Student::getName).reversed()); return list; } public static Map<Integer, List<Student>> groupby(List<Student> list) { return list.stream().collect(Collectors.groupingBy(Student::getAge)); } public static Map<Integer, Set<Student>> groupbyToSet(List<Student> list) { return list.stream().collect(Collectors.groupingBy(Student::getAge, Collectors.toSet())); } public static Map<String, Student> toMap1(List<Student> list) { return list.stream().collect(Collectors.toMap(Student::getStudentNo, Function.identity())); } public static Map<String, String> toMap2(List<Student> list) { return list.stream().collect(Collectors.toMap(Student::getStudentNo, Student::getName)); } public static List<Student> filter(List<Student> list, Predicate<Student> predicate1, Predicate<Student> predicate2) { return list.stream().filter(predicate1).filter(predicate2).collect(Collectors.toList()); } public static List<Student> limit(List<Student> list, Predicate<Student> predicate, int limit) { return list.stream().filter(predicate).limit(limit).collect(Collectors.toList()); } public static long count(List<Student> list, Predicate<Student> predicate) { return list.stream().filter(predicate).count(); } public static List<String> flatMap(String[]... lists) { List<String> rtn = Collections.emptyList(); if (lists != null && lists.length > 0) { rtn = Stream.of(lists).flatMap(array -> Stream.of(array)).map(s -> s.toUpperCase()) .collect(Collectors.toList()); } return rtn; } }
package biz.neustar.ultra.rest.client; import java.io.IOException; import java.util.Arrays; import java.util.List; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.mockito.Mockito; import biz.neustar.ultra.rest.constants.ZoneType; import biz.neustar.ultra.rest.dto.AccountList; import biz.neustar.ultra.rest.dto.RRSetList; import biz.neustar.ultra.rest.dto.ZoneInfoList; import biz.neustar.ultra.rest.dto.ZoneOutInfo; public class RestApiClientTest { private RestApiClient restApiClient; private String tokenFileName; private String userPassFile; @Before public void setup() { restApiClient = Mockito.mock(RestApiClient.class); } @Test public void testGetZonesOfAccount() throws IOException { restApiClient.deleteZone("zoneName"); } // TODO - Need to replace this test with the one using Mockito @Test public void testAllMethodsOnActualEnvt() throws IOException { // Do not fail the test if the server is down or not-reachable this.userPassFile= "/Users/npartang/Projects/java_rest_api_client/rest_user.txt"; this.tokenFileName = "/Users/npartang/Projects/java_rest_api_client/rest_tokens.txt"; try { restApiClient = new RestApiClient( "http://restapi-useast1b01-01.qa.ultradns.net:8080/", this.userPassFile, this.tokenFileName); } catch(Exception e) { return; } String accountName = "selautomation10"; String zoneName = "narayantest40.biz."; // Create a primary zone restApiClient.createPrimaryZone(accountName, zoneName); System.out.println("after primary creation"); // Get zone metadata for the primary zone created as part of test ZoneOutInfo zoneOutInfo = restApiClient.getZoneMetadata(zoneName); Assert.assertNotNull(zoneOutInfo); Assert.assertNotNull(zoneOutInfo.getProperties()); Assert.assertEquals(zoneName, zoneOutInfo.getProperties().getName()); Assert.assertEquals(ZoneType.PRIMARY, zoneOutInfo.getProperties().getType()); // List the zones for account passing the primary zone created as part of test String offset = "0"; String limit = ""+Integer.MAX_VALUE; String sort = "NAME"; String reverse = "true"; ZoneInfoList outZoneInfoList = restApiClient.getZonesOfAccount(accountName, "zone_type:PRIMARY", offset, limit, sort, reverse); Assert.assertNotNull(outZoneInfoList); Assert.assertNotNull(outZoneInfoList.getResultInfo()); //Assert.assertEquals(8, outZoneInfoList.getResultInfo().getReturnedCount()); Assert.assertNotNull(outZoneInfoList.getList()); Assert.assertNotNull(outZoneInfoList.getList().get(0)); Assert.assertNotNull(outZoneInfoList.getList().get(0).getProperties()); //Assert.assertEquals(zoneName, outZoneInfoList.getList().get(0).getProperties().getName()); Assert.assertEquals(ZoneType.PRIMARY, outZoneInfoList.getList().get(0).getProperties().getType()); // Create a new RRSet of type 'A' & the primary zone created as part of test List<String> rdata = Arrays.asList("12.12.12.13"); String ownerName = "selautomation10"; Integer ttl = new Integer(300); restApiClient.createRRSet(zoneName, "A", ownerName, ttl, rdata); // List the RRSet of type 'A' & of the primary zone created as part of test //RRSetList rrSetList = restApiClient.getRRSetsByType(zoneName, "A", "owner:selautomation10", offset, limit, sort, reverse); //RRSetList rrSetList = restApiClient.getRRSetsByType(zoneName, "1", "owner:selautomation10", offset, limit, sort, reverse); /* Assert.assertNotNull(rrSetList); Assert.assertNotNull(rrSetList.getResultInfo()); Assert.assertEquals(1, rrSetList.getResultInfo().getReturnedCount()); Assert.assertNotNull(rrSetList.getRrSets()); Assert.assertEquals(1, rrSetList.getRrSets().size()); Assert.assertEquals("A (1)", rrSetList.getRrSets().get(0).getRrtype()); Assert.assertEquals(ownerName, rrSetList.getRrSets().get(0).getOwnerName()); Assert.assertEquals(rdata, rrSetList.getRrSets().get(0).getRdata()); Assert.assertEquals(ttl, rrSetList.getRrSets().get(0).getTtl()); */ // List the RRSets of the primary zone created as part of test RRSetList rrSetList = restApiClient.getRRSets(zoneName, "owner:selautomation10", offset, limit, "TYPE", reverse); // By default 2 records (NS & SOA) would be automatically created with zone creation, so they must be returned Assert.assertNotNull(rrSetList); Assert.assertNotNull(rrSetList.getResultInfo()); //Assert.assertEquals(2, rrSetList.getResultInfo().getReturnedCount()); Assert.assertNotNull(rrSetList.getRrSets()); //Assert.assertEquals(2, rrSetList.getRrSets().size()); //Assert.assertEquals("NS (2)", rrSetList.getRrSets().get(0).getRrtype()); //Assert.assertEquals("SOA (6)", rrSetList.getRrSets().get(1).getRrtype()); // Update the existing RRSet of type 'A' & the primary zone created as part of test ttl = 500; restApiClient.updateRRSet(zoneName, "A", ownerName, ttl, rdata); // List the RRSets of the primary zone created as part of test rrSetList = restApiClient.getRRSets(zoneName, "owner:selautomation10", offset, limit, "TYPE", reverse); // List the updated RRSet of type 'A' & of the primary zone created as part of test //rrSetList = restApiClient.getRRSetsByType(zoneName, "A", null, offset, limit, sort, reverse); Assert.assertNotNull(rrSetList); Assert.assertNotNull(rrSetList.getResultInfo()); Assert.assertEquals(1, rrSetList.getResultInfo().getReturnedCount()); Assert.assertNotNull(rrSetList.getRrSets()); Assert.assertEquals(1, rrSetList.getRrSets().size()); Assert.assertEquals("A (1)", rrSetList.getRrSets().get(0).getRrtype()); //Assert.assertEquals(ownerName, rrSetList.getRrSets().get(0).getOwnerName()); Assert.assertEquals(rdata, rrSetList.getRrSets().get(0).getRdata()); Assert.assertEquals(ttl, rrSetList.getRrSets().get(0).getTtl()); // Delete the existing RRSet of type 'A' & the primary zone created as part of test restApiClient.deleteRRSet(zoneName, "A", ownerName); /* // List the updated RRSet of type 'A' & of the primary zone created as part of test try { rrSetList = restApiClient.getRRSetsByType(zoneName, "A", null, offset, limit, sort, reverse); Assert.fail("An exception should be thrown as record of type 'A' doesnot exist"); } catch(Exception e) { // Expecting an exception } */ // Delete the zone created restApiClient.deleteZone(zoneName); // Get the account details for user AccountList accountList = restApiClient.getAccountDetails(); Assert.assertNotNull(accountList); Assert.assertNotNull(accountList.getList()); Assert.assertTrue(accountList.getList().size() > 0); Assert.assertTrue(accountList.getList().get(0).getNumberOfUsers() > 0); // Get the version of REST API server String outVersion = restApiClient.getVersion(); Assert.assertNotNull(outVersion); // Get the status of REST API server String outStatus = restApiClient.getStatus(); Assert.assertNotNull(outStatus); } }
package br.com.rcmoutinho.javatohtml.core.tag; import static org.junit.Assert.assertEquals; import java.util.ArrayList; import java.util.List; import org.junit.Before; import org.junit.Test; import br.com.rcmoutinho.javatohtml.core.Element; import br.com.rcmoutinho.javatohtml.core.ElementUtils; import br.com.rcmoutinho.javatohtml.core.exception.UnsupportedTagException; /** * Unit test for {@link Table}. * * @rcmoutinho * @author rodrigo.moutinho * @date 10 de jan de 2017 * @email rcm1989@gmail.com */ public class TableTest { private String theadToHtml; private String tbodyToHtml; private String tfootToHtml; private String trToHtml; private List<Class<? extends Element<?>>> notSupportedElements; @Before public void beforeTesting() { this.theadToHtml = "<table><thead></thead></table>"; this.tbodyToHtml = "<table><tbody></tbody></table>"; this.tfootToHtml = "<table><tfoot></tfoot></table>"; this.trToHtml = "<table><tr></tr></table>"; this.notSupportedElements = new ArrayList<Class<? extends Element<?>>>( ElementUtils.getAllImplementedElements()); // removes supported elements this.notSupportedElements.remove(Thead.class); this.notSupportedElements.remove(Tbody.class); this.notSupportedElements.remove(Tfoot.class); this.notSupportedElements.remove(Tr.class); } @Test public void checkSupportedElementsToAppend() { assertEquals(this.theadToHtml, new Table().append(new Thead()).toHtml()); assertEquals(this.tbodyToHtml, new Table().append(new Tbody()).toHtml()); assertEquals(this.tfootToHtml, new Table().append(new Tfoot()).toHtml()); assertEquals(this.trToHtml, new Table().append(new Tr()).toHtml()); } @Test public void checkSupportedElementsToPrepend() { assertEquals(this.theadToHtml, new Table().prepend(new Thead()).toHtml()); assertEquals(this.tbodyToHtml, new Table().prepend(new Tbody()).toHtml()); assertEquals(this.tfootToHtml, new Table().prepend(new Tfoot()).toHtml()); assertEquals(this.trToHtml, new Table().prepend(new Tr()).toHtml()); } @Test public void checkUnsupportedElementsToAppend() { int unsupportedTagCount = new ElementTester().countUnsupportedTagExceptionToAppend(new Table(), this.notSupportedElements); assertEquals(unsupportedTagCount, this.notSupportedElements.size()); } @Test public void checkUnsupportedElementsToPrepend() { int unsupportedTagCount = new ElementTester().countUnsupportedTagExceptionToPrepend(new Table(), this.notSupportedElements); assertEquals(unsupportedTagCount, this.notSupportedElements.size()); } @Test(expected = UnsupportedTagException.class) public void stringAppendNotSupported() { new Table().append("text"); } @Test(expected = UnsupportedTagException.class) public void stringPrependNotSupported() { new Table().prepend("text"); } }